body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
---|---|---|---|---|
<p>I've written a backup script to make a backup of the latest modified files in 12 hours. Basically, it searches two directories for modified files (statically coded) then the <code>find</code> command is used to find the related files. A log file is then created to keep a list of the files. Later on, they are used to form a list of files and these files are used for the backup by tar.</p>
<p>Let me know which parts could be developed so that I can improve on and learn new things.</p>
<pre><code>#!/usr/bin/env python
''' backup script to make a backup of the files
that are newer than 12 hours in the
home directory
see
" man find "
" man tar "
for more information on the dates and the specific options
on how to set different specifications for the selections
'''
import sys
import os
import time
if (len(sys.argv) != 2):
# if argument count is different
# than 2, then there is an error
print "Error on usage -> binary <hours_count_back>"
quit()
else:
# convert to integer value
hours_back = int(sys.argv[1])
message_start = "Operation is starting".center(50, '-')
message_end = "Operation terminated with success".center(50,'-')
#
print message_start
# source directories to check for backup
source = [ '/home/utab/thesis', '/home/utab/Documents' ]
# find files newer than 24 hours
# change to the target directories
newer_files = []
#
log_file = "log.dat"
# cmd to find newer files
# than 24 hours
cmd_find = "find . -type f -a -mmin " + str(-hours_back*60) + " > " + log_file
for directory in source:
# iterate over the directories
# change to the directory first
os.chdir(directory)
# apply the command
os.system(cmd_find);
# files are found with respect to the current directory
# change the "." to directory for correct backups
c = 0
# process log file
files = []
lines = []
log_in = open(log_file,'r')
# read lines without \n character
while 1:
l = log_in.readline()
if not l:
break
# do not include the newline
# -1 is for that
lines.append(l[:-1])
#
for l in lines:
l_dummy = l.replace( '.', directory, 1 )
files.append(l_dummy)
# extend the list with newer files
newer_files.extend(files)
#print newer_files
print newer_files
# date
today = time.strftime('%Y%m%d')
# current time of the date
# possible to do different backups in different times of the day
now = time.strftime('%H%M%S')
#
target_directory = "/home/utab/"
target = target_directory + today + "_" + now + \
'.tgz'
# do the actual back up
backup_cmd = "tar -C ~ -zcvf %s %s" % ( target , ' '.join(newer_files) )
status = os.system(backup_cmd)
if status == 0:
print message_end
else:
print "Back-up failed"
</code></pre>
| [] | [
{
"body": "<p>A general suggestion which might yield a performance boost: if you can somehow determine that the directories in the <code>source</code> lists are on different harddisks, you could execute the main loop (which spends most of the time in the <code>find</code> invocation, I guess) in parallel.</p>\n\n<p>That being said, you could replace </p>\n\n<pre><code>for l in lines:\n l_dummy = l.replace( '.', directory, 1 )\n files.append(l_dummy)\n# extend the list with newer files\nnewer_files.extend(files)\n</code></pre>\n\n<p>with a list comprehension:</p>\n\n<pre><code>newer_files.extend([l.replace( '.', directory, 1 ) for l in lines])\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-14T07:32:26.430",
"Id": "1876",
"ParentId": "1866",
"Score": "3"
}
},
{
"body": "<p>The script is vulnerable to an injection attack. If anyone can write files under any of the directories to be backed up then the script can be made to execute code of their choosing. (I realize that this is your home directory and \"this could never happen\" but bear with me for a moment). The problem is that a non-validated string is passed to <code>os.system()</code>:</p>\n\n<pre><code>backup_cmd = \"tar -C ~ -zcvf %s %s\" % ( target , ' '.join(newer_files) )\nstatus = os.system(backup_cmd)\n</code></pre>\n\n<p>Attacker just needs to:</p>\n\n<pre><code>cd some/where/writable\ntouch '; rm -rf ~'\n</code></pre>\n\n<p>But it doesn't even need to be a malicious attack. If any of the files have characters in their names that are interesting to the shell then the script may fail. A tamer example: if any filename contains a hash character (<code>#</code>) then all subsequent filenames in the <code>newer_files</code> list will be ignored and will not be backed up by <code>tar(1)</code>.</p>\n\n<p>Instead please consider using <a href=\"http://docs.python.org/library/os.html#os.execv\" rel=\"noreferrer\"><code>os.exec*()</code></a> or better still the <a href=\"http://docs.python.org/library/subprocess.html\" rel=\"noreferrer\"><code>subprocess</code> module</a>. These take a vector of arguments rather than a string and so do not suffer from the same problem.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-14T12:46:15.550",
"Id": "1881",
"ParentId": "1866",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "1881",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-13T18:30:45.843",
"Id": "1866",
"Score": "8",
"Tags": [
"python",
"linux"
],
"Title": "Linux backup script in Python"
} | 1866 |
<p>I present you my first ever module to learn some Erlang awaiting your scrutiny . It does a word frequency count using map/reduce . I'm an Erlang noob, so I would very much like feedback about:</p>
<p>Unneeded verbosity / code</p>
<p>Erlang 'style' mistakes</p>
<p>Things that can be done more elegantly</p>
<pre><code>-module(main).
-export([map/1]).
-export([main/0]).
-export([reducer_wrapper/1]).
-export([reducer/2]).
-define(NUMBER_OF_PARTITIONS, 100).
main() ->
Lines = readlines('pg20417.txt') ,
lists:foreach( fun main:map/1, Lines ),
start_reduce().
%% signals all reducer_wrappers that all emits are received, and the actual reduce can be started
start_reduce() ->
lists:foreach( fun(PartitionNr) -> get_reducer(PartitionNr) ! start_reduce end, lists:seq(1, ?NUMBER_OF_PARTITIONS) ).
%% emits every word with cnt = 1
map(Line) ->
Words = string:tokens( string:to_lower(Line), " .,;:\n()?"),
lists:foreach ( fun(Word) -> get_reducer( Word, ?NUMBER_OF_PARTITIONS ) ! {emit, {Word, [1]}} end, Words ).
%% returns the reducer Pid
get_reducer( PartitionNr ) ->
ProcessName = list_to_atom( lists:concat( [PartitionNr, '_reducer'] ) ),
case whereis( ProcessName ) of
undefined ->
Pid = spawn(?MODULE, reducer_wrapper, [[]]),
register( ProcessName, Pid ),
Pid;
Pid ->
Pid
end.
get_reducer( Key, NumberOfPartitions ) ->
get_reducer( erlang:phash2(Key) rem NumberOfPartitions + 1 ).
%% the reducer wrapper proces
reducer_wrapper(KeyValueTuples) ->
receive
{ emit, KeyValueTuple } ->
reducer_wrapper( [KeyValueTuple] ++ KeyValueTuples );
start_reduce ->
Dictionary = lists:foldl( fun main:reducer/2, dict:new(), KeyValueTuples ),
show_all( dict:to_list(Dictionary) )
end.
reducer( { Key, [Cnt] }, Dictionary ) ->
case dict:is_key( Key, Dictionary ) of
true ->
dict:store( Key, dict:fetch( Key, Dictionary ) + Cnt, Dictionary );
false ->
dict:store( Key, Cnt, Dictionary )
end.
readlines(FileName) ->
{ok, Device} = file:open(FileName, [read]),
get_all_lines(Device, []).
get_all_lines(Device, Accum) ->
case io:get_line(Device, "") of
eof -> file:close(Device), Accum;
Line -> get_all_lines(Device, Accum ++ [Line])
end.
show_all([Head|Tail]) ->
io:format("~p~n", [Head]),
show_all(Tail);
show_all([]) ->
void.
</code></pre>
| [] | [
{
"body": "<p>A few initial points:</p>\n\n<ul>\n<li>Your mapping phase is all done on one process, so you're not getting any parallelism. You should fire off <code>M</code> mappers to do the mapping for you, and give them bits of the data to map over. They can pass this on to one of <code>R</code> reducers who do the reduction.</li>\n<li><code>[KeyValueTuple] ++ KeyValueTuples</code> is slow as you're creating lists and concatenating them together. Instead, just prepend values to the list in O(1) time: <code>[KeyValueTuple|KeyValueTuples]</code></li>\n<li>The way you're spawning/creating the reducer process is a bit unnecessary. If I were you I'd spawn <code>R</code> reducers up front and dish out the work in a round-robin fashion. This will give you better control of load distribution.</li>\n<li>Instead of calling <code>dict:is_key</code> then, if <code>true</code>, calling <code>dict:fetch</code> do both of them in one step by calling <code>dict:find</code>, then matching against <code>{ok, Value}</code> or <code>error</code>. This saves on the double-lookup.</li>\n</ul>\n\n<p>As a general comment, you've really tied together both map/reduce and word counting. Ideally what you'd want to do is have a structure/module which knows about how to do map/reduce by itself, and be ignorant of the work that's going on. You would then have another module which is able to invoke a map/reduce job by passing in the Map function, the Reduce function, the number of mappers and reducers and the data that's being processed.</p>\n\n<p>I realise you're learning, so you don't need to do all this. But down the track I'd recommend attempting to abstract away the map/reduce stuff into a reusable module.</p>\n\n<p>Hope that helps.\nOJ</p>\n\n<p>PS. were you hoping for someone to show you how they'd code it up? I'm new to this code review site and I'm not sure whether I should be posting \"fixed\" code or not :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-15T14:49:34.820",
"Id": "3201",
"Score": "0",
"body": "Great feedback, exactly what I was hoping for. Tnx! It's indeed nothing near a sane Map Reduce implementation in Erlang as the focus was getting acquainted with the language ;-).\n\nThe round-robin would probably not work for the reducers, as the order of the received keys is important."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-15T13:12:22.810",
"Id": "1905",
"ParentId": "1869",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "1905",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-13T22:55:30.887",
"Id": "1869",
"Score": "6",
"Tags": [
"erlang"
],
"Title": "Newbie Map/Reduce word frequency counter"
} | 1869 |
<p>I have a method that gets an RSS feed using LINQ to XML and returns a collection of an object that grabs only the data I need. There's really only one other method in the class I'm concerned about that you'll see in the sample -- RemoveUrlNoise.</p>
<p>How do I test a method like this or change it to be more testable?</p>
<pre><code> public IEnumerable<PostDetails> GetPostDetails(string rssUrl)
{
XElement feed = XElement.Load(rssUrl);
var items = from item in feed.Elements("channel").Elements("item")
select item;
return items.Select(item => new PostDetails
{
Title = item.Element("title").Value,
Url = RemoveUrlNoise(item.Element("guid").Value),
PubDate = item.Element("pubDate").Value
}).OrderBy(i => i.PubDateAsDateTime).ToList();
}
</code></pre>
| [] | [
{
"body": "<p>Separate the concerns of fetching the feed XML from parsing it by extracting a class (e.g. FeedReader) to do the reading. Your IFeedReader would be generically reusable and look something like:</p>\n\n<pre><code>public interface IFeedReader\n{\n XElement Load(string url);\n}\n</code></pre>\n\n<p>with implementation</p>\n\n<pre><code>public class FeedReader : IFeedReader\n{\n public XElement Load(string url)\n {\n return XElement.Load(url);\n }\n}\n</code></pre>\n\n<p>You then inject an IFeedReader through the constructor and use it to fetch the data in your method. This lets you use a Fake or a Mock of the IFeedReader, depending on your preference, to return appropriate results for your unit test.</p>\n\n<p>consider reading up on: <a href=\"http://martinfowler.com/articles/injection.html\">inversion of control (IoC) and dependency injection (DI)</a>, and <a href=\"http://en.wikipedia.org/wiki/Mock_object\">mock object frameworks</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-14T03:59:36.407",
"Id": "1871",
"ParentId": "1870",
"Score": "10"
}
}
] | {
"AcceptedAnswerId": "1871",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-14T02:07:10.930",
"Id": "1870",
"Score": "2",
"Tags": [
"c#",
"linq",
"unit-testing"
],
"Title": "How would I unit test a method that gets data from an RSS feed?"
} | 1870 |
<p><img src="https://i.stack.imgur.com/npc8B.gif" alt="queens"></p>
<blockquote>
<p>Figure 2.8: A solution to the
eight-queens puzzle. The
``eight-queens puzzle'' asks how to
place eight queens on a chessboard so
that no queen is in check from any
other (i.e., no two queens are in the
same row, column, or diagonal). One
possible solution is shown in figure
2.8. One way to solve the puzzle is to work across the board, placing a queen
in each column. Once we have placed k
- 1 queens, we must place the kth queen in a position where it does not
check any of the queens already on the
board. We can formulate this approach
recursively: Assume that we have
already generated the sequence of all
possible ways to place k - 1 queens in
the first k - 1 columns of the board.
For each of these ways, generate an
extended set of positions by placing a
queen in each row of the kth column.
Now filter these, keeping only the
positions for which the queen in the
kth column is safe with respect to the
other queens. This produces the
sequence of all ways to place k queens
in the first k columns. By continuing
this process, we will produce not only
one solution, but all solutions to the
puzzle.</p>
<p>We implement this solution as a
procedure queens, which returns a
sequence of all solutions to the
problem of placing n queens on an n× n
chessboard. Queens has an internal
procedure queen-cols that returns the
sequence of all ways to place queens
in the first k columns of the board.</p>
</blockquote>
<pre><code>(define (queens board-size)
(define (queen-cols k)
(if (= k 0)
(list empty-board)
(filter
(lambda (positions) (safe? k positions))
(flatmap
(lambda (rest-of-queens)
(map (lambda (new-row)
(adjoin-position new-row k rest-of-queens))
(enumerate-interval 1 board-size)))
(queen-cols (- k 1))))))
(queen-cols board-size))
</code></pre>
<blockquote>
<p>In this procedure rest-of-queens is a
way to place k - 1 queens in the first
k - 1 columns, and new-row is a
proposed row in which to place the
queen for the kth column. Complete the
program by implementing the
representation for sets of board
positions, including the procedure
adjoin-position, which adjoins a new
row-column position to a set of
positions, and empty-board, which
represents an empty set of positions.
You must also write the procedure
safe?, which determines for a set of
positions, whether the queen in the
kth column is safe with respect to the
others. (Note that we need only check
whether the new queen is safe -- the
other queens are already guaranteed
safe with respect to each other.)</p>
</blockquote>
<p>I found this task to be especially difficult. I think I have a working answer, but I'm sure that there is a much better way. My current solution feels like a popsicle-stick bridge held together with duct tape, poised to fall apart at any moment. I know it's messy, so I must apologize in advance. If you can't follow it let me know and I'll try to rewrite it a bit if possible. For now, though, I need to take a break! How can I improve my code?</p>
<pre><code>(define (enumerate-interval i j) (if (= i j) (list j) (cons i (enumerate-interval (+ i 1) j))))
(define (filter f seq) (if (null? seq) null (if (f (car seq)) (cons (car seq) (filter f (cdr seq))) (filter f (cdr seq)))))
(define (flatmap op seq)
(foldr append null (map op seq)))
(define (queens board-size)
(define (empty-board)
(map (lambda (row)
(map (lambda (col) 0)
(enumerate-interval 1 board-size)))
(enumerate-interval 1 board-size)))
(define (adjoin-position new-row k rest-of-queens)
(cond ((and (= new-row 1)
(= k 1)) (cons (cons 1
(cdar rest-of-queens))
(cdr rest-of-queens)))
((> k 1) (cons (car rest-of-queens)
(adjoin-position new-row
(- k 1)
(cdr rest-of-queens))))
(else (let ((adjoined (adjoin-position (- new-row 1)
k
(cons (cdar rest-of-queens)
(cdr rest-of-queens)))))
(cons (cons (caar rest-of-queens)
(car adjoined))
(cdr adjoined))))))
(define (queen-cols k)
(if (= k 0)
(list (empty-board))
(filter
(lambda (positions) (safe? k positions))
(flatmap
(lambda (rest-of-queens)
(map (lambda (new-row)
(adjoin-position new-row k rest-of-queens))
(enumerate-interval 1 board-size)))
(queen-cols (- k 1))))))
(queen-cols board-size))
(define col car)
(define row cdr)
(define (indexOf x seq)
(define (rec i remains)
(cond ((null? remains) (error "No x found in seq." x seq))
((= (car remains) x) i)
(else (rec (+ i 1) (cdr remains)))))
(rec 0 seq))
(define (nth n seq)
(cond ((null? seq) (error "Sequence shorter than n" seq n))
((= n 1) (car seq))
(else (nth (- n 1) (cdr seq)))))
(define (all-true seq)
(cond ((null? seq) true)
((car seq) (all-true (cdr seq)))
(else false)))
(define (upto k rows)
(if (or (= k 0)
(null? rows))
null
(cons (car rows) (upto (- k 1) (cdr rows)))))
(define (safe? k positions)
(let ((uptok-positions (upto (- k 1) positions))
(kth-position (nth k positions)))
(define (col-row-coords pos)
(define (process-row rownum rows)
(define (process-col colnum row)
(cond ((null? row) null)
((= (car row) 1) (cons rownum colnum))
(else (process-col (+ colnum 1) (cdr row)))))
(if (null? rows)
null
(cons (process-col 1 (car rows))
(process-row (+ rownum 1) (cdr rows)))))
(process-row 1 pos))
(let ((col-and-row (filter (lambda (x) (not (null? x))) (col-row-coords uptok-positions)))
(k-coord (cons k (indexOf 1 kth-position))))
(define (diagonal? p1 p2)
(= (abs (- (col p1) (col p2)))
(abs (- (row p1) (row p2)))))
(all-true (map (lambda (pos)
(and (not (= (col k-coord)
(col pos)))
(not (= (row k-coord)
(row pos)))
(not (diagonal? k-coord pos)))) col-and-row)))))
</code></pre>
<p>EDIT: Thanks for the feedback! I have a new version here. I would appreciate any feedback you have. </p>
<pre><code>(define (enumerate-interval i j) (if (> i j) null (cons i (enumerate-interval (+ i 1) j))))
(define (filter f seq) (if (null? seq) null (if (f (car seq)) (cons (car seq) (filter f (cdr seq))) (filter f (cdr seq)))))
(define (flatmap op seq)
(foldr append null (map op seq)))
(define (queens board-size)
(define (empty-board) '())
(define (adjoin-position new-row k rest-of-queens)
(append rest-of-queens (list (cons new-row k))))
(define (queen-cols k)
(if (= k 0)
(list (empty-board))
(filter
(lambda (positions) (safe? k positions))
(flatmap
(lambda (rest-of-queens)
(map (lambda (new-row)
(adjoin-position new-row k rest-of-queens))
(enumerate-interval 1 board-size)))
(queen-cols (- k 1))))))
(queen-cols board-size))
(define col car)
(define row cdr)
(define (threatens? q1 q2)
(define (diagonal? q1 q2)
(= (abs (- (col q1) (col q2)))
(abs (- (row q1) (row q2)))))
(or (= (col q1) (col q2))
(= (row q1) (row q2))
(diagonal? q1 q2)))
(define (nth n seq) (if (= n 1) (car seq) (nth (- n 1) (cdr seq))))
(define (except-nth n seq)
(cond ((null? seq) '())
((= n 1) (cdr seq))
(else (cons (car seq) (except-nth (- n 1) (cdr seq))))))
(define (safe? k positions)
(define (rec me threats)
(or (null? threats)
(and (not (threatens? me (car threats)))
(rec me (cdr threats)))))
(rec (nth k positions)
(except-nth k positions)))
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-14T10:53:16.287",
"Id": "62807",
"Score": "0",
"body": "Begin with `(define empty-board null)`."
}
] | [
{
"body": "<p>I do not know scheme that much that I be able to read this code, but I have idea how to avoid counting rotations and reflections (if you have not implement it yourself)</p>\n\n<ol>\n<li>Place 1st queen on A1 to A4</li>\n<li>Queen placed on H column should have row number higher that column number of A queen.</li>\n<li>Queen placed on 1 row should have column letter higher than row number of A queen.</li>\n</ol>\n\n<p>I might be missing something</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-14T06:55:49.207",
"Id": "1874",
"ParentId": "1872",
"Score": "0"
}
},
{
"body": "<p>Well, an empty board should be represented by an empty list.</p>\n\n<pre><code> (define (empty-board) '())\n</code></pre>\n\n<p>You can represent the board state just as a list of pairs that contain the coordinates of the queens. Using 0..7 as the coordinates, you get</p>\n\n<pre><code> (define (adjoin-position x y board) (cons (cons x y) board))\n</code></pre>\n\n<p>Ok, so now you need to have a way to check if the queen on row k is safe with respect to the others. If you take advantage of the structure of the \"queens\" procedure, you can do this easier (because the queen you are checking on is the queen added last to the board, so it is at the beginning of the list of positions). Assuming you don't take a shortcut like this, you need to do two things: fetch the location of the queen on row k and then perform the arithmetics. You can use the Scheme procedure assv for this, i.e.</p>\n\n<pre><code> (define (get-queen row board) (assv row board))\n</code></pre>\n\n<p>This returns the pair, or #f if nothing is found.</p>\n\n<p>You can write a procedure that checks if two queens at (x, y) and (a, b) threaten each other:</p>\n\n<pre><code> (define (threatens? x y a b)\n ... ;; left as an exercise to the reader\n )\n</code></pre>\n\n<p>After which the procedure (safe? row board) can be implemented easily by iterating the queen positions from the board list (another exercise).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-15T04:39:03.190",
"Id": "1899",
"ParentId": "1872",
"Score": "2"
}
},
{
"body": "<p>As we are looking for a subset of positions where each column is occupied by exactly one queen, we can represent an NxN board setup in a simpler way - as a list of N numbers, each ranging from 1 to N, representing row number taken by the queen in the 1st ... Nth columns. Empty board would still be an emplty list.</p>\n\n<p>Then we can use <code>cons</code> as <code>adjoin-position</code>, and check particular k-queens position by taking the first queen position and iterating over remaining k-1 queens, checking if the delta between positions equals zero or the number of iteration. With this approach <code>safe?</code> doesn't even need an explicit <code>k</code> as an argument - it is just the length of the position passed to <code>safe?</code> and is used implicity by iterating over the <code>(cdr position)</code>:</p>\n\n<pre><code>(define (queens board-size)\n (define (queen-cols k)\n (if (= k 0)\n (list '())\n (filter\n (lambda (position) (safe? position))\n (flatmap\n (lambda (rest-of-queens)\n (map (lambda (new-row)\n (cons new-row rest-of-queens))\n (enumerate-interval 1 board-size)))\n (queen-cols (- k 1))))))\n (define (safe? position)\n (safe-iter? (car position) 1 (cdr position)))\n (define (safe-iter? fst n rest-position)\n (cond ((null? rest-position) true)\n ((= fst (car rest-position)) false)\n ((= (abs (- fst (car rest-position))) n) false)\n (else (safe-iter? fst (+ n 1) (cdr rest-position)))))\n (queen-cols board-size))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-21T14:18:45.613",
"Id": "4281",
"ParentId": "1872",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-14T05:35:31.547",
"Id": "1872",
"Score": "6",
"Tags": [
"lisp",
"scheme",
"sicp",
"n-queens"
],
"Title": "Eight-queens puzzle"
} | 1872 |
<p>Here's an interesting scenario that I encountered the other day. I did eventually reach a solution on my own. However, I'd welcome any comments and better approaches.</p>
<p><strong>The requirements</strong></p>
<p>I want to generate JAXB objects based on a collection of XSDs using XJC as part of a Maven build. I'll be using JAXB-RI 2.1 as the implementation.</p>
<p>In addition, I want to make sure that all objects implement a signature interface (e.g. <code>MySignature</code>) which has no methods. Also, I want to avoid using <code>XmlGregorianCalendar</code> and have Joda <code>DataTime</code> instead (with a suitable adapter that I'll provide called <code>DateUtils</code> with <code>parse()</code> and <code>format()</code> methods).</p>
<p>Finally, I want to be able to select certain objects to act as root elements so I'll need to selectively add <code>@XmlRootElement</code> to some objects, and I have suitable XPath expressions to locate them. </p>
<p>I can't make any changes to the XSDs. </p>
<p><strong>The approach</strong></p>
<p><strong>Step 1</strong> - Configuring the pom.xml</p>
<p>Configure Maven to use the XJC plugin as follows:</p>
<pre class="lang-xml prettyprint-override"><code><build>
<plugins>
<plugin>
<groupId>org.jvnet.jaxb2.maven2</groupId>
<artifactId>maven-jaxb2-plugin</artifactId>
<version>0.7.4</version>
<executions>
<execution>
<id>generate-domain1</id>
<goals>
<goal>generate</goal>
</goals>
<configuration>
<strict>false</strict>
<schemaIncludes>
<value>domain1.xsd</value>
</schemaIncludes>
<bindingIncludes>
<include>domain1-bindings.xjb</include>
</bindingIncludes>
<extension>true</extension>
<generatePackage>org.example.domain1</generatePackage>
<generateDirectory>${project.build.directory}/generated-sources/domain1</generateDirectory>
<args>
<arg>-Xannotate</arg>
</args>
<plugins>
<plugin>
<groupId>org.jvnet.jaxb2_commons</groupId>
<artifactId>jaxb2-basics</artifactId>
<version>0.6.0</version>
</plugin>
<plugin>
<groupId>org.jvnet.jaxb2_commons</groupId>
<artifactId>jaxb2-basics-annotate</artifactId>
<version>0.6.0</version>
</plugin>
</plugins>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</code></pre>
<p>The use of a dedicated execution configuration is there to allow additional mutually exclusive XSDs to be built using a different target output path. </p>
<p><strong>Step 2</strong> - Configure the bindings</p>
<p>Include the following as <code>src/main/resources/domain1-bindings.xjb</code>.</p>
<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<jaxb:bindings
xmlns:jaxb="http://java.sun.com/xml/ns/jaxb" xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:annox="http://annox.dev.java.net"
xsi:schemaLocation="http://java.sun.com/xml/ns/jaxb http://java.sun.com/xml/ns/jaxb/bindingschema_2_0.xsd"
jaxb:extensionBindingPrefixes="xjc annox"
version="2.1">
<jaxb:globalBindings>
<jaxb:serializable uid="1"/>
<!-- All generated classes must have MySignature interface (supplied in dependencies) -->
<xjc:superInterface name="org.example.MySignature"/>
<!-- All temporal fields are implemented as Joda DateTime and use DateUtils as an adapter -->
<jaxb:javaType
name="org.joda.time.DateTime"
xmlType="xs:time"
parseMethod="org.example.DateUtils.parseDateTime"
printMethod="org.exmaple.DateUtils.formatDateTime"
/>
</jaxb:globalBindings>
<!-- Application of annotations to selected classes within schemas -->
<!-- org.example.SomeRootType @XmlRootElement -->
<jaxb:bindings schemaLocation="domain1.xsd" node="/xs:schema">
<jaxb:bindings node="xs:complexType[@name='SomeRootType']">
<annox:annotate>
<annox:annotate annox:class="javax.xml.bind.annotation.XmlRootElement" name="SomeRootType"/>
</annox:annotate>
</jaxb:bindings>
</jaxb:bindings>
</jaxb:bindings>
</code></pre>
<p><strong>Troubleshooting</strong></p>
<p>If you encounter the infamous</p>
<blockquote>
<p>Unsupported binding namespace "". Perhaps you meant "<a href="http://annox.dev.java.net">http://annox.dev.java.net</a>"</p>
</blockquote>
<p>then you need to examine your <code>bindings.xjb</code> to make sure that you're using the correct namespace URIs (as defined above) and have included them into <code>extensionBindingPrefixes</code>.</p>
| [] | [
{
"body": "<p>The <code><jaxb:javaType /></code> tag generates a new <code>org.w3._2001.xmlschema.AdapterN</code> class for each new javaType definition. So a better approach would be:</p>\n\n<ul>\n<li>Create a class extending <a href=\"http://docs.oracle.com/javase/6/docs/api/javax/xml/bind/annotation/adapters/XmlAdapter.html\" rel=\"noreferrer\"><code>XmlAdapter<String, _To_></code></a>. In it you will have to override the both methods defined. So in example, the class could be <code>org.example.DateUtilsAdapter</code>.</li>\n<li><p>Use this tag instead:</p>\n\n<pre><code><xjc:javaType\n name=\"org.joda.time.DateTime\"\n xmlType=\"xs:time\"\n adapter=\"org.example.DateUtilsAdapter\" />\n</code></pre></li>\n</ul>\n\n<p><a href=\"http://jaxb.java.net/nonav/2.1.13/docs/vendorCustomizations.html#javaType\" rel=\"noreferrer\">Source</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-13T16:26:45.183",
"Id": "65534",
"Score": "0",
"body": "I have an example with a java.util.Date Adapter (JaxbDateAdapter). [Source here](https://gist.github.com/ghusta/6701630)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-22T09:13:04.310",
"Id": "14934",
"ParentId": "1877",
"Score": "8"
}
},
{
"body": "<p>I tried your example in Eclipse and got a warning:</p>\n\n<pre><code>cvc-complex-type.3.2.2: Attribute 'jaxb:extensionBindingPrefixes' is not allowed to appear in \n element 'jaxb:bindings'.\n</code></pre>\n\n<p>When I changed the URL from 2.0 to 2.1 it removed the warning.</p>\n\n<p>Before: <a href=\"http://java.sun.com/xml/ns/jaxb/bindingschema_2_0.xsd\" rel=\"noreferrer\">http://java.sun.com/xml/ns/jaxb/bindingschema_2_0.xsd</a><br>\nAfter: <a href=\"http://java.sun.com/xml/ns/jaxb/bindingschema_2_1.xsd\" rel=\"noreferrer\">http://java.sun.com/xml/ns/jaxb/bindingschema_2_1.xsd</a></p>\n\n<pre><code><jaxb:bindings\n xmlns:jaxb=\"http://java.sun.com/xml/ns/jaxb\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"\n xmlns:xjc=\"http://java.sun.com/xml/ns/jaxb/xjc\"\n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xmlns:annox=\"http://annox.dev.java.net\"\n xsi:schemaLocation=\"http://java.sun.com/xml/ns/jaxb http://java.sun.com/xml/ns/jaxb/bindingschema_2_1.xsd\"\n jaxb:extensionBindingPrefixes=\"xjc annox\"\n version=\"2.1\">\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-01-09T11:55:41.197",
"Id": "77076",
"ParentId": "1877",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-14T09:32:02.847",
"Id": "1877",
"Score": "29",
"Tags": [
"java",
"xml",
"jodatime",
"maven",
"jaxb"
],
"Title": "JAXB XJC code generation - adding @XmlRootElement and Joda DateTime"
} | 1877 |
<p>It seems to play up sometimes and I'm not sure if this is due to the class itself or the way I'm using it. Can someone confirm that this is a 'good' implementation of a <code>VertexArrayObject</code> class?</p>
<pre><code>//The following code is public domain
public class VertexArray : GraphicsResource
{
protected readonly int ID;
DrawMode _drawMode;
VertexLayout _vertexType;
protected BufferUsageHint bufferUsage = BufferUsageHint.StaticDraw;
int vertexCount;
int vertexBufferID;
public DrawMode DrawMode
{
get { return _drawMode; }
set { _drawMode = value; }
}
public int VertexCount
{
get { return vertexCount; }
}
public BufferUsageHint BufferUsage
{
get { return bufferUsage; }
set { bufferUsage = value; }
}
public VertexArray()
: base()
{
ID = createVAO();
disposed = false;
}
public VertexArray(DrawMode drawMode)
: base()
{
_drawMode = drawMode;
ID = createVAO();
disposed = false;
}
int createVAO()
{
int id;
GL.GenBuffers(1, out vertexBufferID);
GL.GenVertexArrays(1, out id);
GL.BindVertexArray(id);
GL.BindBuffer(BufferTarget.ArrayBuffer, vertexBufferID);
VenGFX.currentVAO = this;
return id;
}
public void Bind()
{
if (vertexCount == 0)
throw new Exception("Vertex buffer has no data, and therefore can't be used");
if (disposed)
throw new ObjectDisposedException(ToString());
GL.BindVertexArray(ID);
VenGFX.currentVAO = this;
}
public void SetData<T>(T[] Array) where T : struct, IVertex
{
GL.BindVertexArray(ID);
if (Array.Length > 0 && Array[0].Layout != _vertexType)
setVertexType(Array[0].Layout);
GL.BindBuffer(BufferTarget.ArrayBuffer, vertexBufferID);
GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(Array.Length * _vertexType.SizeInBytes), Array, bufferUsage);
vertexCount = Array.Length;
VenGFX.currentVAO = this;
}
public void SetData<T>(T[] Array, int length) where T : struct, IVertex
{
GL.BindVertexArray(ID);
if (Array != null && Array.Length > 0 && Array[0].Layout != _vertexType)
setVertexType(Array[0].Layout);
GL.BindBuffer(BufferTarget.ArrayBuffer, vertexBufferID);
GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(length * _vertexType.SizeInBytes), Array, bufferUsage);
vertexCount = length;
VenGFX.currentVAO = this;
}
void setVertexType(VertexLayout layout)
{
_vertexType = layout;
layout.Set();
}
protected override void Release()
{
if (VenGFX.currentVAO == this)
{
GL.BindVertexArray(0);
VenGFX.currentVAO = null;
}
int id = ID;
GL.DeleteBuffers(1, ref vertexBufferID);
GL.DeleteVertexArrays(1, ref id);
}
}
</code></pre>
<p>To draw with it, I write</p>
<pre><code>if (mesh.VertexCount == 0)
return;
if (currentVAO != mesh)
mesh.Bind();
GL.DrawArrays((BeginMode)(int)mesh.DrawMode, 0, mesh.VertexCount);
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-07-30T08:51:27.070",
"Id": "325040",
"Score": "0",
"body": "I found many similarities with my code: https://github.com/luca-piccioni/OpenGL.Net.Objects/blob/master/OpenGL.Net.Objects/VertexArrays.cs"
}
] | [
{
"body": "<p>I know nothing of OpenGL and what a correct implementation of a VertexArrayObject should look like, but I do have a couple of observations:</p>\n\n<ul>\n<li>I like that the <code>ID</code> private field is <code>readonly</code>, ...but its naming breaks the naming convention for private fields, which should be either <code>id</code> or <code>_id</code> - looking at the other private fields <code>_id</code> would be more consistent.</li>\n<li>I don't see why the other fields <code>vertexCount</code> and <code>vertexBufferID</code> (should be <code>vertexBufferId</code>) aren't prefixed with an underscore as well.</li>\n<li>Vertical whitespace between methods/members isn't consistent either. Skip a line between <code>}</code> and the next member, it'll breathe better.</li>\n</ul>\n\n\n\n<pre><code>public VertexArray()\n : base()\n</code></pre>\n\n<p>The <code>: base()</code> part is redundant. Base constructor always gets called.</p>\n\n<p>In the <code>Release()</code> override, you're doing this:</p>\n\n<pre><code> int id = ID;\n GL.DeleteBuffers(1, ref vertexBufferID);\n GL.DeleteVertexArrays(1, ref id);\n</code></pre>\n\n<p>Whatever <code>DeleteVertexArrays</code> is doing with <code>id</code> (passed by reference), you're not doing anything with the [possibly] modified value, I'm guessing because <code>ID</code> is <code>readonly</code>. But this is clearly a case where the \"why\" would be nicely explained with a short comment.</p>\n\n<p>Lastly, properties like <code>DrawMode</code> that use a non-readonly backing field...</p>\n\n<pre><code>DrawMode _drawMode;\npublic DrawMode DrawMode\n{\n get { return _drawMode; }\n set { _drawMode = value; }\n}\n</code></pre>\n\n<p>...would probably be better off rewritten as auto-properties:</p>\n\n<pre><code>public DrawMode DrawMode { get; set; }\npublic BufferUsageHint BufferUsag { get; set; }\npublic int VertexCount { get; private set; }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T05:14:44.087",
"Id": "41535",
"ParentId": "1880",
"Score": "6"
}
},
{
"body": "<p>I know this is an old question and has already been reviewed but I feel it's worth adding to in case anyone else happens to stumble across it or have a similar solution/question.</p>\n\n<p>Firstly, I'd like point out that Matt's answer covers most of the syntactical/small changes that should be made to the code, so I'd like to address the question:</p>\n\n<blockquote>\n <p>Is this an acceptable implementation of a OpenGL VertexArrayObject class?</p>\n</blockquote>\n\n<p><strong>Short answer:</strong> I would say no</p>\n\n<p><strong>Long answer:</strong> Well, here we go...</p>\n\n<h2><strong>Vertex Array Objects</strong></h2>\n\n<p>Before we proceed with the implementation, it is key to understand what exactly it is that we are implementing. The code in the OP is not what I would say is a Vertex Array Object (I'll delve into why not later), but for now, let us briefly define a VAO.</p>\n\n<p>To summarise <a href=\"http://ogldev.atspace.co.uk/www/tutorial32/tutorial32.html\" rel=\"nofollow\">the link</a>:</p>\n\n<blockquote>\n <p>A VAO is a special type of object that encapsulates all the data that is associated with the vertex processor. Instead of containing the actual data, it holds references to the vertex buffers, the index buffer and the layout specification of the vertex itself</p>\n</blockquote>\n\n<p>Sounds like we will be implementing some object that has to deal with a fair few things right? wrong.\nLike a lot of OpenGL 'objects', a VAO is simply identified by an integer given to us from the following command (OpenTK bindings):</p>\n\n<pre><code>GL.GenVertexArray();\n</code></pre>\n\n<p>It is essential to note that by saying we want to define a VertexArrayObject class, we are simply stating that we want a wrapper around the OpenGL 'object'. Therefore, all we have to do is identify the possible members & operations that the class will need.</p>\n\n<p>Where to start? Well, <a href=\"https://www.opengl.org/wiki/Vertex_Specification#Vertex_Array_Object\" rel=\"nofollow\">the spec</a> is always a good place. </p>\n\n<p>Briefly, we can identify that it will need an integer member that stores the result of the above OpenGL invocation and also the following operations:</p>\n\n<ul>\n<li><code>GL.GenVertexArray()</code></li>\n<li><code>GL.BindVertexArray(...)</code></li>\n<li><code>GL.DeleteVertexArray(...)</code></li>\n</ul>\n\n<p>I'd like to emphasise that really, all we are doing is wrapping an OpenGL object in a way such that we can interface to it in a more .NET manner.</p>\n\n<p><strong>Quickly back to OP's implementation</strong>\nIt is doing far more than what a VAO is responsible for:</p>\n\n<ol>\n<li>It is concerning itself with Vertex Buffers (When really, these are themselves an OpenGL object that should be wrapped separately to the VAO).</li>\n<li>It is aware of how things will be drawn</li>\n<li>It is responsible for buffer creation (again, this should be separate)</li>\n<li>It is responsible for setting vertex data.</li>\n</ol>\n\n<p>One point that really sticks out is the <code>CreateVAO</code> method.\nThis should be responsible for creating the Handle to the OpenGL integer only. Currently, it is also generating handles to VBOs <em>and</em> binding the buffer objects. Also, your implementation is 'hard-coding' the type of Buffer that will be bound - <code>ArrayBuffer</code>. What if you wanted to support a different buffer type?</p>\n\n<p>Another is the <code>Bind</code> method. You're throwing an <code>exception</code> if there is no buffer data, but this is not how VAOs behave. We are free to generate and bind VAOs without the presence of any buffers or with empty buffers.</p>\n\n<p>The <code>ID</code> field would probably be better as a property with a private setter. This represents the 'handle' and will change as pointed out by Mat. You're stating that this integer will never change after initialisation but we know that on the OpenGL side, the integer it represents does mutate. Your code should show its intent and the behaviour between objects should be consistent.</p>\n\n<p>An important note is that your class is dealing with unmanaged resources in the form of handles to OpenGL 'objects' and yet you are not handling this in the recommended way. Currently, you're cleaning up these resources in the <code>Release</code> method. I can see that your <code>GraphicsResource</code> contains a <code>disposed</code> boolean member, yet this is not used in your 'clean-up' code from what I can see. </p>\n\n<p>Consider what happens if this method is invocated more than once. You would be attempting to delete a handle that has already been deleted. </p>\n\n<p>If another developer was to use this class, and he was experienced in using OpenGL, he would soon become confused that this 'wrapped' version does not share the behaviour of the <code>OpenGL</code> one.</p>\n\n<p>With this said, let's get back to an implementation I feel would be better.</p>\n\n<p><strong>Suggested Implementation</strong></p>\n\n<p>This could be improved, but a simple implementation follows:</p>\n\n<pre><code>internal sealed class VertexArrayObject : IDisposable\n{\n internal int Handle { get; private set; }\n\n private bool isDisposed = false;\n\n internal VertexArrayObject(bool bind = false)\n {\n this.Handle = GL.GenVertexArray();\n if (bind)\n {\n Bind();\n }\n }\n\n internal void Bind()\n {\n CheckForDisposed();\n GL.BindVertexArray(this.Handle);\n }\n\n internal void UnBind()\n {\n CheckForDisposed();\n GL.BindVertexArray(0);\n }\n\n private void CheckForDisposed()\n {\n if (this.isDisposed)\n {\n throw new ObjectDisposedException(GetType().FullName);\n }\n }\n\n public void Dispose()\n {\n Dispose(true);\n GC.SuppressFinalize(this);\n }\n\n private void Dispose(bool manual)\n {\n if (!this.isDisposed)\n {\n if (manual){ }\n if (this.Handle != -1)\n {\n GL.DeleteVertexArray(this.Handle);\n }\n this.isDisposed = true;\n }\n }\n\n ~VertexArrayObject()\n {\n Dispose(false);\n }\n}\n</code></pre>\n\n<p>Note: I've made the class internal only due to the fact that in my experience, I prefer to hide the OpenGL side from users of a game engine, but obviously that depends on how you're using the class/the goals of your application.</p>\n\n<p>Obviously the above does not give you any functionality beside being a basic wrapper around the OpenGL 'object'. However, this has the following advantages:</p>\n\n<ul>\n<li>It is minimalist - You really are just getting a VAO, which is what we would expect, not a VAO with internally hidden buffers and features that should be separated out into other classes.</li>\n<li>It will be used just as the OpenGL 'object' would, except it hides the OpenGL calls.</li>\n</ul>\n\n<p>In conclusion, I hope this answer addressed the points that were missing regarding the original question. I'm not saying this is the definitive way to implement a Vertex Array Object in C#, just an interesting point at which to begin.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-02-02T02:56:51.600",
"Id": "143604",
"Score": "0",
"body": "Great points, cheers"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-22T03:25:50.173",
"Id": "74442",
"ParentId": "1880",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-14T12:27:41.573",
"Id": "1880",
"Score": "5",
"Tags": [
"c#",
"object-oriented",
"opengl"
],
"Title": "OpenGL VertexArrayObject class"
} | 1880 |
<p>I am quite new to Java and was trying to improve my skills a little by doing a binary file reader. The choosen one was the <a href="http://en.wikipedia.org/wiki/Type-length-value" rel="nofollow">TLV</a> format. I've chosen that one for being reasonably simple, but not so simple. Also I had some concrete examples with good documentation which I could follow for decoding.</p>
<p>The reader works, but I ended up with a class that seems way too big to be right. I wonder if anyone can break down this code into something more robust.</p>
<pre><code>package tlv;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import tlv.errors.MissingI10ParameterException;
import tlv.errors.ParseI10ParameterException;
import tlv.errors.TLVFileException;
/**
* Represents a TLV file.
* Expects class File, which represents a TLV file formated as:
* [HEADER]
* [LogicalBlock-1]
* [DataSegmentHeader-1]
* [DataSegment-1]
* [DataSegmentTrailer-1]
* (...)
* [DataSegmentHeader-n]
* [DataSegment-n]
* [DataSegmentTrailer-n]
*
*/
public class DiriTlvFile {
ArrayList<LogicalBlock> dirisegs = new ArrayList<LogicalBlock>();
int tbc = 114;
public DiriTlvFile(File tlv) throws TLVFileException {
DataInputStream dis = null;
try {
// Here BufferedInputStream is added for fast reading.
dis = new DataInputStream(new BufferedInputStream(new FileInputStream(tlv)));
// Header data
byte[] ba = new byte[3];
/* This is the fixes header added
We just skip it straight away. */
dis.skipBytes(114);
LogicalBlock lb = null;
// Iterate over main file parts
while (dis.available() > 0) {
if (dis.read(ba, 0, 3)!= 3)
throw new TLVFileException("Error reading DataSegmentID (wrong byte count) @" + tbc);
tbc += 3;
String headerId = new String(ba);
// File header
if (headerId.equalsIgnoreCase("I01")) {
lb = new LogicalBlock();
// Skip uninteresting part of header
dis.skipBytes(50);
tbc += 50;
// Data Segment body
} else if (headerId.equalsIgnoreCase("I10")) {
if (lb == null)
throw new TLVFileException( "Logical Block was not initiated! (Missing I01 structure in file).");
byte[] dsheader = new byte[25];
if (dis.read(dsheader, 0, 25) != 25) // Head of the DS
throw new TLVFileException( "Error reading DataSegmentHeader (I10, wrong byte count) @ " + tbc);
tbc += 25;
int dssize = (dsheader[24] & 0xFF) - 1; // Size of DS body (+the header itself?)
byte[] dsbody = new byte[dssize]; // Body of DS
// Read DataSegmentBody
if (dis.read(dsbody, 0, dssize) != dssize)
throw new TLVFileException( "Error reading DataSegmentBody (I10, wrong byte count) @ " + tbc);
tbc += dssize;
// Create the datasegments
try {
lb.addDataSegment(new I10DataSegment(headerId, dsheader, dsbody));
} catch (MissingI10ParameterException e) {
// TODO - Improve this message using the mandatory parameter list from the exception
throw new TLVFileException("Error parsing DataSegment body (I10) : Missing one of mandatory parameters.");
} catch (ParseI10ParameterException e) {
throw new TLVFileException("Error parsing DataSegment body (I10) : Could not parse DataSegmentParameters.");
}
} else if (headerId.equalsIgnoreCase("I03")) {
// total records read
byte[] trailertotrecs = new byte[3];
// Have left the loop, means it found the footer
byte[] trailerbody = new byte[4];
if (dis.read(trailerbody, 0, 4) != 4) // Trailer Body
throw new TLVFileException( "Error reading Trailer Body (I03, wrong byte count) @ " + tbc);
tbc += 4;
System.arraycopy(trailerbody, 1, trailertotrecs, 0, 3);
// TODO - compare the number of records read with the information in the footer
dirisegs.add(lb);
} else {
throw new TLVFileException("Unknown Segment ID found");
}
}
// dispose all the resources after using them.
dis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public Iterator<LogicalBlock> getLogicalBlocks() {
return dirisegs.iterator();
}
public Iterator<DataSegment> getDataSegments(){
ArrayList<DataSegment> a = new ArrayList<DataSegment>();
Iterator<LogicalBlock> i = getLogicalBlocks();
while (i.hasNext()){
Iterator<DataSegment> j = i.next().getDataSegments();
while (j.hasNext()){
a.add((DataSegment)j.next());
}
}
return a.iterator();
}
}
</code></pre>
<p>P.S.: I've omitted the other classes as they are pretty much only byte-parsing.</p>
| [] | [
{
"body": "<p>Of course the constructor is too long, but you need to be careful when you factor out some parts into separate private methods, especially with error handling. Right now error handling isn't correct: <code>dis.close();</code> will never be called in case of an file error etc, leaving the stream open. Getting this right is tricky, so I'd suggest to use a tool like <a href=\"http://findbugs.sourceforge.net/\" rel=\"nofollow\">Findbugs</a>.</p>\n\n<p>Use interfaces for your variable types if possible, e.g. <code>List<LogicalBlock> dirisegs = new ArrayList<LogicalBlock>();</code></p>\n\n<p>Member variables should almost always be <code>private</code>. If you need extenal access, you should prefer getter methods. Even then you need to be careful with mutable objects like Collections or <code>Date</code>: To be on the safe side you need to make defensive copies.</p>\n\n<p>You use a lot of \"magical numbers\" like 114, 25 etc. If possible, make them \"constants\" (<code>final static int</code>) with a meaningful name. Same holds for Strings like <code>\"I01\"</code>.</p>\n\n<p>Why do you return an <code>Iterator</code>s in <code>getLogicalBlocks</code> and <code>getDataSegments</code>? I don't know the use case good enough, but I think twice before I give back something potentially less useful than I already have. But if you decide that you really need <code>Iterators</code>, did you consider to implement the <code>Iterable</code> interface? If iterating is a common operation for your class, it would be convenient to be able to use it in enhanced for-loops.</p>\n\n<p>Is there a reason that <code>getDataSegments</code> isn't implemented that way?</p>\n\n<pre><code>public Iterator<DataSegment> getDataSegments(){\n List<DataSegment> a = new ArrayList<DataSegment>();\n for(LogicalBlock logicalBlock : dirisegs) {\n for(Iterator<DataSegment> j = logicalBlock.getDataSegments(), j.hasNext();) {\n a.add(j.next());\n }\n }\n return a.iterator();\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-04-06T23:14:02.407",
"Id": "2946",
"Score": "0",
"body": "Hey! Thanks for the tips! specially on the error handling, will look into that. As for the method you mention, it is sort of a kludge I used to output all the data I read straight away in higher level classes. the correct use would be iterate over \"LogicalBlock\"s then get the DataSegments. Just did this way cos there was nothing useful in the LogicalBlocks at the moment :P"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2011-04-06T21:45:20.333",
"Id": "1688",
"ParentId": "1885",
"Score": "1"
}
},
{
"body": "<p>One thing you could consider, is basing your implementation on interfaces. </p>\n\n<p>For example, you could make <code>DiriTlvFile</code> an interface like this: </p>\n\n<pre><code>interface DiriTlvFile {\n public Iterator<LogicalBlock> getLogicalBlocks();\n public Iterator<DataSegment> getDataSegments(); \n}\n</code></pre>\n\n<p>and since <code>getDataSegments</code> is most likely the same in all implementations an abstract class</p>\n\n<pre><code>abstract class AbstractDiriTlvFile implements DiriTlvFile {\n public Iterator<DataSegment> getDataSegments() {\n // ...\n }\n}\n</code></pre>\n\n<p>And then use a \"loader\" interface like this</p>\n\n<pre><code>interface DiriTlvFileLoader {\n public DiriTlvFile loadDiriTlvFile();\n}\n</code></pre>\n\n<p>Which you'd implement using the code you used in the constructor:</p>\n\n<pre><code>class DiriTlvFileLoaderFromFile implements DiriTlvFileLoader {\n\n protected File tlv;\n\n public DiriTlvFileLoaderFromFile(File tlv) {\n this.tlv = tlv;\n }\n\n public DiriTlvFile loadDiriTlvFile() {\n List<LogicalBlock> dirisegs = new ArrayList<LogicalBlock>();\n\n // ...\n\n return new AbstractDiriTlvFile() {\n public Iterator<LogicalBlock> getLogicalBlocks() {\n return dirisegs.iterator();\n }\n }\n }\n}\n</code></pre>\n\n<p>This would let you factor out variants, for example, base <code>DiriTlvFileLoaderFromFile</code> on <code>DiriTlvFileLoaderFromInputStream</code> and use the latter to create <code>DiriTlvFileLoaderFromURL</code> for loading from a net resource.</p>\n\n<hr>\n\n<p>Currently your <code>getDataSegments</code> copies all the data into a new list each time it's called. But if you have <code>LogicalBlock</code> implement <code>Iterable</code>, you could instead implement a \"flattening iterator\", that actually iterates over the items without copying them. For example using:</p>\n\n<pre><code>public class FlattenIterable<T> implements Iterable<T> {\n private Iterable<Iterable<T>> iterable;\n\n public FlattenIterable(Iterable<Iterable<T>> iterable) {\n this.iterable = iterable;\n }\n\n public Iterator<T> iterator() {\n return new FlattenIterator<T>(iterable.iterator());\n }\n\n static class FlattenIterator<T> implements Iterator<T> {\n private Iterator<Iterable<T>> iterables;\n private Iterator<T> currentIterator;\n\n public FlattenIterator(Iterator<Iterable<T>> iterator) {\n this.iterables = iterator;\n currentIterator = null;\n }\n\n private void nextIterable() {\n currentIterator = iterables.next().iterator();\n }\n\n public boolean hasNext() {\n if (currentIterator == null) {\n if (iterables.hasNext()) {\n nextIterable();\n } else {\n return false;\n }\n }\n\n while (!currentIterator.hasNext() && iterables.hasNext()) {\n nextIterable();\n }\n\n return currentIterator.hasNext();\n }\n\n public T next() {\n return currentIterator.next();\n }\n\n public void remove() {\n throw new UnsupportedOperationException(\"Remove not supported\"); \n }\n }\n}\n</code></pre>\n\n<p>(Based on <a href=\"http://langexplr.blogspot.com/2007/12/combining-iterators-in-java.html\" rel=\"nofollow\">http://langexplr.blogspot.com/2007/12/combining-iterators-in-java.html</a>)</p>\n\n<p>you can implement <code>AbstractDiriTlvFile</code> as</p>\n\n<pre><code>abstract class AbstractDiriTlvFile implements DiriTlvFile {\n\n protected Iterable<DataSegment> dataSegmentFlattenIterable = \n new FlattenIterable<DataSegment>(getLogicalBlocks());\n\n public Iterator<DataSegment> getDataSegments() {\n return dataSegmentFlattenIterable.iterator();\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-07T08:59:25.270",
"Id": "1710",
"ParentId": "1885",
"Score": "1"
}
},
{
"body": "<p>Firstly, i should mention that i don't really understand the file format. You say it's TLV, but you seem to be reading mostly fixed-length chunks.</p>\n\n<p>I'd split the tasks of parsing and holding the data. I'd write a sort of <code>TLVInputStream</code> or <code>TLVParser</code> class, which has a method <code>readChunk</code>, which reads a single TLV triple from an underlying stream and returns it. Usage is like:</p>\n\n<pre><code>TLVInputStream input = new TLVInputStream(new FileInputStream(someFile));\nChunk chunk = input.readChunk();\n</code></pre>\n\n<p>The constructor would do the header skipping. <code>readChunk</code> would catch an <code>EOFException</code> from the read of the first (and only the first) byte in the tag, and deal with that by returning <code>null</code>, to indicate the end of the file (like how <code>BufferedReader.readLine</code> returns <code>null</code> at end of file). EOFExceptions anywhere else in a chunk should be passed through, as they really are errors.</p>\n\n<p>I wouldn't do decoding of specific chunk types in the <code>readChunk</code> method. Rather than treating chunk lengths as something to be validated, i would use them to control reading. <code>readChunk</code> would read the chunk header, read the length, then read that many bytes of input, and return the chunk. Validating the lengths of the chunks belongs in a higher level than the IO code.</p>\n\n<p>Then I'd have a separate class which holds chunks. Call it <code>ChunkFile</code> or something. That contains the chunks, and do validation on them (eg checking the length) as they are added. If you later wanted to add methods to operate on the chunks, they would go here.</p>\n\n<p>I'd have a third, small, class, which uses a <code>TLVInputStream</code> to read a file and make a <code>ChunkFile</code> object. This is simple enough that it could perhaps be a static factory method on <code>TLVInputStream</code>.</p>\n\n<p>There are a few small details I'd change. If counting the total number of bytes is important, then move the read and count operations into a single method that does both, and always use that. That means you don't have to remember to update the count whenever you read. You do a lot of <code>dis.read(buf, 0, len) == len</code> - you should use <code>readFully</code> for that.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-06T16:55:00.183",
"Id": "1886",
"ParentId": "1885",
"Score": "1"
}
},
{
"body": "<ul>\n<li>Program against interfaces, e.g. <code>List<LogicalBlock> dirisegs = new ArrayList<LogicalBlock>();</code></li>\n<li>Use variable names with meaning, e.g. <code>byteCount</code> instead of <code>tbc</code> </li>\n<li>Don't write <code>e.printStackTrace()</code>, do something useful (propagate error, log error...)</li>\n<li>Your <code>DataInputStream</code> won't be close in case of an error. You should move the closing to a finally clause (of course there you need an extra try-catch) </li>\n<li>The constructor is way to long, split it up</li>\n<li>Why don't you give back a <code>List</code> in <code>getDataSegments</code> (you already have one)? <code>Iterator</code> is less useful</li>\n<li>Rename <code>getLogicalBlocks</code> to <code>iterator()</code> and add an <code>extends Iterable<LogicalBlock></code> to your class, then you can use the class in enhanced for-loops.</li>\n<li>Try to make operations \"atomic\", e.g. bundle reading from a stream and increasing the counter in a little method:</li>\n</ul>\n\n<p>.</p>\n\n<pre><code>public void read(DataInputStream dis, byte[] buffer, String errorMessage) \n throws IOException,TLVFileException {\n if (dis.read(buffer, 0, buffer.length) != buffer.length) \n throw new TLVFileException(errorMessage + tbc);\n tbc += buffer.length;\n}\n</code></pre>\n\n<p><code>getDataSegments</code> can be shortened to:</p>\n\n<pre><code>public Iterator<DataSegment> getDataSegments(){\n List<DataSegment> result = new ArrayList<DataSegment>();\n for(LogicalBlock lb : dirisegs) {\n Iterator<DataSegment> segments = lb.getDataSegments();\n while (segments .hasNext()){\n result.add(segments .next());\n }\n }\n return result.iterator();\n} \n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-21T20:25:39.947",
"Id": "3335",
"Score": "0",
"body": "BTW, I remembered that I already answered that question on stack overflow, but I thought that answer were lost by migrating. Now the old answer got merged, too. It contains some points I forgot here, so I leave it..."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-21T06:52:20.567",
"Id": "2017",
"ParentId": "1885",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-06T16:32:26.190",
"Id": "1885",
"Score": "1",
"Tags": [
"java",
"beginner"
],
"Title": "How to make this TLV Reader class look nicer and work smoother?"
} | 1885 |
<pre><code>var studentRepo = new StudentRepository();
int gradeParaleloId = Convert.ToInt32(cmbGradeParalelo.SelectedValue);
var students = studentRepo.FindAllStudentsFromGradeParalelo(gradeParaleloId);
int year = DateTime.Now.Year;
int month = Convert.ToInt32(cmbMes.SelectedIndex) + 1;
AttendanceRepository attendanceRepo = new AttendanceRepository();
for (int i = 0; i < students.Count; i++)
{
for (int j = 1; j < dataGridView1.Columns.Count; j++)
{
DateTime date = new DateTime(year, month, j);
var student = students[i];
var attendance = attendanceRepo.FindAttendance(student.StudentId, date);
if (attendance == null)
{
attendance = new Data.Repositories.Attendance();
attendanceRepo.Add(attendance);
}
attendance.StudentId = student.StudentId;
attendance.DateOfAttendance = date;
attendance.Attended = dataGridView1[j, i].Value.ToString();
}
}
attendanceRepo.SaveChanges();
</code></pre>
<p>My main thorn in the side is that for each day in the month, I have to query the database, and see if a record already exists in the DB for that day and student.</p>
<p>The upside is that I'm putting each attendance in the datacontext and only pushing the save at the very end as a transaction of sorts. </p>
<p>So I'm not inserting on every day for every student. Imagine for a class of 40 students. That's an easy \$40 * 30 = 1200\$ queries on the spot.</p>
<p>Is there some way for me to streamline this? I'm more concerned about this line:</p>
<pre><code>var attendance = attendanceRepo.FindAttendance(student.StudentId, date);
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-15T05:12:54.613",
"Id": "3188",
"Score": "1",
"body": "40*30=1200, not 120"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-15T12:28:08.467",
"Id": "3192",
"Score": "0",
"body": "I thought I typed that...let me edit. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-15T12:39:46.720",
"Id": "3193",
"Score": "0",
"body": "Are you having any performance issues? Try to time how long that many queries would take."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-16T22:19:50.287",
"Id": "3226",
"Score": "0",
"body": "This just highlights one of the issues with the Repository pattern that doesn't allow for the ability to add/update in one go."
}
] | [
{
"body": "<p>First of all, minor beef. I'd reccommend that you change your index names to be more descriptive, particularly the inner one. For instance you could make your repo query</p>\n\n<pre><code>DateTime date = new DateTime(year, month, **day**);\n</code></pre>\n\n<p>Much more readable. When an index has a name, name it.</p>\n\n<p>If you're having performance issues, try separating out the queries. In psuedocode:</p>\n\n<pre><code>foreach day in month\n get students_with_records from database\n\n foreach student in the_class\n if student NOT in students_with_records\n add record\n</code></pre>\n\n<p>This method will put the search through the student records on the client...it should be faster, since you will only have one query per day rather than one query per day <em>per student</em>. You really should profile the app and see if it's an issue, though.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-16T22:14:35.457",
"Id": "3225",
"Score": "0",
"body": "This approach is ok, so long as there isn't a LOT of students. Otherwise you'll be pulling in a lot of data which you aren't going to use at all. If the DB is on a remote server this could be a nightmare."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-16T00:35:00.283",
"Id": "1921",
"ParentId": "1890",
"Score": "4"
}
},
{
"body": "<p>Couple of things:</p>\n\n<ol>\n<li><p>Although I can't tell for sure, it looks as if you're storing attendance if the student is present. Your database will grow very quickly that way. If possible, you might want to consider having a calendar table for the school year that designates school days. That way, you will only need to store if the student is absent or tardy. Present days will be assumed and can be calculated from the calendar table. </p></li>\n<li><p>This is small, but the following code may not work either:\n<code>int year = DateTime.Now.Year</code></p></li>\n</ol>\n\n<p>Take, for example, a teacher that wants to go back and correct attendance in December.<br>\nIt looks as if they will actually be selecting for December 2011, not 2010. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-18T03:49:46.710",
"Id": "3251",
"Score": "0",
"body": "Regarding the second point, that's a deliberate decision. The administrator does not want anyone tampering with legacy data (year old+ data) at all. That information is read-only so to speak."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-18T14:32:59.543",
"Id": "3258",
"Score": "0",
"body": "Would Dec 20, 2010 be considered \"year old+ data\" on Jan 3, 2011?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-18T02:55:07.433",
"Id": "1938",
"ParentId": "1890",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-15T00:37:04.003",
"Id": "1890",
"Score": "5",
"Tags": [
"c#",
"entity-framework"
],
"Title": "Small method for saving student attendance"
} | 1890 |
<p>From <a href="http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-15.html" rel="nofollow">SICP 2.2.4</a>:</p>
<p>The textbook has already defined a function (right-split ...) as follows:</p>
<blockquote>
<pre><code>(define (right-split painter n)
(if (= n 0)
painter
(let ((smaller (right-split painter (- n 1))))
(beside painter (below smaller smaller)))))
</code></pre>
</blockquote>
<p>and they have indicated that there exists a procedure (up-split ...) which has much the same structure.</p>
<blockquote>
<p>Exercise 2.45. Right-split and
up-split can be expressed as instances
of a general splitting operation.
Define a procedure split with the
property that evaluating</p>
<pre><code>(define right-split (split beside below))
(define up-split (split below beside))
</code></pre>
<p>produces procedures right-split and
up-split with the same behaviors as
the ones already defined.</p>
</blockquote>
<p>I wrote the following function, but I'm not sure the best way to test it. What do you think?</p>
<pre><code>(define (split step1 step2)
(define (split-f painter n)
(if (= n 0)
painter
(let ((smaller (split-f painter (- n 1))))
(step2 (step1 smaller smaller)))))
split-f)
(define right-split (split beside below))
(define up-split (split below beside))
</code></pre>
| [] | [
{
"body": "<p>In order to test it, you need to have definitions for things like beside and below. There's something strange in the text book code because the painter \"smaller\" is not actually scaled in the code, or is it indicated that \"below\" and \"beside\" scale their arguments? Anyway, you can just define</p>\n\n<pre><code> (define (below a b) `(below ,a, b))\n (define (beside a b) `(beside ,a ,b))\n</code></pre>\n\n<p>so e.g. (right-split 'apple 1) should produce as result</p>\n\n<pre><code> '(beside apple (below apple apple))\n</code></pre>\n\n<p>You can verify from the structure of the terms that your code works correctly.</p>\n\n<p>Your (split ...) function has a bug, as \"painter\" is missing from the line where you call \"step2\". The code should read</p>\n\n<pre><code> (step2 painter (step1 smaller smaller))\n</code></pre>\n\n<p>Otherwise it looks fine to me.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-15T04:30:45.160",
"Id": "1898",
"ParentId": "1895",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "1898",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-15T02:37:44.667",
"Id": "1895",
"Score": "3",
"Tags": [
"lisp",
"scheme",
"sicp"
],
"Title": "Writing a general purpose \"split\" function (for SICP's imaginary language)"
} | 1895 |
<blockquote>
<p><strong>Exercise 2.46.</strong></p>
<p>A two-dimensional
vector v running from the origin to a
point can be represented as a pair
consisting of an x-coordinate and a
y-coordinate. Implement a data
abstraction for vectors by giving a
constructor make-vect and
corresponding selectors xcor-vect and
ycor-vect. In terms of your selectors
and constructor, implement procedures
add-vect, sub-vect, and scale-vect
that perform the operations vector
addition, vector subtraction, and
multiplying a vector by a scalar:</p>
<p>$$ (r_1, y_1) + (r_2, y_2) = (r_1 + r_2, y_1 + y_2) \\ (r_1, y_1) - (r_2, y_2) = (r_1 - r_2, y_1 - y_2) \\ s \cdot (r, y) = (sr, sy) $$</p>
</blockquote>
<p>I wrote the following:</p>
<pre><code>(define (make-vect xcor ycor) (cons xcor ycor))
(define xcor-vect car)
(define ycor-vect cdr)
(define (add-vect v1 v2) (make-vect (+ (xcor-vect v1) (xcor-vect v2))
(+ (ycor-vect v1) (ycor-vect v2))))
(define (sub-vect v1 v2) (make-vect (- (xcor-vect v1) (xcor-vect v2))
(- (ycor-vect v1) (ycor-vect v2))))
(define (scale-vect v1 s) (make-vect (* (xcor-vect v1) s)
(* (ycor-vect v1) s)))
</code></pre>
<p>Can it be improved?</p>
| [] | [
{
"body": "<p>No.</p>\n\n<p>If this would be production code, you would be better off by</p>\n\n<pre><code> (define (sub-vect v1 v2) (add-vect v1 (scale-vect v2 -1)))\n</code></pre>\n\n<p>However, this is not what the exercise asks for, as everything should be written \"in terms of constructors and selectors\".</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-15T04:25:20.437",
"Id": "1897",
"ParentId": "1896",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "1897",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-15T03:01:40.737",
"Id": "1896",
"Score": "2",
"Tags": [
"lisp",
"scheme",
"sicp"
],
"Title": "Adding, subtracting, and multiplying a vector by a scalar"
} | 1896 |
<p>I have a class which is responsible for checking whether a website is up or down. I've made it to run asynchronously, but I would like critique if this is a good/bad way or if there is another better way to do it.</p>
<pre><code>class UrlChecker {
private readonly IValidationCondition _condition;
private readonly Dictionary<string, UrlStatus> _status = new Dictionary<string, UrlStatus>();
private readonly object _lock = new object();
public UrlChecker(IValidationCondition condition) {
_condition = condition;
}
public void CheckRange(IEnumerable<string> urls, Action<Dictionary<string, UrlStatus>> callback) {
var options = new ParallelOptions {MaxDegreeOfParallelism = 5};
Parallel.ForEach(urls, options, Check);
callback(_status);
}
private void Check(string url) {
Console.WriteLine("Checking " + url);
var req = (HttpWebRequest) WebRequest.Create(url);
req.Timeout = 10 * 10000; // 10 seconds
HttpWebResponse resp;
try {
resp = (HttpWebResponse)req.GetResponse();
}
catch(WebException ex) {
// We got an exception, consider it as down
lock (_lock)
_status.Add(url, UrlStatus.Down);
return;
}
if(resp.StatusCode != HttpStatusCode.OK) {
lock (_lock)
_status.Add(url, UrlStatus.Down);
return;
}
using(var reader = new StreamReader(resp.GetResponseStream())) {
// Check for empty response
var html = reader.ReadToEnd();
if(string.IsNullOrEmpty(html)) {
lock(_lock) {
_status.Add(url, UrlStatus.Down);
}
}
// Validate against condition
if(!_condition.IsValid(html)) {
lock(_lock) {
_status.Add(url, UrlStatus.Down);
}
return;
}
}
// We reached the end without problems, it's a valid url
lock(_lock) {
_status.Add(url, UrlStatus.OK);
}
}
}
</code></pre>
<p>It's called like so:</p>
<pre><code>checker.CheckRange(urls, status => {
if(status.Any(x => x.Value == UrlStatus.Down))
EmailFailing(message);
});
</code></pre>
<p>The second parameter is obviously a callback that's invoked when all checks are done.</p>
<p>Am I locking correctly?</p>
<p>Is this an acceptable way of doing it? Checking with Fiddler proves that it's working correctly, but is there a better way?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-22T11:44:46.563",
"Id": "24241",
"Score": "0",
"body": "@Kiquenet Unfortunately not at the moment. I'll see if I can extract it from my project."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-22T19:56:40.810",
"Id": "24283",
"Score": "0",
"body": "It would be great, thx"
}
] | [
{
"body": "<p>I don't see how this runs asynchronously. <code>callback(_status);</code> will still only be called after all processing is finished, parallel or not. In this case this makes the callback rather redundant, as it does the same as a simple return value.</p>\n\n<p>If you want to make it asynchronous you'll need to store the callback as a member variable, but return immediately in <code>CheckRange</code>. Start the actual processing on a separate thread by e.g. using a <a href=\"http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx\" rel=\"nofollow\"><code>BackgroundWorker</code></a>. Once this execution completes, you can call the stored callback with the result.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-15T13:15:31.467",
"Id": "3195",
"Score": "0",
"body": "Is not all checks run asynchronously (5 at a time)? The callback is invoked when all urls are checked, and that's what i want."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-15T13:19:37.403",
"Id": "3197",
"Score": "0",
"body": "That's called in parallel, hence the name of `Parallel.ForEach`. Asynchronous means: [Calling functions asynchronously causes the system to execute them in the background on a secondary thread while the calling function continues to do other work.](http://support.microsoft.com/kb/315582) If that's not the behavior you want, you can just `return _status;` instead of the callback."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-15T14:25:42.143",
"Id": "3198",
"Score": "0",
"body": "ah, of course. I mean parallel. English is not my primary language and I thought async and parallel had the same meaning. Am I approaching parallelism in a correct way?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-15T14:43:51.903",
"Id": "3200",
"Score": "0",
"body": "@alexn: I don't see any problems no. I would benchmark this however and see whether the speed of execution is indeed sped up. Otherwise there is no point to this approach. And again, just remove the Action and use a return value."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-15T13:11:24.727",
"Id": "1904",
"ParentId": "1903",
"Score": "4"
}
},
{
"body": "<p>The only issue I can see is if your implementation of IValidationCondition is not thread safe. It doesn't sound like something that would have any state, but I figured it should probably be stated explicitly in the code's documentation (either as a requirement of the interface or the UrlChecker's constructor).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-16T08:40:25.603",
"Id": "3215",
"Score": "0",
"body": "That's a good point that i haven't thought of. But you're correct, it does not have any state. Thanks."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-16T00:53:21.823",
"Id": "1922",
"ParentId": "1903",
"Score": "3"
}
},
{
"body": "<p>the amount you are locking is not so cool..... I'd make an \"Add\" method that does your locking for you</p>\n\n<p>general rule of thumb with multithreading..... do all your synchronization in the most minimal tiniest piece of code as possible. ie, try and make it all go through one spot so you have limited points of failure. ( personally I tend to put things through synchronized queues )</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-17T21:33:22.590",
"Id": "1937",
"ParentId": "1903",
"Score": "3"
}
},
{
"body": "<p>Have you considered using a <a href=\"http://msdn.microsoft.com/en-us/library/dd287191.aspx\" rel=\"nofollow\">ConcurrentDictionary</a> rather than implementing the locking yourself? It's bundled with the <a href=\"http://msdn.microsoft.com/en-us/devlabs/ee794896.aspx\" rel=\"nofollow\">Reactive Extensions</a> if you're still on .NET 3.5.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-19T06:10:47.643",
"Id": "3279",
"Score": "0",
"body": "Thanks, that's a good tip. I was not aware of ConcurrentDictionary but it seems to be exactly what i want."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-18T23:38:37.440",
"Id": "1962",
"ParentId": "1903",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "1904",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-15T11:10:27.720",
"Id": "1903",
"Score": "4",
"Tags": [
"c#",
"asynchronous"
],
"Title": "Asynchronous website monitor"
} | 1903 |
<p>I have been reviewing the code of a new co-worker and, although in general I think it's OK, there's a thing that causes me mixed feelings:</p>
<pre><code> private void Method(...)
{
Thread t = new Thread(() =>
{
// Some ~50 lines of code here
});
t.Start();
}
</code></pre>
<p>This is no big deal, but I'm curious about what you guys think of it.
Is this exactly what lambdas are for? Or just the opposite? I try to avoid any lambda which doesn't fit on a couple lines at most...</p>
| [] | [
{
"body": "<p>I think it should be a separate method rather than a lambda expression. If the method is as large as 50 lines then you should seriously think about breaking it up anyway, being an anonymous method only compounds the issue. It may be better to extract portions of the method instead, but that is a decision that you will need to make based on the actual code in the method.</p>\n\n<p>My general rule-of-thumb is that if an anonymous method spans more than half the screens height then it's too big and should be a separate named method.</p>\n\n<hr>\n\n<p><strong>Update</strong> in response to Timwi's comments:</p>\n\n<p>When a method is well named, the name helps to describe what the method is <em>intended</em> to do, both where it is used and where it is defined. Anonymous methods don't get this, and so to understand it you need to rely on the context more. This is fine when if the anonymous method is simple but if its large and/or there is deep nesting involved (within or containing various control structures) the behavior can become much less obvious.</p>\n\n<p>The \"exact\" example used by the OP is not too bad because the containing method is very simple, but I don't see any real benefit (for either performance or readability) and so would still prefer to have it as a separate method.</p>\n\n<p>Of-course, \"readability\" <em>is</em> a bit subjective. Most people will agree on the extreme cases but the edge cases are probably better discussed with, and a consensus drawn from those actually responsible for maintaining it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-16T09:03:13.733",
"Id": "3216",
"Score": "1",
"body": "@Brian Reichle: Hmmm... thanks for your input. I don't want to discuss the optimal size of a function (be it 20, 50, 100 or 200 LOC). That's worth a question of its own. I was asking about the more general issue: is it good practice to use lambdas more than a few (maybe 4 or 5 at most) lines long? And your answer seems to be: \"Yes, it is\" :-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-18T01:35:37.603",
"Id": "3248",
"Score": "0",
"body": "@Brian: How big is your screen? :P"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-18T03:02:16.567",
"Id": "3249",
"Score": "0",
"body": "@Mehrdad: Arbitrarily small :). It's a \"rule of thumb\", it's not meant to be specific. the basic idea is that you want a \"good\" amount of context around the lambda expression visible at the same time as the expression itself."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-19T20:17:58.370",
"Id": "3305",
"Score": "0",
"body": "“I think it should be a separate method rather than a lambda expression.” — Uhm, why? Do you have a reason for this viewpoint or are you just saying it because a lot of people say it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-20T08:51:42.160",
"Id": "3315",
"Score": "0",
"body": "@Timwi: I updated my response with more detail on the \"why\"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-20T08:58:44.027",
"Id": "3317",
"Score": "0",
"body": "@Brian It’s nice to see that the rationale you added in response to @Timwi reads more or less like the rationale *I* added in response to @Timwi."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-20T09:01:32.633",
"Id": "3318",
"Score": "0",
"body": "@Timwi: These are my opinions that I have gained through my own personal experiences, both working with others and in my own personal projects/experiments. Although I am happy to follow an agreed style drawn from a consensus with my colleagues, I still form my own opinions based on what I feel to be the pro's and con's."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-20T09:07:12.490",
"Id": "3319",
"Score": "0",
"body": "@Konrad Rudolph: I would just like to be clear that I did not see your response until after I updated my post :)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-20T10:50:16.720",
"Id": "3320",
"Score": "0",
"body": "@Brian: _\"but I don't see any real benefit\"_: As [stated in my answer](http://codereview.stackexchange.com/questions/1911/long-function-as-a-lambda-right-or-wrong/1933#1933), just making a method private doesn't mean it's entirely encapsulated. The logic becomes available to the entire class. Following the same reasoning everywhere, does result in reduced readability IMHO. _What function does what where why now?_"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-02T13:14:56.683",
"Id": "15224",
"Score": "2",
"body": "Testability is yet another reason... @Chris Phillips' answer below deserves upvotes too :)"
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-15T23:14:31.950",
"Id": "1920",
"ParentId": "1911",
"Score": "13"
}
},
{
"body": "<p>I think that a method this long really deserve a name. Even if it is only used once, a name would be a good way to describe what is this lambda doing and it would be way more significant than a comment or something like this.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-17T11:09:45.643",
"Id": "3234",
"Score": "1",
"body": "Thanks for answering! The existing method (called 'Method' in my code) only creates a thread to do what the lambda does. So it could have the name you would assign to the lambda, making your point moot :-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-22T22:14:46.137",
"Id": "3344",
"Score": "0",
"body": "-1 Sorry, but you make a poor argument. How is a method name _more significant_ than a comment? I know the self-documenting code opinion, but \"being more significant\" is definitly not an advantage, it's rather the other way around."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-23T02:54:26.283",
"Id": "3346",
"Score": "0",
"body": "@StevenJeuris I am sorry but comments are often unupdated and unread. Function names are, on the contrary, always read, and must fit with what they do. Martin Fowler have wrote a wonderful book about those kind of things, you should read it. http://www.amazon.com/Refactoring-Improving-Design-Existing-Code/dp/0201485672/ref=pd_sim_b_1"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-23T06:34:17.587",
"Id": "3349",
"Score": "0",
"body": "That's what I meant when I said I know the self-documenting code opinion, and [here is my opinion about the comments argument](http://programmers.stackexchange.com/questions/69538/are-outdated-comments-an-urban-myth/69544#69544). Still have to read that book though. Perhaps it's just my poor perception of your word of choosing, but when I read \"more significant\" in that phrase I interpret it as \"it tells more what it is doing\". Which is not the case ... hence the downvote."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-16T21:52:40.483",
"Id": "1931",
"ParentId": "1911",
"Score": "1"
}
},
{
"body": "<p>In my opinion no preferable answer can be given without seeing the exact code. I <a href=\"http://whathecode.wordpress.com/2010/12/07/function-hell/\" rel=\"nofollow\">don't like splitting code into smaller methods just for the sake of making methods smaller</a>, as opposed to Brian Reichle's answer (and many other people that follow this approach).</p>\n\n<p>If the code of the thread <em>is and can</em> only be used locally, I would leave it in there regardless of the LOC. Using a lambda has the advantage that you don't 'pollute' your class with an extra private method which is only called from one location. This provides for <strong>better <em>encapsulation</em></strong>, which is a core principle of OO which makes it shine.</p>\n\n<p>If the code of the thread <em>were to be reuseable</em>, I would rather think about splitting the behavior in a separate class than in a separate method, unless the code only makes sense in the original class.</p>\n\n<p>Also as a sidenote; I realize you probably just named your code as to get the idea across, but I'd make sure the name of <code>Method</code> would indicate it only starts a certain action, but doesn't finish it. E.g. <code>StartSomeMethod</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-17T19:32:41.027",
"Id": "3238",
"Score": "0",
"body": "@Steven Jeuris: Thanks, your answer really makes sense."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-18T15:58:34.803",
"Id": "3265",
"Score": "0",
"body": "@Steven I was about to disagree but then I read your blog, and more importantly the original code by Uncle Bob. Now I can’t help but disagree, at least with the general point."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-18T16:19:46.033",
"Id": "3266",
"Score": "0",
"body": "@Konrad: You lost me by mentioning disagree twice. What is your opinion on what now? :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-18T19:28:48.327",
"Id": "3268",
"Score": "1",
"body": "@Steve Sorry, the second “disagree” should have been “agree”."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-19T20:13:34.863",
"Id": "3303",
"Score": "2",
"body": "I completely agree with this answer. I don’t understand why it is not upvoted more. The other (more upvoted answer) is very blanket and doesn’t back itself up. This answer is much more thoughtful."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-02T13:13:56.997",
"Id": "15223",
"Score": "1",
"body": "How would you test this 50-line method? That, alone, is a reason to extract the functionality to another method/class. I really doubt this code would ever have been written test-first, and it is most likely difficult to test after-the-fact as well."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-02T13:17:42.600",
"Id": "15225",
"Score": "0",
"body": "@Jedidja: By testing the (reusable) calls which occur there separately. Anything else is specific to the context of the code running in the thread. So testing whether it works outside of a thread is a bit pointless."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-02T13:21:32.103",
"Id": "15226",
"Score": "1",
"body": "@StevenJeuris I think it would be interesting to see the both the code in the 50-line method, and the rest of the class that Method belongs too. I do have to agree we're all kind of making blanket statements without seeing the code. In general, though, when I've come across this type of code, it's often been refactorable."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-17T14:37:42.207",
"Id": "1933",
"ParentId": "1911",
"Score": "10"
}
},
{
"body": "<p>It depends :-)</p>\n\n<p>ignoring the splitting things into smaller methods debate... the code is already in a method. The part to do with threading is a tiny amount of the method. The lambda is just a construct to make the code multithreaded. If that was the intention of the method. Then thats ok. </p>\n\n<p>It comes down to purity vs utility. Its easy to see this from the perspective of 'lambdas' and have a rule that lambdas should be short and to the point. But in this case its more using the utility of lambdas to wrap threading around a chunk of code. </p>\n\n<p>(for the sake of this question, I'm ignoring if this is a good approach to threading... another example could be that this is a transaction context.... or some other wrapping context ).</p>\n\n<p>So there is utility in using lambdas to wrap contexts around chunks of code without having to break them into a separate method. But as long as its not an excuse for badly factored code and it seems to make sense given the context of what you are doing.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-17T21:27:18.277",
"Id": "1936",
"ParentId": "1911",
"Score": "3"
}
},
{
"body": "<p>My rule of thumb for lambdas is: the should be no more than <strong>a single expression</strong>. The expression itself may be arbitrarily complex (within reasons) but as soon as I need more than one expression (or one statement, for a statement lambda) I use a separate method instead.</p>\n\n<p>This isn’t an arbitrary rule either: in C# (and several other languages) there’s special syntax support for single-expression lambdas. As soon as you need more than one expression the conciseness of lambdas is lost, and you end up with a nameless function body.</p>\n\n<p>I prefer proper functions then since the name of a function itself is very useful to identify the function’s task: this is very much in the interest of self-documenting code.</p>\n\n<p>There’s one exception to the rule: when I need to access a comparatively large number of local variables (say, more than two) and would need to create private variables for those then the lambda may occasionally become longer than a single statement.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-19T20:16:08.217",
"Id": "3304",
"Score": "2",
"body": "I don’t get why programmers seem to be such fans of such blanket rules. “Lambdas should be no more than a single expression” — uhm, why? What sense does it make to say this outright without taking into account any specific circumstances, which are guaranteed to be widely different from case to case?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-20T08:08:23.540",
"Id": "3311",
"Score": "0",
"body": "@Timwi I grant that it’s a rough rule of thumb. But one that is greatly supported by C#’s syntax: for single-expression lambdas you don’t need parentheses. Once you need parentheses you lose all of the conciseness of lambdas. And consequently, also one of the advantages of lambdas over proper functions. Proper functions of course also have advantages over lambdas: for one, they have a proper name that gives some clue as to their function. So setting the break-even point of trade-offs at one expression seems very reasonable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-20T08:08:55.097",
"Id": "3313",
"Score": "0",
"body": "@Timwi And, FWIW if you read some of my other answers you’ll se that I’m no fan of blanket rules. So you applied a blanket rule to accuse me of applying blanket rules. How ironic."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-20T08:55:48.257",
"Id": "3316",
"Score": "0",
"body": "@Timwi: a \"blanket rule\" is not the same as a \"rule of thumb\". Where the blanket rule implies that it should always be followed, the rule of thumb is more of a rough guide or starting point that is still subject to common sense and the more specific details of each situation."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-21T15:35:58.757",
"Id": "3331",
"Score": "0",
"body": "① “Once you need parentheses you lose all of the conciseness of lambdas” — excuse me? Even with curlies (I assume that’s what you meant) it is still more concise than a method declaration. — ② “for one, they have a proper name that gives some clue as to their function” — and so does a lambda assigned to a local variable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-22T10:42:24.477",
"Id": "3339",
"Score": "0",
"body": "@Timwi ① so not “all of” the conciseness, but the crucial bit (IMHO). ② true. But there is still ③: namely, it makes the surrounding method longer which is always bad if you strive to keep your methods concise and easier to understand. As soon as you need to scroll to read one method, you’ve lost. The human brain (well; *my* brain) can’t cope any more. As long as you don’t need to scroll I’ll concede that the use of multi-expression lambdas is probably advantageous."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-22T14:40:41.357",
"Id": "3341",
"Score": "1",
"body": "@Konrad: Interesting — so your brain has trouble with long methods but not with even longer classes with a plethora of single-use methods? Personally, *my* brain prefers a long method consisting of well-commented chunks (which you can just read from top to bottom) over the same code split into several disordered methods (where you have to keep jumping around). Of course, if the method has a lot of logic (ifs, loops, etc.) that’s a different matter — but the OP’s method only instantiates and starts a thread..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-22T17:22:39.120",
"Id": "3342",
"Score": "1",
"body": "Thank you for your answer, Konrad. Even if I don't fully agree with your view, I don't think you deserver those downvotes. Perhaps I don't fully understand this site."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-22T22:09:32.337",
"Id": "3343",
"Score": "0",
"body": "@Jaime Pardos: The answer to this question is quite subjective. When this happens, up and downvotes are more _agree/disagree_ than _correct/incorrect_. I didn't downvote this one since it's a well formulated opinion which favors self-documenting code and conciseness (small functions) over encapsulation. There are arguments to prefer small functions, like [comment rot](http://programmers.stackexchange.com/q/69538/15464) and test driven development. I see more value in my answer, but know a lot of people see value in this opinion, otherwise I would have downvoted."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-23T13:18:21.193",
"Id": "3352",
"Score": "1",
"body": "@Timwi “so your brain has trouble with long methods but not with even longer classes with a plethora of single-use methods?” Yes, absolutely. This is one of the very few established facts of the psychology of programming: methods that span more than a screen become incomprehensible (Code Complete, I believe). Note that I also agree with Steven’s answer. There’s always a trade-off involved."
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-18T15:50:07.620",
"Id": "1955",
"ParentId": "1911",
"Score": "0"
}
},
{
"body": "<p>With a proper comment you create a \"local function\", so you don't create new global names unnecesarily. IMO it is a good thing somewhat similar to using local variables vs global ones.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-22T19:40:33.790",
"Id": "2036",
"ParentId": "1911",
"Score": "1"
}
},
{
"body": "<p>Keeping it local is good. However for clarity you may want to assign the lambda expression to a Func or Action variable, and then do your threading code. This would help in making the threading code easier to understand on sight without mixing in the details of the actual code that is being threaded. In other languages it is not uncommon to declare the method to be threaded inside of the method that is calling it (javascript, ada, f#, etc.).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-23T18:36:15.533",
"Id": "2048",
"ParentId": "1911",
"Score": "1"
}
},
{
"body": "<p>Setting aside the debate of short vs. long lambdas for a moment, something I don't see mentioned in any of the other answers yet is testability.</p>\n\n<p>If you put the thread body in a separate method, then you can test it's logic separately from the threading logic. This avoids all the difficulties and pitfalls of trying to unit test threaded code (starting, stopping, waiting, etc). </p>\n\n<p>I find that this applies to most cases where lambdas are used. If it makes sense to test the code separately (and if its more than line or two, it probably does), then it is much easier to test properly using a separate method than a lambda inline.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-04T08:24:25.023",
"Id": "5798",
"Score": "0",
"body": "That's the best argument I've seen for not using long lambdas. Well done."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-02T13:12:44.440",
"Id": "15222",
"Score": "1",
"body": "Why hasn't this been upvoted more? :) If someone was writing this TDD style, I doubt a 50-line lambda inside a Thread would have ever happened. And, furthermore, even if you're writing tests *after* the fact, splitting out responsibility into another method (or class) is going to help testing immensely."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-05-17T00:58:09.727",
"Id": "18977",
"Score": "0",
"body": "See my reply [on Jedidja's comment](http://codereview.stackexchange.com/questions/1911/long-function-as-a-lambda-right-or-wrong#comment15225_1933). Nothing prevents your from TDD'ing the sh*t out of the methods used inside the 50-line lambda. _\"Anything else is specific to the context of the code running in the thread. So testing whether it works outside of a thread is a bit pointless.\"_"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-10T09:19:06.207",
"Id": "65198",
"Score": "0",
"body": "@StevenJeuris - it's not \"testing whether it works outside of a thread\", it's testing whether it works, period. If you have a 50-line method that means complexity, which means you need to test it, prove it correct, or live with the possibility of bugs."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-02T19:34:22.640",
"Id": "3812",
"ParentId": "1911",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "1933",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-15T16:04:18.557",
"Id": "1911",
"Score": "16",
"Tags": [
"c#",
"lambda"
],
"Title": "Long function as a lambda, right or wrong?"
} | 1911 |
<p>The script is fully working, but I ask is there a better way I can do this rather than name all of the query variables, <code>$q</code>, <code>$q1</code> etc, and then use <code>if</code> <code>else</code> statements to execute the code.</p>
<pre><code><?php
// open the mysql connection
require_once('mysqli.php');
// successful login variables
$q = $dbc -> prepare("SELECT * FROM accounts WHERE email = ? && password = ? && logcount != ''");
$q -> bind_param('ss', ($_POST['email']), ($_POST['password']));
$q -> execute();
$q -> store_result();
// wrong password variables
$q1 = $dbc -> prepare("SELECT * FROM accounts WHERE email = ? && password != ? && logcount != ''");
$q1 -> bind_param('ss', ($_POST['email']), ($_POST['password']));
$q1 -> execute();
$q1 -> store_result();
// not active variables
$q2 = $dbc -> prepare("SELECT * FROM accounts WHERE email = ? && logcount = ''");
$q2 -> bind_param('s', ($_POST['email']));
$q2 -> execute();
$q2 -> store_result();
// successful login query
if ($q -> num_rows == 1) {
$q = $dbc -> prepare("UPDATE accounts SET logcount = logcount+1 WHERE email = ?");
$q -> bind_param('s', ($_POST['email']));
$q -> execute();
$dbc -> close();
header('location: shack');
exit();
}
// wrong password query
elseif ($q1 -> num_rows == 1) {
echo '<p>Your password is incorrect.</p>';
}
// not activated query
elseif ($q2 -> num_rows == 1) {
echo '<p>Your account is not activated.</p>';
}
// blank email form entry
elseif (empty($_POST['email'])) {
echo '<p>You did not fill in an email on the login form.</p>';
}
// account not found
else {
echo '<p>An account could not be found.</p>';
}
// close the mysql connection
$dbc -> close();
?>
</code></pre>
| [] | [
{
"body": "<p>Appears you are storing cleartext passwords and doing a 1:1 comparison. <strong>This is bad</strong>. </p>\n\n<p>You can clean the code up by doing the following and executing <strong>1</strong> query to MySQL:</p>\n\n<pre><code>require_once('mysqli.php'); \n// successful login variables \n$q = $dbc -> prepare(\"SELECT email,dbClearTextPassword,accountActive FROM accounts WHERE email = ?\"); \n$q -> bind_param('s', ($_POST['email'])); \n$q -> execute(); \n$q -> store_result();\n\n// check to see if you returned any information from your query\nif ($q->num_rows == 0) { \n // email doesn't exist in db .. #fail\n exit;\n}\n\nif ($q['accountActive'] != '1') { \n // email account is not active .. #fail\n exit;\n}\n\n// check the password matches \nif ($_POST['clearTextPassword'] == $q['dbClearTextPassword']) { \n // do some of your fancy code to process the successful login\n} else { \n // do some other fancy code to process a login failure\n}\n\n$dbc->close();\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-15T12:12:00.927",
"Id": "3208",
"Score": "0",
"body": "Ye I haven't got round to hashing the passwords yet, just still trying to get the cleanest code possible, I haven't seen this method yet, I will try implementing it and see what happens :) Thanks"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-15T12:16:00.653",
"Id": "3209",
"Score": "0",
"body": "will you donate 10% of your contract earnings to a non-profit organization that supports depressed coders if this answers your question?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-15T12:17:53.130",
"Id": "3210",
"Score": "0",
"body": "Haha this is a non profit website, and it seems that I cannot just use simply $q['value'] as it returns an object error!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-15T12:37:06.333",
"Id": "3211",
"Score": "3",
"body": "you need to spend more time reading about how to work with mysqli results. my code was a quick example to show you the concepts of how to clean up your code ... answering your question. it was not meant to be a production example."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-15T13:12:50.720",
"Id": "3212",
"Score": "2",
"body": "@Basic 1982301 Programmers nodded in disappointment after reading that comment"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-16T13:52:29.137",
"Id": "3218",
"Score": "0",
"body": "@Basic: Try using $q->value, but as others mentioned read the documentation on mysqli and it will explain this."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-15T12:06:23.993",
"Id": "1916",
"ParentId": "1915",
"Score": "5"
}
},
{
"body": "<p>About efficiency: I suggest do not select data which do not needed.</p>\n\n<p>For example, intead of</p>\n\n<pre><code>SELECT * FROM accounts WHERE email = ? && password = ? && logcount != ''\n</code></pre>\n\n<p>use</p>\n\n<pre><code>SELECT COUNT(*) FROM accounts WHERE email = ? && password = ? && logcount != ''\n</code></pre>\n\n<p>Also I fully agree with @sdolgy about not storing password as plain text.</p>\n\n<p>Another point, not about efficiency, but about OOP design and readability: split code to few classes:</p>\n\n<ul>\n<li>All SQL queries go to DAO layer</li>\n<li>All checks move to service layer (which calls DAO-methods and throw exception when error occurs)</li>\n<li>All other actions leave as is</li>\n</ul>\n\n<p>See also: <a href=\"http://en.wikipedia.org/wiki/Data_access_object\" rel=\"nofollow\">DAO pattern</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-04T09:03:10.913",
"Id": "2230",
"ParentId": "1915",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-15T11:47:00.597",
"Id": "1915",
"Score": "5",
"Tags": [
"php",
"mysql"
],
"Title": "Simple activation script"
} | 1915 |
<p>I've been using the following the code to store temporal error messages in <code>TempData</code>, to be displayed from my master page on production sites without any problems, but is this a good way of doing it?</p>
<h2>The controller helper code:</h2>
<pre><code>namespace System.Web.Mvc
{
public static class Controllers
{
public static void SetMessage(this ControllerBase controller, string message)
{
List<string> messages = controller.TempData["Messages"] as List<string> ?? new List<string>();
messages.Add(message);
controller.TempData["Messages"] = messages;
}
public static void SetErrorMessage(this ControllerBase controller, string errorMessage)
{
List<string> messages = controller.TempData["ErrorMessages"] as List<string> ?? new List<string>();
messages.Add(errorMessage);
controller.TempData["ErrorMessages"] = messages;
}
}
}
</code></pre>
<h2>Example Use:</h2>
<pre><code>public ActionResult Edit()
{
// .. do stuff
this.SetMessage("You edited X.");
return View();
}
</code></pre>
<h2>Here is the rendering code:</h2>
<pre><code><%
if (TempData["ErrorMessages"] != null)
{
%>
Error Messages
<%
foreach (string s in TempData["ErrorMessages"] as List<string>)
{
%><%=s%><%
}
}
if (TempData["Messages"] != null)
{
%>
Messages
<%
foreach (string s in TempData["Messages"] as List<string>)
{
%><%=s%><%
}
}
%>
</code></pre>
<p>Can you spot any issues?</p>
| [] | [
{
"body": "<p>On the whole the approach is fine, but do <em>not</em> use <code>TempData</code> unless you're looking to populate this information across redirects. <code>TempData</code> comes with a host of issues, and its behaviour isn't quite what you think.</p>\n\n<p><code>ViewData</code>, on the other hand, is designed exactly for this purpose but comes with the caveat that it <em>doesn't</em> persist across redirects.</p>\n\n<p>Therefore, if you're looking to put something in place which allows developers to push messages into your views easily, you need to expose the ability to put data in either <code>ViewData</code> or <code>TempData</code>, depending on whether they want to redirect or not.</p>\n\n<p>Another option is to clear the <code>TempData</code> entry manually after the call has finished, but I wouldn't recommend this approach.</p>\n\n<p>As a final point, your function names <code>SetMessage</code> and <code>SetErrorMessage</code> are misleading in that they imply you've got one spot only for the message. To me, as a user of your function, when doing this:</p>\n\n<pre><code>this.SetMessage(\"Foo\");\nthis.SetMessage(\"Bar\");\n</code></pre>\n\n<p>I would assume that my message is now set to \"Bar\", but behind the scenes it's a list with both \"Foo\" and \"Bar\". I'd recommend changing your function names to <code>AddMessage</code> and <code>AddErrorMessage</code> instead, which implies that behind the scenes there is a collection of elements.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-17T08:19:43.360",
"Id": "3228",
"Score": "0",
"body": "I agree the function names are misleading. `AddMessage` would be better. I used ViewData initially, but if you add a message in an action, and then redirect the user - the messages are lost. Without resorting to `Session`, TempData is meant exactly for passing that type of data around."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-17T09:33:42.173",
"Id": "3230",
"Score": "0",
"body": "That's exactly what I said in my response :) But bear in mind that you can leave data hanging around in TempData if you _don't_ redirect. It has side effects. Leave it in the hands of the caller to decide, provide them with both options."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-17T10:14:51.623",
"Id": "3231",
"Score": "0",
"body": "is TempData not automatically cleared between request cycles?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-17T21:24:52.480",
"Id": "3243",
"Score": "0",
"body": "Yes it is, but you have to _have_ a request cycle. If you add to TempData and you *don't* direct it will still be there when the user does their next action. This can result in undesirable behaviour."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-16T22:09:46.900",
"Id": "1932",
"ParentId": "1926",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-16T15:50:01.877",
"Id": "1926",
"Score": "5",
"Tags": [
"c#",
"asp.net-mvc-2"
],
"Title": "Storing Temporal Message Lists in ASP.NET MVC TempData"
} | 1926 |
<p>I am making a simple transposition cipher. I am testing the program with the word "computer" with the secret key "5,2,8,3,7,1,4,6", where the encrypt method will put the 5th letter 'u' in the first position, 2nd letter 'o' in 2nd position, 8th letter 'r' in 3rd position...</p>
<p>So the output would be:<br>
original: computer<br>
encrypted:uormecpt<br>
decrypted:computer </p>
<p>Right now my decrypt method is of O(n^2). How can I make this faster?</p>
<p>Where char[] y would be uormecpt. The z[j] - 1 is the offset as my iterator starts from 0, but my key starts at 1.</p>
<pre><code>public static char[] decrypt(char[] y, int[] z)
{
char[] decrypted = new char[y.length];
for (int i = 0; i < y.length; i++)
{
for (int j = 0; j < y.length; j++)
{
if (i == z[j]-1)
decrypted[i] = y[j];
}
}
return decrypted;
}
</code></pre>
| [] | [
{
"body": "<p>If you can assume that every index in the encrypted message is included in the key, You can loop over the key and encrypted message together, placing each letter into the correct decrypted message slot directly:</p>\n\n<pre><code>public static char[] decrypt(char[] encrypted, int[] key)\n{\n char[] decrypted = new char[encrypted.length];\n\n for (int i = 0; i < encrypted.length; i++)\n {\n decrypted[key[i]] = encrypted[i];\n }\n\n return decrypted;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-16T18:57:13.470",
"Id": "1928",
"ParentId": "1927",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": "1928",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-16T18:16:07.340",
"Id": "1927",
"Score": "5",
"Tags": [
"java",
"algorithm"
],
"Title": "How can I make my decrypt method more efficient?"
} | 1927 |
<p>I have this version comparison function in java. </p>
<p>Any cleaner way to write this without all the nested 'if' statements? </p>
<p>Note that the suggestions must be in Java code only.</p>
<pre><code>@Override
public int compareTo(Version o)
{
int result = this.major.compareTo(o.major);
if (result == 0)
{
result = this.minor.compareTo(o.minor);
if (result == 0)
{
result = this.minor2.compareTo(o.minor2);
if (result == 0)
{
result = this.suffix.compareTo(o.suffix);
}
}
}
return result;
}
</code></pre>
<p>Edit: </p>
<p>Just to be clear on the 'type' of the fields of the Version class:</p>
<pre><code>Integer major, minor, minor2;
String suffix;
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-18T11:46:14.610",
"Id": "3255",
"Score": "2",
"body": "The nesting pretty much reflects the cascading structure of the data - why do you want to get rid of it? PHP-Coder shows an legitimate solution but I wouldn't necessarily prefer it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-28T18:04:41.367",
"Id": "62833",
"Score": "0",
"body": "If your only concern is readability you may convert the version to a string and then just compare."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-29T03:43:52.433",
"Id": "62834",
"Score": "0",
"body": "with a pure string comparison, 10.0.0 will be less than 9.0.0."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-03-18T11:27:13.587",
"Id": "151784",
"Score": "0",
"body": "I just found a Java Library ([Java SemVer](https://github.com/zafarkhaja/jsemver)) that supports the Semantic Versioning Specification. Download the library/source and use it. The usage is pretty simple. `Version v1 = Version.valueOf(\"1.2.3\"); Version v2 = Version.valueOf(\"1.2.0\"); System.out.println(v1.compareTo(v2));`"
}
] | [
{
"body": "<p>In the apache.common package (very usefull by the way) </p>\n\n<p>There is a <code>CompareToBuilder</code>. Works like a charm (like the <code>ToStringBuilder</code>)</p>\n\n<p><a href=\"http://commons.apache.org/lang/api-2.6/org/apache/commons/lang/builder/CompareToBuilder.html\">http://commons.apache.org/lang/api-2.6/org/apache/commons/lang/builder/CompareToBuilder.html</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-17T20:41:25.803",
"Id": "3240",
"Score": "0",
"body": "cant add dependency to a 3rd party library for a small function. Any improvement will have to be a refactoring of the code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-17T20:45:41.713",
"Id": "3241",
"Score": "0",
"body": "Trust me, including this package will help your code on many different level, take a look at all the functions it offer.\nIf you really can't include it in your code, then it is a good proof of concept that it can be done with reflexion. _Answer to the question:_ So you could avoid all those if with reflexion."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-17T20:47:37.560",
"Id": "3242",
"Score": "0",
"body": "The down side is that reflexion is quite slow, compared with \"normal\" code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-17T22:05:27.330",
"Id": "3244",
"Score": "0",
"body": "A CompareToBuilder?! Are you _serious_? Adding bloat to a comparison... WTF has the Java world come to?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-17T22:06:00.117",
"Id": "3245",
"Score": "0",
"body": "@OJ I don't understand, what do you mean?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-17T22:36:13.833",
"Id": "3246",
"Score": "0",
"body": "I'm saying that a class that exists just to construct simple comparisons is yet another example of over-engineering bloatware that has become typical of the Java world."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-18T20:23:19.207",
"Id": "3269",
"Score": "3",
"body": "@OJ, bloat is all the code out there implementing this exact pattern without using a common code to do so."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-18T22:44:46.210",
"Id": "3273",
"Score": "2",
"body": "@Winston: Sorry, but I think that's utter rubbish. I don't need to construct a class, fill it with stuff and call a method just to compare a few elements together. Bloat is not \"lack of code reuse\", bloat is writing wrappers for extremely small things like this. Seriously, comparing internal values does _not_ require \"infrastructure\" or \"builder\" classes like this. If you feel compelled to use them, fine, so long as I don't have to maintain it. I don't agree with rubbish like this being taught to others though."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-19T01:24:02.783",
"Id": "3275",
"Score": "0",
"body": "@OJ, the question is how complex a pattern has to be before it makes sense to move it into a common place. Either duplicating the pattern or wrapping overly simply patterns both produce bloat. I think it is worthwhile when after extracting the pattern the code making use of the pattern is clearer and simpler. Looking at the Java CompareToBuilder class it probably fails that test. No, it certainly fails that test."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-19T01:25:07.993",
"Id": "3276",
"Score": "0",
"body": "Other languages pass the test. For example, in python I could put the elements to be compared in a tuple and compare those. This has the same results, and is simpler and easier to understand then the explicit logic version."
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-17T20:39:08.130",
"Id": "1935",
"ParentId": "1934",
"Score": "5"
}
},
{
"body": "<p>One point which I may suggest is reorder <code>if</code> statements to reduce indentation:</p>\n\n<pre><code>@Override\npublic int compareTo(Version o)\n{\n int result = this.major.compareTo(o.major);\n if (result != 0)\n {\n return result;\n }\n\n result = this.minor.compareTo(o.minor);\n if (result != 0)\n {\n return result;\n }\n\n result = this.minor2.compareTo(o.minor2);\n if (result != 0)\n {\n return result;\n }\n\n return this.suffix.compareTo(o.suffix);\n}\n</code></pre>\n\n<p>Also, I think you can omit <code>this</code> keyword.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-18T11:23:44.107",
"Id": "3254",
"Score": "2",
"body": "I agree about the suffix, and because of the premature return, no `else` is needed. But the cascading nature of the problem is imho clearer to see from nested structure."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-18T04:03:14.417",
"Id": "1939",
"ParentId": "1934",
"Score": "13"
}
},
{
"body": "<p>If you expect often, that two versions will be the same reference, you could start your method with a check for that. And you may strip the noisy 'this'. However, the cascading nature of the check is pretty fine expressed in the nesting - I would keep it.</p>\n\n<pre><code>@Override\npublic int compareTo (Version o)\n{\n if (this == o)\n return 0;\n int result = major.compareTo (o.major);\n if (result == 0)\n {\n result = minor.compareTo (o.minor);\n if (result == 0)\n {\n result = minor2.compareTo (o.minor2);\n if (result == 0)\n {\n result = suffix.compareTo (o.suffix);\n }\n }\n }\n return result;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-18T11:54:54.857",
"Id": "1945",
"ParentId": "1934",
"Score": "7"
}
},
{
"body": "<p>I like @php-coder's approach best, but I'd get rid of the unnecessary braces for even greater readability:</p>\n\n<pre><code>@Override public int compareTo(Version o) {\n if (this == o) return 0;\n\n int result = major.compareTo(o.major);\n if (result != 0) return result;\n\n result = minor.compareTo(o.minor);\n if (result != 0) return result;\n\n result = minor2.compareTo(o.minor2);\n if (result != 0) return result;\n\n return suffix.compareTo(o.suffix); \n}\n</code></pre>\n\n<p>Your compareTo method assumes that none of the fields can be null; watch out for that if you don't know for a fact it's always true.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-23T01:11:26.307",
"Id": "3345",
"Score": "0",
"body": "IMO it is a correct for the code to assume that `o` is non-null. It is best practice to assume that it is a programming error if `o` or a component field is `null` ... unless the javadocs clearly say otherwise."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-18T13:48:50.840",
"Id": "1946",
"ParentId": "1934",
"Score": "4"
}
},
{
"body": "<p>This <em>might</em> be a little bit over-the-top, but how about a more object oriented approach? Assume this little helper enum:</p>\n\n<pre><code>public enum Compare {\n LT, EQ, GT;\n\n public int toInt() {\n switch(this) {\n case LT: return -1;\n case EQ: return 0;\n case GT: return 1;\n default: throw new AssertionError(); \n } \n }\n\n public Compare cp(int v1, int v2) {\n if(this == EQ) return v1 < v2 ? LT : v1 > v2 ? GT : EQ;\n else return this;\n }\n\n //... here the cp methods for other primitives \n\n public <T extends Comparable<T>> Compare cp(T v1, T v2) {\n if(this == EQ) {\n int result = v1.compareTo(v2);\n return result < 0 ? LT : result > 0 ? GT : EQ;\n } else {\n return this;\n } \n }\n}\n</code></pre>\n\n<p>Then we can write:</p>\n\n<pre><code>import static somepackage.Compare.*;\n\n@Override\npublic int compareTo(Version that) {\n return EQ.cp(this.major, that.major)\n .cp(this.minor, that.minor)\n .cp(this.minor2, that.minor2)\n .toInt();\n}\n</code></pre>\n\n<p>Note that unnecessary comparisions will be skipped in the cp methods.</p>\n\n<p><strong>[Update]</strong></p>\n\n<p>Apache Commons does something similar: <a href=\"http://commons.apache.org/lang/api-2.5/org/apache/commons/lang/builder/CompareToBuilder.html\" rel=\"nofollow\">http://commons.apache.org/lang/api-2.5/org/apache/commons/lang/builder/CompareToBuilder.html</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-23T04:16:30.097",
"Id": "3348",
"Score": "0",
"body": "you are right. it *is* a bit over the top ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-23T13:14:42.617",
"Id": "3351",
"Score": "0",
"body": "I think it depends on the context. I wouldn't use this in performance critical code. However if I had a lot of big business objects, it could be more important to get comparision *right* than fast, and then this approach could be helpful."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-22T22:16:12.480",
"Id": "2038",
"ParentId": "1934",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "1945",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-17T20:31:43.300",
"Id": "1934",
"Score": "11",
"Tags": [
"java"
],
"Title": "Version comparison function"
} | 1934 |
<p>I am trying to learn how to write good, clean, and efficient JavaScript. I consider myself a novice, at best, in JavaScript. Any comments are appreciated.</p>
<p>In an effort to become a better JavaScript programmer, I am trying to write a simple JavaScript animation using HTML5's new canvas element. Functionally speaking, when the canvas is clicked, a new circle (or Ball) is added to the canvas and begins moving to the lower right corner of the canvas. When the ball hits a wall or collides with another ball, the speed at which the x and y coordinates are moving is inverted.</p>
<p>Is it a good idea to be modifying the <code>this</code> object? For instance does the following pattern make sense?</p>
<pre><code>function Point(I) {
this.x = I.x;
this.y = I.y;
this.z = I.z;
return this;
}
</code></pre>
<p>Is there any reason why I shouldn't be sending a object and pulling variables off of the input object? I like the syntax for creation, but are there any problems with this pattern?</p>
<pre><code>new Point({
x: 10,
y: 30
});
new Point({
x: 50,
y: 25
z: 3
});
</code></pre>
<p><strong>Full Code</strong></p>
<pre><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Ball Collision</title>
<script src="js/modernizr-1.7.js"></script>
<script>
window.onload = function () {
//"use strict";
// Source: http://www.html5rocks.com/tutorials/canvas/notearsgame/
Number.prototype.clamp = function(min, max) {
return Math.min(Math.max(this, min), max);
};
if (Modernizr.canvas) {
var canvas = document.createElement('canvas'),
ctx = canvas.getContext('2d');
canvas.width = 500;
canvas.height = 375;
canvas.style.border = "3px solid red";
function Point(I) {
console.log("Point created");
this.x = I.x;
this.y = I.y;
this.z = I.z;
return this;
}
function Ball(I) {
console.log("Ball created");
var SPEED_LIMIT = 10;
this.point = new Point(I.point);
this.radius = (I.radius > 10 ? I.radius : 10);
this.color = I.color;
this.speed = new Point(I.speed);
this.collision = false;
this.mass = I.mass || 1;
this.draw = function() {
this.point.x = this.point.x.clamp(0 + this.radius, canvas.width - this.radius);
this.point.y = this.point.y.clamp(0 + this.radius, canvas.height - this.radius);
ctx.beginPath();
ctx.arc(this.point.x, this.point.y, this.radius, 0, Math.PI*2, false);
ctx.closePath();
ctx.fillStyle = this.color;
ctx.fill();
};
this.update = function() {
this.clear();
if ( this.point.x <= this.radius || this.point.x >= (canvas.width - this.radius)) {
this.speed.x *= -1;
}
if ( this.point.y <= this.radius || this.point.y >= (canvas.height - this.radius)) {
this.speed.y *= -1;
}
if ( this.speed.x > SPEED_LIMIT ) {
this.speed.x = SPEED_LIMIT;
}
if ( this.speed.x < SPEED_LIMIT * -1 ) {
this.speed.x = SPEED_LIMIT * -1;
}
if ( this.speed.y > SPEED_LIMIT ) {
this.speed.y = SPEED_LIMIT;
}
if ( this.speed.y < SPEED_LIMIT * -1 ) {
this.speed.y = SPEED_LIMIT * -1;
}
this.point.x += this.speed.x;
this.point.y += this.speed.y;
};
this.clear = function() {
ctx.beginPath();
ctx.arc(this.point.x - 1, this.point.y - 1, this.radius + 2, 0, Math.PI*2, false);
ctx.closePath();
ctx.fillStyle = "#fff";
ctx.fill();
};
return this;
}
var balls = [];
function handleCollisions() {
function collide(ball1, ball2) {
ball1.speed.x *= -1;
ball2.speed.x *= -1;
ball1.speed.y *= -1;
ball2.speed.y *= -1;
}
function checkCollisions() {
var i, j, a, b;
for ( i = 0; i < balls.length; i++ ) {
for ( j = i+1; j < balls.length; j++ ) {
a = balls[i];
b = balls[j];
var dx = Math.abs(a.point.x - b.point.x);
var dy = Math.abs(a.point.y - b.point.y);
var d = (dx*dx)+(dy*dy);
var r = (a.radius + b.radius) * (a.radius + b.radius);
if ( d < r && ( !a.collision || !b.collision ) ) {
a.collision = true;
b.collision = true;
collide(a, b);
} else if ( d > r ) {
a.collision = false;
b.collision = false;
}
}
}
}
checkCollisions();
}
function update() {
balls.forEach(function(ball) {
ball.update();
});
handleCollisions();
}
function draw() {
balls.forEach(function(ball) {
ball.draw();
});
}
var FPS = 30;
var loop = setInterval( function() {
update();
draw();
}, 1000/FPS);
canvas.onclick = function(e) {
var radiusAndMass = Math.floor(Math.random() * 50) + 1;
var speed = Math.floor(Math.random() * 10) + 1;
balls.push(new Ball({
point: {
//x: Math.floor(Math.random() * canvas.width),
//y: Math.floor(Math.random() * canvas.height),
x: e.offsetX,
y: e.offsetY
},
color: "#"+((1<<24)*Math.random()|0).toString(16),
radius: radiusAndMass,
mass: radiusAndMass,
speed: {
x: speed,
y: speed
}
}));
};
document.getElementById('canvas-container').appendChild(canvas);
}
};
</script>
</head>
<body>
<div id="wrap">
<div id="canvas-container">
</div>
</div>
</body>
</html>
</code></pre>
| [] | [
{
"body": "<p>I think that pattern is fine. It has the advantage that you have \"named arguments\", which is very readable and can be useful if you call the some function/constructor with different sets of arguments. </p>\n\n<p>The only thing I'd suggest is to use another name for the parameter, because capital letters are generally used for constructor functions:</p>\n\n<pre><code>function Point(p) {\n this.x = p.x;\n this.y = p.y;\n this.z = p.z;\n return this;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-19T14:33:12.660",
"Id": "1982",
"ParentId": "1940",
"Score": "2"
}
},
{
"body": "<blockquote>\n <p>Is it a good idea to be modifying the this object? For instance does the following pattern make sense?</p>\n\n<pre><code>function Point(I) {\n this.x = I.x;\n this.y = I.y;\n this.z = I.z;\n return this;\n}\n</code></pre>\n</blockquote>\n\n<p>Yes and no. Modifying <code>this</code> is normal in a constructor function, but what you're doing here is unusual. Something like this would be more common:</p>\n\n<pre><code>function Point(x, y, z) {\n this.x = x;\n this.y = y;\n this.z = z;\n}\n</code></pre>\n\n<p>With this parameter list, it's very clear what we are passing in (3D coordinates); with just <code>I</code>, it's not clear unless we read the code in the constructor. Not a huge deal here, but with <code>Ball</code>, we have no clue what <code>I</code> is supposed to contain unless we read the entire constructor. </p>\n\n<p>There's no reason to <code>return this</code>; you're invoking it with <code>new</code>, and the result of that expression will be the constructed object. The function doesn't need to return anything.</p>\n\n<blockquote>\n <p>Is there any reason why I shouldn't be sending a object and pulling variables off of the input object? I like the syntax for creation, but are there any problems with this pattern?</p>\n</blockquote>\n\n<p>There's nothing <em>wrong</em> with it, but since your <code>Point</code> doesn't do anything (i.e. it has no function properties, only <code>x</code>, <code>y</code> and <code>z</code>) you might as well forget about <code>Point</code> and just use object literals if you're passing object literals to the <code>Point</code> constructor anyway. In other words, you're creating an object literal and then copying all of its properties into something that happens to be called a \"Point\" but aside from that has the exact same capabilities as the object you passed into the constructor. Why do that extra step?</p>\n\n<hr>\n\n<p>With <code>Ball</code>, you should attach function properties to <code>Ball.prototype</code> rather than assign them inside of the constructor. There is no reason for each <code>Ball</code> object to have its own separate set of function properties, and doing so incurs extra overhead. In other words, with your code <code>someBall.draw != anotherBall.draw</code>, but it would be much more efficient if all balls reference the same <code>draw</code> function property.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-12T04:05:17.357",
"Id": "54041",
"ParentId": "1940",
"Score": "7"
}
},
{
"body": "<p>I don't think there are any strong reasons towards any of the approaches (object vs values), but I will list out all the advantages/disadvantages of both ways so that you'll choose what seems better for you:</p>\n<h3>Passing in an object of the structure you're describing (<code>function Point(I)</code>)</h3>\n<p><strong>[+]</strong> creating new instances from older instances or compatible objects (anything with x, y and z) is trivial: <code>new Point(oldPoint)</code> or <code>new Point(thingThatQuaksLikeAPoint)</code>*</p>\n<p><strong>[-]</strong> creating new instances from just numbers becomes tedious and annoying (and creates garbage (which MAY be an issue in some cases (really bad for number crunching/real time apps on slow hardware/bad JS implementations))). <code>new Point({ x: 1, y: 2, z: 3 })</code> vs <code>new Point(1, 2, 3)</code>\nOr, take the following function for instance:</p>\n<pre><code>function add(P1, P2) {\n var newX = P1.x + P2.x;\n var newY = P1.y + P2.y;\n var newZ = P1.z + P2.z;\n\n return new Point({ x: newX, y: newY, z: newZ });\n \n // why do I have to wrap my numbers it in an object?!? :(\n // new Point(newX, newY, newZ); is so much more to the point!\n}\n</code></pre>\n<p><strong>[-]</strong> the constructor has access to more than it needs to - it's nice in general to set fences in your app and guarantee that some boundaries are not crossed. If you pass in a full object then by mistake or temptation you might modify the state of the passed object (which leads to very subtle bugs)</p>\n<h3>Passing in individual components (<code>function Point(x, y, z)</code>)</h3>\n<p><strong>[+]</strong> creating new instances from numbers is trivial, sweet short and to the point - it's as easy as <code>new Point(1, 2, 3)</code></p>\n<p><strong>[-]</strong> if calling with other Points then it will become tedious to extract x, y and z every time <code>new Point(otherPoint.x, otherPoint.y, otherPoint.z)</code> vs <code>new Point(otherPoint)</code></p>\n<h2>So why not support both ways?!</h2>\n<pre><code>function Point(x, y, z) {\n if (arguments.length === 1) {\n // we got only one argument - it's a Point!\n var that = x; // just aliasing\n this.x = that.x;\n this.y = that.y;\n this.z = that.z;\n } else {\n // let's presume there can be only these 2 cases\n this.x = x;\n this.y = y;\n this.z = z;\n }\n}\n</code></pre>\n<p>This might be a bit slower, but it's worth it IMO - it makes creating points a breeze ;)</p>\n<hr />\n<p>I do see a couple of bits of code which could be improved in the sample that you pasted. If you're looking to write nice, clean JS then consider looking up how the <em>prototype</em> works. Also learn why <em>requestAnimationFrame</em> is much nicer than <em>setTimeout</em> (which is nicer than <em>setInterval</em>). Also, you may use <code>rgb(1, 2, 3)</code> as a valid color instead of <code>#010203</code>.</p>\n<p>* See <a href=\"http://en.wikipedia.org/wiki/Duck_typing\" rel=\"noreferrer\">duck typing</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-13T21:01:55.063",
"Id": "54198",
"ParentId": "1940",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-18T04:12:47.170",
"Id": "1940",
"Score": "8",
"Tags": [
"javascript",
"beginner",
"animation",
"collision"
],
"Title": "Canvas Drawing/Animation"
} | 1940 |
<p>I'm working on interfacing some older positioning equipment with an arduino, but having done the majority of my work with higher level language I'm having trouble adjusting to the limitations of AVR-GCC.</p>
<p>I basically have two questions: Is this a good way to parse out the strings? What can I do to optimize this code for an embedded platform?</p>
<pre><code>// this is in the global scope of my program. normally accepted as bad code,
// but it seems to make sense in the context of an embedded platform.
// "global" cache
int data[10];
void getPosition(){
// position message is always less than 25 bytes with null termination characters
byte bufferIndex = 0;
char buffer[25];
// read the position command from the serial port
// should look like:
// D20BIX+00733Y+00080S99\r\n
//
// and we need the X+00000 and Y+00000 parts
//
if (Serial.available() > 0){
while (Serial.available() > 0 && bufferIndex < 25){
buffer[bufferIndex] = Serial.read();
if (buffer[bufferIndex++] == '\n'){
buffer[bufferIndex] = '\0';
break;
}
}
Serial.flush();
// check to see if we have good orientation on the buffer by
// checking for lines starting with model identifier 'D'
String input = String(buffer);
if (buffer[0] == 'D' && bufferIndex <=24){
int x_result = data[1];
int y_result = data[4];
String check;
char token_buffer[8] = {'0', '0', '0', '0', '0', '0', '0', '0' };
// scan for x, target token is X+00000
String x_token = input.substring(5, 11);
check = x_token.substring(2, 6);
check.toCharArray(token_buffer, 8);
x_result = atoi(token_buffer);
if (x_token[1] == '-'){
x_result *= -1;
}
// scan for y, target token is Y+00000
String y_token = input.substring(12, 18);
check = y_token.substring(2, 6);
check.toCharArray(token_buffer, 8);
y_result = atoi(token_buffer);
if (y_token[1] == '-'){
y_result *= -1;
}
// finalize results
data[1] = x_result;
data[4] = y_result;
}
}
}
</code></pre>
| [] | [
{
"body": "<p>IMHO string parsing is not a good idea for embedded applications. If you really care for speed, it would be better to use some binary format w/o dynamic length numbers etc.</p>\n\n<p>I suggest you cannot change protocol due to legacy code/hardware. Then you could try turning your parser into finite automate. You just make a table (first index for current state, second index for a class of read char, value is new state and function to call) and then <code>(state, f) = transition[state][class_of[*s++]]; f();</code> Files, generated with YACC for some simple grammars, could be helpful.</p>\n\n<p>If you need just some minor modifications to your code, here you are.\nFirst you read data into your buffer. All you have to do then is just some calculations with Horner scheme:</p>\n\n<pre><code>x_result = ((buffer[5]-'0')*10+buffer[6]-'0')*10+... ;\nif (buffer[4] == '-') x_result =- x_result;\n</code></pre>\n\n<p>String constructor, substring method and other string operations are quite costly.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-19T21:42:56.707",
"Id": "1992",
"ParentId": "1942",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "1992",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-18T06:02:04.393",
"Id": "1942",
"Score": "3",
"Tags": [
"c++"
],
"Title": "String parsing with AVR-GCC"
} | 1942 |
<p>I have a form that submits to a servlet that has optional parameters. If they are empty they are just ignored. This is the template I am using:</p>
<pre><code>if (!(param = (String)params.get("httpParam")).equals("")) {
// Handle parameter
}
</code></pre>
<p>It doesn't quite feel right. It <em>works</em>, but I think it could be more readable. Any suggestions?</p>
| [] | [
{
"body": "<p>I suggest extract code for getting parameter to separate method (see <a href=\"http://sourcemaking.com/refactoring/extract-method\" rel=\"nofollow\">extract method</a> refactoring's tehnique):</p>\n\n<pre><code>param = getOptionalParameter(\"httpParam\");\nif (! param.isEmpty()) {\n // Handle parameter\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-18T14:24:54.833",
"Id": "1948",
"ParentId": "1947",
"Score": "4"
}
},
{
"body": "<p>You can populate a map containing all your parameters and than convert that map into POJO:</p>\n\n<pre><code> HashMap map = new HashMap();\n Enumeration names = request.getParameterNames();\n while (names.hasMoreElements()) {\n String name = (String) names.nextElement();\n map.put(name, request.getParameterValues(name));\n }\n BeanUtils.populate(data, map);\n</code></pre>\n\n<p>Where 'data' is your POJO class with attributes corresponding to your parameter names.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-03T11:26:26.570",
"Id": "10134",
"Score": "1",
"body": "How about request.getParameterMap() instead of while loop?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-19T08:45:12.197",
"Id": "1969",
"ParentId": "1947",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "1948",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-18T13:54:19.507",
"Id": "1947",
"Score": "7",
"Tags": [
"java",
"null",
"servlets"
],
"Title": "Handling optional parameters in a servlet"
} | 1947 |
<p>I have decided to go PDO and have started implementing it on one of my webprojects. I have limited programing skills but can usually pull it off with some tutorials and forums.</p>
<p>Here is my code this far and it works fine but how is the code correct regarding the picking up errors, syntax, order and begintransaction etc.? Have I missunderstood anything? Is anything unneccesary?</p>
<p>connect.php</p>
<pre><code> <?php
try {
$DBH = new PDO("mysql:host=$host;dbname=$database", $username, $password, array(
PDO::ATTR_PERSISTENT => true
));
$DBH -> exec("set names utf8");
}
catch(PDOException $e) {
echo $e->getMessage();
}
?>
</code></pre>
<p>query.php</p>
<pre><code>try {
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$DBH->beginTransaction();
$STH = $DBH->prepare('SELECT id from users where uid = :uid');
$STH->setFetchMode(PDO::FETCH_ASSOC);
$STH->bindParam(':uid', $uid); // $uid value is set
$STH->execute();
$uid_in_db = $STH->rowCount();
if($uid_in_db==0){ //=new user, insert info in db.
$STH = $DBH->prepare("INSERT INTO USERS (uid,namn) VALUES (:uid, :name)");
$STH->bindParam(':uid', $uid);
$STH->bindParam(':namn', $_POST['namn']); // a value posted form user input
$STH->execute();
}
$DBH->commit(); //
} catch (Exception $e) {
$DBH->rollBack();
echo "Fel: " . $e->getMessage();
}
}else{
$error=1;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-18T14:12:03.700",
"Id": "3256",
"Score": "0",
"body": "I don't see any need for transactions. You only have 1 insert. Do you plan to add more write queries? Note that by beginning a transaction you don't issue any implicit locks on the tables."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-18T14:31:09.210",
"Id": "3257",
"Score": "0",
"body": "Thanks, I changed that since now. What do you mean by mean with `don't issue any implicit locks on the tables`? thanks!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-18T14:15:15.587",
"Id": "137277",
"Score": "0",
"body": "You may want to check out the disadvantages of using persistent connections with PDO. You may not really need to use that option. [What are the disadvantages of using persistent connection in PDO?](http://stackoverflow.com/questions/3332074/what-are-the-disadvantages-of-using-persistent-connection-in-pdo)"
}
] | [
{
"body": "<p>Instead of checking for a UID collision before an insert, I would put a unique key on that column, and then write fallback code for the case (very very unlikely) when two collide. That way you can simplify your logic and reduce the number of queries to one instead of two. You also don't need a transaction if you implement this change, since there is only 1 query.</p>\n\n<pre><code>//you can remove the outer try/catch since only the execute() should possibly fail\n$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //<~ put this in the initialize of the db connection\n$STH = $DBH->prepare(\"INSERT INTO USERS (uid,namn) VALUES (:uid, :name)\");\n$STH->bindParam(':uid', $uid);\n$STH->bindParam(':namn', $_POST['namn']); // a value posted form user input\ntry {\n $STH->execute();\n} catch( PDOException $e ) {\n //deal with collision \n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-18T14:35:45.257",
"Id": "3259",
"Score": "0",
"body": "1.I put the errormode in under `$DBH -> exec(\"set names utf8\");\n` is that OK? 1b.what is the differende from `catch(PDOException $e)`and `catch(Exception $e)`? 2. Ichanged so that the try is only around the `$STH->execute();`is that something I can always follow? 3.I did not quite understand the uid as key and the fallback case. But I would really like to slim the script. Though I might need to specify that the uid is the uid from FBAPI that is set when a user login to the site and the script should see if the user is in the db or show the form to add info. so the uid will in most cases exist."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-18T14:43:49.673",
"Id": "3261",
"Score": "0",
"body": "@Joseph PDOException is more correct, since it would let any other exception (which would be more serious) to be emitted (I updated my example). If you put a unique key on column in the database, the database will reject any duplicate uid entires and cause `$STH->execute()` to raise an exception."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-18T14:58:52.000",
"Id": "3262",
"Score": "0",
"body": "Ok now I understand but do you think it is a good solution since as I described the id will in most cases be a duplicate (for every pageload by a returning user) and thus be an error. Also question 1 in comment above, is the catch error line put correctly and should I remove it when in production? Thanks!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-18T15:08:49.287",
"Id": "3263",
"Score": "0",
"body": "@Joseph Taking that into consideration, I might actually lean towards you original solution. Since the normal case would be to only run 1 query. I was under the impression that you were creating a user entity, not a session. I wouldn't consider it good practice to use an insert to check if a row already exists."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-18T15:18:05.517",
"Id": "3264",
"Score": "0",
"body": "Ok thanks, yes I was a bit unclear. Can you please look at the other questions I gave in the comments above regarning your other suggestions. thanks"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-18T14:12:10.033",
"Id": "1950",
"ParentId": "1949",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "1950",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-18T14:08:16.753",
"Id": "1949",
"Score": "4",
"Tags": [
"php",
"mysql",
"pdo"
],
"Title": "Implementing PDO, code correct so far?"
} | 1949 |
<p>I just wrote this small inch <-> cm conversion program. It works just fine, although I know that I've done some things in a rather stupid manner and that it could be improved.</p>
<pre><code>def conversion():
try: amount = int(raw_input("Please enter the value: "))
except ValueError:
print "Please specify a valid amount."
return conversion()
answer = raw_input("Please choose between converting FROM kilograms/pounds: ")
if answer == "kilograms":
return amount * 2.2
elif answer == "pounds":
return amount / 1.45
else:
print "Please choose between kilograms and pounds."
restart = raw_input("Try again? ")
if restart == "yes":
return conversion()
elif restart == "y":
return conversion()
else:
print "Okay, bye."
return
print conversion()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-24T16:49:42.230",
"Id": "110541",
"Score": "1",
"body": "where are cm and inch?"
}
] | [
{
"body": "<p>The first point would be the separation of concerns: every entity (function, class …) should only be responsible for <em>one</em> task (except, ironically, printing the result).</p>\n\n<p>In your code, one function (<code>conversion</code>) is responsible for everything. Try separating the different issues:</p>\n\n<ul>\n<li>user input</li>\n<li>conversion</li>\n<li>output</li>\n</ul>\n\n<p>Granted, for such a very small program the result will almost certainly be larger. But it will also be much clearer and easier to extend.</p>\n\n<p>Next up, your use of recursion. I love recursion as much (more!) as the next programmer but in your case a few loops wouldn’t hurt readability.</p>\n\n<p>A third point, magic constants should be avoided. Your use of the conversion factors <code>2.2</code> and <code>1.45</code> is innocuous enough but it soon becomes a problem in larger programs. Use properly-named constants instead.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-18T15:38:52.217",
"Id": "1953",
"ParentId": "1952",
"Score": "6"
}
},
{
"body": "<p>I would not recommend you to structure the app this way. A cleaner solution (IMHO) would be to have the values being inputted by arguments to the script so that you call it using <code>./convert --inch 5.2</code> or <code>./convert --cm 5.2</code>. Also to have all functionality mashed together in one function isn't good practice, you should divide input/output and function at least.</p>\n\n<p>I did however make my own version that should be pretty equal as far as functionality goes, although i suspect some things differ. And it is not really a better solution... just different. </p>\n\n<pre><code>#!/usr/bin/python2\n\ndef convert(value, frm):\n try:\n amount = int(value)\n except:\n throw Exception(\"Value is not an numeric\")\n return amount * 2.2 if frm == \"kilograms\" else (1/1.45) if frm == \"pounds\" else throw Exception(\"Can only convert from kilograms or pounds\")\n\ndef ask_user():\n while(True):\n amount = raw_input(\"Please enter the value: \");\n frm = raw_input(\"Please choose between converting FROM kilograms/pounds: \")\n try:\n result = convert(amount, frm)\n print \"The result is \" + result + \" \" + \"pounds\" if frm == \"kilograms\" else \"kilograms\"\n except Exception as e:\n print e\n print \"Please try again\"\n continue\n restart = raw_input(\"Try again? \");\n if restart[0] == 'y':\n continue\n else:\n print \"Okey, bye.\"\n break\n\nif __name__ = '__main__': # This row is to be able to import the file without the question being asked on import.\n ask_user()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-18T15:40:09.750",
"Id": "1954",
"ParentId": "1952",
"Score": "2"
}
},
{
"body": "<p>Don't use recursion in this case. Python doesn't optimize tail recursion and after long session script can show your <code>RuntimeError: maximum recursion depth exceeded</code>.</p>\n\n<p>Don't use <a href=\"http://docs.python.org/tutorial/floatingpoint.html\" rel=\"nofollow\">floating point arithmetic</a> in this case. Use <a href=\"http://speleotrove.com/decimal/\" rel=\"nofollow\">decimal arithmetic</a> with <a href=\"http://docs.python.org/library/decimal.html#module-decimal\" rel=\"nofollow\">decimal</a> module. For example:</p>\n\n<pre><code>>>> 100 * 2.2\n220.00000000000003\n>>> from decimal import Decimal\n>>> Decimal(\"100\") * Decimal(\"2.2\")\nDecimal('220.0')\n</code></pre>\n\n<p>Split logic and presentation. For now there is no way to use this converter with Web UI or as a library for a bigger program. For example you can start with low level functions like this:</p>\n\n<pre><code>def kilograms_to_pounds(amount):\n return amount * Decimal(\"2.2\")\n\ndef pounds_to_kilograms(amount):\n return amount / Decimal(\"1.45\")\n</code></pre>\n\n<p>Then you can create front-end function like this:</p>\n\n<pre><code>converters = {\n (\"kilograms\", \"pounds\"): kilograms_to_pounds,\n (\"pounds\", \"kilograms\"): pounds_to_kilograms,\n}\n\ndef convert(amount, from_, to):\n c = converters.get((from_, to))\n if c is None:\n raise ValueError(\"converter not found\")\n return c(amount)\n\n>>> convert(Decimal(\"100\"), \"pounds\", \"kilograms\")\nDecimal('68.96551724137931034482758621')\n</code></pre>\n\n<p>Later you can add aliases like this (or as function decorator):</p>\n\n<pre><code>aliases = {\n \"kg\": \"kilograms\",\n \"lb\": \"pounds\",\n ...\n}\n\ndef convert(amount, from_, to):\n from_ = aliases.get(from_, from_)\n to = aliases.get(to, to)\n c = converters.get((from_, to))\n if c is None:\n raise ValueError(\"converter not found\")\nreturn c(amount)\n\n>>> convert(Decimal(\"100\"), \"lb\", \"kg\")\nDecimal('68.96551724137931034482758621')\n</code></pre>\n\n<p>With this architecture you can later add other converters to your library and you need to call only <code>convert()</code> function from your UI loop.</p>\n\n<p>Also I don't like your UI. For example if I need to convert 10 values from kilograms to pounds I need to enter value then I need to enter \"kilograms\". By adding modes to your converter you can save me 10 lines. For example user first enter \"kilograms to pounds\" and this conversion mode stored and displayed in the prompt. Then user can enter values which will be converted from kilograms to pounds. Later user can change conversion mode by entering \"pounds to kilograms\".</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-18T19:14:31.077",
"Id": "1956",
"ParentId": "1952",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-18T14:57:51.360",
"Id": "1952",
"Score": "5",
"Tags": [
"python",
"converting"
],
"Title": "Inch <-> cm conversion program"
} | 1952 |
<p>Below I have some jQuery code that handles footnotes. My question is actually about the formatting and indentation of the code, so I won't bother trying to explain what the code does beyond that.</p>
<p>I'd like to know what patterns of indentation are considered the most maintainable and readable when chaining jQuery function calls of the form: <code>$(foo).foo(bar).foo(function(){ bar; }).foo(function(){ bar; });</code></p>
<p>Here is my specific code and the formatting/indentation that I've come up with:</p>
<pre><code>$('.footnote[id^="ret_"]')
.removeAttr('title')
.removeAttr('alt')
.mouseenter(function(e) {
var footnote = $('#footnote_cont_' + this.id.substring(4)).html();
$footnoteTooltip.stop(true, false);
//only completely hide and change text/position if we are hovering over a different footnote
if($footnoteTooltip.html() != footnote)
$footnoteTooltip.hide().html(footnote).css({ left: e.pageX + 10, top: e.pageY + 15});
$footnoteTooltip.fadeTo(fadeTime, opacity);
})
.mouseleave(function() {
$footnoteTooltip.delay(fadeTime).fadeOut(fadeTime);
})
;
</code></pre>
<p>Is there a more readable way of indenting this?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-15T15:30:19.810",
"Id": "36941",
"Score": "0",
"body": "@jonnysooter: my question was specifically about the indentation and formatting. why would you change the indentation and formatting of the code in the question? rolling back to my initial revision"
}
] | [
{
"body": "<p>My suggestion:</p>\n\n<pre><code>$('.footnote[id^=\"ret_\"]')\n .removeAttr('title')\n .removeAttr('alt')\n .mouseenter(function(e) {\n var footnote = $('#footnote_cont_' + this.id.substring(4)).html(); \n $footnoteTooltip.stop(true, false);\n\n //only completely hide and change text/position if we are hovering over a different footnote\n if($footnoteTooltip.html() != footnote)\n $footnoteTooltip.hide().html(footnote).css({ left: e.pageX + 10, top: e.pageY + 15});\n\n $footnoteTooltip.fadeTo(fadeTime, opacity);\n }).mouseleave(function() {\n $footnoteTooltip.delay(fadeTime).fadeOut(fadeTime);\n });\n</code></pre>\n\n<ul>\n<li>Three or four spaces indentation - your preference. My opinion is that two spaces is more difficult to read (although Lisp uses it).</li>\n<li>Semicolon on same line as last method call. The only time I approve of having it on it's own line is an empty <code>while</code>.</li>\n<li><code>}).mouseLeave()</code> I put the call on the same line as the end of the block to make it clear that you're calling the method of the object returned.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2011-04-18T20:04:50.747",
"Id": "1958",
"ParentId": "1957",
"Score": "7"
}
},
{
"body": "<p>I agree with the majority of what <a href=\"https://codereview.stackexchange.com/questions/1957/indentation-and-formatting-for-chained-jquery-methods/1958#1958\">Michael K</a> said. And I'd also do the following:</p>\n\n<pre><code>$('.footnote[id^=\"ret_\"]').removeAttr('title').removeAttr('alt').mouseenter(function(e) {\n var footnote = $('#footnote_cont_' + this.id.substring(4)).html(); \n $footnoteTooltip.stop(true, false);\n\n //only completely hide and change text/position if we are hovering over a different footnote\n if($footnoteTooltip.html() != footnote) {\n $footnoteTooltip.hide().html(footnote).css({ left: e.pageX + 10, top: e.pageY + 15});\n }\n\n $footnoteTooltip.fadeTo(fadeTime, opacity);\n}).mouseleave(function() {\n $footnoteTooltip.delay(fadeTime).fadeOut(fadeTime);\n});\n</code></pre>\n\n<ul>\n<li>Personally I find the newlines on the chained <code>removeAttr</code> and <code>mouseenter</code> really interrupts the flow of the method, so I'd remove those.</li>\n<li>I would also add braces <code>{ }</code> after the single line if statement (that's more of a preference so that I don't get bit by subtle bugs.)</li>\n<li>And like Michael K, I would line up the <code>}).mouseLeave()</code> call on the same line as the end of the block - however my treatment of the first line changes where that alignment occurs.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-19T15:10:32.060",
"Id": "1984",
"ParentId": "1957",
"Score": "2"
}
},
{
"body": "<p>I personally find \"bind('event') and trigger('event') to be cleaner and they are supposed to act faster, since that's what is done behinde the curtains anyway.</p>\n\n<p>So it'd be:</p>\n\n<pre><code>$('.footnote[id^=\"ret_\"]')\n .bind('mouseenter', function(e) {\n // code\n })\n .bind('mouseleave', function(e) {\n // code \n });\n</code></pre>\n\n<p>I'd also recommend not to use $ as a prefix for the jQuery objects - <a href=\"http://www.bennadel.com/blog/1778-Using-Variable-In-jQuery-Code-Is-Just-Hungarian-Notation.htm\" rel=\"nofollow\">http://www.bennadel.com/blog/1778-Using-Variable-In-jQuery-Code-Is-Just-Hungarian-Notation.htm</a>. I agree with what's written in that blog post – you don't prefix arrays with arr_, booleans with is_, numbers with \"num_\" etc. And if you do – you probably shouldn't :-)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-21T11:47:00.930",
"Id": "2020",
"ParentId": "1957",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-18T19:48:45.480",
"Id": "1957",
"Score": "9",
"Tags": [
"javascript",
"jquery"
],
"Title": "Indentation and formatting for chained jQuery methods"
} | 1957 |
<p>I need to get the total milliseconds to the next mid-day (12:00:00) to signal a timer that will run once a day. </p>
<p>Assuming the application can be shut down and started anytime, is this code to get the milliseconds left to midday (used to set the timer) correct? (It doesn't need to be exact; it can be off by a few seconds.)</p>
<pre><code>TimeSpan now = DateTime.Now.TimeOfDay;
TimeSpan target = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 12, 0, 0).TimeOfDay;
double r = target.TotalMilliseconds - now.TotalMilliseconds;
if (r > 0) // It's before noon
;
else // It's after noon
r = TimeSpan.FromTicks(TimeSpan.TicksPerDay).TotalMilliseconds + r;
t = new Timer(DoWork, null, r, TimeSpan.FromTicks(TimeSpan.TicksPerDay));
</code></pre>
<p>Can it be done more efficiently or in fewer lines of code?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-19T12:57:08.847",
"Id": "3292",
"Score": "0",
"body": "If it can be off by a few seconds, why are you worried about millisecond resolution?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-19T12:59:57.410",
"Id": "3293",
"Score": "2",
"body": "I'm not worried, it's just how I started to solve it... also, it *can be* off, but if I can avoid it, it's better"
}
] | [
{
"body": "<pre><code>if (r > 0) // It's before noon\n ;\nelse // It's after noon\n r = TimeSpan.FromTicks(TimeSpan.TicksPerDay).TotalMilliseconds + r; \n</code></pre>\n\n<p>Change to:</p>\n\n<pre><code>if (r <= 0) // It's after noon\n r = TimeSpan.FromTicks(TimeSpan.TicksPerDay).TotalMilliseconds + r;\n</code></pre>\n\n<p>No need to have an <code>if</code> that does nothing.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-18T20:36:14.457",
"Id": "3270",
"Score": "0",
"body": "I actually like to leave that for readability and to let the next person that reads the code know I considered the other part of the condition"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-18T23:17:45.343",
"Id": "3274",
"Score": "0",
"body": "@Juan: If you like to indicate that, change your comment likewise. \"Only update when ...\" No need to indicate all other possibilities."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-18T20:34:01.540",
"Id": "1960",
"ParentId": "1959",
"Score": "8"
}
},
{
"body": "<p>In terms of efficiency, you should hardly be worrying about that. But I think you could make this a little more human readable / self-explanatory and a little less complicated than it is / looks. </p>\n\n<pre><code>/// <summary>\n/// Returns the period of time left before the specified hour is due to elapse\n/// </summary>\n/// <param name=\"hour\">And integer representing an hour, \n/// where 0 is midnight, 12 is midday, 23 is eleven et cetera</param>\n/// <returns>A TimeSpan representing the calculated time period</returns>\npublic static TimeSpan GetTimeUntilNextHour(int hour)\n{\n var currentTime = DateTime.Now;\n var desiredTime = new DateTime(DateTime.Now.Year,\n DateTime.Now.Month, DateTime.Now.Day, hour, 0, 0);\n var timeDifference = (currentTime - desiredTime);\n var timePeriod = currentTime.Hour >= hour ?\n (desiredTime.AddDays(1) - currentTime) :\n -timeDifference;\n return timePeriod;\n}\n</code></pre>\n\n<p>In hindsight and largely due to my attention being drawn by comments, this could be shorter, by omitting the <code>timeDifference</code> variable assignment and calculating in-line, further, we don't need to negate the value of either; and also we can <code>return</code> rather than assign <code>timePeriod</code>: </p>\n\n<pre><code>var currentTime = DateTime.Now;\nvar desiredTime = new DateTime(DateTime.Now.Year,\n DateTime.Now.Month, DateTime.Now.Day, hour, 0, 0);\nreturn currentTime.Hour >= hour ?\n (desiredTime.AddDays(1) - currentTime) :\n desiredTime - currentTime;\n</code></pre>\n\n<p>A few notes here to qualify my statement...</p>\n\n<ul>\n<li><p>Lines aren't expensive, but if you must have this on eight lines you could still do so - I've purposely dropped <code>desiredTime</code> to cover two lines, not strictly to stay on <a href=\"http://tuomaspelkonen.com/2010/03/why-code-lines-still-should-not-exceed-79-characters/\" rel=\"nofollow noreferrer\">the safe side</a> of <a href=\"http://plope.com/Members/chrism/python_line_length_hell\" rel=\"nofollow noreferrer\">history</a> (though it helps), but just to maintain flow - where line endings are relative rather than sporadic, think of a paperback book.</p></li>\n<li><p>I'd recommend naming things aptly, that way sometimes people don't necessarily need examine <em>how</em> the code does what it does, which allows them to either A) scan and find what they're looking or B) figure it out without having to wonder what was going through <em>that guys head</em>. </p></li>\n<li><p>Use of <a href=\"http://msdn.microsoft.com/en-us/library/bb383973.aspx\" rel=\"nofollow noreferrer\">implicitly typed variables</a> (<code>var</code>), these are available from C# 3.0 onwards; this feature allows us to omit the specific type name completely when assigning a value / reference as part of the declaration - <a href=\"https://stackoverflow.com/questions/41479/use-of-var-keyword-in-c\">just be sure to use this wisely, clarity should maintained for the reader</a>. You didn't specify which language version you're using, so this may not be available to you, but bear it in mind for the future.</p></li>\n<li><p><code>DateTime</code> provides <a href=\"http://msdn.microsoft.com/en-us/library/ff986512.aspx\" rel=\"nofollow noreferrer\">operators</a> to that allow us to work with them directly in this instance, so no need to bother with <code>FromTicks</code>, <code>TotalMilliseconds</code>, <code>TotalTicks</code>, <code>TimeOfDay</code> et cetera.</p></li>\n<li><p>As a final note: an empty statement (<code>;</code>) produces a compiler warning, these shouldn't be ignored and, in any place I know, you'd at least have to explain yourself if someone came across this; it could also produce a compile-time error depending on the environment - that and the preceding condition are not only redundant in this case but neither are they indicative of anything, so much so that even <em>you</em> felt obliged to leave a comment.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-19T07:18:36.470",
"Id": "3280",
"Score": "0",
"body": "your `currentTime.Hour > hour` doesn't take minutes/seconds into account, i.e. 12:55 is also after midday"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-19T07:47:27.027",
"Id": "3283",
"Score": "0",
"body": "Oops, good spot - misinterpreted your comment at first, a simple mistake and fix, a `>=` check would suffice, in that case. Let me update that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-19T15:30:29.367",
"Id": "3296",
"Score": "0",
"body": "I don’t get why you declare that extra variable `timeDifference` for one of the `?:` cases but not the other; and why you declare it *negative*. Why not just `var timePeriod = currentTime.Hour >= hour ? (desiredTime.AddDays(1) - currentTime) : (desiredTime - currentTime)`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-19T15:33:34.660",
"Id": "3297",
"Score": "0",
"body": "@Timwi: Early hours of morn obviously had their way - I agree this could be shorter, by a single line."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-19T15:38:53.513",
"Id": "3298",
"Score": "0",
"body": "@Timwi: Or by two lines, if you `return` instead of assigning `timePeriod`."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-19T00:43:35.907",
"Id": "1963",
"ParentId": "1959",
"Score": "4"
}
},
{
"body": "<ol>\n<li><p>Because I like a challenge (at least, one that I'm not completely lost at):</p>\n\n<pre><code>long now = DateTime.Now.Ticks;\nconst long noon = TimeSpan.TicksPerHour*12;\nlong r = ((noon - now + TimeSpan.TicksPerDay) % TimeSpan.TicksPerDay)\n / TimeSpan.TicksPerMillisecond;\n</code></pre>\n\n<p>No branches, minimal conversions, and no floating point. Not too much \"magic\", if you know why the modulo works and why the added <code>TicksPerDay</code> is necessary.</p></li>\n<li>I'll point out that this question seems like a form of premature (and wrongheaded) optimization, unless it's a purely theoretical exercise (a form of code golf?) - it's probably better to leave it in the form you understand, especially if this code only runs once (or once per day). If you're doing this one million times, then you're creating a million <code>Timer</code>s.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-19T02:31:14.973",
"Id": "1964",
"ParentId": "1959",
"Score": "8"
}
},
{
"body": "<p>I would leave your code mostly as-is, at least the logic, but IMO there are some readability issues: </p>\n\n<ul>\n<li>empty <code>if</code> statement. As already mentioned there are other ways to show that you've taken both scenarios were taken into account.</li>\n<li><code>r</code> variable? Something more sensible might be here. <code>millisecondsToTarget</code>?</li>\n<li>I would also replace <code>TimeSpan.FromTicks(TimeSpan.TicksPerDay)</code> with <code>TimeSpan.FromDays(1)</code> but that's pretty subjective, I can see a point in your version also.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-19T07:36:10.283",
"Id": "1968",
"ParentId": "1959",
"Score": "4"
}
},
{
"body": "<p>On a normal day there are 43,200,000 ms. from midnight until noon. How many are there from midnight until noon on the days daylight savings time starts / ends, in other words, is there a problem using the difference of two DateTimes on those days? </p>\n\n<p>If you are going to use the difference of two datetimes then use the UTC version of them.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-19T12:58:44.263",
"Id": "1980",
"ParentId": "1959",
"Score": "3"
}
},
{
"body": "<ol>\n<li><p>I don't like the way you interleave calls to <code>DateTime.Now</code> with the calculation. Makes it hard to test.</p>\n\n<p>I recommend separating logic from external state, such as a clock. I prefer to write the logic in a functional style: Simple inputs that produce an output without touching anything else.</p></li>\n<li><p>Calling <code>DateTime.Now</code> multiple times can give different results each time in principle, but that's unlikely in practice.</p></li>\n<li><p>Assuming you use <code>System.Threading.Timer</code>, you don't need milliseconds at all, since the <code>Timer</code> takes a <code>TimeSpan</code>.</p>\n\n<p>Similarly those roundtrips to <code>Ticks</code> are useless. Just use <code>TimeSpan.FromDays(1)</code> or <code>TimeSpan.FromHours(12)</code>.</p></li>\n</ol>\n\n<p>So I'd create one function containing the logic:</p>\n\n<pre><code>private static TimeSpan TimeUntilMidday(DateTime current)\n{\n DateTime target = current.Date.AddHours(12);// today's midday \n if(target < current)\n target = target.AddDays(1); // tomorrow's midday\n return target - current;\n}\n</code></pre>\n\n<p>And then use it with:</p>\n\n<pre><code>new Timer(DoWork, null, TimeUntilMidday(DateTime.Now), TimeSpan.FromDays(1))\n</code></pre>\n\n<p>This makes it easy to add test-cases for corner cases:</p>\n\n<pre><code>Assert(TimeUntilMidday(new DateTime(2000, 1, 1, 12, 0, 0)) == TimeSpan.Zero)\n</code></pre>\n\n<p>Such a test can clearly document your intent for such a special case. Without it it's not clear what you want to do if it's currently exactly midday - run instantly or wait a full day.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-04T16:42:02.010",
"Id": "21306",
"ParentId": "1959",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "1963",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-18T20:30:09.077",
"Id": "1959",
"Score": "10",
"Tags": [
"c#",
"datetime"
],
"Title": "Getting the miliseconds from now to the next midday"
} | 1959 |
<p><a href="http://www.djangoproject.com/" rel="nofollow">Django</a>, "the web framework for perfectionists with deadlines", is a Python-based framework for creating web applications.</p>
<p>With a powerful object-based database mapper, a clean syntax for mapping URLs to views, a simple template language and a convenient automatically generated administration interface, Django is one of the most popular of the Python web frameworks. </p>
<p>Django focuses on automating as much as possible while adhering to the <a href="http://c2.com/cgi/wiki?DontRepeatYourself" rel="nofollow">DRY principle</a>. It lets you build high-performing, elegant Web applications quickly.</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-19T05:27:39.047",
"Id": "1965",
"Score": "0",
"Tags": null,
"Title": null
} | 1965 |
Django is a Python-based framework for creating web applications. | [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-19T05:27:39.047",
"Id": "1966",
"Score": "0",
"Tags": null,
"Title": null
} | 1966 |
<p>I want to join strings together, but when doing this it often happens that there is a comma too many, and therefore I need to remove that comma. In this code, I use the <code>substring</code> to delete the two last characters.</p>
<p>How can this become more elegant?</p>
<pre><code>List<String> paramList = new ArrayList<String>( );
paramList.add( "param1" );
paramList.add( "param2" );
StringBuilder result = new StringBuilder();
for ( String p : paramList )
{
result.append( p ).append( ", " );
}
String withoutLastComma = result.substring( 0, result.length( ) - ", ".length( ) );
System.err.println( withoutLastComma );
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-19T20:01:39.063",
"Id": "3926",
"Score": "8",
"body": "How about instead of adding comma and then removing it just not add comma to the last item? using the index based approach would have been fine.\n\nfor (int i = 0; i < paramList.size()-1; i++)\n{\n result.append( p ).append( \", \" );\n}"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-18T21:07:00.313",
"Id": "88160",
"Score": "1",
"body": "Swapping the order of appends--`result.append(\", \").append(p)`--allows you to use the simpler extraction: `result.substring(\", \".length())`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-12-06T03:02:37.977",
"Id": "208893",
"Score": "0",
"body": "Apparently a new best answer is below: http://codereview.stackexchange.com/a/58588/23451"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-12-20T17:58:07.910",
"Id": "212351",
"Score": "0",
"body": "If you don't want to use an external library, your solution provides the best readability imo. From all possibilities, I always use this one (although usually with `result.deleteCharAt(result.length)` which doesn't fit in here)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-28T06:18:51.550",
"Id": "410706",
"Score": "0",
"body": "Rather than using any external library for this purpose, it is better to use Streams library provided in Java 8. Use this - \n\n**paramList.stream().map(String::valueOf).collect(Collectors.joining());**"
}
] | [
{
"body": "<pre><code>for ( String p : paramList )\n{\n if (result.length() > 0) result.append( \", \" );\n result.append( p );\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-19T12:44:29.457",
"Id": "3291",
"Score": "0",
"body": "I've always used this method. It's clear. It looks nearly the same in any language. I've never seen where the extra comparison would ever have enough weight per iteration to make a difference."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-20T03:40:20.193",
"Id": "3946",
"Score": "3",
"body": "I used this solution in .NET, until I discovered that `string` has a static `Join` method. I'm surprised Java doesn't have something similar built-in."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-20T17:45:37.670",
"Id": "37261",
"Score": "0",
"body": "I like how this answer actually shows how to solve the problem, not just avoid it by using a library method. Not that using the library method is wrong though, its just you still don't see how it is actually solved."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-22T16:49:33.753",
"Id": "103263",
"Score": "0",
"body": "It is exactly what StringUtils.join seems to be doing."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-19T10:03:20.663",
"Id": "1974",
"ParentId": "1973",
"Score": "98"
}
},
{
"body": "<p>One may use string utility methods such as <code>StringUtil.join</code> to concatenate elements in an array or a collection object. Consult the StringUtil API's <a href=\"http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#join(java.lang.Object[],%20char)\" rel=\"noreferrer\"><code>StringUtil.join</code></a> entry.</p>\n\n<p>For example:</p>\n\n<pre><code>StringUtils.join([\"a\", \"b\", \"c\"], \"--\") // => \"a--b--c\"\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-19T11:23:44.053",
"Id": "3288",
"Score": "0",
"body": "I will add a tool library. First i have to check the differences between apache commons and google guave."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-24T23:04:11.230",
"Id": "3372",
"Score": "43",
"body": "I don't see how something this simple can justify adding a library."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-25T13:04:06.193",
"Id": "3381",
"Score": "8",
"body": "@Wes: If you are working with critical production code and do not want to take on unnecessary dependencies (or have a policy requirement not to use external libraries) and have the time to write/test/debug/optimize your own methods, then by all means, roll your own. I made the assumption that OP is looking for a simple solution for a non-critical task."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-18T21:00:54.517",
"Id": "88159",
"Score": "2",
"body": "Guava has [`Joiner`](http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Joiner.html): `Joiner.on(\", \").join(paramList)`. It provides helpful options such as skipping `null` values, too. Oops, already an [answer](http://codereview.stackexchange.com/a/1976/1635)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-31T03:18:33.293",
"Id": "105187",
"Score": "23",
"body": "Java 8 now also has a `String.join()` method, see my [answer below](http://codereview.stackexchange.com/a/58588/50159)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-12-20T17:53:32.537",
"Id": "212348",
"Score": "0",
"body": "this corresponds to php's `implode()` function, I guess"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-11-13T18:21:09.187",
"Id": "276095",
"Score": "2",
"body": "@Athas: By repeating that statement for every new utility method you end up with a self made copy of all the methods of that library. And I don't even ask for the unit tests that you wrote for \"something this simple\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-28T06:10:26.770",
"Id": "410705",
"Score": "0",
"body": "Rather than using any external library for this purpose, it is better to use Streams library provided in Java 8. Use this - \nparamList.stream().map(String::valueOf).collect(Collectors.joining());"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-19T10:06:53.653",
"Id": "1975",
"ParentId": "1973",
"Score": "133"
}
},
{
"body": "<p>One of possible ways is a using <a href=\"http://guava-libraries.googlecode.com/svn/tags/release09/javadoc/com/google/common/base/Joiner.html\">Joiner</a> from <a href=\"http://code.google.com/p/guava-libraries/\">Google Guava library</a>:</p>\n\n<pre><code>result = Joiner.on(\", \").join(paramList);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-19T10:20:12.093",
"Id": "1976",
"ParentId": "1973",
"Score": "36"
}
},
{
"body": "<p>A couple of alternate options here - any of such can simply only resolve to making the intentions clear, although it's hardly an issue.</p>\n\n<p>It might be a little clearer, albeit not much, using <code>lastIndexOf</code>:</p>\n\n<pre><code>String withoutLastComma = result.substring(0, result.lastIndexOf(\",\"));\n</code></pre>\n\n<p>Or just refactor a little, which could be more explanatory:</p>\n\n<pre><code>StringBuilder result = new StringBuilder();\nfor (int i = 0; i < paramList.size(); i++)\n{ \n result.append(paramList.get(i));\n if (i + 1 != paramList.size())\n result.append(\", \");\n}\nSystem.err.println(result);\n</code></pre>\n\n<p>Or, lastly, use a string utility library as linked in other answers provided; though, the thought of doing so brings the term <em>'sledgehammer to crack a nut'</em> to mind, but it might well be justified depending on what other operations you require to carry out.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-19T12:23:25.893",
"Id": "3289",
"Score": "1",
"body": "This makes the code more complex. Replacing the foreach with a for statement makes it a bit more complex. However your solution works and is correct, but you have to make sure not bringing in extra complexity."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-19T12:27:04.360",
"Id": "3290",
"Score": "0",
"body": "I would argue that complexity in such a trivial construct is far, far from being reached (though understand where you're coming from in terms of _'more complex'_) - it is clear and self-explanatory for the everyday / professional programmer (IMO). Even just the following of the original warrants such changes, I think: `( 0, result.length( ) - \", \".length( ) );` And, thanks for the input. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-20T08:08:30.500",
"Id": "3312",
"Score": "0",
"body": "for this sample you are right. But imagine a scenario with a couple of nested loops. In that case you get something like result[i].result[j].result[k]. In those cases a foreach might be a more readable solution because it is easy to make a small mistake like using 1 instead of i or mixup the i,j & k variable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-20T08:36:15.923",
"Id": "3314",
"Score": "0",
"body": "@Gertjan: I agree, luckily we're not in that situation here. ;)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-19T10:29:40.693",
"Id": "1977",
"ParentId": "1973",
"Score": "13"
}
},
{
"body": "<p>I believe it's better to know how to write it <em>and then</em> use a library. I usually prefer to make a check <em>before</em> the loop, thus avoiding to have to check every time in the loop:</p>\n\n<pre><code>int size = paramList.size();\nif (size > 0) {\n result.append(paramList.get(0));\n for (int i = 1; i < size; ++i) {\n result.append(\", \").append(paramList.get(i));\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-12-05T10:54:38.077",
"Id": "280148",
"Score": "2",
"body": "Now you have two lines where you append your items to your result, instead of one. This is bad style. Don't duplicate lines for the sake of easiness. It will make it harder to maintain this code properly and faultlessly."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-19T12:08:25.103",
"Id": "1979",
"ParentId": "1973",
"Score": "45"
}
},
{
"body": "<pre><code>String listString = Arrays.toString(paramList.toArray());\nSystem.err.println( listString );\n</code></pre>\n\n<p>Will return:</p>\n\n<pre><code>[param1, param2]\n</code></pre>\n\n<p>This has the added benefit of using the String.valueOf(object) method which will print 'null' in the case of null objects. The Arrays.toString() method is also pretty straight forward if you just want to reimplement it.\nRemoving the brackets:</p>\n\n<pre><code> int iMax = paramList.size() - 1;\n if (iMax == -1) {\n return \"\";\n }\n String[] params = paramList.toArray();\n StringBuilder b = new StringBuilder();\n for (int i = 0; ; i++) {\n String param = params[i];\n b.append(param);\n if (i == iMax) {\n return b.toString();\n }\n b.append(\", \");\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-19T15:57:00.053",
"Id": "2479",
"ParentId": "1973",
"Score": "4"
}
},
{
"body": "<p>That's strange that nobody has mentioned iterator-wise approach so far. </p>\n\n<p>So here it goes:</p>\n\n<pre><code>public static <E> String join(Iterable<E> iterable, String delim) {\n Iterator<E> iterator = iterable.iterator();\n if (!iterator.hasNext()) {\n return \"\";\n }\n\n StringBuilder builder = new StringBuilder(iterator.next().toString());\n while (iterator.hasNext()) {\n builder.append(delim).append(iterator.next().toString());\n }\n\n return builder.toString();\n}\n</code></pre>\n\n<p>No messing with indexes, substringing, etc, etc.</p>\n\n<p>And let's use it:</p>\n\n<pre><code>List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7);\nSystem.out.println(join(list, \", \"));\n</code></pre>\n\n<p><strong>Update:</strong>\nNPE-safe approach would be avoid using <code>toString()</code> on <code>next()</code> (thanks @David Harkness):</p>\n\n<pre><code>public static <E> String join(Iterable<E> iterable, String delim) {\n Iterator<E> iterator = iterable.iterator();\n if (!iterator.hasNext()) {\n return \"\";\n }\n\n StringBuilder builder = new StringBuilder(iterator.next());\n while (iterator.hasNext()) {\n builder.append(delim).append(iterator.next());\n }\n\n return builder.toString();\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-18T21:10:06.753",
"Id": "88161",
"Score": "5",
"body": "There's no need for the `toString()` calls on the elements since `StringBuilder` does that automatically. Plus you're risking an NPE."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-07T20:51:34.173",
"Id": "21443",
"ParentId": "1973",
"Score": "20"
}
},
{
"body": "<p>What I use is a variable that I initialize as empty and then set inside the loop.</p>\n\n<pre><code>List<String> paramList = new ArrayList<String>( );\nparamList.add(\"param1\");\nparamList.add(\"param2\");\n\nString separator = \"\";\n\nStringBuilder result = new StringBuilder();\nfor (String p : paramList)\n{\n result.append(separator)\n result.append(p);\n separator = \", \";\n}\n\nSystem.err.println(result.toString());\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-04T15:16:21.550",
"Id": "60169",
"Score": "0",
"body": "I often use this for languages without \"join\" functions, like PL/SQL..."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-27T19:16:44.870",
"Id": "24440",
"ParentId": "1973",
"Score": "16"
}
},
{
"body": "<p>I like this technique:</p>\n\n<pre><code>private String join(Iterable<?> items, String sep) {\n Iterator<?> iter = items.iterator();\n if (!iter.hasNext()) {\n return \"\";\n }\n\n StringBuilder builder = new StringBuilder();\n builder.append(iter.next());\n while (iter.hasNext()) {\n builder.append(sep).append(iter.next());\n }\n\n return builder.toString();\n}\n</code></pre>\n\n<p>What I like about it is there is no wasted <code>if</code> condition inside the loop.</p>\n\n<p>Here are some unit tests to go with it:</p>\n\n<pre><code>@Test\npublic void testEmptyCollection() {\n Assert.assertTrue(join(Collections.emptyList(), \", \").isEmpty());\n}\n\n@Test\npublic void testJoinSingleItem() {\n String item = \"hello\";\n Assert.assertEquals(item, join(Collections.singletonList(item), \", \"));\n}\n\n@Test\npublic void testJoinTwoItems() {\n Integer item1 = 4;\n Integer item2 = 9;\n String sep = \", \";\n String expected = item1 + sep + item2;\n Assert.assertEquals(expected, join(Arrays.asList(item1, item2), sep));\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-18T21:12:52.830",
"Id": "88162",
"Score": "1",
"body": "Then you'll love [Alexey's answer](http://codereview.stackexchange.com/a/21443/1635) above. ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-18T21:46:05.823",
"Id": "88169",
"Score": "1",
"body": "Ah, too many answers, I overlooked that one. Normally I would have just left some suggestions in comments, instead of a full-blown answer. Too late now, I'll just keep this anyway, for the few small extras I added."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-18T20:39:41.703",
"Id": "51088",
"ParentId": "1973",
"Score": "7"
}
},
{
"body": "<p>Java 8 provides a <code>String.join()</code> method, so you can do it without depending on an external library.</p>\n\n<pre><code>List<String> paramList = new ArrayList<String>();\nparamList.add(\"param1\");\nparamList.add(\"param2\");\n\nString withoutLastComma = String.join(\", \", paramList);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-31T03:40:25.280",
"Id": "105189",
"Score": "0",
"body": "This answer is [being discussed on meta](http://meta.codereview.stackexchange.com/questions/2169/new-answers-on-old-questions-using-new-language-features)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-31T09:09:05.933",
"Id": "105259",
"Score": "0",
"body": "Thanks for the explanation @rolfl. Sorry, I didn't notice the question was so old. :("
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-10-20T15:18:58.070",
"Id": "198652",
"Score": "1",
"body": "On a realated note you can use `Collectors.joining()` as well."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-03T16:31:38.737",
"Id": "477605",
"Score": "0",
"body": "There was a [proposed edit](https://codereview.stackexchange.com/review/suggested-edits/132527) for this answer which was rejected but could be a viable solution - it [appears to have the same output](https://onlinegdb.com/ByO-gLS38)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-31T03:14:48.847",
"Id": "58588",
"ParentId": "1973",
"Score": "71"
}
},
{
"body": "<p>Surprised no one has contributed a unit test specification:</p>\n\n<ul>\n<li>a useful result should contain <code>max(0, paramList.length() - 1)</code> commas.</li>\n<li>a robust solution should not throw <code>IndexOutOfBoundsException</code> if the list is empty.</li>\n<li>an efficient solution would provide a realistic <code>StringBuilder</code> capacity estimate.</li>\n</ul>\n\n<p>The result can be misleading or useless if any parameter contains a comma. Java8 <code>String.join</code> should be redesigned to flag this \"delimiter collision\" possibility at compile time, and only accept strings to be joined that can be split again afterwards because they have already been escaped or quoted or do not or cannot contain the delimiter.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-31T19:26:26.270",
"Id": "407235",
"Score": "0",
"body": "There are a few problems with this (old) answer: 1. This would greatly decrease performance. 2. This is usually unnecessary. 3. \"Can be split again\" might rely on heuristics which can lead to random errors. 4. There is not necessarily a good way to fix the error flagged."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-30T08:54:42.767",
"Id": "61543",
"ParentId": "1973",
"Score": "4"
}
},
{
"body": "<p>As an alternative of manually going through the loop to construct the comma-separated contents of the List, you can take advantage of the List's <code>toString()</code> method alongside with <code>substring</code> method of <code>String.</code> </p>\n\n<pre><code>String contents = paramList.toString(); //returns [param 1, param2]\n\n//remove `[` and `]`\nSystem.out.println(contents.substring(1, contents.length()-1));\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-01T03:50:23.427",
"Id": "64344",
"ParentId": "1973",
"Score": "2"
}
},
{
"body": "<p>Here's a more efficient alternative to the <code>delete</code> method, which just breaks the <code>StringBuilder</code> <a href=\"https://stackoverflow.com/questions/5192512/how-can-i-clear-or-empty-a-stringbuilder\">without asking</a> for chars or positions:</p>\n\n<pre><code>@Test\npublic void appendTest (){\n final String comma = \", \";\n\n List<String> paramList = new ArrayList<>();\n paramList.add( \"param1\" );\n paramList.add( \"param2\" );\n\n StringBuilder result = new StringBuilder();\n for (String s : paramList) {\n result.append(s).append(comma);\n }\n if (!paramList.isEmpty()){\n result.setLength(result.length() - comma.length());\n }\n\n System.out.println(result);\n\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-11-28T19:01:55.000",
"Id": "148377",
"ParentId": "1973",
"Score": "2"
}
},
{
"body": "<p>If you are using java 8, you can use <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/StringJoiner.html\" rel=\"noreferrer\">StringJoiner</a> like;</p>\n\n<pre><code>StringJoiner sj = new StringJoiner(\",\");\nfor ( String p : paramList )\n{\n sj.add(p);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-20T13:02:13.700",
"Id": "196889",
"ParentId": "1973",
"Score": "4"
}
},
{
"body": "<p>When we use stream we do have more flexibility, like<br />\n<code>map</code> ⟶ convert any array object to string<br />\n<code>filter</code> ⟶ remove when it is empty<br />\n<code>join</code> ⟶ add joining character</p>\n<pre><code> //Deduplicate the comma character in the input string\n String[] splits = input.split("\\\\s*,\\\\s*");\n return Arrays.stream(splits).filter(StringUtils::isNotBlank).collect(Collectors.joining(", "));\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-02T06:24:17.630",
"Id": "258998",
"ParentId": "1973",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "1975",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-19T09:36:47.943",
"Id": "1973",
"Score": "164",
"Tags": [
"java",
"strings"
],
"Title": "Remove Last Comma"
} | 1973 |
<p>Could someone review an <a href="https://stackoverflow.com/questions/5644093/returning-first-result-where-case-result-x/5680184#5680184">accepted answered</a> I gave on Stack Overflow?</p>
<p>The use-case is as follows:</p>
<blockquote>
<p>Given a messaging system where a user
can receive a message from a single
user and send messages to one or more
users, return the most recent
communication (sent or received)
between a passed userId and the
individual(s) that user communicated
with.</p>
</blockquote>
<p>For the example, I have three tables:</p>
<p><strong>Users</strong></p>
<blockquote>
<pre class="lang-none prettyprint-override"><code>id user_name
1 Walker
2 John
3 Kate
</code></pre>
</blockquote>
<p><strong>Messages</strong></p>
<blockquote>
<pre class="lang-none prettyprint-override"><code>id senderid body time
1 1 ignored 1 2010-04-01 00:00:00.000
2 1 ignored 2 2010-04-02 00:00:00.000
3 3 ignored 3 2010-04-03 00:00:00.000
4 1 msg A to john and kate 2010-04-10 00:00:00.000
5 3 msg b from kate to walker and john 2010-04-11 00:00:00.000
</code></pre>
</blockquote>
<p><strong><code>messages_recipients</code></strong></p>
<blockquote>
<pre class="lang-none prettyprint-override"><code>id messageid userid
1 1 2
2 1 3
3 2 2
4 3 1
5 4 2
6 4 3
7 5 1
8 5 2
</code></pre>
</blockquote>
<p>The data is tailored in such a way that I want a list of communications between user Walker and the people Walker has spoken with. </p>
<p>You can see a list of these messages by running the following SQL statement:</p>
<pre class="lang-sql prettyprint-override"><code>SELECT
u2.user_name AS Sender,
u1.user_name AS Receiver,
m.body,
m.time
FROM
messages m
JOIN
messages_recipients mr ON m.id = mr.messageid
JOIN
users u1 ON mr.userid = u1.id
JOIN
users u2 ON m.senderid = u2.id
ORDER BY
time DESC
</code></pre>
<p>Now that we have the test scenario, the part I want reviewed: returning the most recently communicated message between Walker, John, and Kate.</p>
<pre class="lang-sql prettyprint-override"><code>BEGIN
DECLARE @UserId INT = 1
--A. Main Query
SELECT
CASE
WHEN mtemp.senderid = 1 --@UserId
THEN
CONCAT('Message To: ', receivers.user_name)
ELSE
CONCAT('Message From: ' , senders.user_name)
END AS MessageType,
mtemp.body,
mtemp.time
FROM
messages mtemp
INNER JOIN users senders ON
mtemp.senderid = senders.id
INNER JOIN
(
--B. Inner Query determining most recent message (based on time)
-- between @UserID and the person @UserID
-- Communicated with (either as sender or receiver)
select userid,max(maxtime) as maxmaxtime from
(
--C.1. First part of Union Query Aggregating sent/received messages on passed @UserId
SELECT
m2.body,
kk.*
FROM
`messages` m2 INNER JOIN
(
SELECT DISTINCT
userid,
MAX(m.time) AS MaxTime
FROM
messages m INNER JOIN
messages_recipients mr ON m.id = mr.messageid AND
m.senderid = 1 --@UserId
GROUP BY
mr.userid
) kk on m2.time = kk.MaxTime and m2.senderid = 1 --@UserId
UNION
--C.2. Second part of Union Query Aggregating sent/received messages on passed @UserId
SELECT
m1.body,
jj.*
FROM
`messages` m1 INNER JOIN
----C.2a. Inner most query of users users who sent message to userid
(SELECT DISTINCT
senderid as userid,
MAX(m.time) AS MaxTime
FROM
messages m INNER JOIN
messages_recipients mr ON m.id = mr.messageid AND
mr.userid = 1 --@UserId
GROUP BY
m.senderid) jj on m1.time = jj.MaxTime and m1.senderid = jj.userid
) MaximumUserTime
group by
MaximumUserTime.userid
) AggregatedData on mtemp.time = AggregatedData.maxmaxtime
INNER JOIN users receivers on AggregatedData.userid = receivers.id
ORDER BY `time` DESC
END
</code></pre>
<p>To test in <code>phpMyAdmin</code>, you'll have to remove the comments and the <code>BEGIN</code>/<code>END</code> <code>DECLARE</code> statements as well. I just wanted to post this as if it would look in a procedure.</p>
<p>When I run this query I get the following results:</p>
<blockquote>
<pre class="lang-none prettyprint-override"><code>MessageType body time
Message From: Kate msg b from kate to walker and john 2010-04-11 00:00:00.000
Message To: John msg A to john and kate 2010-04-10 00:00:00.000
</code></pre>
</blockquote>
<p>That's the most recent communications concerning Walker among all those users who have communicated with Walker.</p>
<p>Is there a better way to run this query?</p>
| [] | [
{
"body": "<p>My solution has a similar complexity to yours (14 steps in <code>EXPLAIN</code>), assuming MySQL's query optimizer is smart enough. However, in my opinion, this formulation will be much easier to understand.</p>\n\n<pre><code>SELECT IF(recipientid,\n CONCAT('Message To: ', recipient.user_name),\n CONCAT('Message From: ', sender.user_name)) AS MessageType,\n body,\n time\n FROM\n ( -- Join messages with recipients, relabeling userids in terms of interlocutor and self\n SELECT messageid, time, body, NULL AS senderid, userid AS recipientid, userid AS interlocutor, senderid AS self\n FROM messages_recipients\n INNER JOIN messages\n ON messages.id = messageid\n UNION\n SELECT messages.id, time, body, senderid, NULL, senderid, userid\n FROM messages_recipients\n INNER JOIN messages\n ON messages.id = messageid\n ) AS thread_latest\n LEFT OUTER JOIN users AS recipient\n ON recipient.id = recipientid\n LEFT OUTER JOIN users AS sender\n ON sender.id = senderid\n WHERE\n -- Discard all but the latest message in each thread\n NOT EXISTS (\n SELECT messageid\n FROM\n (\n SELECT messageid, time, userid AS interlocutor, senderid AS self\n FROM messages_recipients\n INNER JOIN messages\n ON messages.id = messageid\n UNION\n SELECT messages.id, time, senderid, userid\n FROM messages_recipients\n INNER JOIN messages\n ON messages.id = messageid\n ) AS thread_later\n WHERE\n thread_later.self = thread_latest.self AND\n thread_later.interlocutor = thread_latest.interlocutor AND\n thread_later.time > thread_latest.time\n ) AND\n self = 1 --@UserId\n ORDER BY time DESC;\n</code></pre>\n\n<p>The main insight is that once you relabel senders and recipients in terms of interlocutor and self, it's just a simple matter of filtering out the results. Retain only those messages where <code>self</code> is the user in question. Then, every row that has the same <code>interlocutor</code> conceptually constitutes a thread.</p>\n\n<p>Notice that there is a subquery that appears twice. We can make it clearer by creating a view.</p>\n\n<pre><code>CREATE VIEW threads AS\n -- Messages I sent\n SELECT messageid, time, body, NULL AS senderid, userid AS recipientid, userid AS interlocutor, senderid AS self\n FROM messages_recipients\n INNER JOIN messages\n ON messages.id = messageid\n UNION\n -- Messages I received\n SELECT messages.id, time, body, senderid, NULL, senderid, userid\n FROM messages_recipients\n INNER JOIN messages\n ON messages.id = messageid;\n\nSELECT IF(recipientid,\n CONCAT('Message To: ', recipient.user_name),\n CONCAT('Message From: ', sender.user_name)) AS MessageType,\n body,\n time\n FROM\n threads AS thread_latest\n LEFT OUTER JOIN users AS recipient\n ON recipient.id = recipientid\n LEFT OUTER JOIN users AS sender\n ON sender.id = senderid\n WHERE\n NOT EXISTS (\n SELECT messageid\n FROM threads AS thread_later\n WHERE\n thread_later.self = thread_latest.self AND\n thread_later.interlocutor = thread_latest.interlocutor AND\n thread_later.time > thread_latest.time\n ) AND\n self = 1 --@UserId\n ORDER BY time DESC;\n</code></pre>\n\n<hr>\n\n<p>I'll take this opportunity to point out that this query is where PostgreSQL really shines. Two features in PostgreSQL (since version 8.4) make it easy. The <a href=\"http://www.postgresql.org/docs/8.4/interactive/queries-with.html\"><code>WITH</code> clause</a> lets you define a helper view in the query itself. More importantly, \n<a href=\"http://www.postgresql.org/docs/8.4/interactive/tutorial-window.html\">window functions</a> let you partition the threads by interlocutor, which is precisely the tricky part about this problem.</p>\n\n<pre><code>WITH threads(messageid, time, body, senderid, recipientid, interlocutor, self) AS (\n -- Messages I sent\n SELECT messageid, time, body, NULL, userid, userid, senderid\n FROM messages_recipients\n INNER JOIN messages\n ON messages.id = messageid\n UNION\n -- Messages I received\n SELECT messages.id, time, body, senderid, NULL, senderid, userid\n FROM messages_recipients\n INNER JOIN messages\n ON messages.id = messageid\n)\nSELECT CASE WHEN recipientid IS NOT NULL\n THEN 'Message To: ' || recipient.user_name\n ELSE 'Message From: ' || sender.user_name\n END AS MessageType,\n body,\n time\n FROM (\n SELECT *,\n RANK() OVER (PARTITION BY interlocutor ORDER BY time DESC) AS thread_pos\n FROM threads\n WHERE self = 1 --@UserId\n ) AS my_threads\n LEFT OUTER JOIN users AS recipient\n ON recipient.id = recipientid\n LEFT OUTER JOIN users AS sender\n ON sender.id = senderid\n WHERE thread_pos = 1 -- Only the latest message per thread\n ORDER BY time DESC;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T15:32:16.383",
"Id": "47289",
"Score": "0",
"body": "Thanks for taking the time to give a detailed answer to this 2+ year old question."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T10:12:24.973",
"Id": "29833",
"ParentId": "1981",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "29833",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-19T14:24:10.287",
"Id": "1981",
"Score": "6",
"Tags": [
"sql",
"mysql"
],
"Title": "Retrieving the most recent communication from a user"
} | 1981 |
<p>I needed to write code in WPF for a client. The application is done with prism (not my decision, they already had people working on it), so I got a sparkling clean new module to work in. Since this was my first time writing WPF code going to production, I wanted to handle the code in a good manner. I decided to go MVVM.</p>
<p>I structured the module as follows (I do need to move the <code>RelayCommand</code> and <code>ViewModelBase</code>):</p>
<ul>
<li>Services (<code>IItemTypeService.cs</code>, <code>ItemTypeService.cs</code>)</li>
<li>ViewModels (<code>ItemTypeViewModel.cs</code>, <code>ItemTypeViewModel.cs</code>, <code>RelayCommand.cs</code>, <code>ViewModelBase.cs</code>)</li>
<li>Views (<code>ItemTypeAdminView.xaml</code>, <code>ItemTypeDetailView.xaml</code>)</li>
</ul>
<p>The <code>ViewModelBase</code> implements <code>INotifyPropertyChanged</code>.</p>
<p>The <code>ItemTypeAdminView</code> is the main view. <code>ItemTypeDetailView</code> is a user control and is put into the <code>ItemTypeAdminView</code>. The <code>ItemTypeAdminView</code> will in the future be expanded with other sections, and those sections will use the same information as the <code>ItemTypeDetailView</code>.</p>
<p>Therefore, I made a <code>ViewModel</code> for the <code>ItemTypeAdminView</code>, not for the <code>ItemTypeDetailView</code>. Every <code>ItemType</code> is coming from Linq2SQL (yes, I know about EF - I wasn't involved in this part), and is wrapped in a <code>ItemTypeViewModel</code> so it can implement the <code>INotifyPropertyChanged</code>.</p>
<p>The code for the <code>ItemTypeAdminViewModel</code>:</p>
<pre><code>public class ItemTypeAdminViewModel : ViewModelBase
{
#region private fields
private ICollectionView collectionView;
private IItemTypeService itemTypeService;
#endregion
#region automatic properties
public ObservableCollection<ItemTypeViewModel> ItemTypes { get; private set; }
public IEnumerable<Company> Companies { get; private set; }
public IEnumerable<CompanyGTIN> CompanyGTINs { get; private set; }
private Company selectedCompany;
public Company SelectedCompany
{
get { return selectedCompany; }
set
{
selectedCompany = value;
LoadCompanyGTINs();
}
}
#endregion properties
#region constructors
public ItemTypeAdminViewModel(IItemTypeService itemTypeService)
{
this.itemTypeService = itemTypeService;
Initialize();
}
#endregion
#region private methods
private void Initialize()
{
//Should I wrap in Try/Catch? Try/Catch is expensive, must find something else...
ItemTypes = new ObservableCollection<ItemTypeViewModel>(itemTypeService.GetItemTypes());
Companies = itemTypeService.GetCompanies();
collectionView = CollectionViewSource.GetDefaultView(ItemTypes);
}
private void LoadCompanyGTINs()
{
CompanyGTINs = itemTypeService.GetCompanyGTINs(selectedCompany.ID);
OnPropertyChanged("CompanyGTINs");
}
#endregion
#region commands
public ICommand GoToFirstItemType
{
get
{
return new RelayCommand(() => collectionView.MoveCurrentToFirst(),
() => collectionView.CurrentPosition >= 1);
}
}
public ICommand GoToLastItemType
{
get
{
return new RelayCommand(() => collectionView.MoveCurrentToLast(),
() => collectionView.CurrentPosition < (ItemTypes.Count - 1));
}
}
public ICommand NextItemType
{
get
{
LoadCompanyGTINs();
return new RelayCommand(() => collectionView.MoveCurrentToNext(),
() => collectionView.CurrentPosition < (ItemTypes.Count - 1));
}
}
public ICommand PreviousItemType
{
get
{
return new RelayCommand(() => collectionView.MoveCurrentToPrevious(),
() => collectionView.CurrentPosition >= 1);
}
}
#endregion
}
</code></pre>
<p>And the code for the <code>ItemTypeDetailView</code> XAML:</p>
<pre><code><Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid DataContext="{Binding ItemTypes}">
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TextBlock Text="Name:" />
<TextBox Grid.Column="2" Text="{Binding Name}" />
<TextBlock Grid.Row="1" Text="Description:" />
<TextBox Grid.Column="1" Grid.Row="1" Text="{Binding Description}" />
<TextBlock Grid.Row="2" Text="Manufacturer:" />
<ComboBox Grid.Column="1" Grid.Row="2"
DisplayMemberPath="Name"
ItemsSource="{Binding Path=DataContext.Companies, RelativeSource={RelativeSource FindAncestor, AncestorType=UserControl, AncestorLevel=2}}"
Name="ManufacturerComboBox"
SelectedItem="{Binding Mode=TwoWay, Path=DataContext.SelectedCompany, RelativeSource={RelativeSource FindAncestor, AncestorType=UserControl, AncestorLevel=2}}"
SelectedValue="{Binding ManufacturerID}"
SelectedValuePath="ID" />
<TextBlock Grid.Row="10" Text="Manufacturer Product Code:"/>
<TextBox Grid.Column="1" Grid.Row="10" Text="{Binding ManufacturerProductCode}" />
<TextBlock Grid.Row="11" Text="Manufacturer Product GS1 Code:"/>
<TextBox Grid.Column="1" Grid.Row="11" Text="{Binding ManufacturerProductGS1Code}" />
<TextBlock Grid.Row="12" Text="GS1GTINID:"/>
<ComboBox DisplayMemberPath="GTIN"
Grid.Column="1" Grid.Row="12"
IsSynchronizedWithCurrentItem="True"
ItemsSource="{Binding Path=DataContext.CompanyGTINs, RelativeSource={RelativeSource FindAncestor, AncestorType=UserControl, AncestorLevel=2}}"
SelectedValue="{Binding GS1GTINID}"
SelectedValuePath="ID" />
</Grid>
<Grid Grid.Row="2">
<StackPanel Grid.Row="4" Orientation="Horizontal">
<Button Command="{Binding GoToFirstItemType}">&lt;&lt;</Button>
<TextBlock Margin="5,0,5,0" />
<Button Command="{Binding PreviousItemType}">&lt;</Button>
<TextBlock Margin="5,0,5,0" />
<Button Command="{Binding NextItemType}">&gt;</Button>
<TextBlock Margin="5,0,5,0" />
<Button Command="{Binding GoToLastItemType}">&gt;&gt;</Button>
<TextBlock Margin="5,0,5,0" />
<Button Command="{Binding New}">New</Button>
</StackPanel>
</Grid>
</Grid>
</code></pre>
<p>I am really curious about what could be improved structure/code wise and/or what should be left out.</p>
| [] | [
{
"body": "<p>ViewModel generally looks good though I would still propose some changes: </p>\n\n<ol>\n<li><p>I do not see why do you need <code>collectionView</code> field. You're moving it's <code>CurrentItem</code> but neither it nor the entire view is exposed anywhere. </p></li>\n<li><p><code>public ICommand NextItemType</code>. Why do you have <code>LoadCompanyGTINs()</code> call here? You have several similar <code>Move...</code> methods but only here you have this call.</p></li>\n</ol>\n\n<hr>\n\n<p>Regarding View: </p>\n\n<ol>\n<li><p>You have strange layout in the inner <code>Grid</code>. It has two columns but you're setting inner <code>Grid.Control</code> attached properties to <code>1</code> and <code>2</code> instead of <code>0</code> and <code>1</code> </p></li>\n<li><p>Generally <code>Bindings</code> in your view look <strong>VERY</strong> strange. First of all I would recommend never ever bind <code>DataContext</code> inside view (<code><Grid DataContext=\"{Binding ItemTypes}\"></code>). If something inside view has separate <code>DataContext</code> then it should be a separate <code>View+ViewModel</code>. Because of this binding you have to use <code>RelativeSource</code> inside for some other controls which is not good. The bindings inside first grid which do not have <code>RelativeSource</code> also look strange. For example <code><TextBox Grid.Column=\"2\" Text=\"{Binding Name}\" /></code>. With such binding I think it tries to locate a <code>Name</code> property on <code>ItemTypes</code> collection but this is an <code>ObservableCollection</code> which doesn't have such property so it should not work. The same about <code>Description</code>. </p></li>\n<li><p>If you really need <code>RelativeSource</code> then at least try to avoid using it with <code>RelativeSource={RelativeSource FindAncestor, AncestorType=UserControl, AncestorLevel=2}</code>. I've tried to guess what will be the result <code>Source</code> for binding but had no luck. I would recommend using something like <code>RelativeSource={RelativeSource FindAncestor, AncestorType=local:ItemTypeDetailView}</code> instead.</p></li>\n</ol>\n\n<p>Generally I would insist only on getting rid of those weird bindings in your View, the rest is more or less ok.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-19T18:07:01.053",
"Id": "3300",
"Score": "0",
"body": "Thank you for your review :-) **1)** I don't think I get this one. I use a field so that the commands (first, next, previous, last) can access that. **2)** You're right. That shouldn't belong there at all. I put it there to check something out and got sidetracked. **3)** Again - this was indeed wrong. Fixed it. **4)** You'd be right to think that `Text=\"Binding Name\"` gets it from the ItemTypes collection, because that's what the containing `Grid`'s datacontext is set to. ObservableCollection indeed does not have a `Name` property, but the ItemTypes that are contained in it do."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-19T18:11:38.697",
"Id": "3301",
"Score": "0",
"body": "**4) Cont'd** What I wanted to do here is not to have a ViewModel for the ItemTypesDetailView, but move everything up one level. Hence, the ItemTypes collection is in ItemTypeAdminViewModel and not have a ItemTypesDetailViewModel that has the ItemTypes collection in it. The reason for this is that there will be other User Controls that will also need some of the information of ItemTypes.\n **5)** I had to use `AncestorLevel=2` here because Prism modules do not have a Main Window, just a... eh.. 'Main' user control."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-19T17:54:31.050",
"Id": "1985",
"ParentId": "1983",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-19T15:00:48.820",
"Id": "1983",
"Score": "7",
"Tags": [
"c#",
"wpf",
"mvvm",
"xaml"
],
"Title": "View Model Base"
} | 1983 |
<p><a href="http://www.ruby-lang.org/" rel="nofollow">Ruby</a> is an open-source, dynamic, object-oriented, interpreted language that combines the good bits from Perl, Smalltalk, and Lisp. Its primary purpose is to "help every programmer in the world to be productive, and to enjoy programming, and to be happy." Ruby focuses on simplicity and productivity.</p>
<p>Ruby was initially conceived on February 24, 1993 by <a href="http://en.wikipedia.org/wiki/Yukihiro_Matsumoto" rel="nofollow">Yukihiro Matsumoto</a> ('Matz'), and version 1.0 was released in 1996. The current stable version is <a href="http://en.wikipedia.org/wiki/Ruby_%28programming_language%29#Ruby_2.2" rel="nofollow">2.2.2</a>.</p>
<p>Ruby's mindshare spiked around 2005 due to Ruby on Rails, an MVC (Model, View, Controller) framework for building web applications, and usage continues to grow as of 2013 with Ruby continuing to find acceptance in the commercial marketplace.</p>
<p>Ruby supports multiple programming paradigms, including functional, object oriented and imperative. It also has a dynamic type system and automatic memory management; it is therefore similar in varying respects to Smalltalk, Python, Perl, Lisp, Dylan, and CLU.</p>
<p>You can download the Ruby source code from <a href="http://www.ruby-lang.org/en/downloads/" rel="nofollow">ruby-lang.org</a> or from <a href="https://github.com/ruby/ruby" rel="nofollow">GitHub</a>.</p>
<h2>Naming Conventions<sup><a href="http://rubylearning.com/satishtalim/ruby_names.html" rel="nofollow">1</a></sup></h2>
<p><strong>Ruby Names</strong> are used to refer to constants, variables, methods, classes, and modules. <em>The first character of a name helps Ruby to distinguish its intended use.</em> Certain names are reserved words and should not be used as variable, method, class, or module name. Lowercase letter means the characters "a" through "z". Uppercase letter means "A" through "Z", and digit means "0" through "9". A name is an uppercase letter, lowercase letter, or an underscore ("_"), followed by <strong><em>Name characters</em></strong> (this is any combination of upper- and lowercase letters, underscore and digits).</p>
<p><strong>Variables</strong></p>
<p>Variables in Ruby can contain data of any type. You can use variables in your Ruby programs <em>without any declarations</em>. Variable name itself denotes its scope (local, global, instance, etc.).</p>
<ul>
<li>A <strong>local</strong> variable (declared within an object) name consists of a lowercase letter (or an underscore) followed by name characters (<code>sunil</code>, <code>_z</code>, <code>hit_and_run</code>).</li>
<li>An <strong>instance</strong> variable (declared within an object always "belongs to" whatever object <strong>self</strong> refers to) name starts with an "at" sign (<code>@</code>) followed by a <em>name</em> (<code>@sign</code>, <code>@_</code>, <code>@Counter</code>).</li>
<li>A <strong>class</strong> variable (declared within a class) name starts with two "at" signs (<code>@@</code>) followed by a <em>name</em> (<code>@@sign</code>, <code>@@_</code>, <code>@@Counter</code>). A class variable is shared among all objects of a class. Only one copy of a particular class variable exists for a given class. Class variables used at the top level are defined in <strong>Object</strong> and behave like global variables. <em>Class variables are rarely used in Ruby programs</em>.</li>
<li><strong>Global</strong> variables start with a dollar sign (<code>$</code>) followed by name characters. A global variable name can be formed using <code>$-</code> followed by any single character (<code>$counter</code>, <code>$COUNTER</code>, <code>$-x</code>). Ruby defines a number of global variables that include other punctuation characters, such as <code>$_</code> and <code>$-K</code>.</li>
</ul>
<p><strong>Constants</strong></p>
<p>A <strong>constant</strong> name starts with an uppercase letter followed by name characters. Class names and module names are constants, and follow the constant naming conventions. Examples: <code>module MyMath</code>, <code>PI=3.1416</code>, <code>class MyPune</code>.</p>
<p><strong>Method Names</strong></p>
<p><strong>Method</strong> names should begin with a lowercase letter (or an underscore). <code>?</code>, <code>!</code> and <code>=</code> are the only weird characters allowed as method name suffixes (<code>!</code> or <strong>bang</strong> labels a method as dangerous - specifically, as the dangerous equivalent of a method with the same name but without the bang)</p>
<p>Knowledge Base:</p>
<ul>
<li><a href="http://apidock.com/ruby" rel="nofollow">API (APIdock)</a></li>
<li><a href="http://tryruby.org/" rel="nofollow">Try Ruby</a></li>
</ul>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-19T18:30:15.843",
"Id": "1986",
"Score": "0",
"Tags": null,
"Title": null
} | 1986 |
Ruby is a multi-platform, open-source, dynamic, object-oriented, interpreted language created by Yukihiro Matsumoto (Matz) in 1993. | [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-19T18:30:15.843",
"Id": "1987",
"Score": "0",
"Tags": null,
"Title": null
} | 1987 |
<p><strong>Ruby on Rails</strong> is an open-source web framework that's optimized for programmer happiness and sustainable productivity. It lets you write beautiful code by favouring convention over configuration.</p>
<ul>
<li><a href="http://rubyonrails.org/" rel="nofollow">Ruby on Rails website</a></li>
<li><a href="http://weblog.rubyonrails.org/" rel="nofollow">Riding Rails official blog</a></li>
<li><a href="http://api.rubyonrails.org/" rel="nofollow">API documentation</a></li>
<li><a href="http://apidock.com/" rel="nofollow">Collaborative API documentation</a></li>
<li><a href="http://railsapi.com/" rel="nofollow">Rails Searchable API Doc</a></li>
<li><a href="http://guides.rubyonrails.org/" rel="nofollow">Rails Guides</a></li>
<li><a href="http://screencasts.com/" rel="nofollow">Rails Screencasts</a></li>
<li><a href="http://github.com/rails/rails/" rel="nofollow">Rails Source Code</a></li>
<li><a href="https://rails.lighthouseapp.com/projects/8994-ruby-on-rails" rel="nofollow">Rails Lighthouse Issue Tracker</a></li>
</ul>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-19T18:34:49.847",
"Id": "1988",
"Score": "0",
"Tags": null,
"Title": null
} | 1988 |
Ruby on Rails is an open-source web development framework written in Ruby. If your question code is written in Ruby on Rails, tag with Ruby as the language tag. Many things are defined by convention, freeing you from having to re-invent things to stay productive. | [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-19T18:34:49.847",
"Id": "1989",
"Score": "0",
"Tags": null,
"Title": null
} | 1989 |
<p><a href="https://www.python.org/" rel="nofollow noreferrer">Python</a> is a <a href="https://wiki.python.org/moin/Why%20is%20Python%20a%20dynamic%20language%20and%20also%20a%20strongly%20typed%20language" rel="nofollow noreferrer">dynamic and strongly typed</a> programming language that is used for <a href="https://python.org/about/apps" rel="nofollow noreferrer">a wide range of applications</a>. It is a general-purpose, high-level programming language that is designed to emphasize usability.</p>
<p>Python allows programmers to express concepts in fewer lines of code than would be possible in languages such as <a href="/questions/tagged/c" class="post-tag" title="show questions tagged 'c'" rel="tag">c</a>, and the language has constructs intended to be used to create clear programs in a variety of domains.</p>
<p>Two similar but incompatible major versions of Python are in widespread use: 2.7 is supported <a href="https://www.python.org/dev/peps/pep-0373/#id2" rel="nofollow noreferrer">until 2020</a> to run old scripts and dependencies, and version 3 first came out in 2008. Please mention the version and implementation that you are using when asking a question about Python.</p>
<p>Python supports multiple programming paradigms, including object-oriented, imperative, and functional programming styles. It features a fully dynamic type system and automatic memory management, similar to that of <a href="/questions/tagged/scheme" class="post-tag" title="show questions tagged 'scheme'" rel="tag">scheme</a>, <a href="/questions/tagged/ruby" class="post-tag" title="show questions tagged 'ruby'" rel="tag">ruby</a>, <a href="/questions/tagged/perl" class="post-tag" title="show questions tagged 'perl'" rel="tag">perl</a> and <a href="/questions/tagged/tcl" class="post-tag" title="show questions tagged 'tcl'" rel="tag">tcl</a>.</p>
<p>Like other <a href="https://en.wikipedia.org/wiki/Dynamic_programming_language" rel="nofollow noreferrer">dynamic languages</a>, Python is often used as a scripting language, but is also used in a wide range of non-scripting contexts. Using third-party tools, Python code can be packaged into standalone executable programs. Python interpreters are available for many operating systems.</p>
<p>CPython, the reference implementation of Python, is free and open source software and has a community-based development model, as do nearly all of its alternative implementations. There are a wide variety of implementations more suited for specific environments or tasks.</p>
<p>The philosophy of Python is succinctly formulated in <a href="https://python.org/dev/peps/pep-0020" rel="nofollow noreferrer"><em>The Zen of Python</em></a> written by Tim Peters, which can be revealed by issuing this command at the interactive interpreter:</p>
<pre><code>>>> import this
</code></pre>
<p>The documentation can also be accessed offline for your installation of Python in the following manner:</p>
<ol>
<li>Going into <code>Your_Python_install_dir/Doc</code>. There is a complete Python documentation present for the version of Python installed on your computer.</li>
<li>Running <code>pydoc x</code> or <code>python -m pydoc x</code> from the command prompt or terminal displays documentation for module <code>x</code>.</li>
</ol>
<p>Unlike many other languages Python uses an indentation based syntax and this may take some getting used to for programmers familiar with braces for syntax.</p>
<pre><code>>>> from __future__ import braces
File "<stdin>", line 1
SyntaxError: not a chance
</code></pre>
<p>To help with the transition, it is recommended to use a properly configured text editor created for programmers or an IDE. Python comes with a basic IDE called <a href="https://docs.python.org/2/library/idle.html" rel="nofollow noreferrer">IDLE</a> to get you started. Other popular examples are the charity-ware Vim, the free GNU <a href="/questions/tagged/emacs" class="post-tag" title="show questions tagged 'emacs'" rel="tag">emacs</a> and <a href="/questions/tagged/eclipse" class="post-tag" title="show questions tagged 'eclipse'" rel="tag">eclipse</a>+PyDev. Take a look at this <a href="https://en.wikipedia.org/wiki/List_of_integrated_development_environments_for_Python#Python" rel="nofollow noreferrer">IDE comparison list</a> for many other alternatives.</p>
<hr>
<h2>Tagging recommendation:</h2>
<p>Use the <a href="/questions/tagged/python" class="post-tag" title="show questions tagged 'python'" rel="tag">python</a> tag for all Python related questions. If you believe your question may be even more specific, you can include a version specific tag such as <a href="/questions/tagged/python-3.x" class="post-tag" title="show questions tagged 'python-3.x'" rel="tag">python-3.x</a>.</p>
<hr>
<h2>References</h2>
<ul>
<li>Official documentation for the current stable versions: <a href="https://docs.python.org/2.7/" rel="nofollow noreferrer">2.7</a> and <a href="https://docs.python.org/3/" rel="nofollow noreferrer">3</a>.</li>
<li><a href="https://en.wikipedia.org/wiki/Python_%28programming_language%29" rel="nofollow noreferrer">Python (programming language)</a> (Wikipedia)</li>
<li><a href="https://wiki.python.org/moin/BeginnersGuide/Programmers" rel="nofollow noreferrer">Python for Programmers</a></li>
<li><a href="http://www.tutorialspoint.com/python/python_quick_guide.htm" rel="nofollow noreferrer">Python - Quick Guide</a></li>
<li><a href="https://docs.python.org/3/howto/pyporting.html" rel="nofollow noreferrer">Porting Python 2 Code to Python 3</a></li>
<li>The non-profit <a href="https://www.python.org/psf/" rel="nofollow noreferrer">Python Software Foundation</a> manages <a href="https://en.wikipedia.org/wiki/CPython" rel="nofollow noreferrer">CPython</a>.</li>
<li><a href="https://www.python.org/psf/" rel="nofollow noreferrer">PSF</a> License Agreement for Python <a href="https://docs.python.org/2.7/license.html" rel="nofollow noreferrer">2.7</a> and <a href="https://docs.python.org/3/license.html" rel="nofollow noreferrer">3</a></li>
</ul>
<hr>
<h2>Popular <a href="https://wiki.python.org/moin/WebFrameworks" rel="nofollow noreferrer">web frameworks</a> based on Python</h2>
<ul>
<li><p><a href="https://www.djangoproject.com" rel="nofollow noreferrer"><strong>Django</strong></a></p>
<p>The Web framework for perfectionists (with deadlines). Django makes it easier to build better Web apps more quickly and with less code. Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. It lets you build high-performing, elegant Web applications quickly. Django focuses on automating as much as possible and adhering to the DRY (Don't Repeat Yourself) principle.</p></li>
<li><p><a href="http://flask.pocoo.org" rel="nofollow noreferrer"><strong>Flask</strong></a></p>
<p>Flask is a micro-framework for Python based on Werkzeug, Jinja 2, and good intentions.</p></li>
<li><p><a href="http://www.cherrypy.org" rel="nofollow noreferrer"><strong>CherryPy</strong></a></p>
<p>CherryPy is a pythonic, object-oriented web framework that enables developers to build web applications in much the same way they would build any other object-oriented Python program. This results in smaller source code developed in less time. CherryPy has been in use for over 7 years, and it is being used in production by many sites, from the simplest to the most demanding.</p></li>
<li><p><a href="http://www.pylonsproject.org/projects/pyramid/about" rel="nofollow noreferrer"><strong>Pyramid</strong></a></p>
<p>A lightweight Web framework emphasizing flexibility and rapid development. It combines the very best ideas from the worlds of Ruby, Python and Perl, providing a structured but extremely flexible Python web framework. It is also one of the first projects to leverage the emerging WSGI standard, which allows extensive re-use and flexibility, but only if you need it.</p></li>
<li><p><a href="http://webpy.org" rel="nofollow noreferrer"><strong>web.py</strong></a></p>
<p>web.py is a web framework for Python that is as simple as it is powerful. web.py is in the public domain; you can use it for whatever purpose with absolutely no restrictions. web.py lets you write web apps in Python.</p></li>
<li><p><a href="http://grok.zope.org" rel="nofollow noreferrer"><strong>Grok</strong></a></p>
<p>Grok is built on the existing Zope 3 libraries, but aims to provide an easier learning curve and a more agile development experience. It does this by placing an emphasis on convention over configuration and DRY (Don't Repeat Yourself).</p></li>
</ul>
<h2>Popular Mathematical/Scientific computing libraries in Python</h2>
<ul>
<li><p><a href="http://www.numpy.org" rel="nofollow noreferrer"><strong>NumPy</strong></a></p>
<p>NumPy is the fundamental package for scientific computing with Python. It contains among other things:</p>
<ul>
<li>a powerful N-dimensional array object</li>
<li>sophisticated (broadcasting) functions</li>
<li>tools for integrating C/C++ and Fortran code</li>
<li>useful linear algebra, Fourier transform, and random number capabilities</li>
</ul>
<p>These features also make it possible to use NumPy in general-purpose database applications.</p></li>
<li><p><a href="http://scipy.org" rel="nofollow noreferrer"><strong>SciPy</strong></a></p>
<p>SciPy is an open source library for the Python programming language consisting of mathematical algorithms and functions often used in science and engineering. SciPy includes algorithms and tools for tasks such as optimization, clustering, discrete Fourier transforms, linear algebra, signal processing and multi-dimensional image processing. SciPy is closely related to NumPy and depends on many NumPy functions, including a multidimensional array that is used as the basic data structure in SciPy.</p></li>
<li><p><a href="http://matplotlib.org/" rel="nofollow noreferrer"><strong>matplotlib</strong></a></p>
<p>matplotlib is a plotting library for the Python programming language and its NumPy numerical mathematics extension. It provides an object-oriented API for embedding plots into applications using general-purpose GUI toolkits like wxPython, Qt, or GTK. There is also a procedural "pylab" interface based on a state machine (like OpenGL) designed to closely resemble that of MATLAB.</p></li>
<li><p><a href="http://pandas.pydata.org/" rel="nofollow noreferrer"><strong>pandas</strong></a></p>
<p>pandas, the Python Data Analysis Library, is an open source, BSD-licensed library providing high-performance, easy-to-use data structures and data analysis tools for the Python programming language.</p></li>
</ul>
<hr>
<h3>Other Sites</h3>
<ul>
<li><a href="http://python.org/community/lists/#tutor" rel="nofollow noreferrer">Tutor mailing list</a></li>
<li><a href="http://python.org/community/lists/#python-help" rel="nofollow noreferrer">python-help mailing list</a></li>
<li><a href="http://www.pycon.org" rel="nofollow noreferrer">PyCon</a></li>
<li><a href="http://www.pythonweekly.com" rel="nofollow noreferrer">Python Weekly</a></li>
<li><a href="http://pycoders.com" rel="nofollow noreferrer">Pycoder's Weekly</a></li>
<li><a href="https://groups.google.com/forum/#!forum/comp.lang.python" rel="nofollow noreferrer">Python Google Group</a></li>
</ul>
<hr>
<h2>Free Python programming Books</h2>
<ul>
<li><a href="http://en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6" rel="nofollow noreferrer">Wikibooks' Non-Programmers Tutorial for Python</a></li>
<li><a href="http://docs.python.org/tutorial" rel="nofollow noreferrer">The Official Python Tutorial</a></li>
<li><a href="http://www.itmaybeahack.com/homepage/books/python.html" rel="nofollow noreferrer">Building Skills in Python Version 2.6</a> (Steven F. Lott)</li>
<li><a href="http://www.swaroopch.org/notes/Python" rel="nofollow noreferrer">A Byte of Python</a> (Swaroop C H.)</li>
<li><a href="http://www.brpreiss.com/books/opus7/html/book.html" rel="nofollow noreferrer">Data Structures and Algorithms in Python</a> (Bruno R. Preiss)</li>
<li><a href="http://www.diveintopython.net" rel="nofollow noreferrer">Dive into Python</a></li>
<li><a href="http://www.diveinto.org/python3" rel="nofollow noreferrer">Dive into Python 3</a></li>
<li><a href="http://www.greenteapress.com/thinkpython/thinkCSpy" rel="nofollow noreferrer">How to Think Like a Computer Scientist: Learning with Python</a> (Allen Downey, Jeff Elkner and Chris Meyers)</li>
<li><a href="http://inventwithpython.com" rel="nofollow noreferrer">Invent Your Own Computer Games With Python</a> (Al Sweigart)</li>
<li><a href="http://learnpythonthehardway.org" rel="nofollow noreferrer">Learn Python The Hard Way</a> (Zed A. Shaw)</li>
<li><a href="http://inventwithpython.com/pygame" rel="nofollow noreferrer">Making Games with Python & Pygame</a> (Albert Sweigart)</li>
<li><a href="http://www.nltk.org/book" rel="nofollow noreferrer">Natural Language Processing with Python</a> (Steven Bird, Ewan Klein, and Edward Loper)</li>
<li><a href="http://openbookproject.net/pybiblio" rel="nofollow noreferrer">Python Bibliotheca</a></li>
<li><a href="http://openbookproject.net/py4fun" rel="nofollow noreferrer">Python for Fun</a> (Chris Meyers)</li>
<li><a href="http://www.briggs.net.nz/snake-wrangling-for-kids.html" rel="nofollow noreferrer">Snake Wrangling For Kids</a> (Jason R. Briggs)</li>
<li><a href="http://www.greenteapress.com/thinkpython/thinkpython.pdf" rel="nofollow noreferrer">Think Python (PDF file)</a> (Allen Downey)</li>
<li><a href="http://python3porting.com" rel="nofollow noreferrer">Porting to Python 3</a> (Lennart Regebro)</li>
</ul>
<hr>
<h2>Interactive Python learning</h2>
<ul>
<li><a href="http://pythonmonk.com" rel="nofollow noreferrer">Python Monk</a> - Interactive Python learning in the browser</li>
<li><a href="http://www.codecademy.com/tracks/python" rel="nofollow noreferrer">Codeacademy</a> - Learn the fundamentals of Python and dynamic programming</li>
<li><a href="http://www.codeskulptor.org" rel="nofollow noreferrer">CodeSkulptor</a> - Interactive online IDEfor Python programming</li>
<li><a href="https://www.coursera.org/course/interactivepython" rel="nofollow noreferrer">Coursera</a> - Online course for introduction to interactive Python programming</li>
<li><a href="http://www.checkio.org" rel="nofollow noreferrer">CheckiO</a> - Game world you can explore using your Python programming skills</li>
<li><a href="http://www.repl.it/languages/Python" rel="nofollow noreferrer">Repl.it</a> - Online interpreter for Python that it allow saving code for later demonstration</li>
</ul>
<hr>
<h2>Python Online Courses</h2>
<ul>
<li><a href="https://class.coursera.org/pythonlearn-001/auth/auth_redirector?type=login&subtype=normal" rel="nofollow noreferrer">Programming for Everybody</a> - Introduction to programming using Python.</li>
<li><a href="https://class.coursera.org/interactivepython-004/auth/auth_redirector?type=login&subtype=normal" rel="nofollow noreferrer">An Introduction to Interactive Programming in Python</a> - The name explains itself.</li>
</ul>
<hr>
<h2>Python for Scientists</h2>
<ul>
<li><a href="http://nbviewer.ipython.org/gist/rpmuller/5920182" rel="nofollow noreferrer">A Crash Course in Python for Scientists</a></li>
</ul>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2011-04-20T00:57:25.853",
"Id": "1994",
"Score": "0",
"Tags": null,
"Title": null
} | 1994 |
Python is an interpreted, general-purpose high-level programming language whose design philosophy emphasizes code readability. Use the python tag for all Python related questions. If you believe your question may be even more specific, you can include a version specific tag such as python-3.x. | [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2011-04-20T00:57:25.853",
"Id": "1995",
"Score": "0",
"Tags": null,
"Title": null
} | 1995 |
<blockquote>
<p><strong>Exercise 2.54</strong></p>
<p>Two lists are said to
be <code>equal?</code> if they contain equal
elements arranged in the same order.</p>
<p>For example,</p>
<pre><code>(equal? '(this is a list) '(this is a list))
</code></pre>
<p>is true, but</p>
<pre><code>(equal? '(this is a list) '(this (is a) list))
</code></pre>
<p>is false. To be more precise, we can
define <code>equal?</code> recursively in terms of
the basic <code>eq?</code> equality of symbols by
saying that <code>a</code> and <code>b</code> are <code>equal?</code> if they
are both symbols and the symbols are
<code>eq?</code>, or if they are both lists such
that <code>(car a)</code> is <code>equal?</code> to <code>(car b)</code> and
<code>(cdr a)</code> is <code>equal?</code> to <code>(cdr b)</code>. Using
this idea, implement <code>equal?</code> as a
procedure.</p>
</blockquote>
<p>I wrote the following:</p>
<pre><code>(define (equal? a b)
(or (and (and (symbol? a) (symbol? b)) (eq? a b))
(and (null? a) (null? b))
(and (and (and (not (null? a))
(list? a))
(and (not (null? b))
(list? b)))
(and (equal? (car a) (car b))
(equal? (cdr a) (cdr b))))))
</code></pre>
<p>Can this be improved?</p>
| [] | [
{
"body": "<p>Since the <code>and</code> operation is associative, one could write:</p>\n\n<pre><code>(and (and (symbol? a) (symbol? b)) (eq? a b))\n</code></pre>\n\n<p>as:</p>\n\n<pre><code>(and (symbol? a) (symbol? b) (eq? a b))\n</code></pre>\n\n<p>Similarly:</p>\n\n<pre><code>(and (and (and (not (null? a)) \n (list? a))\n (and (not (null? b))\n (list? b)))\n (and (equal? (car a) (car b))\n (equal? (cdr a) (cdr b))))\n</code></pre>\n\n<p>is equivalent to:</p>\n\n<pre><code>(and (not (null? a))\n (not (null? b))\n (list? a)\n (list? b)\n (equal? (car a) (car b))\n (equal? (cdr a) (cdr b)))\n</code></pre>\n\n<p>One could extend the definition of <code>equal?</code> to work with both lists and pairs simply by changing the test <code>list?</code> to <code>pair?</code>. This also obviates the need to test for non-nullity within the same <code>and</code> clause.</p>\n\n<p>Using the above guidelines, one may write a shorter definition thus:</p>\n\n<pre><code>(define (equal? a b)\n (or (and (symbol? a) (symbol? b) (eq? a b))\n (and (null? a) (null? b))\n (and (pair? a)\n (pair? b)\n (equal? (car a) (car b))\n (equal? (cdr a) (cdr b)))))\n</code></pre>\n\n<p>Conceptually, one may think of null, symbol, and pair as types. To test for equality of two objects, one needs to check that their types are the same and then test for equality in that type.</p>\n\n<p>Thus, to test for equality, if we see that objects are symbols, test for <code>eq?</code>; if we see that objects are null, no further test is necessary so they're equal; if we see that objects are pairs, test for equality of car and cdr.</p>\n\n<p>This insight allows one to extend the definition of <code>equal?</code> to other types (hash tables, vectors, etc.) if one should choose to do so in the future.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-09-06T08:42:58.307",
"Id": "189896",
"Score": "0",
"body": "That's associativity, not commutativity."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-20T12:34:17.840",
"Id": "2000",
"ParentId": "1996",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "2000",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-20T03:54:39.923",
"Id": "1996",
"Score": "3",
"Tags": [
"lisp",
"scheme",
"sicp"
],
"Title": "equal? predicate for lists"
} | 1996 |
<blockquote>
<p><strong>Exercise 2.56.</strong></p>
<p>Show how to extend the
basic differentiator to handle more
kinds of expressions. For instance,
implement the differentiation rule</p>
<p>$$ \frac{d(u^n)}{dr} = nu^{n-1}(\frac{du}{dr})$$</p>
<p>by adding a new clause to the deriv
program and defining appropriate
procedures exponentiation?, base,
exponent, and make-exponentiation.
(You may use the symbol ** to denote
exponentiation.) Build in the rules
that anything raised to the power 0 is
1 and anything raised to the power 1
is the thing itself.</p>
</blockquote>
<p>From the book:</p>
<pre><code>(define (deriv exp var)
(cond ((number? exp) 0)
((variable? exp)
(if (same-variable? exp var) 1 0))
((sum? exp)
(make-sum (deriv (addend exp) var)
(deriv (augend exp) var)))
((product? exp)
(make-sum
(make-product (multiplier exp)
(deriv (multiplicand exp) var))
(make-product (deriv (multiplier exp) var)
(multiplicand exp))))
</code></pre>
<p>I added:</p>
<pre><code> ((exponentiation? exp)
(make-product (exponent exp)
(make-exponentiation (base exp) (- (exponent exp) 1))))
</code></pre>
<p>Book:</p>
<pre><code> (else
(error "unknown expression type -- DERIV" exp))))
(define (variable? x) (symbol? x))
(define (same-variable? v1 v2)
(and (variable? v1) (variable? v2) (eq? v1 v2)))
(define (make-sum a1 a2)
(cond ((=number? a1 0) a2)
((=number? a2 0) a1)
((and (number? a1) (number? a2)) (+ a1 a2))
(else (list '+ a1 a2))))
(define (=number? exp num)
(and (number? exp) (= exp num)))
(define (make-product m1 m2)
(cond ((or (=number? m1 0) (=number? m2 0)) 0)
((=number? m1 1) m2)
((=number? m2 1) m1)
((and (number? m1) (number? m2)) (* m1 m2))
(else (list '* m1 m2))))
(define (sum? x)
(and (pair? x) (eq? (car x) '+)))
(define (addend s) (cadr s))
(define (augend s) (caddr s))
(define (product? x)
(and (pair? x) (eq? (car x) '*)))
(define (multiplier p) (cadr p))
(define (multiplicand p) (caddr p))
</code></pre>
<p>I added:</p>
<pre><code>(define (exponentiation? x)
(and (pair? x) (eq? (car x) '**)))
(define (base s) (cadr s))
(define (exponent s) (caddr s))
(define (make-exponentiation m1 m2)
(cond ((=number? m2 0) 1)
((= m2 1) m1)
(else (list '** m1 m2))))
</code></pre>
<p>Can this be improved?</p>
| [] | [
{
"body": "<p>Your definitions are correct except for one minor detail. The <code>cond</code> clause:</p>\n\n<pre><code>((= m2 1) m1)\n</code></pre>\n\n<p>should be:</p>\n\n<pre><code>((=number? m2 1) m1)\n</code></pre>\n\n<p>since one needs to test first whether <code>m2</code> is a number.</p>\n\n<p>Stylistically, I would prefer to define <code>base</code> and <code>exponent</code> as:</p>\n\n<pre><code>(define base cadr)\n(define exponent caddr)\n</code></pre>\n\n<p>although there is certainly nothing wrong with your definitions.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-20T12:52:33.790",
"Id": "2001",
"ParentId": "1997",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "2001",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-20T05:38:26.970",
"Id": "1997",
"Score": "1",
"Tags": [
"lisp",
"scheme",
"sicp",
"symbolic-math"
],
"Title": "Extending basic differentiator to handle more kinds of expressions"
} | 1997 |
<blockquote>
<p>Exercise 2.57. Extend the
differentiation program to handle sums
and products of arbitrary numbers of
(two or more) terms. Then the last
example above could be expressed as</p>
<p><code>(deriv '(* x y (+ x 3)) 'x)</code></p>
<p>Try to do this by changing only the
representation for sums and products,
without changing the deriv procedure
at all. For example, the addend of a
sum would be the first term, and the
augend would be the sum of the rest of
the terms.</p>
</blockquote>
<p>I wrote the following solution.</p>
<pre><code>(define (deriv exp var)
(cond ((number? exp) 0)
((variable? exp)
(if (same-variable? exp var) 1 0))
((sum? exp)
(make-sum (deriv (addend exp) var)
(deriv (augend exp) var)))
((product? exp)
(make-sum
(make-product (multiplier exp)
(deriv (multiplicand exp) var))
(make-product (deriv (multiplier exp) var)
(multiplicand exp))))
((exponentiation? exp)
(make-product (exponent exp)
(make-exponentiation (base exp) (- (exponent exp) 1))))
(else
(error "unknown expression type -- DERIV" exp))))
(define (variable? x) (symbol? x))
(define (same-variable? v1 v2)
(and (variable? v1) (variable? v2) (eq? v1 v2)))
(define (make-sum . a)
(define (iter sum rest)
(cond ((null? rest) (if (zero? sum) '() (list sum)))
((=number? (car rest) 0) (iter sum (cdr rest)))
((number? (car rest)) (iter (+ sum (car rest)) (cdr rest)))
(else (cons (car rest) (iter sum (cdr rest))))))
(let ((result (iter 0 a)))
(if (= (length result) 1)
(car result)
(cons '+ result))))
(define (=number? exp num)
(and (number? exp) (= exp num)))
(define (make-product . a)
(define (iter product rest)
(cond ((null? rest) (if (= 1 product) '() (list product)))
((=number? (car rest) 1) (iter product
(cdr rest)))
((number? (car rest)) (iter (* product (car rest))
(cdr rest)))
(else
(let ((result (iter product (cdr rest))))
(if (and (pair? result) (eq? (car result) 0))
(list 0)
(cons (car rest) result))))))
(let ((result (iter 1 a)))
(if (= (length result) 1)
(car result)
(cons '* result))))
(define (sum? x)
(and (pair? x) (eq? (car x) '+)))
(define (addend s) (cadr s))
(define (augend s) (if (> (length s) 3)
(cons '+ (cddr s))
(caddr s)))
(define (product? x)
(and (pair? x) (eq? (car x) '*)))
(define (multiplier p) (cadr p))
(define (multiplicand p) (if (> (length p) 3)
(cons '* (cddr p))
(caddr p)))
(define (exponentiation? x)
(and (pair? x) (eq? (car x) '**)))
(define (base s) (cadr s))
(define (exponent s) (caddr s))
(define (make-exponentiation m1 m2)
(cond ((=number? m2 0) 1)
((= m2 1) m1)
(else (list '** m1 m2))))
</code></pre>
<p>Can it be improved? In particular, look closely at make-product and make-sum.</p>
| [] | [
{
"body": "<p>Your have the right ideas for implementing <code>make-sum</code> and <code>make-product</code>. You may improve upon them in the following ways, in my opinion.</p>\n\n<p>Within the two functions, you employ an inner function <code>iter</code> to partition numeric and non-numeric terms. Traditionally, one uses the name <code>iter</code> to represent an iterative function; your definition, however, is most certainly recursive. To make it truly iterative, one may use two accumulators--one for the sum of all numeric terms and the other for the rest of the terms. Then one may return the <code>cons</code> of the two accumulators when the iteration terminates.</p>\n\n<p>One may allow <code>make-sum</code> (and similarly <code>make-product</code>) to handle other sum-type objects in its terms list as well--simply test with <code>sum?</code>, then append its terms.</p>\n\n<p>Finally, there are several cases that must be handled when iteration terminates: <code>rest</code> may be empty or it may contain one or more items; <code>sum-numbers</code> may be zero or non-zero.</p>\n\n<p>Here's an implementation (naming scheme is slightly different from yours--in the <code>iter</code> function, <code>terms</code> is the list of remaining terms to be iterated upon, <code>sum-numbers</code> is the sum of all numeric terms seen so far, <code>rest</code> is a list of all non-numeric terms seen so far):</p>\n\n<pre><code>(define (make-sum . terms)\n (define (iter terms sum-numbers rest)\n (cond\n ((null? terms) (cons sum-numbers rest))\n ((=number? (car terms) 0) (iter (cdr terms) sum-numbers rest))\n ((number? (car terms)) (iter (cdr terms) (+ sum-numbers (car terms)) rest))\n ((sum? (car terms)) (iter (append (cdar terms) (cdr terms)) sum-numbers rest))\n (else (iter (cdr terms) sum-numbers (cons (car terms) rest)))))\n (let*\n ((result (iter terms 0 null))\n (sum-numbers (car result))\n (rest (cdr result)))\n (if (null? rest)\n sum-numbers\n (if (zero? sum-numbers)\n (if (null? (cdr rest))\n (car rest)\n (cons '+ rest))\n (cons '+ (cons sum-numbers rest))))))\n\n(define (make-product . terms)\n (define (iter terms sum-numbers rest)\n (cond\n ((null? terms) (cons sum-numbers rest))\n ((=number? (car terms) 0) (cons 0 null))\n ((=number? (car terms) 1) (iter (cdr terms) sum-numbers rest))\n ((number? (car terms)) (iter (cdr terms) (* sum-numbers (car terms)) rest))\n ((product? (car terms)) (iter (append (cdar terms) (cdr terms)) sum-numbers rest))\n (else (iter (cdr terms) sum-numbers (cons (car terms) rest)))))\n (let*\n ((result (iter terms 1 null))\n (sum-numbers (car result))\n (rest (cdr result)))\n (if (null? rest)\n sum-numbers\n (if (zero? sum-numbers)\n (if (null? (cdr rest))\n (car rest)\n (cons '* rest))\n (cons '* (cons sum-numbers rest))))))\n</code></pre>\n\n<p>One may also simplify the definitions of <code>augend</code> and <code>multiplicand</code> by using <code>make-sum</code> and <code>make-product</code> respectively:</p>\n\n<pre><code>(define (augend s) (apply make-sum (cddr s)))\n\n(define (multiplicand p) (apply make-product (cddr p)))\n</code></pre>\n\n<p>Note the similarities between <code>make-sum</code> and <code>make-product</code>. It may be possible to factor out some code. One may also use library functions such as <code>partition</code> (if available) to simplify the code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-25T00:57:50.277",
"Id": "3375",
"Score": "0",
"body": "I see what you mean about (augend ) and (multiplicand ) as well as the iter/rec naming. Could you elaborate a bit on why it is better to add the additional (product? ) or (sum? ) test? I think I understand, but I'm curious what you think."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-25T12:46:53.347",
"Id": "3380",
"Score": "0",
"body": "@jaresty: By handling a sum-type object in `make-sum`, the following simplification becomes possible: `(make-sum 2 '(+ 5 x))` => `'(+ 7 x)`"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-24T11:45:29.103",
"Id": "2061",
"ParentId": "1998",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "2061",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-20T06:57:20.540",
"Id": "1998",
"Score": "5",
"Tags": [
"lisp",
"scheme",
"sicp"
],
"Title": "Extend sums and products functions"
} | 1998 |
<p>I am making a website using the MVP pattern. It is a simple website, so for the repository I use Linq2SQL. My architecture is basically:</p>
<p>(View - Presenter) - Service Layer - Domain Models.</p>
<p>The View consists of 10 dropdownlists, and a submit button.</p>
<p>Between the (View - Presenter) and the Service Layer I use DTO's to exchange information. But here is as well where my problem lies; the Service Layer gets the data from the DataContext. This data is in all sorts of types, ints, strings, etc. My View mostly needs everything in strings. Now I need to fill a DTO to send to the Presenter. The question is if I should already format everything so that it can be consumed by the presenter/view, or should the Presenter do this? For now, I have the Presenter do it, but I find the code a bit ghastly. Please review my code (p.s I am aware I should use DI - it will be applied ;-)):</p>
<pre><code>using Business;
using System.Collections.Generic;
using Service;
using DTOs;
using System.Text;
namespace Web
{
public class PredictionDetailsPresenter
{
private readonly IDriverService driverService;
private readonly IPredictionDetailsView predictionDetailsView;
private readonly IPredictionService predictionService;
#region constructors
public PredictionDetailsPresenter(IPredictionDetailsView predictionDetailsView)
: this(predictionDetailsView, new DriverService(), new PredictionService())
{
}
public PredictionDetailsPresenter(IPredictionDetailsView predictionDetailsView, IDriverService driverService,
IPredictionService predictionService)
{
this.predictionDetailsView = predictionDetailsView;
this.driverService = driverService;
this.predictionService = predictionService;
}
#endregion
#region public methods
public void Initialize()
{
predictionDetailsView.SetFirstListItemOfPositionDropDownLists(" ---Select Driver--- ");
foreach (Driver driver in driverService.GetAllDrivers())
{
predictionDetailsView.AddDriver(driver.Name, driver.Id.ToString());
}
PredictionServiceInitializeResponse response = predictionService.Initialize("Belgian Grand Prix");
predictionDetailsView.RaceId = response.RaceId.ToString();
predictionDetailsView.DateAndTimeOfRace = response.DateAndTimeOfRace.ToString();
predictionDetailsView.RaceTitle = response.RaceTitle;
predictionDetailsView.SelectedDriverIdDriverPolePosition = (response.SelectedDrivers[(int)DriverPositions.PolePosition]).ToString();
predictionDetailsView.SelectedDriverIdDriver2ndPosition = (response.SelectedDrivers[(int)DriverPositions.SecondPosition]).ToString();
predictionDetailsView.SelectedDriverIdDriver3rdPosition = (response.SelectedDrivers[(int)DriverPositions.ThirdPosition]).ToString();
predictionDetailsView.SelectedDriverIdDriver4thPosition = (response.SelectedDrivers[(int)DriverPositions.FourthPosition]).ToString();
predictionDetailsView.SelectedDriverIdDriver5thPosition = (response.SelectedDrivers[(int)DriverPositions.FifthPosition]).ToString();
predictionDetailsView.SelectedDriverIdDriver6thPosition = (response.SelectedDrivers[(int)DriverPositions.SixthPosition]).ToString();
predictionDetailsView.SelectedDriverIdDriver7thPosition = (response.SelectedDrivers[(int)DriverPositions.SeventhPosition]).ToString();
predictionDetailsView.SelectedDriverIdDriver8thPosition = (response.SelectedDrivers[(int)DriverPositions.EightPosition]).ToString();
predictionDetailsView.SelectedDriverIdDriver9thPosition = (response.SelectedDrivers[(int)DriverPositions.NinthPosition]).ToString();
predictionDetailsView.SelectedDriverIdDriver10thPosition = (response.SelectedDrivers[(int)DriverPositions.TenthPosition]).ToString();
}
public void ProcessPrediction()
{
PredictionServiceInsertRequest predictionServiceInsertRequest = new PredictionServiceInsertRequest();
predictionServiceInsertRequest.SelectedDrivers.Add(DriverPositions.PolePosition.ToString(),
new Driver { Id = int.Parse(predictionDetailsView.SelectedDriverIdDriverPolePosition), Name = predictionDetailsView.SelectedNameDriverPolePosition });
predictionServiceInsertRequest.SelectedDrivers.Add(DriverPositions.SecondPosition.ToString(),
new Driver { Id = int.Parse(predictionDetailsView.SelectedDriverIdDriver2ndPosition), Name = predictionDetailsView.SelectedNameDriver2ndPosition });
predictionServiceInsertRequest.SelectedDrivers.Add(DriverPositions.ThirdPosition.ToString(),
new Driver { Id = int.Parse(predictionDetailsView.SelectedDriverIdDriver3rdPosition), Name = predictionDetailsView.SelectedNameDriver3rdPosition });
predictionServiceInsertRequest.SelectedDrivers.Add(DriverPositions.FourthPosition.ToString(),
new Driver { Id = int.Parse(predictionDetailsView.SelectedDriverIdDriver4thPosition), Name = predictionDetailsView.SelectedNameDriver4thPosition });
predictionServiceInsertRequest.SelectedDrivers.Add(DriverPositions.FifthPosition.ToString(),
new Driver { Id = int.Parse(predictionDetailsView.SelectedDriverIdDriver5thPosition), Name = predictionDetailsView.SelectedNameDriver5thPosition });
predictionServiceInsertRequest.SelectedDrivers.Add(DriverPositions.SixthPosition.ToString(),
new Driver { Id = int.Parse(predictionDetailsView.SelectedDriverIdDriver6thPosition), Name = predictionDetailsView.SelectedNameDriver6thPosition });
predictionServiceInsertRequest.SelectedDrivers.Add(DriverPositions.SeventhPosition.ToString(),
new Driver { Id = int.Parse(predictionDetailsView.SelectedDriverIdDriver7thPosition), Name = predictionDetailsView.SelectedNameDriver7thPosition });
predictionServiceInsertRequest.SelectedDrivers.Add(DriverPositions.EightPosition.ToString(),
new Driver { Id = int.Parse(predictionDetailsView.SelectedDriverIdDriver8thPosition), Name = predictionDetailsView.SelectedNameDriver8thPosition });
predictionServiceInsertRequest.SelectedDrivers.Add(DriverPositions.NinthPosition.ToString(),
new Driver { Id = int.Parse(predictionDetailsView.SelectedDriverIdDriver9thPosition), Name = predictionDetailsView.SelectedNameDriver9thPosition });
predictionServiceInsertRequest.SelectedDrivers.Add(DriverPositions.TenthPosition.ToString(),
new Driver { Id = int.Parse(predictionDetailsView.SelectedDriverIdDriver10thPosition), Name = predictionDetailsView.SelectedNameDriver10thPosition });
predictionServiceInsertRequest.RaceId = predictionDetailsView.RaceId;
PredictionServiceInsertResponse response = predictionService.Insert(predictionServiceInsertRequest);
if (response.Success)
{
predictionDetailsView.Message = "Your prediction has been inserted succesfully";
}
else
{
StringBuilder sb = new StringBuilder();
foreach (var error in response.Errors)
{
sb.AppendFormat("{0}<br />", error);
}
predictionDetailsView.Message = sb.ToString();
}
}
#endregion
}
public enum DriverPositions
{
PolePosition = 1,
SecondPosition = 2,
ThirdPosition = 3,
FourthPosition = 4,
FifthPosition = 5,
SixthPosition = 6,
SeventhPosition = 7,
EightPosition = 8,
NinthPosition = 9,
TenthPosition = 10
}
}
</code></pre>
| [] | [
{
"body": "<p>Best practice is to let the presenter handle the formatting. If you are, for example, dealing with multiple views, the code will be much easier to maintain and also be parsed/formatted from just the one location.</p>\n\n<p>By the look of your code, i'd suggest you use a simple POCO-class for the data binding that occurrs between the Presenter and the View. Name and position would be sufficient properties.</p>\n\n<pre><code>public class DriverDTO\n{ \n public int Position {get;set;}\n public string Name {get;set;}\n}\n\npublic interface IPredictionDetailsView \n{\n public IList<DriverDTO> SelectedDrivers {get; set;}\n}\n</code></pre>\n\n<p>Or you could just use a <code>Dictionary<int, string></code> to store the values in. That way you will always have unique positions, if that is a requirement.</p>\n\n<p>Best regards,\nMattias</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-25T16:47:18.767",
"Id": "2091",
"ParentId": "2002",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-20T14:38:57.080",
"Id": "2002",
"Score": "3",
"Tags": [
"c#"
],
"Title": "MVP presenter code in C# - possible troubles with DTO's"
} | 2002 |
<p><strong>Background</strong>:<br>
This began with <a href="http://jcoglan.com/">James Colgan</a>'s <a href="https://github.com/jcoglan/lisp-dojo">Lisp-Dojo</a> for Ruby. My implementation can be found <a href="https://github.com/antarestrader/lisp-dojo">here</a>. I then moved on to <a href="http://en.wikibooks.org/wiki/Write_Yourself_a_Scheme_in_48_Hours">Write yourself a scheme in 48 hours</a>. This question has to do with one of the implementation decisions.</p>
<p><strong>Code</strong>:</p>
<p>My implementation of <code>eval</code> </p>
<pre><code>--# The eval function takes a scope and paresed Lisp value and
--# returns the resulting Lisp Value.
--# String, Number and Bool return themselves.
--# An Atom trys to find its self in the scope and retrun that value
--# A List is evaluated using the normal Lisp rules.
eval :: LispScope-> LispVal -> IOThrowsError LispVal
eval s val@(String _) = return val
eval s (Atom val) = do
(liftIO $ getValue s val) >>= maybe (throwError $ "Value not in scope: " ++ val) (return)
eval s val@(Number _) = return val
eval s val@(Bool _) = return val
eval scope (List (fn:lvs)) = do
fun <- eval scope fn
case fun of
Syntax f _-> f scope lvs
Function f _-> evalMap scope lvs >>= f
val -> throwError $ (show val) ++ " is not a function"
eval scope (List []) = return $ List []
eval _ badForm = throwError $ "Unrecognized form: " ++ show badForm
</code></pre>
<p>Note two things: 1) I do not refer to any special forms, 2) the use of Syntax for hygenic forms.</p>
<p>This is a piece of code from <a href="http://en.wikibooks.org/wiki/Write_Yourself_a_Scheme_in_48_Hours">Write yourself a scheme in 48 hours</a>:</p>
<pre><code>--# evaluate the "if" form
eval (List [Atom "if", pred, conseq, alt]) =
do result <- eval pred
case result of
Bool False -> eval alt
otherwise -> eval conseq
</code></pre>
<p>Note that in the tutorial the form is written directly into the eval function. This pattern is followed for other syntaxes like <code>define</code> and <code>lambda</code>.</p>
<p><strong>Question</strong>:
When I implemented my version I followed what I thought was a wise choice demonstrated in <a href="https://github.com/jcoglan/lisp-dojo/tree/jcoglan">James Colgan's solution</a> to the lisp-dojo to keep eval as simple as possible and instead to push the syntax implementations into the root scope. eg:</p>
<pre><code>ifSyntax :: LispScope -> [LispVal] -> IOThrowsError LispVal
ifSyntax s [pred, consequent, alternate] = do
pred' <- eval s pred
case pred' of
Bool False -> eval s alternate
otherwise -> eval s consequent
ifSyntax _ _ = throwError "if: Bad Syntax"
ifVal = (Syntax ifSyntax $ Left "syntax (if)")
--# this is then added to the initial scope
</code></pre>
<p><strong>I would like to know why one choice might be better then the other, and what is typical in real-world implementations.</strong></p>
<p><strong>Reference</strong>:</p>
<p>My definition of the <code>LispVal</code> data type:</p>
<pre><code>type LispScope = Scope LispVal
data Lambda = Lambda {params :: [String], body :: [LispVal]}
data LispVal = Atom String
| List [LispVal]
| Number Integer
| Real Double
| String String
| Function ([LispVal] -> IOThrowsError LispVal) (Either String Lambda)
| Syntax (LispScope -> [LispVal] -> IOThrowsError LispVal) (Either String Lambda)
| Bool Bool
| Port Handle
</code></pre>
| [] | [
{
"body": "<p>When I went through the WYAS48 I made the same decision of breaking the bits of <code>eval</code> off into smaller functions. I found this made testing easier since I could focus on just one function at a time.</p>\n\n<p>I find that having a function be one massive bunch of logic is not helpful. In an imperative language the equivalent would be a single function with a ton of if/else or case/switch logic. Whenever I see that I tend to break things off into more manageable functions.</p>\n\n<p>The issue that tends to happen is the little functions need some kind of state from the original big function. Finding this out and resolving it can be difficult at times and others just plain messy. The code is often better for it in the end.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-08T19:30:41.890",
"Id": "86615",
"Score": "5",
"body": "Congratulations! You are officially a [zombie killer](http://meta.codereview.stackexchange.com/a/1511/23788)! Well done!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-08T19:24:10.620",
"Id": "49256",
"ParentId": "2003",
"Score": "8"
}
}
] | {
"AcceptedAnswerId": "49256",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-20T15:53:33.260",
"Id": "2003",
"Score": "11",
"Tags": [
"lisp",
"scheme",
"haskell"
],
"Title": "On Implementing a Lisp"
} | 2003 |
<p>I just started learning how to code PHP as well as HTML and as a challenge for myself I put together a questionnaire with what I have learnt so far which isn't as much as I would like to know e.g. sessions, databases, etc. Anyhoo, I would like to get the review of peers and would appreciate any constructive suggestions, ideas, etc. Here it does...
<pre><code>//Initialize page
$startpage = isset($_POST['page']) ? $_POST['page'] : 1;
$endpage = 11;
//Initialize score
$score = isset($_POST['score']) ? $_POST['score'] : 0;
if(isset($_POST['submit'])) {
$questions = array('question1' => 'superglobal', 'question2' => 'formsubmission', 'question3' => 'declare', 'question4' => 'symbol', 'question5' => 'statement', 'question6' => 'division', 'question7' => 'codeans',
'question8' => 'email', 'question9' => 'super', 'question10' => 'switch');
foreach($questions as $questionkey => $questionvalue) {
$questionpost = isset($_POST[$questionvalue]) ? $_POST[$questionvalue] : '';
if($questionkey == 'question'.$startpage && empty($questionpost)) {
$errormsg = 'Please select an answer for '. $questionkey;
echo $errormsg . '<br />';
}
}
//Answers
$answers = array('question1' => 'if', 'question2' => 'post', 'question3' => '$a', 'question4' => ';', 'question5' => '3', 'question6' => '%', 'question7' => 'infinite', 'question8' => 'mail',
'question9' => array('get', 'post', 'request'), 'question10' => array('break'));
//Loop through post array
foreach($questions as $questionkey => $questionvalue) {
// echo $postkey. '=' .$postvalue;
if(!empty($_POST[$questionvalue]) && $questionkey == 'question'.$startpage) {
//Loop through answers
foreach($answers as $key => $value) {
if(is_array($value)) {
foreach($value as $arraykey => $arrayvalue) {
if($questionkey == $key && $_POST[$questionvalue][$arraykey] == $arrayvalue) {
// echo $key. '=' .$arrayvalue;
echo 'Your answer for '. $questionkey .' was correct';
$startpage = $startpage + 1;
$score = $score + 1;
break;
}
else if($questionkey == $key && $_POST[$questionvalue][$arraykey] != $arrayvalue) {
echo 'Your answer for '. $questionkey .' was incorrect';
echo $_POST[$questionvalue][$arraykey];
break;
}
}
}
else {
if($questionkey == $key && $_POST[$questionvalue] == $value) {
// echo $key. '=' .$value. '<br />';
echo 'Your answer for '. $questionkey .' was correct';
$startpage = $startpage + 1;
$score = $score + 1;
// echo $questionkey;
// echo $key;
break;
}
else if($questionkey == $key && $_POST[$questionvalue] != $value) {
echo 'Your answer for '. $questionkey .' is incorrect';
// echo $questionvalue;
// echo $questionkey;
// echo $key;
break;
}
}
}
}
}
//Debug
// print_r($_POST);
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>Questionnaire</title>
</head>
<body>
<h1>Questionnaire</h1>
<p>This is a sample questionnaire that you can take and evaluate your results. Below are some tips</p>
<ol>
<li>This questionnaire has total of 10 questions</li>
<li>Each question is worth 1 point totalling 10 points</li>
<li>There are 8 multiple choice and 2 multi-select questions</li>
<li>At the end of the questionnaire, you'll be presented with your score</li>
</ol>
<form name="questionnaire" method="post" action="questionnaire.php">
<?php
echo
'<input type="hidden" name="page" value="'. $startpage. '">';
echo
'<input type="hidden" name="score" value="' . $score .'">';
switch($startpage) {
case(1):
echo
'<div> Question 1. Which one of these is a super global? <br />
<input type="radio" name="superglobal" value="if">if
<input type="radio" name="superglobal" value="and">and
<input type="radio" name="superglobal" value="get">GET
<input type="radio" name="superglobal" value="array">array
</div>';
break;
case(2):
echo
'<div> Question 2. Which one of these hides the values when submitting a form? <br />
<input type="radio" name="formsubmission" value="get">GET
<input type="radio" name="formsubmission" value="send">SEND
<input type="radio" name="formsubmission" value="parcel">PARCEL
<input type="radio" name="formsubmission" value="post">POST
</div>';
break;
case(3):
echo
'<div> Question 3. Select which one these is the correct way of declaring a variable? <br />
<input type="radio" name="declare" value="a">a
<input type="radio" name="declare" value="$a">$a
<input type="radio" name="declare" value="%a">%a
<input type="radio" name="declare" value="%a">%a
</div>';
break;
case(4):
echo
'<div> Question 4. Which symbol would you have at the end of a statemement <br />
<input type="radio" name="symbol" value=";">;
<input type="radio" name="symbol" value="#">#
<input type="radio" name="symbol" value="*">*
<input type="radio" name="symbol" value="/">/
</div>';
break;
case(5):
echo
'<div> Question 5. Select which one of these statements is true? <br />
<input type="radio" name="statement" value="2">a++ equals to 2 if a is 1
<input type="radio" name="statement" value="3">++a is equals to 3 if a is 2
<input type="radio" name="statement" value="divide">\ is the symbol for divisions
<input type="radio" name="statement" value="zero">0 is the value that represents true
</div>';
break;
case(6):
echo
'<div> Question 6. Which symbol gives the remainder in a division? <br />
<input type="radio" name="division" value=")">)
<input type="radio" name="division" value="}">}
<input type="radio" name="division" value="%">%
<input type="radio" name="division" value=";")>;
</div>';
break;
case(7):
echo
'<div> Question 7. What will the code below return <br />
<pre>
$a=1
while($a < 10) {
echo $a;
}
</pre>
<input type="radio" name="codeans" value="one">1
<input type="radio" name="codeans" value="zero">0
<input type="radio" name="codeans" value="infinite">infinite loop
<input type="radio" name="codeans" value="3">3
</div>';
break;
case(8):
echo
'<div> Question 8. What function can you use to send an email <br />
<input type="radio" name="email" value="mail">mail
<input type="radio" name="email" value="email">email
<input type="radio" name="email" value="mailto">mailto
<input type="radio" name="email" value="send">send
</div>';
break;
case(9):
echo
'<div> Question 9. Which of the following are super-globals?<br />
<input type="checkbox" name="super[]" value="get">GET
<input type="checkbox" name="super[]" value="post">POST
<input type="checkbox" name="super[]" value="request">REQUEST
<input type="checkbox" name="super[]" value="process">PROCESS
</div>';
break;
case(10):
echo
'<div> Question 10. Which of the following are true to exit a switch statement? <br />
<input type="checkbox" name="switch[]" value="exit">exit
<input type="checkbox" name="switch[]" value="die">die
<input type="checkbox" name="switch[]" value="drop">drop
<input type="checkbox" name="switch[]" value="break">break
</div>';
break;
case(11):
echo 'Congratulations, you have completed the test and you scored.'. $score;
break;
}
?>
<?php
if($startpage < $endpage) {
echo '<div><input type="submit" name="submit" value="submit"></div>';
}
?>
</form>
</body>
</html>
</code></pre>
| [] | [
{
"body": "<p>I think you may improve your code by using <a href=\"http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller\" rel=\"nofollow\">MVC pattern</a>. In your case, for example, I had recommend:</p>\n\n<ul>\n<li>extract all logic to class (don't print any message or use $_POST directly from it).</li>\n<li>try to minimize mixing HTML and PHP code</li>\n<li>try to minimize any logic in View (for example, instead of <code>if ($startpage < $endpage)</code> I prefer <code>if ($showSubmitButton)</code>)</li>\n<li>use session to store score</li>\n<li>switch with all questions looks monstrous, so IMHO you may move each question to file like <code>1.txt</code> and use something like <code>readfile($startpage)</code> (don't forget to check it for integer and allowed range before!)</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-20T21:13:43.243",
"Id": "3323",
"Score": "0",
"body": "Thanks. I am new to the world of coding and have no idea how to implement MVC however I will certainly look into how to use MVC. In a layperson's example, what is MVC, how does it work, what do I have to do different?\n\nWhen you say 'extract all logic to class (don't print any message or use $_POST directly from it).', what do you mean exactly? Can you give me examples?\n\nIn the your example of using if ($showSubmitButton)) would $showSubmitbutton = $startpage < $endpage?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-20T21:14:01.887",
"Id": "3324",
"Score": "0",
"body": "continued;\n\nI agree that the swtich statements are monstorus but hope to improve the code once I learn how to read from a file and database.\n\nAs for using sessions, I have yet to learn how to use them.\n\nOverall, how would you rate my coding for a person who just started learning how to code?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-21T01:40:34.437",
"Id": "3326",
"Score": "0",
"body": "@PeanutsMonkey MVC stands for Model-View-Controller, and it's what's called a design pattern. Design patterns are, well... Software designs that follow certain patterns or structures of proven usability. In an MVC patterned application, your data, logic and output are all abstracted to different processes relatively independent of each other. You'll learn more about design patterns when you study object-oriented programming."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-21T03:34:39.177",
"Id": "3327",
"Score": "0",
"body": "Your code is better than many newbie writes, so go ahead! And yes, `$showSubmitButton` should be initialized by `$startpage < $endpage`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-21T08:12:21.530",
"Id": "3328",
"Score": "0",
"body": "&& 65Fbef05 - Thanks for the heads-up. I'll definitely look at the Model-View-Controller."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-20T17:56:50.610",
"Id": "2005",
"ParentId": "2004",
"Score": "3"
}
},
{
"body": "<p>For someone who is just picking up the language, I'd say you're off to a great start. Don't be afraid to abstract the different pieces of your program logic to many separate files and including them only when needed - It will make future revisions much less of a headache. When you are dealing with large blocks of output data like in your switch statement, PHP's output buffer can be your greatest friend. Your program also presents a great opportunity for you to get acquainted with the <code>DOMDocument</code> extension - its relative purpose is structured output. Referencing what @php-coder suggested, once you get comfortable working with a database, you can start abstracting your application into purpose-driven layers - The Model-View-Controller design pattern is a pretty common method among popular PHP frameworks. PHP 5.3 and its common extensions host roughly 1,300 built-in functions - Have fun with it; it's a great language! +1 for your first review.</p>\n\n<p>Edit:</p>\n\n<p>How to style your code is normally a matter of personal preference and readability, but if you are looking for some general guidance, take a look at the <a href=\"http://framework.zend.com/manual/en/coding-standard.coding-style.html\" rel=\"nofollow\">Zend Framework Coding Style Guidelines</a>. It's mostly just a reference for ZF extension authors, but it's none the less helpful for general interests.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-21T08:13:24.027",
"Id": "3329",
"Score": "0",
"body": "Thanks for the vote of confidence. Will have a peek at the DOMDocument extension. Is it part of PHP?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-21T11:26:50.517",
"Id": "3330",
"Score": "0",
"body": "I haven't seen an instance of PHP5 installed without it."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-21T01:29:56.867",
"Id": "2008",
"ParentId": "2004",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-20T16:33:20.010",
"Id": "2004",
"Score": "3",
"Tags": [
"php",
"form"
],
"Title": "PHP Questionnaire Code Peer Review"
} | 2004 |
<p>How can I make this sort faster and better?</p>
<pre><code>function OrderBy(a,b) {
if (a < b) return -1;
if (a > b) return 1;
return 0;
}
SortBy = function($th) {
var $tbody = $th.closest('tbody');
var $table = $tbody.parent();
$tbody.detach();
$('#Processing').show('fast',function () {
var column = $th.index();
var rows = $tbody.find('tr').get();
rows.sort(function(rowA,rowB) {
var keyA = $(rowA).children('td').eq(column).text();
var keyB = $(rowB).children('td').eq(column).text();
return OrderBy(keyA,keyB);
});
$.each(rows, function(index,row) {
$tbody.append(row);
});
$table.append($tbody);
});
};
</code></pre>
| [] | [
{
"body": "<p>You could read the cell texts before sorting, so that it doesn't have to happen repeatedly in the order function:</p>\n\n<pre><code> var rowsWithText = $tbody.find('tr').map(function() {\n return {\n row: this, \n text: $(this).children('td').eq(column).text()\n };\n });\n rowsWithText.sort(function(rowA, rowB) {\n return OrderBy(rowA.text, rowB.text);\n });\n $.each(rowsWithText, function(index,row) {\n $tbody.append(row.row);\n });\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-21T20:39:15.207",
"Id": "3336",
"Score": "0",
"body": "I've seen the map function before, but haven't paid any attention to it. I'll check it out. Thanks!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-21T12:27:18.100",
"Id": "2022",
"ParentId": "2006",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "2022",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-20T18:14:47.777",
"Id": "2006",
"Score": "2",
"Tags": [
"javascript",
"jquery"
],
"Title": "Ordering cell rows and columns"
} | 2006 |
<pre><code>if params[:package]
city_ids = []
city = params[:package].delete 'city'
city_ids << city if city.to_i > 0
cities = params[:package].delete 'cities'
city_ids += cities if cities.class == Array && cities.length > 0
params[:package][:cities] = city_ids.map{ |c| City.get(c) }.compact
end
</code></pre>
| [] | [
{
"body": "<p>This code looks pretty clean to me. Here are a few thoughts:</p>\n\n<p>I'm not sure what your ORM is (or even that <code>City</code> is database backed), but most have a way to fetch more then one record at a time. Making a single call will save time and Database resources.</p>\n\n<p>Another thought is that you are inducing a lot of local vars: <code>city_ids</code>, <code>city</code>, <code>cities</code>. What about trying to build up the array of ids in <code>params[:package][:cities]</code>? e.g.</p>\n\n<pre><code>#if cities is not an array, it is bad date get rid of it.\nparams[:package].delete 'cities' unless params[:package][:cities].kind_of? Array\nparams[:package][:cities] ||= []\nparams[:package][:cities] << (params[:package].delete 'city') if params[:package][:cities].to_i > 0\nparams[:package][:cities] = params[:package][:cities].map{ |c| City.get(c) }.compact\n</code></pre>\n\n<p>The code above doesn't seem very DRY because it has all this <code>params[:package]</code> stuff. If you do things like this a lot (your question makes it sound like you do) factor the operation out into a separate method:</p>\n\n<pre><code>def extract_nested_reference(hash,values) # change name as appopriate\n if hash\n hash.delete values unless hash[values].kind_of? Array\n hash[values] ||=[]\n hash[values] << hash[values.singularize] if hash[values.singularize].to_i > 0\n\n hash[values] = hash[values].map do |x|\n Object.const_get(values.singularize.constantize).get(c) \n end.compact\n end\nend\n</code></pre>\n\n<p>This method could then be called with <code>extract_nested_reference(params[:package],'cities')</code>. Refactoring like this will also encourage you to be consistent in how you build you params hash, and allow you to reuse code.</p>\n\n<p>Finally, your question asked about better ways of dealing with hashes. I don't think there is. You will find code very similar to this living in most popular gems. AS you say, it is kind of clunky, and therefore and excellent candidate for a code redactor.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-21T19:40:31.113",
"Id": "3334",
"Score": "0",
"body": "You are right about ORM. I'm usind marvellous DataMapper and it invokes just one sql statement instead of `city_ids.count` with this code: `City.all(:id => city_ids.compact)`"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-21T15:42:14.020",
"Id": "2027",
"ParentId": "2007",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "2027",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-20T22:15:56.337",
"Id": "2007",
"Score": "4",
"Tags": [
"ruby"
],
"Title": "Nicer way to work params"
} | 2007 |
<p>I had some difficulty with this problem, so I'm sure there is a better way. Here is the question from <a href="http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-16.html" rel="nofollow">SICP</a>:</p>
<blockquote>
<p><strong>Exercise 2.58</strong></p>
<p>Suppose we want to
modify the differentiation program so
that it works with ordinary
mathematical notation, in which + and
* are infix rather than prefix operators. Since the differentiation
program is defined in terms of
abstract data, we can modify it to
work with different representations of
expressions solely by changing the
predicates, selectors, and
constructors that define the
representation of the algebraic
expressions on which the
differentiator is to operate.</p>
<p><strong>a.</strong> Show how to do this in order to
differentiate algebraic expressions
presented in infix form, such as</p>
<pre><code>(x + (3 * (x + (y + 2))))
</code></pre>
<p>To simplify the task, assume that +
and * always take two arguments and
that expressions are fully parenthesized.</p>
<p><strong>b.</strong> The problem becomes substantially
harder if we allow standard algebraic
notation, such as</p>
<pre><code>(x + 3 * (x + y + 2))
</code></pre>
<p>which drops unnecessary
parentheses and assumes that
multiplication is done before
addition. Can you design appropriate
predicates, selectors, and
constructors for this notation such
that our derivative program still
works?</p>
</blockquote>
<p>I wrote the following solution to part b (some parts came from the text):</p>
<pre><code>(define (deriv exp var)
(cond ((number? exp) 0)
((variable? exp)
(if (same-variable? exp var) 1 0))
((sum? exp)
(make-sum (deriv (addend exp) var)
(deriv (augend exp) var)))
((product? exp)
(make-sum
(make-product (multiplier exp)
(deriv (multiplicand exp) var))
(make-product (deriv (multiplier exp) var)
(multiplicand exp))))
(else
(error "unknown expression type -- DERIV" exp))))
(define (variable? x) (symbol? x))
(define (same-variable? v1 v2)
(and (variable? v1) (variable? v2) (eq? v1 v2)))
(define (join op seq)
(foldr (lambda (a b) (cons a (if (null? b) b (cons op b)))) null seq))
(define (make-sum . a)
(define (iter sum rest)
(cond ((null? rest) (if (zero? sum) '() (list sum)))
((=number? (car rest) 0) (iter sum (cdr rest)))
((number? (car rest)) (iter (+ sum (car rest)) (cdr rest)))
(else (cons (car rest) (iter sum (cdr rest))))))
(let ((result (iter 0 a)))
(cond ((null? result) 0)
((= (length result) 1) (car result))
(else (join '+ result)))))
(define (=number? exp num)
(and (number? exp) (= exp num)))
(define (make-product . a)
(define (iter product rest)
(cond ((null? rest) (if (= 1 product) '() (list product)))
((=number? (car rest) 1) (iter product
(cdr rest)))
((number? (car rest)) (iter (* product (car rest))
(cdr rest)))
(else
(let ((result (iter product (cdr rest))))
(if (and (pair? result) (eq? (car result) 0))
(list 0)
(cons (car rest) result))))))
(let ((result (iter 1 a)))
(cond ((null? result) 1)
((eq? (length result) 1) (car result))
(else (join '* result)))))
(define (sum? x)
(and (pair? x)
(or
(member '+ x)
(and (eq? 1 (length x))
(pair? (car x))
(pair? (member '+ (car x)))))))
(define (items-before op seq)
(if (eq? (cadr seq) op)
(list (car seq))
(cons (car seq) (items-before op (cdr seq)))))
(define (items-after op seq)
(if (eq? (car seq) op)
(cdr seq)
(items-after op (cdr seq))))
(define (addend s) (if (and (eq? (length s) 1) (pair? (car s)))
(addend (car s))
(let ((result (items-before '+ s)))
(if (eq? 1 (length result)) (car result) result))))
(define (augend s) (if (and (eq? (length s) 1) (pair? (car s)))
(augend (car s))
(let ((result (items-after '+ s)))
(if (eq? 1 (length result)) (car result) result))))
(define (product? x)
(define (no-plus-just-times seq) (not (member '+ seq)) (pair? (member '* seq)))
(and (pair? x)
(or
(and (no-plus-just-times x))
(and (eq? (length x) 1) (pair? (car x)) (no-plus-just-times (car x))))))
(define (multiplier p) (if (and (eq? (length p) 1) (pair? (car p)))
(multiplier (car p))
(car p)))
(define (multiplicand p) (if (eq? (length p) 1)
(if (pair? (car p))
(multiplicand (car p))
(car p))
(caddr p)))
</code></pre>
<p>How can this be improved?</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-21T01:31:57.973",
"Id": "2009",
"Score": "5",
"Tags": [
"lisp",
"scheme",
"sicp",
"math-expression-eval"
],
"Title": "Standard Algebraic Derivative Calculator"
} | 2009 |
<p>For web-uploading of Cyrillic-named images, I've written the script below:</p>
<pre><code>#!/usr/bin/python
# coding=utf-8
import os
import argparse
import shutil
class Error: pass
class FolderError(Error): pass
def copytranstree (src, dst):
names = os.listdir( src )
try:
os.makedirs( dst )
except WindowsError:
pass
errors = []
for name in names:
srcname = os.path.join( src, name )
dstname = os.path.join( dst, ''.join([translit.get(x, x) for x in name.decode( input_parametres.encoding ).lower()]).encode( input_parametres.encoding ) )
try:
if os.path.isdir( srcname ):
copytranstree( srcname, dstname )
else:
shutil.copy2( srcname, dstname )
except (IOError, os.error), why:
errors.append( ( srcname, dstname, str( why ) ))
except Error, err:
errors.extend( err.args[0] )
try:
shutil.copystat( src, dst )
except WindowsError:
pass
except OSError, why:
errors.extend( (src, dst, str(why) ) )
if errors:
raise Error( errors )
parser = argparse.ArgumentParser(description='Copy directory tree with transliterated pathnames')
parser.add_argument('-e','--encoding', help='File system encoding', default='utf-8')
parser.add_argument('-s','--src', help='Source folder name', default='./' )
parser.add_argument('-d','--dst', help='Destination folder name', default='./')
input_parametres = parser.parse_args()
translit = dict(zip(u"абвгдеёзийклмнопрстуфхьъ", "abvgdeeziyklmnoprstufh'~"))
translit.update({u'ц': 'tz', u'ч': 'ch', u'ш': 'sh', u'ы': 'yi',
u'э': 'ye', u'ю': 'ju', u'я': 'ja', u' ': '_'})
src = os.path.abspath( input_parametres.src )
dst = os.path.abspath( input_parametres.dst )
if not os.path.exists( dst ):
dstname = ''.join([translit.get(x, x) for x in dst.decode( input_parametres.encoding ).lower()]).encode( input_parametres.encoding ).lower()
os.makedirs( dstname )
dst = os.path.abspath( dstname )
if not os.path.exists( src ) or os.path.isfile( dst ):
raise FolderError()
copytranstree( src, dst )
</code></pre>
<p>The script transliterates and copies a tree of files from a source folder to destination, considering encoding passed to the script (UTF for Ubuntu, CP121 for Windows).</p>
<p>Any ideas for common improvement of structure for Linux OS?</p>
| [] | [
{
"body": "<ol>\n<li>All exceptions in python should\ninherit from an Exception class.</li>\n<li>WindowsError only works on Windows, its better to use the more general OSError</li>\n<li>You twice have a very long line to transliterate a string. Put it in a function and call it</li>\n<li>You should put any code that is part of the script proper in a main function.</li>\n<li>You shouldn't throw exceptions that you know won't be caught. </li>\n<li>The way you collect errors by throwing them up the stack is ugly.</li>\n<li>If you split the walking logic from the file operation logic the code will be clearer.</li>\n</ol>\n\n<p>My updates (completely untested and probably wrong):</p>\n\n<pre><code>#!/usr/bin/python\n# coding=utf-8\n\nimport os\nimport argparse\nimport shutil\n\nclass CommandError(Exception):\n \"\"\"\n Thrown when the user has made a mistake in the command line\n \"\"\"\n\ndef transliterated_walk(encoding, src, dst):\n \"\"\"\n A generator which will walk over src producing them\n along with the transliterated versions in dst\n \"\"\"\n files = []\n for filename in os.listdir(src):\n src_path = os.path.join(src, filename)\n dest_path = os.path.join(dest, transliterated(encoding, filename))\n\n if os.path.isdir(path):\n for entry in transliterated_walk(encoding, src_path, dest_path):\n yield entry\n else:\n files.append( (src_path, dest_path) )\n yield src, dest, files\n\ndef copytranstree (encoding, src, dst):\n errors = []\n\n for src_path, dest_path, filenames in transliterated_walk(encoding, src, dest):\n try:\n os.makedirs( dest_path )\n except WindowsError:\n pass\n\n for src_filename, dest_filename in filenames:\n try:\n shutil.copy2( src_filename, dst_filename )\n except (IOError, os.error) as why:\n errors.append( (src_filename, dest_filename, str(why) )\n\n try:\n shutil.copystat( src, dst )\n except OSError as why:\n errors.append( (src_path, dst_path, str(why) ) )\n\n\nTRANSLIT = dict(zip(u\"абвгдеёзийклмнопрстуфхьъ\", \"abvgdeeziyklmnoprstufh'~\"))\nTRANSLIT.update({u'ц': 'tz', u'ч': 'ch', u'ш': 'sh', u'ы': 'yi',\n u'э': 'ye', u'ю': 'ju', u'я': 'ja', u' ': '_'})\n\ndef transliterate(encoding, string):\n decoded = string.decode(encoding).lower()\n transliterated = ''.join(translit.get(x, x) for x in decoded)\n return transliterated.encode(encoding).lower()\n\ndef main():\n try:\n parser = argparse.ArgumentParser(description='Copy directory tree with transliterated pathnames')\n parser.add_argument('-e','--encoding', help='File system encoding', default='utf-8')\n parser.add_argument('-s','--src', help='Source folder name', default='./' )\n parser.add_argument('-d','--dst', help='Destination folder name', default='./')\n\n input_parametres = parser.parse_args()\n\n\n\n src = os.path.abspath( input_parametres.src )\n dst = os.path.abspath( input_parametres.dst )\n\n if not os.path.exists( dst ):\n dstname = transliterate(dst)\n os.makedirs( dstname )\n dst = os.path.abspath( dstname )\n\n if not os.path.exists( src ):\n raise CommandError('%s does not exist' % src)\n if os.path.isfile( dst ):\n raise CommandError('%s is a file' % dest)\n\n copytranstree( encoding, src, dst )\n except CommandError as error:\n print error\n\nif __name__ == '__main__':\n main()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-21T04:27:35.727",
"Id": "2016",
"ParentId": "2011",
"Score": "8"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-21T01:54:43.660",
"Id": "2011",
"Score": "8",
"Tags": [
"python",
"beginner",
"file-system",
"i18n"
],
"Title": "Web-uploading of Cyrillic-named images"
} | 2011 |
<p>From <a href="http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-16.html" rel="nofollow">SICP</a>:</p>
<blockquote>
<p>Exercise 2.60. We specified that a
set would be represented as a list
with no duplicates. Now suppose we
allow duplicates. For instance, the
set {1,2,3} could be represented as
the list (2 3 2 1 3 2 2). Design
procedures element-of-set?,
adjoin-set, union-set, and
intersection-set that operate on this
representation. How does the
efficiency of each compare with the
corresponding procedure for the
non-duplicate representation? Are
there applications for which you would
use this representation in preference
to the non-duplicate one?</p>
</blockquote>
<p>I wrote the following solution (some parts came from the book):</p>
<pre><code>(define (element-of-set? x set)
(cond ((null? set) false)
((equal? x (car set)) true)
(else (element-of-set? x (cdr set)))))
(define adjoin-set cons)
(define (intersection-set set1 set2)
(cond ((or (null? set1) (null? set2)) '())
((element-of-set? (car set1) set2)
(cons (car set1)
(intersection-set (cdr set1) set2)))
(else (intersection-set (cdr set1) set2))))
(define (union-set set1 set2)
(cond ((null? set1) set2)
((null? set2) set1)
(else (cons (car set1) (union-set (cdr set1) set2)))))1)
</code></pre>
| [] | [
{
"body": "<p>Just as <code>adjoin-set</code> simply became <code>cons</code>, <code>union-set</code> can be defined as:</p>\n\n<pre><code>(define union-set append)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-24T12:19:14.127",
"Id": "2063",
"ParentId": "2012",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "2063",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-21T02:01:44.567",
"Id": "2012",
"Score": "4",
"Tags": [
"lisp",
"scheme",
"sicp"
],
"Title": "Set representation allowing duplicates"
} | 2012 |
<p>From <a href="http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-16.html" rel="nofollow">SICP</a>:</p>
<blockquote>
<p><strong>Exercise 2.61</strong></p>
<p>Give an implementation
of adjoin-set using the ordered
representation. By analogy with
element-of-set? show how to take
advantage of the ordering to produce a
procedure that requires on the average
about half as many steps as with the
unordered representation.</p>
</blockquote>
<pre><code>(define (adjoin-set x set)
(define (rec subset)
(cond ((null? subset) (list x))
((> x (car subset)) (cons (car subset) (rec (cdr subset))))
(else (cons x subset))))
(if (element-of-set? x set)
set
(rec set)))
</code></pre>
<p>Can this be improved?</p>
| [] | [
{
"body": "<p>Calling <code>element-of-set?</code> from <code>adjoin-set</code> introduces unnecessary redundancy. One may incorporate this test within the adjoin-set function (in your case, <code>rec</code> should be the main body of your function, with an <code>=</code> test added):</p>\n\n<pre><code>(define (adjoin-set x set)\n (cond\n ((null? set) (cons x set))\n ((= x (car set)) set)\n ((< x (car set)) (cons x set))\n (else (cons (car set) (adjoin-set x (cdr set))))))\n</code></pre>\n\n<p>This function performs fewer steps since it does not call <code>element-of-set?</code>. However, its complexity is still O(n), which is the same as your implementation's complexity, as well as the complexity of <code>element-of-set?</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-24T12:39:36.207",
"Id": "2064",
"ParentId": "2013",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "2064",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-21T02:15:44.297",
"Id": "2013",
"Score": "2",
"Tags": [
"lisp",
"scheme",
"sicp"
],
"Title": "Adjoin-set for an ordered set representation"
} | 2013 |
<p>I've just finished the Ruby Koans and one of the last projects was creating a Proxy class that sends methods to another class. I was wondering whether you would change anything about my solution (if there's something wrong or a better way to do it). I'm still a beginner and I want to get better.</p>
<pre><code>require File.expand_path(File.dirname(__FILE__) + '/edgecase')
# Project: Create a Proxy Class
#
# In this assignment, create a proxy class (one is started for you
# below). You should be able to initialize the proxy object with any
# object. Any messages sent to the proxy object should be forwarded
# to the target object. As each message is sent, the proxy should
# record the name of the method send.
#
# The proxy class is started for you. You will need to add a method
# missing handler and any other supporting methods. The specification
# of the Proxy class is given in the AboutProxyObjectProject koan.
class Proxy
attr_reader(:messages)
def method_missing(method_name, *args, &block)
if @methods_to_pass.include?(method_name.to_s)
@messages << method_name
@object.__send__(method_name, *args, &block)
else
super(method_name, *args, &block)
end
end
def called?(method_name)
@messages.include?(method_name)
end
def number_of_times_called(method_name)
@messages.count(method_name)
end
def initialize(target_object)
@methods_to_pass, @messages = [], []
@object = target_object
@object.class.instance_methods(true).each { |method_name| @methods_to_pass << method_name; method_name }
end
end
# The proxy object should pass the following Koan:
#
class AboutProxyObjectProject < EdgeCase::Koan
def test_proxy_method_returns_wrapped_object
# NOTE: The Television class is defined below
tv = Proxy.new(Television.new)
assert tv.instance_of?(Proxy)
end
def test_tv_methods_still_perform_their_function
tv = Proxy.new(Television.new)
tv.channel = 10
tv.power
assert_equal 10, tv.channel
assert tv.on?
end
def test_proxy_records_messages_sent_to_tv
tv = Proxy.new(Television.new)
tv.power
tv.channel = 10
assert_equal [:power, :channel=], tv.messages
end
def test_proxy_handles_invalid_messages
tv = Proxy.new(Television.new)
assert_raise(NoMethodError) do
tv.no_such_method
end
end
def test_proxy_reports_methods_have_been_called
tv = Proxy.new(Television.new)
tv.power
tv.power
assert tv.called?(:power)
assert ! tv.called?(:channel)
end
def test_proxy_counts_method_calls
tv = Proxy.new(Television.new)
tv.power
tv.channel = 48
tv.power
assert_equal 2, tv.number_of_times_called(:power)
assert_equal 1, tv.number_of_times_called(:channel=)
assert_equal 0, tv.number_of_times_called(:on?)
end
def test_proxy_can_record_more_than_just_tv_objects
proxy = Proxy.new("Code Mash 2009")
proxy.upcase!
result = proxy.split
assert_equal ["CODE", "MASH", "2009"], result
assert_equal [:upcase!, :split], proxy.messages
end
end
# ====================================================================
# The following code is to support the testing of the Proxy class. No
# changes should be necessary to anything below this comment.
# Example class using in the proxy testing above.
class Television
attr_accessor :channel
def power
if @power == :on
@power = :off
else
@power = :on
end
end
def on?
@power == :on
end
end
# Tests for the Television class. All of theses tests should pass.
class TelevisionTest < EdgeCase::Koan
def test_it_turns_on
tv = Television.new
tv.power
assert tv.on?
end
def test_it_also_turns_off
tv = Television.new
tv.power
tv.power
assert ! tv.on?
end
def test_edge_case_on_off
tv = Television.new
tv.power
tv.power
tv.power
assert tv.on?
tv.power
assert ! tv.on?
end
def test_can_set_the_channel
tv = Television.new
tv.channel = 11
assert_equal 11, tv.channel
end
end
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-29T12:58:00.283",
"Id": "3505",
"Score": "0",
"body": "I'm also experimenting with Ruby, and am looking for examples/a tutorial/exercises which discuss the more advanced ruby features. I finished the chapter in 7 languages in 7 weeks, but apparently [there is more to ruby](http://forums.pragprog.com/forums/147/topics/4414). Judging from the index of files of the koans it is also quite limited. Any other resources, or am I mistaken?"
}
] | [
{
"body": "<pre><code>@methods_to_pass, @messages = [], []\n@object = target_object\n@object.class.instance_methods(true).each { |method_name| @methods_to_pass << method_name; method_name }\n</code></pre>\n\n<p>Couple of things to note here:</p>\n\n<p>First of all the <code>; method_name</code> bit is completely unnecessary. I don't know why you put that there, but it serves no purpose and just confuses the reader.</p>\n\n<p>Secondly <code>foo = []; bar.each {|x| foo << x}</code> is an overly verbose way to copy an array. You can just say <code>foo = bar.dup</code>. However in this case there is no reason to perform a copy, so you can just say <code>foo = bar</code>, i.e. <code>@methods_to_pass = @object.class.instance_methods(true)</code> (but don't - see below).</p>\n\n<p>That being said storing the methods in an array like that is a bad idea for two reasons:</p>\n\n<ol>\n<li>Since checking whether an item is in an array is <code>O(n)</code>, your <code>method_missing</code> method and thus every proxied call becomes <code>O(n)</code>. This is needlessly inefficient.</li>\n<li>If <code>@object</code> has singleton methods or dynamically defined methods, those won't be forwarded as they won't show up in <code>@object.class.instance_methods</code>.</li>\n</ol>\n\n<p>To fix these issues you should get rid of <code>@methods_to_pass</code> and instead use one of the following approaches:</p>\n\n<p>Option a:</p>\n\n<p>In <code>method_missing</code> replace <code>if @methods_to_pass.include?(method_name.to_s)</code> with <code>if @object.respond_to?(method_name)</code>. This will be faster than searching through an array and it will also work for dynamically defined or singleton methods. However it will not work if <code>@object</code> has a custom <code>method_missing</code> method and does not override <code>respond_to?</code> to be in sync with <code>method_missing</code>. If you want to handle that case as well, you'll need to use one of the other two options.</p>\n\n<p>Option b:</p>\n\n<p>Just remove the whole <code>if</code> and always forward (and record) the method call. This way the behavior will be different from your code as invalid calls will be recorded in <code>@messages</code>. However since they will still cause a <code>NoMethodError</code> and the assignment doesn't actually state whether invalid calls should be recorded or not, it still meets the requirements.</p>\n\n<hr>\n\n<p>Now let's talk about the <code>@messages</code> array:</p>\n\n<p>Using an array to store the messages and then using <code>count</code> to find out how often a given message appears is again needless inefficient. What I'd do instead is use a <code>Hash</code> which maps each message to the number of times it's been called. This way you'd write <code>@message = Hash.new(0)</code> instead of <code>@messages = []</code>, <code>@messages[method_name] += 1</code> instead of <code>@messages << method_name</code> and <code>@messages[method_name]</code> instead of <code>@messages.count(method_name)</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-24T13:40:47.067",
"Id": "2067",
"ParentId": "2015",
"Score": "11"
}
},
{
"body": "<p>sepp2k's responses are all good, I would add one more suggestion. Your Proxy class should derive from BasicObject (if you use ruby 1.9.x). At the moment any method defined on <code>Proxy</code> is by definition <em>not</em> missing. For example given: </p>\n\n<pre><code>foo = Foo.new\npfoo = Proxy.new(foo)\n</code></pre>\n\n<p>if I asked for <code>pfoo.class</code> I would get <code>Proxy</code> because <code>class</code> is a method in the inheritance of Proxy. With <code>BasicObject</code> this would instead return <code>Foo</code> and add an entry for <code>\"class\"</code> in the proxy object.</p>\n\n<p>One other nit to pick, I would add an underscore in front of <code>called</code> and <code>number_of_times_called</code>. Putting an underscore in a method is a clue to other programmers that the method is outside the normal operation of a class. In this case it will help prevent name collision with the object you are going to proxy to. The truly paranoid would actually call a method on a separate object to count calls leaving the entire namespace unused. Think what would happen if you tried to proxy a <code>Proxy</code> instance. :) </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-29T00:18:12.230",
"Id": "2151",
"ParentId": "2015",
"Score": "3"
}
},
{
"body": "<p>In my view, there were problems with every one of the suggested solutions, which is why I took a different approach: the wrapper class dynamically programs itself during object initialization: it just \"implements\" <em>every single public method</em> (except for a few system-specific ones) of the wrapped class by recording its name and forwarding the call to the wrapped object.</p>\n\n<p>In this way, not only methods that are <strong><em>not</em></strong> defined in the wrapper class are forwarded, but also (most of) those that <strong><em>are</em></strong> defined. This is crucial if the wrapped class (<code>Television</code> in this example) overwrites some standard method such as <code>to_s</code>. In all the other solutions above, sending the <code>to_s</code> message to the wrapper object will just call the wrapper's <code>to_s</code> (inherited from <code>Object</code>). In my solution, the method being called really is the wrapped object's <strong>own</strong> <code>to_s</code> method.</p>\n\n<p>Moreover, I think my approach is the only one here that makes the wrapper object reply to <code>respond_to?</code> correctly, i.e. returning <code>true</code> for all the methods defined in the wrapped class.</p>\n\n<pre><code>class Proxy\n attr_reader :messages # return an array of messages called\n\n def initialize(target_object)\n @object = target_object\n @methods_called = Hash.new(0);\n @messages = [] # Array for storing the message names\n\n # For each of the object's methods\n methods_to_forward = @object.methods - [:__send__, :object_id, :instance_of?, :method_missing]\n methods_to_forward.each do |method|\n eval \"\"\" def #{method}(*args, &block)\n @methods_called[:#{method}] += 1\n @messages.push :#{method}\n @object.send(:#{method}, *args, &block)\n end \n \"\"\"\n end\n end\n\n def called? method\n number_of_times_called(method) > 0 \n end\n\n def number_of_times_called(method)\n @methods_called[method]\n end\nend\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-23T19:58:21.620",
"Id": "6236",
"ParentId": "2015",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-21T02:38:11.667",
"Id": "2015",
"Score": "11",
"Tags": [
"ruby",
"beginner",
"proxy"
],
"Title": "Ruby Koans Proxy Project"
} | 2015 |
<p>From <a href="http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-16.html" rel="nofollow">SICP</a>:</p>
<blockquote>
<p><strong>Exercise 2.65</strong></p>
<p>Use the results of
exercises 2.63 and 2.64 to give (n)
implementations of union-set and
intersection-set for sets implemented
as (balanced) binary trees.41</p>
</blockquote>
<p>I wrote the following answer:</p>
<pre><code>(define (union-set a b)
(define (rec set1 set2)
(cond ((null? set1) set2)
((null? set2) set1)
((= (car set1) (car set2)) (cons (car set1) (union-set (cdr set1) (cdr set2))))
((> (car set1) (car set2)) (cons (car set1) (union-set (cdr set1) set2)))
(else (cons (car set2) (rec set1 (cdr set2))))))
(let ((ls-result (rec (tree->list a) (tree->list b))))
(partial-tree ls-result (length ls-result))))
(define (intersection-set a b)
(define (rec set1 set2)
(cond ((or (null? set1) (null? set2)) '())
((= (car set1) (car set2)) (cons (car set1) (rec (cdr set1) (cdr set2))))
((> (car set1) (car set2)) (rec set1 (cdr set2)))
((> (car set2) (car set1)) (rec (cdr set1) set2))))
(let ((ls-result (rec (tree->list a) (tree->list b))))
(partial-tree ls-result (length ls-result))))
</code></pre>
<p>Is this answer ok? Could it be better?</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-21T07:15:41.693",
"Id": "2018",
"Score": "2",
"Tags": [
"tree",
"lisp",
"scheme",
"sicp"
],
"Title": "Union-set intersection-set for a binary-tree implementation of sets"
} | 2018 |
<p>I'm writing a function with the following signature:</p>
<pre><code>(Ord a) => [a] -> [Int]
</code></pre>
<p>It's semantics is to find an order-preserving mapping from list of objects to list of <code>Int</code>s.</p>
<p>The version of mine:</p>
<pre><code>import Data.List
import Data.Map (Map, (!))
import qualified Data.Map as Map
renumber :: (Ord a) => [a] -> [Int]
renumber list = let mapping = buildmapping list Map.empty in
map (mapping!) list
where
-- buildmapping :: (Ord a) => [a] -> Map a Int -> Map a Int
buildmapping list mapping = let
mapped = Map.keys mapping
(rest, nextindex) = if (null mapped) then
(list, 1) else
(filter (> maximum mapped) list,
(1+) $ maximum $ Map.elems mapping)
in case rest of
[] -> mapping -- nothing left, return
_ -> buildmapping rest $ Map.insert (minimum rest) nextindex mapping
</code></pre>
| [] | [
{
"body": "<p>I think a sorting-based approach would be simpler than using a map. The basic idea is that we sort the list, assign each item a value based on its position in the list, then undo the sorting and take the value assigned to each item. In order to undo the sorting we have to remember the position each item was at before the sort. So we get the following steps (illustrated using the example input <code>[\"a\", \"c\", \"b\", \"c\"]</code>):</p>\n\n<ol>\n<li>Annotate each item with its index. So <code>[\"a\",\"c\",\"b\",\"c\"]</code> becomes <code>[(1, \"a\"), (2, \"c\"), (3, \"b\"), (4, \"c\")]</code>.</li>\n<li>Sort the annotated items by their value. So for the example we get <code>[(1, \"a\"), (3, \"b\"), (2, \"c\"), (4, \"c\")]</code></li>\n<li>Group the sorted annotated items by their values, so that duplicate items get assigned the same number in the next step. In the example: <code>[[(1, \"a\")], [(3, \"b\")], [(2, \"c\"), (4, \"c\")]]</code></li>\n<li>Now annotate each group with its index again. In the example: <code>[(1, [(1, \"a\")]), (2, [(3, \"b\")]), (3, [(2, \"c\"), (4, \"c\")])]</code>.</li>\n<li>Flatten the groups, so that instead of a list of groups we have a list of items again where each item has an old index and new index. In the example: <code>[(1, (1, \"a\")), (2, (3, \"b\")), (3, (2, \"c\")), (3, (4, \"c\"))]</code>.</li>\n<li>Now undo the sorting by sorting the items by their old index. In the example: <code>[(1, (1, \"a\")), (3, (2, \"c\")), (2, (3, \"b\")), (3, (4, \"c\"))]</code>.</li>\n<li>Lastly map each item to their new index. So for the example we get the output <code>[1,3,2,3]</code>.</li>\n</ol>\n\n<p>This leads to the following code:</p>\n\n<pre><code>{-# LANGUAGE TupleSections #-}\nimport Data.List\nimport Data.Function (on)\nimport Data.Ord (comparing)\n\nrenumber :: (Ord a) => [a] -> [Int]\nrenumber = map fst . unsort . number . indexAndSort\n where\n indexAndSort = sortBy (comparing snd) . zip [1..]\n number = concatMap (\\(i,xs) -> map (i,) xs) . zip [1..] . groupBy ((==) `on` snd)\n unsort = sortBy (comparing (fst . snd))\n</code></pre>\n\n<p>Note that I chose 1-based indices instead of 0-based indices because you start numbering at 1 as well and this way my code produces the same results as yours.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-24T07:41:16.983",
"Id": "3360",
"Score": "0",
"body": "I have tried some `group . sort`-based solutions too, but didn't reach the unsorting part. This way it feels more efficient too, since my algorithm is selection-sort-like, hence quadratic, while `sort` can be `O(n log n)`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-21T14:45:22.750",
"Id": "2026",
"ParentId": "2019",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "2026",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-21T07:45:08.597",
"Id": "2019",
"Score": "4",
"Tags": [
"functional-programming",
"haskell"
],
"Title": "Most elegant approach to writing list renumbering function"
} | 2019 |
<p>I have ext_scaffold (<code>question.js</code>). When I row click I get answers on this question, so</p>
<pre><code>'rowselect': function(sm, row, rec) {
store = new Ext.data.Store({
proxy: new Ext.data.HttpProxy({
url: '/answers/index_all_for_question_id/' + rec.data.id + '?format=ext_json',
method: 'GET'}),
reader: new Ext.data.JsonReader({
root: 'answers',
id: 'id',
totalProperty: 'results'
}, [
{name: 'text', mapping: 'answer.text'},
{name: 'email', mapping: 'answer.respondent.email'}
])
});
grid = Ext.getCmp('answers_grid');
grid.reconfigure(store, new Ext.grid.ColumnModel([
{id: 'text', header: "Answer &darr;", width: 500, sortable: true, dataIndex: 'text'},
{id: 'email', header: "Email", width: 300, sortable: true, dataIndex: 'email'}
]));
grid.store.load();
scaffoldPanel.selectedRecordId = rec.data.id;
scaffoldPanel.getFormPanel().getForm().loadRecord(rec);
}
</code></pre>
<p>and I have another admin file where grids (answer):</p>
<pre><code> var answers_datastore = new Ext.data.Store({
autoLoad: true,
proxy: new Ext.data.HttpProxy({
url: '/answers/index_all_for_question_id/<%= @questions.first.id %>?format=ext_json',
method: 'GET'}),
reader: new Ext.data.JsonReader({
root: 'answers',
id: 'id',
totalProperty: 'results'
},[
{name: 'text', mapping: 'answer.text'},
{name: 'email', mapping: 'answer.respondent.email'}
])
});
var answersGrid = new Ext.grid.GridPanel({
id: 'answers_grid',
store: answers_datastore,
frame: true,
columns: [
{id: 'text', header: "Answer &darr;", width: 500, sortable: true, dataIndex: 'text'},
{id: 'email', header: "Email", width: 300, sortable: true, dataIndex: 'email'}
],
listeners: {
rowdblclick: function(answersGrid, rowI, event) {
Ext.MessageBox.show({
title: "Answer" ,
msg: "A",
closable: true,
autowidth: true
});
}
},
stripeRows: true,
title:'Answers'
});
</code></pre>
<p>How to avoid duplication?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-09T21:53:16.003",
"Id": "10403",
"Score": "0",
"body": "How about something as simple as putting your duplicated values in a variable that you access from both files?"
}
] | [
{
"body": "<p>The trouble with your question is that the code resembles more config than coding and there is nothing wrong with it except that it is not DRY between those 2 files.</p>\n\n<p>It seems that Ext JS supports <code>require</code> as of version 4, so you simply need to extract the common logic/config into a file that you will <code>require</code> into both places.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-27T20:04:00.250",
"Id": "40199",
"ParentId": "2021",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-21T12:24:26.637",
"Id": "2021",
"Score": "4",
"Tags": [
"javascript",
"ext.js"
],
"Title": "Ext JS: Avoid duplication"
} | 2021 |
<p>From <a href="http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-16.html" rel="nofollow">SICP</a>:</p>
<blockquote>
<p>Exercise 2.66. Implement the lookup
procedure for the case where the set
of records is structured as a binary
tree, ordered by the numerical values
of the keys.</p>
</blockquote>
<p>I wrote the following:</p>
<pre><code>(define key car)
(define make-record cons)
(define value cadar)
(define (lookup given-key set-of-records)
(cond ((null? set-of-records) false)
((equal? given-key (key (car set-of-records)))
(car set-of-records))
((< given-key (key (car set-of-records))) (lookup given-key (left-branch set-of-records)))
(else (lookup given-key (right-branch set-of-records)))))
</code></pre>
<p>(The following part is from the book)</p>
<pre><code>(define (entry tree) (car tree))
(define (left-branch tree) (cadr tree))
(define (right-branch tree) (caddr tree))
(define (make-tree entry left right)
(list entry left right))
(define (list->tree elements)
(car (partial-tree elements (length elements))))
(define (partial-tree elts n)
(if (= n 0)
(cons '() elts)
(let ((left-size (quotient (- n 1) 2)))
(let ((left-result (partial-tree elts left-size)))
(let ((left-tree (car left-result))
(non-left-elts (cdr left-result))
(right-size (- n (+ left-size 1))))
(let ((this-entry (car non-left-elts))
(right-result (partial-tree (cdr non-left-elts)
right-size)))
(let ((right-tree (car right-result))
(remaining-elts (cdr right-result)))
(cons (make-tree this-entry left-tree right-tree)
remaining-elts))))))))
</code></pre>
<p>How can my answer be improved?</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-21T13:41:09.663",
"Id": "2024",
"Score": "4",
"Tags": [
"lisp",
"scheme",
"sicp",
"lookup"
],
"Title": "Search on a binary tree"
} | 2024 |
<p>The <code>ConcurrentDictionary<T,V></code> in .NET 4.0 is thread safe but not all methods are atomic.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/dd997369.aspx">This</a> points out that:</p>
<blockquote>
<p>... not all methods are atomic, specifically <code>GetOrAdd</code> and <code>AddOrUpdate</code>. The user delegate that is passed to these methods is invoked outside of the dictionary's internal lock.</p>
</blockquote>
<p><strong>Example Problem:</strong></p>
<p>It is possible for the delegate method to be executed more than once for a given key.</p>
<pre><code>public static readonly ConcurrentDictionary<int, string> store =
new ConcurrentDictionary<int, string>();
[TestMethod]
public void UnsafeConcurrentDictionaryTest()
{
Thread t1 = new Thread(() =>
{
store.GetOrAdd(0, i =>
{
string msg = "Hello from t1";
Trace.WriteLine(msg);
Thread.SpinWait(10000);
return msg;
});
});
Thread t2 = new Thread(() =>
{
store.GetOrAdd(0, i =>
{
string msg = "Hello from t2";
Trace.WriteLine(msg);
Thread.SpinWait(10000);
return msg;
});
});
t1.Start();
t2.Start();
t1.Join();
t2.Join();
}
</code></pre>
<p>The result shown in the Trace window shows "<strong>Hello from t1</strong>" and "<strong>Hello from t2</strong>". This is NOT the desired behavior for most implementations that we are using and confirms the problem noted in the MSDN link above. What we want is for only <em>one</em> of those delegates to be executed.</p>
<p><strong>Proposed Solution:</strong></p>
<p>I have to use the delegate overloads of these methods which led me to investigate this matter further. I stumbled onto <a href="http://kozmic.pl/2010/08/06/concurrentdictionary-in-net-4-not-what-you-would-expect/">this post</a> which suggests using the <code>Lazy<T></code> class to ensure the delegate is only invoked once. With that in mind I wrote the following extension methods to mask the adding of a <code>Lazy<T></code> wrapper to the value.</p>
<pre><code>public static V GetOrAdd<T, U, V>(this ConcurrentDictionary<T, U> dictionary, T key, Func<T, V> valueFactory)
where U : Lazy<V>
{
U lazy = dictionary.GetOrAdd(key, (U)new Lazy<V>(() => valueFactory(key)));
return lazy.Value;
}
public static V AddOrUpdate<T, U, V>(this ConcurrentDictionary<T, U> dictionary, T key, Func<T, V> addValueFactory, Func<T, V, V> updateValueFactory)
where U : Lazy<V>
{
U lazy = dictionary.AddOrUpdate(key,
(U)new Lazy<V>(() => addValueFactory(key)),
(k, oldValue) => (U)new Lazy<V>(() => updateValueFactory(k, oldValue.Value)));
return lazy.Value;
}
</code></pre>
<p><strong>Testing Solution:</strong></p>
<p>Executing the same test above using a <code>ConcurrentDictionary</code> that has a Lazy value results in the value delegate ONLY being executed once (you either see "<strong>Hello from t1</strong>" or "<strong>Hello from t2</strong>")! </p>
<pre><code>public static readonly ConcurrentDictionary<int, Lazy<string>> safeStore =
new ConcurrentDictionary<int, Lazy<string>>();
</code></pre>
<p>So it seems that this approach accomplished the goal.</p>
<p>What do you think of this approach?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-10T18:57:45.713",
"Id": "12000",
"Score": "0",
"body": "So does this mean that if the dictionary was exposed by a third party and was not defined as a <T,Lazy<V>>, you would not be able to do it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-10T19:27:22.700",
"Id": "12003",
"Score": "0",
"body": "@Daryl I don't get your question. These extension methods are designed to operate on a `Dictionary<T, Lazy<V>>`. If the third party doesn't expose the dictionary as that, then you could not use these extension methods without first converting it that type."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-11T19:58:43.470",
"Id": "12104",
"Score": "0",
"body": "Your proposed solution was defined as a dictionary of type <T, U> but your accepted solution moved to one of type <T, Lazy<V>>. I was hoping to get this sort of functionality, without having to change my dictionary to <T, Lazy<V>>. I've instead settled on passing in a object to use as the lock"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-07T09:10:44.690",
"Id": "438349",
"Score": "0",
"body": "It might be worth noting that this approach is not fully thread safe, it just reduces the chance of race a condition, but one can still occur. Consider a case in which the first thread calls Lazy.Value after the assignment of the first Lazy instance and before the the second one's. The next call to Lazy.Value will invoke the method again. This could be a real problem in very high performance applications."
}
] | [
{
"body": "<ul>\n<li><p>Allowing the caller to provide the type argument <code>U</code> implies that they are allowed to use a subclass of <code>Lazy<V></code>, but this will not work as your implementations always creates a new <code>List<V></code> and cast it to <code>U</code>. Since this means <code>U</code> must always be a <code>Lazy<V></code> then why not do away with the extra type argument.</p>\n\n<pre><code>public static V GetOrAdd<T, V>(this ConcurrentDictionary<T, Lazy<V>> dictionary, T key, Func<T, V> valueFactory)\n</code></pre></li>\n<li><p>The name of the new extension methods conflict with the names of the existing methods. For the consumer to use yours instead of the existing methods, they would need to either access via your static class or use explicit type arguments. This could lead to subtle bugs when consumers try to use it as a extension method with type inference.</p>\n\n<pre><code>ExtensionHost.GetOrAdd(safeStore, 7, (i) => i.ToString()); // uses yours\nsafeStore.GetOrAdd<int, Lazy<string>, string>(6, (i) => i.ToString()); // uses yours\nsafeStore.GetOrAdd(5, (i) => i.ToString()); // uses existing\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-23T03:36:09.930",
"Id": "3347",
"Score": "0",
"body": "Thanks for your notes. Great point about the type `U`. Also, I have already been bitten by the _subtle bug_. I agree that my overload too closely resembles the existing `GetOrAdd()` method. I'll incorporate your recommendations."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-23T03:05:00.000",
"Id": "2040",
"ParentId": "2025",
"Score": "15"
}
}
] | {
"AcceptedAnswerId": "2040",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-21T14:27:47.290",
"Id": "2025",
"Score": "35",
"Tags": [
"c#",
"thread-safety"
],
"Title": "Extension methods to make ConcurrentDictionary GetOrAdd and AddOrUpdate thread safe when using valueFactory delegates"
} | 2025 |
<p>I have two elements on my page:</p>
<pre><code><ul id="VerticalMenu></ul>
<ul id="AccordionMenu"></ul>
</code></pre>
<p>I'm calling some JSON with jQuery and loading elements in the <code>div</code>s. I'm curious if there are things I can be doing more efficiently, and better ways to use selectors and JSON.</p>
<pre><code>$().ready(function() {
//Load sections
GetCarlineSections(_BucketID);
});
function GetCarlineSections(bucketID) {
//Get section json list
$.ajax(
{
type: "POST",
url: _ApplicationRootURL + 'GetChildBucketList', //Call the ActionResult to return the JSON object
data: 'parentID=' + bucketID,
success: function (sections) { //'sections' is an array of JSON objects returned by GetChildBucketList
$(sections).each(function () {
$('#VerticalMenu') //Append each item to the #VerticalMenu <ul>
.append(
$('<li/>') //Append a new <li> element to <ul> #VerticalMenu
.addClass('Section')
.html(
$('<h4/>') //Create a new <h4> inside of the <li>
.addClass(this.BucketName)
.html(this.BucketName)
.click({ parentID: this.BucketID }, function (event) { //Attach a click event to the <h4> element
$('#AccordionMenu').empty();
GetSectionSubSections(event.data.parentID); //Event.data.parentID is the id of the bucket represented by this <h4> element
})
)
);
});
}
});
}
function GetSectionSubSections(bucketID) {
$.ajax(
{
type: "POST",
url: _ApplicationRootURL + 'GetChildBucketList',
data: 'parentID=' + bucketID,
success: function (SubSections) { //SubSections are the children buckets of Section, local var bucketID
$(SubSections).each(function () {
$('#AccordionMenu')
.append(
$('<li/>')
.addClass('SubSection')
.html(
$('<h4/>')
.addClass(this.SEOURLName)
.html(this.BucketName)
.click({ parentID: this.BucketID }, function (event) { //Eventdata parentID passes the SubSectionID to the event object
GetSubSectionHeadlines(this, event.data.parentID)
})
)
);
});
}
});
}
function GetSubSectionHeadlines(parentElement, SubSectionID) {
//Get the Headlines based on the parent SubSection
$(parentElement).after($('<ul/>').addClass(parentElement.className));
$.ajax({
type: 'POST',
url: _ApplicationRootURL + 'GetChildBucketList',
data: 'parentID=' + SubSectionID,
success: function (Headlines) {
$(Headlines).each(function () {
$('ul.' + parentElement.className).prepend(
$('<li/>')
.html(this.BucketName)
)
})
}
});
}
</code></pre>
| [] | [
{
"body": "<p>Two small nickpicks at the start: </p>\n\n<ul>\n<li>Empty HTML lists (<code>ul</code>, <code>ol</code>) are strictly spoken invalid. They should contain at least one list item. That said, I believe there is no browser limitation or other technical reason an empty list shouldn't work.</li>\n<li>It is custom for the names of functions, variables and object fields in JavaScript to be written with a small letter at the beginning.</li>\n</ul>\n\n<p>You can optimize adding the list item to the list, by using <code>.map()</code> to create the items and appending them all at once. </p>\n\n<pre><code>$('#VerticalMenu') \n .append(\n $(sections).map(function () {\n $('<li/>') \n // ...\n })\n );\n</code></pre>\n\n<p>BTW, since sections is an array of simple JavaScript objects and not DOM objects it's a bit weird to wrap them in a jQuery object (<code>$(sections).each(...)</code>), because jQuery unwraps them immediately anyway. You should use <code>$.each(sections, ... )</code> (or <code>$.map(sections, ... )</code>) instead.</p>\n\n<p>You are assigning all items in your lists the same class (<code>Section</code> and <code>SubSection</code> respectively). Unless you remove the class later, this is usually a sign of wrong CSS design. If you leave out the class, then instead of the selector <code>.Section { ... }</code> you can use a descendent selector: <code>#VerticalMenu li { ... }</code>.</p>\n\n<p>One last thing: The use of <code>h4</code> elements seems wrong to me. Either this is a menu, then you shouldn't be using header elements at all, or the items in AccordionMenu are subheadlines and be using <code>h5</code> instead.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-22T13:09:48.093",
"Id": "3340",
"Score": "0",
"body": "Awesome. This is exactly the kind of feedback I was looking for. Don't feel bad about being nitpicky, it's that kind of stuff that makes for strong development."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-22T08:03:52.943",
"Id": "2033",
"ParentId": "2028",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "2033",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-21T17:19:17.943",
"Id": "2028",
"Score": "5",
"Tags": [
"javascript",
"jquery",
"json"
],
"Title": "Getting JSON with jQuery and creating lists with click events calling more jQuery and JSON"
} | 2028 |
<p>This journey started with a quest to <a href="https://stackoverflow.com/questions/1297020/creating-the-shortest-possible-case-insensitive-verification-number">create the shortest possible case-insensitive verification number</a>. Based on the answers there, I worked out a <a href="https://stackoverflow.com/questions/1300846/classic-asp-vbscript-implementation-of-crawfords-base32-encoding">Classic ASP/VBScript implementation of Crockford's Base32 Encoding</a> and it has served me well so far.</p>
<p>Out of semi-idle curiosity, I was wondering if there was a way to further improve the performance. To be clear: it works, and it runs more than fast enough. I am planning to use it more extensively and since I never heard back on a better way, I was hoping for a second set of eyes to say "yes, it's as good as it's going to get" or "here's how to make it more awesome" or whatever.</p>
<p>So you don't have to go back to the latter Stack Overflow question to see the code, here it is:</p>
<pre><code>'Base32 encoding functions for shorter, less confusing verification numbers
Const kBase32Digits = "0123456789abcdefghjkmnpqrstvwxyz"
Function ToBase32(ByVal lInput)
Dim lModulo, sTemp
Do Until lInput = 0
lModulo = lInput Mod 32
sTemp = Mid(kBase32Digits, lModulo + 1, 1) & sTemp
lInput = lInput \ 32
Loop
ToBase32 = sTemp
End Function
Function FromBase32(ByVal sInput)
Dim sTemp, sR, i,iY,lLen, zMultiplier
sTemp = LCase(sInput)
sTemp = Replace(sTemp,"o","0")
sTemp = Replace(sTemp,"i","1")
sTemp = Replace(sTemp,"l","1")
sTemp = Replace(sTemp,"u","v")
zMultiplier = 1
lLen = Len(sTemp)
For i = lLen To 1 Step -1
sR = Mid(sTemp, i, 1)
iY = InStr(1, kBase32Digits, sR, vbTextCompare) - 1
FromBase32 = FromBase32 + iY * zMultiplier
zMultiplier = zMultiplier * 32
Next
End Function
</code></pre>
| [] | [
{
"body": "<p>If you really want to chase those milliseconds then I would try following: </p>\n\n<p>1) I consider division operations as slow so I would avoid using two divisions if it can be replaced with one division and some easier operation: </p>\n\n<pre><code>Function ToBase32(ByVal lInput)\n Dim lModulo, sTemp, lNextInput\n Do Until lInput = 0\n lNextInput = lInput \\ 32\n lModulo = lInput - 32 * lNextInput\n sTemp = Mid(kBase32Digits, lModulo + 1, 1) & sTemp\n lInput = lNextInput\n Loop\n ToBase32 = sTemp\nEnd Function\n</code></pre>\n\n<p>2) In some other language I would use bit shift of course instead of diviosion/multiply. But as far as I got vbscript doesn't have bit shifting operators. </p>\n\n<p>3) Your <code>FromBase32</code> method doesn't look optimal to me at all. I would replace those <code>Replace</code> and <code>InStr</code> calls with array of integers for letter chars. This array will contains corresponding base 32 numbers for chars. And you will be able to translate letter into number using array indexing accessor which is much faster operation than looking for a character in a string. Some pseudocode showing how to convert character <code>sR</code> into number: </p>\n\n<pre><code>Dim sR;\n\n// defining an array:\nDim charArray = [ 10, // 'a' char\n 11, // 'b' char\n ...\n 17, // 'h'\n 1 , // 'i' !! \n ...\n 0 , // 'o'\n ...];\n\nDim lNumber;\nif (sR >= 'a' && sR <= 'z')\n lNumber = charArray[sR - 'a'];\nelse // it is digit\n lNumber = sR - '0' // in most languages I know this will convert '1' char into 1 integer\n</code></pre>\n\n<p>P.S. of course I haven't measured anything, I do not even know vbscript, just wanted to give you an idea on what can be changed. </p>\n\n<p>P.P.S.: My second point doesn't take into account that there is a chance that VBScript interpreter will do such an optimization for you.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-21T21:17:24.437",
"Id": "2031",
"ParentId": "2029",
"Score": "5"
}
},
{
"body": "<p>In the <code>FromBase32</code> function, don't use <code>vbTextCompare</code> in your call to <code>InStr</code>. You've already <code>LCase</code>'d the string, so you're just wasting cycles by doing a text comparison.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-07-13T06:48:14.180",
"Id": "3419",
"ParentId": "2029",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-21T19:04:18.143",
"Id": "2029",
"Score": "8",
"Tags": [
"algorithm",
"optimization",
"vbscript",
"asp-classic"
],
"Title": "Is there a more efficient way to do Base 32 encoding/decoding than this?"
} | 2029 |
<p>I don't have any questions about this piece of code; it compiles just fine in Visual Studio 2010. I just wanted to post it to see if anyone has any good ideas on how to simplify it, or pointing out any bad practices I have have done.</p>
<pre><code>// Tic Tac Toe Game
#include <iostream>
#include <iomanip>
using namespace std;
class TicTacToe
{
private:
char Board[3][3];
int play();
void playermove();
int turn(int);
int check (int, int);
void boardProgress(char x[][3]);
int Winner(char x[][3]);
int player1, player2, draw, player,winner,done;
int row, col;
public:
int TG, T1, T2, TD;
void intBoard();
int Stats(int);
char playAgain(char);
}playBall;
int main()
{
playBall.TG = 0,playBall.T1 = 0,playBall.T2 = 0,playBall.TD = 0;
int Winner = 0;
// This will only display when the program is first run
cout << "You, are about to witness the program of the century.\n\n";
char done = false;
while (!done)
{
// This will display before each game
cout << "COMMENCE TIC TAC TOE!!!!\n\n"
"Ladies first, please pick the row then the column (1 through 3).\n\n";
// Play a game and remember who won (if anyone)
playBall.intBoard();
//If you want to play again or not
done = playBall.playAgain(done);
}
// Finish
cout << "\n\nThank you for playing!\n";
system ("pause");
return 0;
}
void TicTacToe::intBoard()
{
done = false;
winner = 0;
player = 2;
player1 = 1;
player2 = 2;
draw = 3;
int i,k;
for (k=0;k<3;k++)
{
for (i=0;i<3;i++)
{
Board[k][i]=0;
}
}
play();
}
int TicTacToe::play()
{
int done = false;
boardProgress(Board);
while(!done)
{
playermove();
boardProgress(Board);
done = Winner(Board);
}
Stats(winner);
return 0;
}
void TicTacToe::playermove()
{
int answer = false;
while (answer == false)
{
cout <<"Row: ";
cin >> row;
row--;
cout <<"Colume: ";
cin >> col;
col--;
answer = check(row,col);
}
player = turn(player);
if (player == 1)
Board[row][col] = 'X';
else if (player == 2)
Board[row][col] = 'O';
else
cout<< "Failed.";
}
int TicTacToe::check(int row, int col)
{
if(Board[row][col] == 0)
{
return true;
}
else if (Board[row][col] != 0)
{
cout <<"Can go there, Dude!\n\n";
return false;
}
else
{
cout<< "Going through Check";
Winner(Board);
}
return false;
}
int TicTacToe::turn(int player)
{
switch(player)
{
case 1: player = 2;
{
cout<<"\nPlayers 1 turn.\n\n";
break;
}
case 2: player = 1;
{
cout<<"\nPlayers 2 turn.\n\n";
break;
}
}
return player;
}
int TicTacToe::Winner(char x[][3])
{
winner = 0;
int count = 0;
int a = row;
int b = col;
for (a=0;a<3;a++)
{
for (b=0;b<3;b++)
{
if (Board[a][b]==0)
{
count++;
}
}
}
if (count > 0)
{
int row, col, r, c, d, ro, co, dO;
for (row=0; row<3; row++)
{
r=0;
ro=0;
for (col=0; col<3; col++)
{
if(x[row][col]=='X')
r++;
if(x[row][col]=='O')
ro++;
if (ro==3)
{
winner=2;
}
if (r==3)
{
winner=1;
}
}
}
for (col=0; col<3; col++)
{
r=0;
ro=0;
for (row=0; row<3; row++)
{
if(x[row][col]=='X')
r++;
if(x[row][col]=='O')
ro++;
if (ro==3)
{
winner=2;
}
if (r==3)
{
winner=1;
}
}
}
if (x[0][0]=='X' && x[1][1]=='X' && x[2][2]=='X')
{
winner=1;
}
else if (x[0][0]=='O' && x[1][1]=='O' && x[2][2]=='O')
{
winner=2;
}
else if (x[2][0]=='X' && x[1][1]=='X' && x[0][2]=='X')
{
winner=1;
}
else if (x[2][0]=='O' && x[1][1]=='O' && x[0][2]=='O')
{
winner=2;
}
}
else if (count == 9)
{
cout << "Its a draw, Bummer.";
winner = 3;
}
else
{
cout<< "Next Player go, MEOW!\n\n";
}
if (winner > 0)
{
done = true;
}
return done;
}
int TicTacToe::Stats(int winner)
{
playBall.TG++;
switch(winner)
{
case 1: T1++;
{
break;
}
case 2: T2++;
{
break;
}
case 3: TD++;
{
break;
}
}
cout<<"You have played this many games: " << TG;
cout<<"\nPlayer1 won has won: " << T1 << " games.";
cout<<"\nPlayer2 won has won: " << T2 << " games.";
cout<<"\nYou have had: " << TD << " draws.";
return 0;
}
char TicTacToe::playAgain(char done)
{
cout <<"\n\nWanna play again!?\n\n";
cout <<"Y/N: ";
cin >> done;
if(done == 'Y' || done == 'y')
{
done = false;
}
else
{
done = true;
}
return done;
}
void TicTacToe::boardProgress(char x[][3])
{
cout << " | | \n";
cout << " " << x[0][0] << " | " << x[0][1] << " | " << x[0][2] <<" \n";
cout << " _____|_____|_____\n";
cout << " | | \n";
cout << " " << x[1][0] << " | " << x[1][1] << " | " << x[1][2] <<" \n";
cout << " _____|_____|_____\n";
cout << " | | \n";
cout << " " << x[2][0] << " | " << x[2][1] << " | " << x[2][2] <<" \n";
cout << " | | \n";
}
</code></pre>
| [] | [
{
"body": "<p>Well for one, you've got some unreachable code:</p>\n\n<pre><code>if(Board[row][col] == 0)\n{\n return true;\n}\nelse if (Board[row][col] != 0)\n{\n cout <<\"Can go there, Dude!\\n\\n\";\n return false;\n}\nelse\n{\n // The cell is neither 0 nor non-0!!!\n // cout << \"What the hell, man?\";\n cout << \"Going through Check\";\n Winner(Board);\n}\nreturn false;\n</code></pre>\n\n<p>Since you're using C++, you should create a <code>Board</code> class that houses the cells and the win check routine. Your class should look like this:</p>\n\n<pre><code>enum Piece {NONE, X, O};\n\npublic class Board {\nprivate:\n Piece cells[3][3];\n\npublic:\n void put(int x, int y, Piece piece);\n Piece get(int x, int y);\n Piece checkWin();\n void clear();\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-23T11:21:20.670",
"Id": "2044",
"ParentId": "2032",
"Score": "11"
}
},
{
"body": "<p>Your winner function can (should) be reduced:</p>\n\n<pre><code>if (x[0][0]=='X' && x[1][1]=='X' && x[2][2]=='X')\n{\n winner=1;\n}\nelse if (x[0][0]=='O' && x[1][1]=='O' && x[2][2]=='O')\n{\n winner=2;\n}\nelse if (x[2][0]=='X' && x[1][1]=='X' && x[0][2]=='X')\n{\n winner=1;\n}\nelse if (x[2][0]=='O' && x[1][1]=='O' && x[0][2]=='O')\n{\n winner=2;\n}\n</code></pre>\n\n<p>First, like Eric said, you need a board class (or game class makes more sense) to manage players with something like:</p>\n\n<pre><code>game.getCurrentPlayer()\ngame.setCurrentPlayer()\n</code></pre>\n\n<p>When a game starts: <em>game.setCurrentPlayer('X') //(or 'O')</em>\nand do that after each move.</p>\n\n<p>Then in your winner function you can use this to reduce the code by half:</p>\n\n<pre><code>player = game.getCurrentPlayer();\nif (x[0][0]==player && x[1][1]==player && x[2][2]==player)\n winner = player;\n//...\n</code></pre>\n\n<p>You also use for loops to check rows and columns.\nJust hardcode everything like you did with the diagonal check. You get 8 conditions:</p>\n\n<pre><code>if (x[0][0]==player && x[0][1]==player && x[0][2]==player) // first row\n</code></pre>\n\n<p>For a small game like TTT you don't need loops to check rows, columns and diagonals, it makes the code hard to read (especially with variables like r, ro, row...etc.)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-15T10:54:53.207",
"Id": "2417",
"ParentId": "2032",
"Score": "3"
}
},
{
"body": "<p>Don't use <code>system(\"pause\");</code>; this is platform-specific. You might even cause a nuclear meltdown. </p>\n\n<p><img src=\"https://i.stack.imgur.com/2QJUF.png\" alt=\"enter image description here\"></p>\n\n<p><code>using namespace std;</code> is bad practice. Read <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">this</a></p>\n\n<p>Why is <code>play()</code> returning an <code>int</code>? You’re not using the returned value, so make it a <code>void</code> function. </p>\n\n<p><code>check()</code> is expected to return an <code>int</code>, yet you return <code>true</code>/<code>false</code>. If someone is reading your code, he/she expects to see an <code>int</code>. Otherwise, that programmer will have to spend more time figuring out what’s happening in the function. If there isn't a compatibility issue with C, have the function return <code>bool</code> instead. Same goes for the <code>Winner()</code> function. </p>\n\n<p><code>player = turn(player)</code>?</p>\n\n<p>Some unnecessary copying here. Pass a reference of the variable <code>player</code> instead, since you are only checking the value of it. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-05T09:11:28.540",
"Id": "64775",
"ParentId": "2032",
"Score": "6"
}
},
{
"body": "<ul>\n<li>Do not pollute your namespace by <code>using namespace std</code> .</li>\n<li><code>winner = 1</code> (2, 3) smells bad, using nice constant or enum would improve readability. Same with board containing 0s and 1s. Do not force your reader to guess / scroll to get that knowledge.</li>\n<li>Your implementation is tightly coupled with console - what forbids you to implement abstract logic encapsulated in class and USE this class in console app? What if you want to port it to GUI app? Can you do it cheaply now?</li>\n<li><code>Winner()</code>? Capitalized letter means class. Always. Do not misguide your reader. Same thing with <code>Stats()</code>.</li>\n<li><code>boardProgress</code>? Hell, how's that better than just <code>printBoard()</code>?</li>\n<li><code>TG</code>? <code>T1</code>? <code>T2</code>? <code>T3</code>? <code>gamesPlayed</code>, <code>gamesWonByPlayer1</code>, <code>gamesWonByPlayer2</code>, <code>gamedDrawn</code> (is it correct form in English?) are a little better I think.</li>\n<li><code>3</code> is a magic number, and it's all over the place. Make it a constant or pass it to constructor, so playing on 4x4 or 5x5 board is also available. Logic won't change.</li>\n<li>As always, multiple indentation is a big 'let's get away from it'. Testing is nightmare, debugging is nightmare, understanding it is nightmare. According to Uncle Bob, more than one indentation is too much. I'm not that radical, but certainly > 2 indentation levels and > 20 lines are too much (see the <code>Winner()</code> method).</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-05T09:53:54.207",
"Id": "64779",
"ParentId": "2032",
"Score": "8"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-22T01:37:41.303",
"Id": "2032",
"Score": "12",
"Tags": [
"c++",
"game",
"tic-tac-toe"
],
"Title": "Tic Tac Toe game"
} | 2032 |
<p>I've found this implementation on the web:</p>
<blockquote>
<pre><code>void insertSort(int a[], int length)
{
int i, j, value;
int k=0;
for(i = 1; i < length; i++)
{
value = a[i];
for (j = i - 1; j >= 0 && a[j] > value; j--)
{
a[j + 1] = a[j];
k++;
}
a[j+1] = value;
}
printf("k=%d", k);
}
</code></pre>
</blockquote>
<p>I have written this:</p>
<pre><code>#include <stdio.h>
#define SIZE 8
int array1[SIZE] = {77, 33, 44, 11, 88, 22, 66, 55};
void PrintArray()
{
int i = 0;
printf("\n");
for(i=0 ; i<SIZE ; i++)
{
printf("%d, ", array1[i]);
}
}
void Insert(int insertPosition, int insertElementIndex)
{
int temp = array1[insertElementIndex];
int i = 0;
for(i=insertElementIndex ; i>=insertPosition ; i--)
{
array1[i] = array1[i-1];
}
array1[insertPosition] = temp;
}
void InsertionSort()
{
int i = 0;
int j = 0;
int k = 0;
for(i=0 ; i<SIZE ; i++)
{
for(j=0 ; j<=i ; j++)
{
if(array1[i] < array1[j])
{
Insert(j, i);
PrintArray();
}
k++;
}
}
printf("k=%d", k);
}
main()
{
PrintArray();
InsertionSort();
//insertSort(array1, SIZE);
PrintArray();
getch();
}
</code></pre>
<p>Is there any problem with this implementation?</p>
| [] | [
{
"body": "<p>First of all, what you implemented is not insertion sort:</p>\n\n<p>Insertion sort uses one loop to iterate over the array, and for each element uses another loop to move the element to its desired location. This makes its running time \\$O(n^2)\\$.</p>\n\n<p>Your algorithm iterates over each pair of elements (using the two nested loops in <code>InsertionSort()</code>) and then for each pair, uses a third loop (the one in <code>Insert</code>) to move the one element to the position of the other if necessary. This makes its running time \\$O(n^3)\\$, which is significantly worse than \\$O(n^2)\\$.</p>\n\n<p>So that's a problem.</p>\n\n<hr>\n\n<p>In addition to that there's also a major usability problem with your function:</p>\n\n<p>By making the array and its size a global variable and a constant instead of parameters, you make reuse of your function as good as impossible. If you want to use the function to sort multiple arrays, you have to copy each one into the global variable, call the sort function, and then copy it back from the global variable again. And this only works if all the arrays have the same size. If the arrays have different sizes it's plain impossible to use your <code>InsertionSort</code> function on them.</p>\n\n<p>So passing the array and its size as parameters is clearly preferable.</p>\n\n<hr>\n\n<p>Lastly, I realize that you're most probably aware of this and this is just a learning exercise, but just in case:</p>\n\n<p>In most real-world applications, quick sort or merge sort are usually preferable to insertion sort, having much better performance characteristics than insertion sort in the majority of cases. So if you want to use this in real code, you should rethink whether you really want to use insertion sort.</p>\n\n<p>Also the standard C library has a sort function built-in, so you don't even have to implement anything yourself.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-22T10:47:40.707",
"Id": "2035",
"ParentId": "2034",
"Score": "14"
}
},
{
"body": "<p>Do not use global variables:</p>\n\n<pre><code>int array1[SIZE] = {77, 33, 44, 11, 88, 22, 66, 55};\n</code></pre>\n\n<p>This will make your code harder to maintain and more prone to bugs bugs because it can be modified from any point in the program.</p>\n\n<p>Instead, initialize it in <code>main()</code> and pass it to any needed functions. This practice of using local objects over global ones should be followed in all of your programs. However, if you're working with constants, it's okay to keep them global because they're already immutable.</p>\n\n<p>This could also be helpful in case you decide to add additional arrays as it would be easier to maintain them all in <code>main()</code>. Although you <em>could</em> instead make them constants and use local copies, you would still have to avoid returning a local array (undefined behavior). Specifically, you cannot return an array itself because <a href=\"https://stackoverflow.com/a/1454992/1950231\">C only returns <em>pointers</em> to arrays</a>, and that pointer will point to local data.</p>\n\n<p>Side-note: remove the commented-out line in <code>main()</code>. It clutters the code a bit, and it's a pointless line even if it remained (<code>SIZE</code> is already global).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T22:28:31.777",
"Id": "47182",
"ParentId": "2034",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-22T10:05:53.340",
"Id": "2034",
"Score": "9",
"Tags": [
"c",
"sorting",
"insertion-sort"
],
"Title": "Insertion sort implementation adapted from the web"
} | 2034 |
<p>I want to split my helpers in different modules (and files), but I found some problems which I got around with the following solution:</p>
<pre><code># app/helpers/application_helper.rb
module ApplicationHelper
include ApplicationContainer
# ...
end
# app/helpers/partials/application_container.rb
module ApplicationContainer
# ...
end
</code></pre>
<p>In particular at the beginning I was looking to have a file <code>/app/helpers/_application_container_helper.rb</code> that gave me <code>uninitialized constant ApplicationHelper::ApplicationContainer</code> (and different other errors playing around it), but right now I'm not even sure that makes sense.
Any Idea or suggestions? </p>
| [] | [
{
"body": "<p>Your current solution is fine, in my opinion. The underscore naming-convention used on view-partials doesn't apply for modules, that's why you got the uninitialized constant-error. If you name it <code>ApplicationHelper::ApplicationContainer</code> it has to be in a file named <code>application_container.rb</code></p>\n\n<p>What you have in your code now is a module you can include in other Helper-modules– just as you would a partial in your views.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-25T11:55:48.317",
"Id": "2082",
"ParentId": "2037",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "2082",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-22T21:25:20.913",
"Id": "2037",
"Score": "6",
"Tags": [
"ruby",
"ruby-on-rails"
],
"Title": "How and where to define a partial helper module"
} | 2037 |
<p>This example comes from <a href="https://stackoverflow.com/questions/5761117/testing-if-colors-equal">a code snippet posted on Stack Overflow</a>:</p>
<pre><code>private double brickVal(Color c) {
if (c == Color.RED) {
return 10.0;
} else if (c == Color.ORANGE) {
return 8.0;
} else if (c == Color.YELLOW) {
return 6.0;
} else if (c == Color.GREEN) {
return 4.0;
} else if (c == Color.CYAN) {
return 2.0;
} else if (c == Color.MAGENTA) {
return 1.0;
} else {
return 1.0;
}
}
</code></pre>
<p>Is the use of <code>==</code> here correct / best practice?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-23T11:11:08.600",
"Id": "3350",
"Score": "1",
"body": "I wouldn't use both in the same function! In what context is this function being used?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-05T07:57:13.170",
"Id": "106299",
"Score": "0",
"body": "This question [was mentioned on meta.](http://meta.codereview.stackexchange.com/questions/2216/can-we-revisit-did-i-write-that-code-myself)"
}
] | [
{
"body": "<p>No, it's not correct (and thus of course also not best practice). For example the condition <code>c == Color.GREEN</code> will be true if the method is called as <code>brickVal(Color.GREEN)</code>, but false if it is called as <code>brickVal(new Color(0, 255, 0))</code>. Since <code>Color.GREEN</code> is equal to <code>new Color(0, 255, 0)</code> this behavior is most likely unintentional (at least I can't imagine a scenario where you'd want for <code>brickVal(Color.GREEN)</code> to behave differently than <code>brickVal(new Color(0,255,0))</code>.</p>\n\n<p>Of course if you know that the method will only ever be called using the \"pre-made\" colors and never using <code>new Color</code>, it will behave correctly. However I'd still advise against using <code>==</code>. I can see no good reason to not use <code>equals</code> and using <code>==</code> comes with the danger that someone might call <code>brickVal</code> with <code>new Color</code> anyway, not knowing that they're not supposed to.</p>\n\n<p>Further given the fact that <code>brickVal</code> apparently is meant to be only called with some specific colors as arguments and it doesn't use any properties of the colors other than their identity, I think an enum might be more suitable here than using the <code>Color</code> class. This way you can use <code>switch</code> instead of <code>if ... else if ...</code> and don't have to worry about anybody passing in <code>new Color</code> as the argument.</p>\n\n<hr>\n\n<p>As a somewhat unrelated note, I find it confusing that the <code>brickVal</code> variable is set in every case except if the argument is <code>RED</code> and in the else case. Obviously I don't know how and where the <code>brickVal</code> variable is going to be used, but this seems like a design smell to me. I also think it's a bad idea to have a variable with the same name as the method.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-23T14:32:07.810",
"Id": "3353",
"Score": "0",
"body": "EDIT-ed question to get rid of the `brickval = ... ` and other cruft that detracted from my main question."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-23T14:11:42.657",
"Id": "2045",
"ParentId": "2039",
"Score": "13"
}
},
{
"body": "<p>My take on this is that it is bad practice.</p>\n\n<p>In some circumstances, this code could be \"correct\" ... in the sense of being bug free as written. Specifically, if the entire application was written to use only a predefined palette of <code>Color</code> objects ... and there was no way that it could introduce new <code>Color</code> objects into this calculation.</p>\n\n<p>The problem is that this is potentially a global (application wide) invariant. Any change to any class might potentially introduce new <code>Color</code> objects and violate the invariant. In short the application is at best \"fragile\".</p>\n\n<p>The other problem is that this dependency on an global invariant makes the class hard to reuse.</p>\n\n<p>For these reasons, my take is that this approach is bad practice ... whether or not it is buggy in the context of the application.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-24T13:09:25.747",
"Id": "3367",
"Score": "1",
"body": "I dont get it. The only problem I see is == vs 'equals', and maybe he should use a lookuptable instead of the repeated ifs."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-26T05:53:43.420",
"Id": "3393",
"Score": "0",
"body": "@Martin - `==` versus equals is the point."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-23T14:46:52.753",
"Id": "2047",
"ParentId": "2039",
"Score": "5"
}
},
{
"body": "<p>Not a good practice.</p>\n\n<p>In the manner that is seems you want to use color - the thing that matters is the value. You want to know if the actual color is the same. It doesn't matter if it is 2 different objects that have the same values or the same object. And <code>==</code> checks if it is the same object.\nwhat you want to use is <code>equals()</code> because <code>equals()</code> checks if the two colors have the same values.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-24T16:46:50.657",
"Id": "2071",
"ParentId": "2039",
"Score": "3"
}
},
{
"body": "<p>The argument <code>c</code> is an instance of Color. When you use the <code>==</code> operator you are checking if the instances are pointing to the same object. In this case (and most cases that I encounter), you do not want to compare pointers, you want to compare values. After all, Color is a class that encapsulates a color value.\nHere is an example:</p>\n\n<pre><code>import java.awt.Color;\n\nclass ColorTest {\n\n public static void main(String args[]) {\n Color c1 = Color.RED;\n Color c2 = new Color(255,0,0);\n System.out.println(c1 == c2); //false - not pointing to the same object\n System.out.println(c1.equals(c2)); //true - both are red\n }\n}\n</code></pre>\n\n<p>This is why all java objects have a <code>equals()</code> method, which is inherited from the <a href=\"http://download.oracle.com/javase/6/docs/api/java/lang/Object.html\" rel=\"nofollow\">Object</a> class: we don't care where it is physically stored in memory, we care about what it represents.</p>\n\n<p>EDIT: So to answer the question \"Is this good practice\" I would say no it is not.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-04T11:26:57.103",
"Id": "106108",
"Score": "0",
"body": "We actually do care a little about their memory location. The first line of any good `equals()` function will always be `if (a == b) return true;`"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-24T21:05:16.650",
"Id": "2072",
"ParentId": "2039",
"Score": "4"
}
},
{
"body": "<p>I tried this and it worked very well:</p>\n\n<pre><code>Color c1 = Color.WHITE;\nColor c2 = new Color(255,255,255);\n\nif(c1.getRGB() == c2.getRGB()) \n\n System.out.println(\"true\");\n\nelse\n\n System.out.println(\"false\");\n\n}\n</code></pre>\n\n<p><code>getRGB</code> function returns an <code>int</code> value with the sum of Red Blue and Green, so we are comparing an <code>int</code> with <code>==</code>, and not an object with equals. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-04T07:50:55.690",
"Id": "106078",
"Score": "1",
"body": "Could you explain why it's better than what the OP does? Specifically, do you feel all color comparisons should be done this way? Why so?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-04T11:25:24.103",
"Id": "106107",
"Score": "0",
"body": "`(255,0,0)` and `(0,255,0)` and `(0,0,255)` are three distinctly different colors whose RGB values all sum up to the same number."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-04T07:42:19.927",
"Id": "58990",
"ParentId": "2039",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "2045",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-23T00:56:02.470",
"Id": "2039",
"Score": "7",
"Tags": [
"java"
],
"Title": "Comparing Color objects with =="
} | 2039 |
<pre><code>string s = Clipboard.GetText().Replace("\r", " ");
string[] lines = s.Split('\n');
int row = dgView.CurrentCell.RowIndex;
int col = dgView.CurrentCell.ColumnIndex;
int linesCount = lines.Count();
if ((row + linesCount) - dgView.RowCount > 0) dgView.Rows.Add((row + linesCount) - dgView.RowCount);
asyncSqlResultsViewer.publicToolStripProgressBar.Maximum = linesCount;
asyncSqlResultsViewer.publicToolStripProgressBar.Step = 1;
asyncSqlResultsViewer.publicToolStripProgressBar.Visible = true;
dgView.ReadOnly = true;
foreach (string line in lines)
{
if (line.Length > 0)
{
string[] cells = line.Split('\t');
for (int i = 0; i < cells.GetLength(0); ++i)
{
if (col + i < dgView.ColumnCount)
{
dgView[col + i, row].Value = cells[i];
}
else
{
break;
}
}
row++;
}
else
{
break;
}
asyncSqlResultsViewer.publicToolStripProgressBar.PerformStep();
}
</code></pre>
<p>It is ridiculously slow. Pasting 500 rows with 5 columns takes about 30 seconds. Please take into consideration that there might be already data in the <code>DataGridView</code> and I don't necessarily want to override it (it all depends on the starting cell). So I don't know how could I use a <code>DataTable</code> and assign it as <code>DataSource</code> in case you had that idea.</p>
| [] | [
{
"body": "<p>I wasn't convinced that the code <em>per se</em>, besides what could be done to improve it, would take this long under 'normal' circumstances. I thought I'd actually test this myself before bed and so threw something together, here's what I did...</p>\n\n<p>I created a WinForms application with the appropriate controls and then used a <code>Stopwatch</code>, only modifying your code (forgetting names of controls) by placing it in a method named <code>PasteData</code> which returned <code>lineCount</code>:</p>\n\n<pre><code>private readonly Stopwatch stopWatch = new Stopwatch();\n\nprivate int PasteData()\n{\n //Your code.\n}\n\nprivate void dataGridView_KeyDown(object sender, KeyEventArgs e)\n{\n if (e.Control && e.KeyCode == Keys.V)\n {\n int linesExisting = dataGridView.RowCount;\n stopWatch.Restart();\n int linesPasted = PasteData();\n stopWatch.Stop();\n TimeSpan timeElapsed = stopWatch.Elapsed;\n\n //UI Updates.\n }\n e.Handled = true;\n}\n</code></pre>\n\n<p>I fired up excel and created 700+ rows of data; 5 columns of random text pasted repeatedly:</p>\n\n<blockquote>\n <p>Axdcfg vkhjbkljhgvf hghbjkl;jbhg vguyhjknjhbgvyhjknb hkghjlkh,njjk;olkm,nhn\n ghvbnmkl;kknjbhvghcgv gbhnmkknkjhbghfvghjkljhgfvhjklhbgvhkjlmnjbhgfcfgyhjknlmnn\n ghvjbkmjnhyuiytui89766890i09u8y675tfvghbjnmkl,;m,nbhh\n tf678cfghjbkm,.g90u87ygybihuionjhgvfctfygyuhio;jolkkjnhbvfc\n iouy43212345678987654321234567890009876543212w3erfghgfdffcv</p>\n</blockquote>\n\n<p>I then copied the whole collection from the clipboard and proceeded to flood our application with it up to a count of almost 300,000 rows, and here are the results:</p>\n\n<p><img src=\"https://i.stack.imgur.com/qakF0.jpg\" alt=\"enter image description here\"></p>\n\n<p>Performance degradation was absolutely negligible. If anything, it was the amount of memory being consumed that was to become a concern.</p>\n\n<p>Do you have any more specific information regarding your predicament? We need to define you 'normal' circumstances. The format and nature of the test data would be nice to know, ideally a sample could be supplied. You could define expected amounts of data that the view might contain. Also, some hardware details, here's some of my basic info:</p>\n\n<ul>\n<li>RAM: 2.00GB</li>\n<li>Processor: AMD Turion 64 X2 TL-60 2.0Ghz</li>\n<li>OS: Windows 7 Ultimate 64bit</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-24T05:09:49.830",
"Id": "3358",
"Score": "1",
"body": "OK I found what the problem was. I had my `AutoSizeColumnsMode` set to `AllCells`. That's it."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-24T01:38:48.023",
"Id": "2058",
"ParentId": "2042",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "2058",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-23T04:46:12.440",
"Id": "2042",
"Score": "6",
"Tags": [
"c#",
".net",
"winforms"
],
"Title": "Why is this code to paste into a DataGridView so slow?"
} | 2042 |
<p>From the text:</p>
<blockquote>
<p>Exercise 2.68. The encode procedure
takes as arguments a message and a
tree and produces the list of bits
that gives the encoded message.</p>
</blockquote>
<pre><code>(define (encode message tree)
(if (null? message)
'()
(append (encode-symbol (car message) tree)
(encode (cdr message) tree))))
</code></pre>
<blockquote>
<p>Encode-symbol is a procedure, which
you must write, that returns the list
of bits that encodes a given symbol
according to a given tree. You should
design encode-symbol so that it
signals an error if the symbol is not
in the tree at all. Test your
procedure by encoding the result you
obtained in exercise 2.67 with the
sample tree and seeing whether it is
the same as the original sample
message.</p>
</blockquote>
<p>The textbook provides the following definitions:</p>
<pre><code>(define (make-leaf symbol weight)
(list 'leaf symbol weight))
(define (leaf? object)
(eq? (car object) 'leaf))
(define (symbol-leaf x) (cadr x))
(define (weight-leaf x) (caddr x))
(define (make-code-tree left right)
(list left
right
(append (symbols left) (symbols right))
(+ (weight left) (weight right))))
(define (left-branch tree) (car tree))
(define (right-branch tree) (cadr tree))
(define (symbols tree)
(if (leaf? tree)
(list (symbol-leaf tree))
(caddr tree)))
(define (weight tree)
(if (leaf? tree)
(weight-leaf tree)
(cadddr tree)))
(define (decode bits tree)
(define (decode-1 bits current-branch)
(if (null? bits)
'()
(let ((next-branch
(choose-branch (car bits) current-branch)))
(if (leaf? next-branch)
(cons (symbol-leaf next-branch)
(decode-1 (cdr bits) tree))
(decode-1 (cdr bits) next-branch)))))
(decode-1 bits tree))
(define (choose-branch bit branch)
(cond ((= bit 0) (left-branch branch))
((= bit 1) (right-branch branch))
(else (error "bad bit -- CHOOSE-BRANCH" bit))))
(define (adjoin-set x set)
(cond ((null? set) (list x))
((< (weight x) (weight (car set))) (cons x set))
(else (cons (car set)
(adjoin-set x (cdr set))))))
(define (make-leaf-set pairs)
(if (null? pairs)
'()
(let ((pair (car pairs)))
(adjoin-set (make-leaf (car pair) ; symbol
(cadr pair)) ; frequency
(make-leaf-set (cdr pairs))))))
(define sample-tree
(make-code-tree (make-leaf 'A 4)
(make-code-tree
(make-leaf 'B 2)
(make-code-tree (make-leaf 'D 1)
(make-leaf 'C 1)))))
(define sample-message '(0 1 1 0 0 1 0 1 0 1 1 1 0))
(define (encode message tree)
(if (null? message)
'()
(append (encode-symbol (car message) tree)
(encode (cdr message) tree))))
</code></pre>
<p>And I wrote the following answer:</p>
<pre><code>(define (member? x set)
(not (equal? (member x set) false)))
(define (encode-branch symbol tree)
(let ((left (left-branch tree))
(right (right-branch tree)))
(cond ((member? symbol (symbols left)) (list 0 left))
((member? symbol (symbols right)) (list 1 right))
(else (error "Symbol is not a member of either left or right branches of the tree - can't encode" symbol tree)))))
(define (encode-symbol symbol tree)
(if (leaf? tree) '()
(let ((new-branch (encode-branch symbol tree)))
(cons (car new-branch) (encode-symbol symbol (cadr new-branch))))))
</code></pre>
<p>How can I improve my solution?</p>
| [] | [
{
"body": "<p>Wouldn't it be easier to unpack the tree into a dictionary mapping each symbol to its corresponding bit string? Then you could simply look up each symbol in the input to generate the corresponding output bits.</p>\n\n<p>EDIT:\nAs suggested by <code>syb0rg</code>, here is an implementation (C#, I'm afraid -- my Lisp is far too rusty -- although it's almost pure). The part pertaining to my suggestion above lives in the <code>HuffmanCodes</code> function at the end.</p>\n\n<pre><code>void Main()\n{\n var corpus = @\"Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.\";\n var hcs = HuffmanCodes(corpus);\n Console.WriteLine(hcs);\n}\n\nDictionary<char, int> Histogram(string corpus) {\n var hg = new Dictionary<char, int>();\n foreach (var x in corpus) {\n int f;\n hg.TryGetValue(x, out f);\n hg[x] = f + 1;\n }\n return hg;\n}\n\nclass HuffTree {\n internal char? Sym; // Non-null iff this is a leaf node with no children.\n internal int Freq;\n internal HuffTree L;\n internal HuffTree R;\n}\n\n// Oh, for a priority queue. This is *really* inefficient!\nHuffTree HuffmanTree(string corpus) {\n var hg = Histogram(corpus);\n var hts = hg.Keys.Select(x => new HuffTree { Sym = x, Freq = hg[x] }).OrderBy(t => t.Freq).ToList();\n while (2 <= hts.Count) {\n var leasts = hts.Take(2).ToList();\n var l = leasts[0];\n var r = leasts[1];\n var newHt = new HuffTree { Freq = l.Freq + r.Freq, L = l, R = r };\n hts = hts.Skip(2).Concat(new HuffTree[] { newHt }).OrderBy(t => t.Freq).ToList();\n }\n return hts.First();\n}\n\nDictionary<char, string> HuffmanCodes(string corpus) {\n var codes = new Dictionary<char, string>();\n Action<HuffTree, string> a = null; // Sweet recursion.\n a = (ht, code) => {\n if (ht.Sym != null) {\n codes[(char)ht.Sym] = code;\n } else {\n a(ht.L, code + \"0\");\n a(ht.R, code + \"1\");\n }\n };\n a(HuffmanTree(corpus), \"\");\n return codes;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-04T02:36:43.500",
"Id": "68854",
"Score": "2",
"body": "You should ***show*** the OP how to do that, and not just tell him an arbitrary way of how to do it. This is how people learn."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-04T02:47:01.770",
"Id": "68860",
"Score": "0",
"body": "@syb0rg, I thought my answer had an obvious implementation. Since the original poster didn't ask for one, maybe he did, too. I can add some code if you'd like to see it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T00:44:01.323",
"Id": "436031",
"Score": "0",
"body": "@Rafe I get the obvious implementation. but implementing in a functional way requires more..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T06:54:35.887",
"Id": "436075",
"Score": "0",
"body": "@fjch1997 I'm not clear I understand your point. Are you saying that a purely functional implementation would do things differently? If so I agree, in that one would use somewhat different data structures; the algorithm would remain the same."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T14:14:18.120",
"Id": "436159",
"Score": "0",
"body": "@Rafe That is true. But I think the OP is mostly stuck on the quirks of a functional language like lisp. For example, there is no built-in dictionary. Also, I don't believe an imperative algorithm is guaranteed to be able to be directly translated into a recursive one. For example, I would need to think very hard to translate [this](https://imgur.com/EMSEZ4z) into [this](https://imgur.com/cOniUdG). They are the same algorithm"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-25T01:48:02.343",
"Id": "436267",
"Score": "1",
"body": "@fjch1997 There's an easy way to transform immediate tail recursive functions like that. That is, (functional) `f(x) = if p(x) then g(x) else f(h(x))` is equivalent to (imperative) `f(x) { while (!p(x)) x = h(x); return g(x); }`."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-10-17T00:06:02.440",
"Id": "5406",
"ParentId": "2043",
"Score": "3"
}
},
{
"body": "<p>For the best performance, a Hashmap (or Dictoinary) data stucture must be used. However, scheme itself does not define such type so I opted for simply traversing the Huffman tree for simpler code.</p>\n\n<pre><code>(define (left-branch tree) (car tree))\n(define (right-branch tree) (cadr tree))\n\n(define (encode message tree)\n (if (null? message)\n '()\n (append (encode-symbol (car message) tree)\n (encode (cdr message) tree))))\n\n(define (encode-symbol-helper symbol tree current-code)\n (if (leaf? tree)\n (if (equal? symbol (cadr tree)) current-code null)\n (let ((left-result (encode-symbol-helper symbol (left-branch tree) (append current-code '(0))))\n (right-result (encode-symbol-helper symbol (right-branch tree) (append current-code '(1)))))\n (if (not (null? left-result)) left-result right-result)\n )))\n\n(define (encode-symbol symbol tree) (encode-symbol-helper symbol tree null))\n\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T02:51:55.457",
"Id": "436044",
"Score": "0",
"body": "I see one piece of proposed code. What [insight](https://codereview.stackexchange.com/help/how-to-answer) does your answer provide about the code presented in the question?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T03:13:22.197",
"Id": "436050",
"Score": "0",
"body": "@greybeard feel free to improve my answer"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-24T01:57:08.687",
"Id": "224777",
"ParentId": "2043",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-23T09:17:31.977",
"Id": "2043",
"Score": "3",
"Tags": [
"lisp",
"scheme",
"sicp"
],
"Title": "Encode-symbol for Huffman tree"
} | 2043 |
<p>From <a href="http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-16.html#%_thm_2.69" rel="nofollow">SICP</a>:</p>
<blockquote>
<p>Exercise 2.69. The following
procedure takes as its argument a list
of symbol-frequency pairs (where no
symbol appears in more than one pair)
and generates a Huffman encoding tree
according to the Huffman algorithm.</p>
<pre><code>(define (generate-huffman-tree pairs)
(successive-merge (make-leaf-set pairs)))
</code></pre>
<p>Make-leaf-set is the procedure given
above that transforms the list of
pairs into an ordered set of leaves.
Successive-merge is the procedure you
must write, using make-code-tree to
successively merge the smallest-weight
elements of the set until there is
only one element left, which is the
desired Huffman tree. (This procedure
is slightly tricky, but not really
complicated. If you find yourself
designing a complex procedure, then
you are almost certainly doing
something wrong. You can take
significant advantage of the fact that
we are using an ordered set
representation.)</p>
</blockquote>
<p>I wrote the following solution:</p>
<pre><code>(define (generate-huffman-tree pairs)
(successive-merge (make-leaf-set pairs)))
(define (successive-merge leaf-set)
(define (iter result leaf-subset)
(if (null? leaf-subset)
result
(let ((first-leaf (car leaf-subset)))
(iter (make-code-tree first-leaf result) (cdr leaf-subset)))))
(iter (make-code-tree (car leaf-set) (cadr leaf-set)) (cddr leaf-set)))
</code></pre>
<p>Is this a good answer? Can it be improved?</p>
| [] | [
{
"body": "<p>It's been a while since I've done any Lisp/Scheme, but I'll make one style point and one algorithmic point.</p>\n\n<p>Style point: it's usually more readable if you define structure projection functions with meaningful names rather than using <code>car</code>, <code>cdr</code>, etc.</p>\n\n<p>Algorithmic point: the simplest way of doing this is to include some priority queue structure from the standard library. Then you simply remove the two least items from the queue, create their combined Huffman tree, and reinsert them into the queue. You're done when the queue contains only one item.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-14T09:58:33.250",
"Id": "17312",
"Score": "0",
"body": "I disagree with your style point. `car` and `cdr` are so fundamental to the language that they will be well understood by anyone reading your code. Redefining them will be more painful as you'll have to deal with each codebases particular convention."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-05-09T03:04:57.870",
"Id": "18627",
"Score": "0",
"body": "@cmh: the problem is not that the reader won't understand what car and cdr mean, rather that the reader has to keep in mind the *structure* of your type rather than its *semantics*."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-10-16T23:48:05.613",
"Id": "5405",
"ParentId": "2046",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-23T14:18:05.923",
"Id": "2046",
"Score": "3",
"Tags": [
"lisp",
"scheme",
"sicp",
"compression"
],
"Title": "Huffman encoding successive-merge function"
} | 2046 |
<p>What would be a prettier/faster way to do handling of multiple errors in Ruby? Here is the code I am working with:</p>
<pre><code>begin
response = session.get url
rescue Patron::HostResolutionError
puts "Error resolving remote host."
exit 1
rescue Patron::PartialFileError
puts "File size mismatch. (Host reported a file size, but the actual file is of different size)"
exit 1
rescue Patron::TimeoutError
puts "Operation timed out."
exit 1
rescue Patron::TooManyRedirects
puts "Tried redirecting too many times."
exit 1
rescue Patron::URLFormatError
puts "Error with the URL format"
exit 1
rescue Patron::UnsupportedProtocol
puts "This URL is using a protocol that we cannot handle."
exit 1
rescue Patron::ConnectionFailed
puts "Error connecting to host. Check your internet connection."
exit 1
end
</code></pre>
| [] | [
{
"body": "<p>Your begin/rescue code does look repetitive, but on the hand it would be easy to extend in the future. If you are certain you will always have this structure (rescue with an error message + exit), you can abstract it, for example:</p>\n\n<pre><code>exceptions = {\n Patron::HostResolutionError => \"Error resolving remote host.\",\n ...\n}\n\nresponse = catch_exceptions(exceptions, :exit_code => 1) { session.get(url) }\n</code></pre>\n\n<p>It's usually handy to write this kind of wrappers so the main code keeps clean (on the other hand, if it gets messier and convoluted it's a good sign the abstraction is just not working).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-23T23:03:46.923",
"Id": "3356",
"Score": "0",
"body": "Apparently, `catch` can only take `0..1` arguments. As I get an error saying so when I try to run this."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-24T06:50:16.373",
"Id": "3359",
"Score": "0",
"body": "@Mark. Sorry, I didn't mean Ruby's catch, this is a custom method. Call it with a different name: catch_exceptions, for example."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-23T22:27:22.187",
"Id": "2056",
"ParentId": "2049",
"Score": "1"
}
},
{
"body": "<p>Since you're rescuing all 7 subclasses of <code>Patron::Error</code>, it would make sense to directly rescue <code>Patron::Error</code> rather than rescuing them one by one.</p>\n\n<p>You're also duplicating work that has already been done for you, by formulating your own error message for each exception: the exceptions will already contain a useful error message, which even contains more information than yours do (for example if the host could not be resolved, the exception's message will contain the hostname that could not be resolved instead of just saying \"Error resolving remote host\").</p>\n\n<p>Lastly I would print error messages to stderr, not stdout, as that's where they're supposed to go.</p>\n\n<p>So I would write the code like this:</p>\n\n<pre><code>begin\n response = session.get url\nrescue Patron::Error => e\n $stderr.puts e.message\n exit 1\nend\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-24T00:36:57.127",
"Id": "2057",
"ParentId": "2049",
"Score": "15"
}
}
] | {
"AcceptedAnswerId": "2057",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-23T21:26:23.647",
"Id": "2049",
"Score": "13",
"Tags": [
"ruby",
"error-handling",
"networking",
"curl"
],
"Title": "Handling many networking exceptions in Ruby"
} | 2049 |
<p>The <a href="http://en.wikipedia.org/wiki/Tiny_Encryption_Algorithm" rel="noreferrer">TEA</a> is a very simple encryption algorithm requiring little time and space - perfect for embedded systems. There are extensions to it, and every version has its flaws (WEP was based on it), but for casual protection it's perfect.</p>
<p>Also, the encrypt and decrypt routines are exactly as found from Wikipedia, so I don't expect anyone to check that I'm following the TEA correctly - I'm more interested in the block routines I've added, though if you notice something about the TEA routines it would be good to know.</p>
<p><strong>tea.h</strong></p>
<pre><code>#ifndef __TEA.H__
#define __TEA.H__
#include <stdint.h>
void encrypt (uint32_t* v, uint32_t* k);
void decrypt (uint32_t* v, uint32_t* k);
void encryptBlock(uint8_t * data, uint32_t * len, uint32_t * key);
void decryptBlock(uint8_t * data, uint32_t * len, uint32_t * key);
#endif
</code></pre>
<p><strong>tea.c</strong></p>
<pre><code>#include "tea.h"
/* encryptBlock
* Encrypts byte array data of length len with key key using TEA
* Arguments:
* data - pointer to 8 bit data array to be encrypted - SEE NOTES
* len - length of array
* key - Pointer to four integer array (16 bytes) holding TEA key
* Returns:
* data - encrypted data held here
* len - size of the new data array
* Side effects:
* Modifies data and len
* NOTES:
* data size must be equal to or larger than ((len + 7) / 8) * 8 + 8
* TEA encrypts in 8 byte blocks, so it must include enough space to
* hold the entire data to pad out to an 8 byte boundary, plus another
* 8 bytes at the end to give the length to the decrypt algorithm.
*
* - Shortcut - make sure that data is at least len + 15 bytes in size.
*/
void encryptBlock(uint8_t * data, uint32_t * len, uint32_t * key)
{
uint32_t blocks, i;
uint32_t * data32;
// treat the data as 32 bit unsigned integers
data32 = (uint32_t *) data;
// Find the number of 8 byte blocks, add one for the length
blocks = (((*len) + 7) / 8) + 1;
// Set the last block to the original data length
data32[(blocks*2) - 1] = *len;
// Set the encrypted data length
*len = blocks * 8;
for(i = 0; i< blocks; i++)
{
encrypt(&data32[i*2], key);
}
}
/* decryptBlock
* Decrypts byte array data of length len with key key using TEA
* Arguments:
* data - pointer to 8 bit data array to be decrypted - SEE NOTES
* len - length of array
* key - Pointer to four integer array (16 bytes) holding TEA key
* Returns:
* data - decrypted data held here
* len - size of the new data array
* Side effects:
* Modifies data and len
* NOTES:
* None
*/
void decryptBlock(uint8_t * data, uint32_t * len, uint32_t * key)
{
uint32_t blocks, i;
uint32_t * data32;
// treat the data as 32 bit unsigned integers
data32 = (uint32_t *) data;
// Find the number of 8 byte blocks
blocks = (*len)/8;
for(i = 0; i< blocks; i++)
{
decrypt(&data32[i*2], key);
}
// Return the length of the original data
*len = data32[(blocks*2) - 1];
}
/* encrypt
* Encrypt 64 bits with a 128 bit key using TEA
* From http://en.wikipedia.org/wiki/Tiny_Encryption_Algorithm
* Arguments:
* v - array of two 32 bit uints to be encoded in place
* k - array of four 32 bit uints to act as key
* Returns:
* v - encrypted result
* Side effects:
* None
*/
void encrypt (uint32_t* v, uint32_t* k) {
uint32_t v0=v[0], v1=v[1], sum=0, i; /* set up */
uint32_t delta=0x9e3779b9; /* a key schedule constant */
uint32_t k0=k[0], k1=k[1], k2=k[2], k3=k[3]; /* cache key */
for (i=0; i < 32; i++) { /* basic cycle start */
sum += delta;
v0 += ((v1<<4) + k0) ^ (v1 + sum) ^ ((v1>>5) + k1);
v1 += ((v0<<4) + k2) ^ (v0 + sum) ^ ((v0>>5) + k3);
} /* end cycle */
v[0]=v0; v[1]=v1;
}
/* decrypt
* Decrypt 64 bits with a 128 bit key using TEA
* From http://en.wikipedia.org/wiki/Tiny_Encryption_Algorithm
* Arguments:
* v - array of two 32 bit uints to be decoded in place
* k - array of four 32 bit uints to act as key
* Returns:
* v - decrypted result
* Side effects:
* None
*/
void decrypt (uint32_t* v, uint32_t* k) {
uint32_t v0=v[0], v1=v[1], sum=0xC6EF3720, i; /* set up */
uint32_t delta=0x9e3779b9; /* a key schedule constant */
uint32_t k0=k[0], k1=k[1], k2=k[2], k3=k[3]; /* cache key */
for (i=0; i<32; i++) { /* basic cycle start */
v1 -= ((v0<<4) + k2) ^ (v0 + sum) ^ ((v0>>5) + k3);
v0 -= ((v1<<4) + k0) ^ (v1 + sum) ^ ((v1>>5) + k1);
sum -= delta;
} /* end cycle */
v[0]=v0; v[1]=v1;
}
</code></pre>
<p><strong>Issues so far:</strong></p>
<p><strong>Coding</strong></p>
<ul>
<li>Using <a href="https://stackoverflow.com/questions/47882/what-is-a-magic-number-and-why-is-it-bad">magic numbers</a> in encrypt and decrypt routines - use #defines instead - Kyle</li>
<li>If the 64 bit encoding functions aren't used outside this module, their prototypes should be in the code, not header - Simon</li>
<li>Add sanity checking to input - Rob</li>
<li>Require that input len is a multiple of 8 bytes - making a requirement we can't enforce or check is a recipe for corruption - Rob</li>
</ul>
<p><strong>Style</strong></p>
<ul>
<li>Using K&R brace style in some places, ANSI in others - consistency - Simon</li>
<li>The long descriptive comment is more useful for the end user if it's in the header file (Header for usage, code for implementation) - Rob</li>
</ul>
<hr>
<p><strong>EDIT:</strong></p>
<p>Someone asked for the implementation I indicated in the original post, so here it is. Note that I've not cleaned it up for presentation.</p>
<p>To decode a file use <code>decode inputfilename outputfilename</code>. To encode a file use <code>decode inputfilename outputfilename e</code>. ANSI C implementation, so it should work anywhere, although the algorithm itself might be endian dependant.</p>
<p>THE DECRYPTED FILE WILL NOT EXACTLY MATCH THE ORIGINAL FILE. This particular implementation leaves a number of null bytes on the end of the decrypted file that were not present in the original. For my application this was acceptable and simplified my particular usage, but you are likely going to need to modify this for your use.</p>
<p>It uses a fixed key on line 4.</p>
<pre><code>#include <stdio.h>
typedef unsigned long uint32_t;
const uint32_t TEAKey[4] = {0x95a8882c, 0x9d2cc113, 0x815aa0cd, 0xa1c489f7};
void encrypt (uint32_t* v, const uint32_t* k);
void decrypt (uint32_t* v, const uint32_t* k);
void btea(uint32_t *v, int n, uint32_t const k[4]);
void simpleencrypt(unsigned char * buffer);
void simpledecrypt(unsigned char * buffer);
int main(int argc, char **argv)
{
FILE *fpin, *fpout;
int bytecount;
unsigned char buffer[9], bufferin[9], bufferout[9];
int i;
if(argc < 3)
{
printf("Use: %s [filenameinput] [filenameoutput]\n", argv[0]);
return 0;
}
if( (fpin = fopen(argv[1], "rb")) == NULL)
{
printf("Problem opening input file %s.\n", argv[1]);
return 0;
}
if( (fpout = fopen(argv[2], "wb")) == NULL)
{
printf("Problem opening output file %s.\n", argv[2]);
return 0;
}
bytecount = 0;
while(fread(buffer, 1, 8, fpin) == 8)
{
if(argc>3)
{
for(i=0;i<8;i++)
{
bufferin[i] = buffer[i];
}
simpleencrypt(buffer);
for(i=0;i<8;i++)
{
bufferout[i] = buffer[i];
}
simpledecrypt(bufferout);
for(i=0;i<8;i++)
{
if(bufferin[i] != bufferout[i])
{
printf("Internal decode test failed.\n");
}
}
}
else
{
simpledecrypt(buffer);
}
fwrite(buffer, 1, 8, fpout);
bytecount+=8;
}
if (!feof(fpin))
{
printf("Unexpected input file error encountered.\n");
}
fclose(fpin);
fclose(fpout);
printf("%s complete, %i bytes total\n",((argc>3) ? "Encrypt" : "Decrypt"), bytecount);
return 0;
}
void simpleencrypt(unsigned char * buffer)
{
uint32_t datablock[2];
datablock[0] = (buffer[0] << 24) | (buffer[1] << 16) | (buffer[2] << 8) | (buffer[3]);
datablock[1] = (buffer[4] << 24) | (buffer[5] << 16) | (buffer[6] << 8) | (buffer[7]);
encrypt (datablock, TEAKey);
buffer[0] = (char) ((datablock[0] >> 24) & 0xFF);
buffer[1] = (char) ((datablock[0] >> 16) & 0xFF);
buffer[2] = (char) ((datablock[0] >> 8) & 0xFF);
buffer[3] = (char) ((datablock[0]) & 0xFF);
buffer[4] = (char) ((datablock[1] >> 24) & 0xFF);
buffer[5] = (char) ((datablock[1] >> 16) & 0xFF);
buffer[6] = (char) ((datablock[1] >> 8) & 0xFF);
buffer[7] = (char) ((datablock[1]) & 0xFF);
}
void simpledecrypt(unsigned char * buffer)
{
uint32_t datablock[2];
datablock[0] = (buffer[0] << 24) | (buffer[1] << 16) | (buffer[2] << 8) | (buffer[3]);
datablock[1] = (buffer[4] << 24) | (buffer[5] << 16) | (buffer[6] << 8) | (buffer[7]);
decrypt (datablock, TEAKey);
buffer[0] = (char) ((datablock[0] >> 24) & 0xFF);
buffer[1] = (char) ((datablock[0] >> 16) & 0xFF);
buffer[2] = (char) ((datablock[0] >> 8) & 0xFF);
buffer[3] = (char) ((datablock[0]) & 0xFF);
buffer[4] = (char) ((datablock[1] >> 24) & 0xFF);
buffer[5] = (char) ((datablock[1] >> 16) & 0xFF);
buffer[6] = (char) ((datablock[1] >> 8) & 0xFF);
buffer[7] = (char) ((datablock[1]) & 0xFF);
}
/* encrypt
* Encrypt 64 bits with a 128 bit key using TEA
* From http://en.wikipedia.org/wiki/Tiny_Encryption_Algorithm
* Arguments:
* v - array of two 32 bit uints to be encoded in place
* k - array of four 32 bit uints to act as key
* Returns:
* v - encrypted result
* Side effects:
* None
*/
void encrypt (uint32_t* v, const uint32_t* k) {
uint32_t v0=v[0], v1=v[1], sum=0, i; /* set up */
uint32_t delta=0x9e3779b9; /* a key schedule constant */
uint32_t k0=k[0], k1=k[1], k2=k[2], k3=k[3]; /* cache key */
for (i=0; i < 32; i++) { /* basic cycle start */
sum += delta;
v0 += ((v1<<4) + k0) ^ (v1 + sum) ^ ((v1>>5) + k1);
v1 += ((v0<<4) + k2) ^ (v0 + sum) ^ ((v0>>5) + k3);
} /* end cycle */
v[0]=v0; v[1]=v1;
}
/* decrypt
* Decrypt 64 bits with a 128 bit key using TEA
* From http://en.wikipedia.org/wiki/Tiny_Encryption_Algorithm
* Arguments:
* v - array of two 32 bit uints to be decoded in place
* k - array of four 32 bit uints to act as key
* Returns:
* v - decrypted result
* Side effects:
* None
*/
void decrypt (uint32_t* v, const uint32_t* k) {
uint32_t v0=v[0], v1=v[1], sum=0xC6EF3720, i; /* set up */
uint32_t delta=0x9e3779b9; /* a key schedule constant */
uint32_t k0=k[0], k1=k[1], k2=k[2], k3=k[3]; /* cache key */
for (i=0; i<32; i++) { /* basic cycle start */
v1 -= ((v0<<4) + k2) ^ (v0 + sum) ^ ((v0>>5) + k3);
v0 -= ((v1<<4) + k0) ^ (v1 + sum) ^ ((v1>>5) + k1);
sum -= delta;
} /* end cycle */
v[0]=v0; v[1]=v1;
}
#define DELTA 0x9e3779b9
#define MX ((z>>5^y<<2) + (y>>3^z<<4)) ^ ((sum^y) + (k[(p&3)^e] ^ z));
void btea(uint32_t *v, int n, uint32_t const k[4]) {
uint32_t y, z, sum;
unsigned p, rounds, e;
if (n > 1) { /* Coding Part */
rounds = 6 + 52/n;
sum = 0;
z = v[n-1];
do {
sum += DELTA;
e = (sum >> 2) & 3;
for (p=0; p<n-1; p++)
y = v[p+1], z = v[p] += MX;
y = v[0];
z = v[n-1] += MX;
} while (--rounds);
} else if (n < -1) { /* Decoding Part */
n = -n;
rounds = 6 + 52/n;
sum = rounds*DELTA;
y = v[0];
do {
e = (sum >> 2) & 3;
for (p=n-1; p>0; p--)
z = v[p-1], y = v[p] -= MX;
z = v[n-1];
y = v[0] -= MX;
} while ((sum -= DELTA) != 0);
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-20T22:53:42.670",
"Id": "28307",
"Score": "0",
"body": "Would you mind explaining the following: 1. \"pointer to 8 bit data array\" means? does that mean the data is read by 8-bits once? 2. In your implementations shows 4 fixed keys, but can it be randomly pick of 4 keys in a file?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-24T18:41:24.313",
"Id": "28487",
"Score": "0",
"body": "@LimTeikWei It just needs a pointer to the data. It treats the data as an array of bytes. Yes, the 4 keys can be any numbers you like."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-01-04T23:21:45.683",
"Id": "215129",
"Score": "0",
"body": "For reference, this is an [Electronic Code Book](https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Electronic_Codebook_.28ECB.29) extension of TEA. As such, it should only be used for small and/or never-repeating data."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-07-31T07:39:25.020",
"Id": "325171",
"Score": "0",
"body": "It seems this is the oldest question on Code Review. NICE!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-10-15T02:21:57.490",
"Id": "337664",
"Score": "0",
"body": "What the hell is \"casual protection\"? Protect or protect not. Broken encryption is worse than useless."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-10-15T13:09:50.130",
"Id": "337712",
"Score": "0",
"body": "@johnwbyrd There are trade-offs for every design choice, including security. If you have questions about whether lesser encryption algorithms have a place in any design, or whether TEA is broken please ask it on the appropriate site."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-10-17T19:49:35.017",
"Id": "338119",
"Score": "0",
"body": "The question was rhetorical, but thanks anyway."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-18T11:22:49.567",
"Id": "465700",
"Score": "0",
"body": "I am amazed. This was the first question asked"
}
] | [
{
"body": "<p>I'm not familiar with your algorithm, but in glancing over your code, it looks like sum and delta are magic numbers. Since delta is shared between encrypt and decrypt, it might be a good idea to #define them at the top of the file.</p>\n\n<p>edit: I just looked at the Wikipedia article and the magic numbers make an appearance in the reference implementation, which has been copied verbatim into your code.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2008-09-06T22:20:45.733",
"Id": "2051",
"ParentId": "2050",
"Score": "4"
}
},
{
"body": "<p>Without looking too closely, I'm struggling to see any major problems with this code. Here are a couple of trivial issues:</p>\n\n<ol>\n<li>Did you mean to use different brace styles? The block functions use (sort of) K&R braces and the 64-bit functions use ANSI braces.</li>\n<li>Are the 64-bit functions ever to be used outside the module? If not, I would move their prototypes to the .c file.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2008-09-06T22:47:46.073",
"Id": "2052",
"ParentId": "2050",
"Score": "5"
}
},
{
"body": "<p>You should add some sanity checking on the incoming arguments, especially if you intend this to be library code used from multiple projects.</p>\n\n<p>I would recommend you change definition of encryptBlock to <strong>require</strong> that len is a multiple of 8 bytes. Requiring that the incoming array is sized to a multiple of 8 bytes, but not enforcing that for len is a sure fire way to get memory corruption when someone forgets (e.g. when they are encrypting strings).</p>\n\n<p>Personally I prefer to have the long descriptive comment in the header file rather than the .c file. Anyone using tea.h will find it more useful there.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2008-09-15T12:45:34.323",
"Id": "3355",
"Score": "0",
"body": "I'm going to require the input be a multiple of 8 bytes for some of what I'm encrypting, so thanks for the suggestion!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T10:35:36.870",
"Id": "444987",
"Score": "0",
"body": "Perhaps more importantly, you should sanity-check the output. There's currently no check that verifies whether the output length of decryptBlock is ≤ the input length. That's a buffer over-read exploit waiting to happen."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2008-09-06T23:26:32.313",
"Id": "2053",
"ParentId": "2050",
"Score": "10"
}
},
{
"body": "<p>I'm actually the opposite if of <a href=\"https://stackoverflow.com/questions/47878/codereview-tiny-encryption-algorithm-for-arbitrary-sized-data#47946\">Rob Walker</a> in that I prefer there to be a nice comment block preceding the functions in the code file as opposed to the header. However, as long as you are constant in where you put your comments, most people shouldn't have an issue unless it goes against your company's manual of style. The only other thing I can think of in terms of style would be a comment block at the start of the files with some general information, for example:</p>\n\n<pre>\n/*-----------------------------------------------------------------------------\n * File - \n * Author(s) - \n *\n * Purpose -\n *\n *----------------------------------------------------------------------------- \n * Notes - \n *-----------------------------------------------------------------------------\n * Revisions - \n *---------------------------------------------------------------------------*/\n</pre>\n\n<p>Sometimes you will also see copyright information in these blocks as well. This is just an example of what one looks like though.</p>\n\n<p>In terms of the code itself, I have to agree with the others in regards to putting the \"magic numbers\" off to the side and making sure they are clearly labeled as to what they do. Ditto for the sanity checking if this is going to be used as part of a library.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 2.5",
"CreationDate": "2008-09-08T13:20:05.000",
"Id": "2054",
"ParentId": "2050",
"Score": "5"
}
},
{
"body": "<p>Implementing ciphers is like optimisation: the first rule is \"Don't do it\". Leave it to the experts, because there are many important details which you will miss if you aren't an expert.</p>\n\n<p>The three things which jump out at me about this are:</p>\n\n<ol>\n<li><p>TEA is broken. It's not \"perfect\" for \"casual protection\". Its <a href=\"http://en.wikipedia.org/wiki/XXTEA\" rel=\"nofollow noreferrer\">successors</a> are also broken, and I personally wouldn't use any of them either, but at least they're less broken.</p></li>\n<li><p>The padding is somewhat unconventional, and guarantees to require an extra half-block. There are <a href=\"http://en.wikipedia.org/wiki/Padding_(cryptography)\" rel=\"nofollow noreferrer\">several approaches</a> which require an extra block only when the message is an integral number of blocks in length.</p></li>\n<li><p>The only mode of operation supported is <a href=\"http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Electronic_codebook_.28ECB.29\" rel=\"nofollow noreferrer\">ECB</a>. This is a big red flag. The question of <a href=\"https://crypto.stackexchange.com/questions/1886/which-one-of-the-block-cipher-modes-is-the-best\">which block mode is the best</a> is not a settled one, but ECB is unquestionably the worst.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-16T23:19:26.213",
"Id": "28066",
"Score": "1",
"body": "One significant advantage it does have, aside from being freely available even outside the US under very liberal terms, is that it's simple and fast even on tiny micro controllers. Yes, it's insecure relative to its key length, but in many applications it is secure enough and the low processing requirements can sometimes make it a worthwhile choice. On most advanced processors though, advanced instruction sets include cryptography friendly operators and even advanced encryption doesn't require much more power than tea, and they should be used instead if the licensing terms are acceptable."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-16T21:53:58.827",
"Id": "17624",
"ParentId": "2050",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": "2053",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2008-09-06T22:17:14.337",
"Id": "2050",
"Score": "32",
"Tags": [
"c",
"algorithm",
"cryptography"
],
"Title": "Tiny Encryption Algorithm (TEA) for arbitrary sized data"
} | 2050 |
<p>5 years ago, when i was in love with <code>VB</code>, I created this simple program to detect if a file is virus or not.</p>
<p>What I'd like is to see if you can help me optimize it, speed-wise.</p>
<p>I open an executable file in a rich textbox control and use the <code>Instr</code> method to search for occurrences of predefined string. The problem is that the <code>Instr</code> method is damn slow when searching files as small as 512KB.</p>
<p>Can the speed be enhanced?</p>
<pre><code>If InStr(1, rt.Text, "scripting.filesystemobject") Then
It does something with FSO
End If
If InStr(1, rt.Text, "thisprogramcannotberunindosmode") Or InStr(1, rt.Text, "thisprogrammustberununderwin32") Then
Probably a DOS program
Else
looks like a GUI program
End If
If InStr(1, rt.Text, "hkey_local_machine") Then
Does something with registry
End If
If InStr(1, rt.Text, "hkey_users") Then
Does something with registry
End If
If InStr(1, rt.Text, "hkey_current_user") Then
Does something with registry
End If
If InStr(1, rt.Text, "hkey_classes_root") Then
Does something with registry
End If
If InStr(1, rt.Text, "hkey_current_config") Then
Does something with registry
End If
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-24T12:55:55.703",
"Id": "3364",
"Score": "0",
"body": "Firstly, are you using .NET or not?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-24T12:57:55.957",
"Id": "3365",
"Score": "0",
"body": "The code is in VB, but i know .NET, and the speed is slow in .vb.net too :("
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-24T13:04:15.460",
"Id": "3366",
"Score": "0",
"body": "What code in VB.NET did you try? if the same code, then nothing is really going to change, is it? If you're using VB.NET, do your best to avoid mixing old VB usage in there. i.e. the code should be re-written for .NET."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-24T15:59:06.753",
"Id": "3369",
"Score": "0",
"body": "exactly which part to rewrite ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-24T16:14:13.710",
"Id": "3370",
"Score": "1",
"body": "By that very question I think we can conclude that you don't _know_ VB.NET. You just compiled legacy VB code using the VB.NET compiler so it would run in a managed environment - this is (just one reason) why I seriously dislike VB.NET."
}
] | [
{
"body": "<p>In VB2010 the instr out performed indexof</p>\n\n<pre><code> Dim ipsum As String = \"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\"\n\n Dim tries As Integer = 100000\n Dim stpw As New Stopwatch\n Dim iof As Integer\n Dim f As String = \"sint\"\n\n stpw.Reset()\n stpw.Start()\n\n For x As Integer = 1 To tries\n iof = ipsum.IndexOf(f)\n Next\n stpw.Stop()\n Label1.Text = stpw.ElapsedMilliseconds.ToString(\"n2\")\n\n stpw.Reset()\n stpw.Start()\n\n For x As Integer = 1 To tries\n iof = InStr(ipsum, f)\n Next\n stpw.Stop()\n Label2.Text = stpw.ElapsedMilliseconds.ToString(\"n2\")\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-25T14:27:08.363",
"Id": "3383",
"Score": "0",
"body": "after testing i'll post"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-25T20:42:24.377",
"Id": "3390",
"Score": "0",
"body": "you might want to consider `IndexOf(f,StringComparison.InvariantCulture)` depending on what's going to be in those strings"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-25T12:46:15.223",
"Id": "2083",
"ParentId": "2059",
"Score": "5"
}
},
{
"body": "<p>I have barely tested this at all, and this code is in and of itself not a complete solution, but I thought I'd offer an entirely different approach. (It may not be faster in practice, but I'm trying to think outside the box...)</p>\n\n<p>Would you be able to take every word in <code>rt.Text</code> (whitespace/punctuation delimited) and plug those words into a <code>Scripting.Dictionary</code>? The search for your key terms in the dictionary should be very fast, assuming the reading in to the dictionary in the first place is any faster.</p>\n\n<p>This is formed from VBA, but you should get the concept:</p>\n\n<pre><code>Sub Test()\n\n Dim sSource As String\n Dim sSplitText() As String\n Dim dictAllWords As New Scripting.Dictionary\n Dim i As Integer\n\n sSource = \"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\"\n\n sSource = Replace(sSource, \",\", \" \") ' Repeat for other punctuation and whitespace...\n\n sSplitText = Split(sSource, \" \")\n\n For i = 0 To UBound(sSplitText)\n If Not dictAllWords.Exists(sSplitText(i)) Then dictAllWords.Add sSplitText(i), sSplitText(i)\n Next i\n\n If dictAllWords.Exists(\"consectetur\") Then\n 'Do your stuff here\n End If\n\nEnd Sub\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-05T17:31:23.090",
"Id": "13365",
"ParentId": "2059",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-24T03:00:13.323",
"Id": "2059",
"Score": "5",
"Tags": [
"vb6",
"performance"
],
"Title": "VB6: String Searching Performance "
} | 2059 |
<p>In my nested <code>for</code> loops below, it is sometimes necessary to exit the outer loop and then continue program execution. Since loop labels and other goto-like constructions are heavily discouraged, I'm a bit afraid of raptors. Is this usage OK? Is there a better way to structure the program?</p>
<pre><code>my @objects = load_objects();
OUTER: for my $obj ( @objects ) {
for my $element ( @{$obj->elements} ) {
if ( is_case_1( $element ) ) {
...
} elsif ( is_case_2( $element ) ) {
...
} else {
warn "invalid element: $element";
last OUTER;
}
stuff_that_assumes_valid_element( $element );
}
stuff_that_assumes_valid_object( $obj );
}
store_objects( @objects );
</code></pre>
| [] | [
{
"body": "<p>In general, the code is OK, i.e. I don't think it must be changed. However, to increase clarity, I would do a couple of things differently:</p>\n\n<p>It's probably better to write an <code>is_valid()</code> method for your objects, so that whole inner loop is a single function call. Then, you can use <code>grep</code> to shorten the outer loop like this:</p>\n\n<pre><code> my @objects = load_objects();\n my @valid_objects = grep { $_->is_valid() } @objects;\n stuff_that_assumes_valid_object($_) for @valid_objects;\n store_objects(@valid_objects);\n</code></pre>\n\n<p>Also, depending on what <code>stuff_that_assumes_valid_element</code> does, you can either put that call into <code>is_valid()</code> or into <code>stuff_that_assumes_valid_object</code>. Either way, your top-level code works with objects and thus shouldn't know too much about single elements inside those objects, that's something the object itself should know and do (see <a href=\"http://en.wikipedia.org/wiki/Law_of_Demeter\" rel=\"nofollow\">Law of Demeter</a> for reasoning).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-24T14:33:48.433",
"Id": "2069",
"ParentId": "2060",
"Score": "3"
}
},
{
"body": "<p>I have two comments to make. The first addresses the use of labels. The second is on why you you might want an exception rather than a logical test.</p>\n<h2>Loop Labels</h2>\n<p>Loop labels and loop control are the one common form of <code>goto</code> that isn't generally frowned upon. (The other form is the rare use of a particular form in AUTOLOADER to seamlessly transfer control to generated code--unless you start experimenting with deeper magics you will never need it.)</p>\n<p><code>@rassie</code>'s point that your tests should be encapsulated in an <code>is_valid()</code> method for your objects is excellent, but I want to comment on another important aspect of using labeled loops: <strong>naming</strong>.</p>\n<p>Using <code>OUTER</code> as a label is like using <code>%hash</code> as a variable. The name tells a maintenance programmer nothing about what is happening or why.</p>\n<p>Perl syntax calls out for a noun-verb naming structure for labels with keywords like <code>next</code> and <code>last</code>. Good names for your outer loop could be <code>OBJECT_TEST</code>, <code>OBJECT_VALIDATION</code>, or <code>OBJECT_CHECK</code>.</p>\n<h2>Exceptions</h2>\n<p>When I look at your code I see a structure that is focussed on the normal case. This is fine as long as you have a way to ensure that errors are caught.</p>\n<p>If your <code>stuff_that_assumes_valid_object()</code> method checks for validity, then throws an exception (via <code>die</code>), then your code becomes very simple.</p>\n<p>This code is identical to your nested loop:</p>\n<pre><code> eval { $_->stuff_that_dies_on_invalid_object() for @objects }; \n store_objects(@objects);\n</code></pre>\n<p>But if you want the behavior in <code>@rassie</code>'s code of filtering out invalid objects and only storing the valid ones, you can do:</p>\n<pre><code>my @to_store = grep {\n eval { $_->stuff_that_dies_on_invalid_object; 1 }\n} @objects;\nstore_objects(@to_store);\n</code></pre>\n<p>It's also nice to know that your calls to code that makes assumptions will be safe. Either you expect a failure and catch the exception, or your program terminates on an unexpected, unsafe operation.</p>\n<p>P.S. <code>@rassie</code> is absolutely right about the Law of Demeter. Keep your object internals and knowledge about them as limited as possible. Consider making <code>store_objects()</code>, <code>assumes_valid_elements()</code> and <code>assumes_valid_objects()</code> code into methods.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-30T18:16:31.243",
"Id": "2714",
"ParentId": "2060",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "2714",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-24T08:13:15.613",
"Id": "2060",
"Score": "3",
"Tags": [
"perl"
],
"Title": "Can I jump like this?"
} | 2060 |
<p>I am new to Rails and have a system that needs to process transactions.</p>
<p>A user can enter a transaction to which one or more users are tied. These users owe some amount of money to the person making the transaction. For example, Bill might buy lunch for 4 friends and the bill is $125. They decide to split the bill 5 ways, so each owes $25. Bill would enter a total of $125 and enter each friend (including himself) as owing $25 to the transaction.</p>
<p>I have code in my controller and in my model to accomplish this goal, but I don't really know if I am using transactions and locking correctly. Also, is this the intended way to have this information in the controller?</p>
<p>I am using a transaction since all of these actions must occur together or fail (atomicity) and I need locking in case multiple users try to submit at the same time (isolation).</p>
<p>Maybe I should let the db on the backend handle locking? Does it do that already - say, MySQL?</p>
<p><strong>trans_controller.rb</strong></p>
<pre><code>class TransController < ApplicationController
# POST trans/
def create
@title = "Create Transaction"
trans_successful = false
# Add the transaction from the client
@tran = Tran.new(params[:tran])
# Update the current user
@tran.submitting_user_id = current_user.id
# Update the data to the database
# This call commits the transaction and transaction users
# It also calls a method to update the balances of each user since that isn't
# part of the regular commit (why isn't it?)
begin
@tran.transaction do
@tran.save!
@tran.update_user_balances
trans_successful = true
end
rescue
end
# Save the transaction
if trans_successful
flash[:success] = 'Transaction was successfully created.'
redirect_to trans_path
else
flash.now[:error] = @tran.errors.full_messages.to_sentence
render 'new'
end
end
</code></pre>
<p><strong>tran.rb</strong></p>
<pre><code>class Tran < ActiveRecord::Base
has_many :transaction_users, :dependent => :destroy, :class_name => 'TransactionUser'
belongs_to :submitting_user, :class_name => 'User'
belongs_to :buying_user, :class_name => 'User'
accepts_nested_attributes_for :transaction_users, :allow_destroy => true
validates :description, :presence => true,
:length => {:maximum => 100 }
#validates :total, :presence => true
validates_numericality_of :total, :greater_than => 0
validates :submitting_user_id, :presence => true
validates :buying_user_id, :presence => true
#validates_associated :transaction_users
validate :has_transaction_users?
validate :has_correct_transaction_user_sum?
validate :has_no_repeat_users?
def update_user_balances
# Update the buying user in the transaction
self.buying_user.lock!
# Update the user's total, since they were in the transction
self.buying_user.update_attribute :current_balance, self.buying_user.current_balance - self.total
# Add an offsetting transaction_user for this record
buying_tran_user = TransactionUser.create!(:amount => -1 * self.total, :user_id => self.buying_user_id, :tran => self)
#if buying_tran_user.valid?
# raise "Error"
#end
# Loop through each transaction user and update their balances. Make sure to lock each record before doing the update.
self.transaction_users.each do |tu|
tu.user.lock!
tu.user.update_attribute :current_balance, tu.user.current_balance + tu.amount
end
end
def has_transaction_users?
errors.add :base, "A transcation must have transaction users." if self.transaction_users.blank?
end
def has_correct_transaction_user_sum?
sum_of_items = 0;
self.transaction_users.inspect
self.transaction_users.each do |key|
sum_of_items += key.amount if !key.amount.nil?
end
if sum_of_items != self.total
errors.add :base, "The transcation items do not sum to the total of the transaction."
end
end
def has_no_repeat_users?
user_array = []
self.transaction_users.each do |key|
if(user_array.include? key.user.email)
errors.add :base, "The participant #{key.user.full_name} has been listed more than once."
end
user_array << key.user.email
end
end
end
</code></pre>
| [] | [
{
"body": "<p>I think it's a bad practice to use transactions in Controllers.\nYou should add a method on the <code>Tran</code> model instead (for example, <code>save_and_update_user_balances</code>):</p>\n\n<pre><code>def create\n @title = \"Create Transaction\"\n\n # Add the transaction from the client\n @tran = Tran.new(params[:tran])\n\n # Update the current user\n @tran.submitting_user_id = current_user.id\n\n # Update the data to the database\n # This call commits the transaction and transaction users \n # It also calls a method to update the balances of each user since that isn't\n # part of the regular commit (why isn't it?)\n if(@tran.save_and_update_user_balances)\n redirect_to trans_path, success: 'Transaction was successfully created.'\n rescue\n flash.now[:error] = @tran.errors.full_messages.to_sentence \n render 'new'\n end\nend\n</code></pre>\n\n<p>In <code>tran.rb</code>:</p>\n\n<pre><code>def save_and_update_user_balances\n transaction do\n begin\n save! \n update_user_balances!\n true\n rescue\n false\n end\n end\nend\n</code></pre>\n\n<p>In <code>update_user_balances!</code> use <code>update_attributes!</code> and force to fail (and rollback) if an error happens.</p>\n\n<p>Also, since <code>update_user_balances!</code> is called inside a transaction, you don't need to create another transaction, or lock. This is because of the way ActiveRecord works:</p>\n\n<blockquote>\n <p>Though the transaction class method is called on some Active Record class, the objects within the transaction block need not all be instances of that class. This is because transactions are per-database connection, not per-model.</p>\n</blockquote>\n\n<p>So the method should be:</p>\n\n<pre><code>def update_user_balances!\n self.buying_user.update_attributes! current_balance: self.buying_user.current_balance - self.total\n\n # Add an offsetting transaction_user for this record\n # Note: You could improve this by using a relationship to create it, like this?\n # transaction_users.create!(amount: -1 * self.total, user_id: buying_user_id)\n TransactionUser.create!(:amount => -1 * self.total, :user_id => self.buying_user_id, :tran => self)\n\n # Loop through each transaction user and update their balances.\n transaction_users.each do |tu|\n tu.user.update_attributes! current_balance: tu.user.current_balance + tu.amount\n end\nend\n</code></pre>\n\n<p>For further reference: <a href=\"http://api.rubyonrails.org/classes/ActiveRecord/Transactions/ClassMethods.html\" rel=\"nofollow\">Ruby on Rails documentation on Transactions</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T22:01:28.493",
"Id": "42818",
"ParentId": "2073",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-24T22:17:48.597",
"Id": "2073",
"Score": "5",
"Tags": [
"beginner",
"ruby",
"ruby-on-rails",
"finance",
"locking"
],
"Title": "Transactions and locking in Rails 3"
} | 2073 |
<p>My friend does a bunch of Java work (commandline, still toying around) and I notice a bunch of try/catch blocks like this:</p>
<pre><code> try {
double a = Double.parseDouble(secondInput);
}
catch(NumberFormatException nFE) {
System.out.println("The input was not an integer.");
try {
Thread.sleep(1997);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.exit(0);
}
</code></pre>
<p>Which, IMO doesn't look very pretty. And I'm wondering what the "better" way to write this code would be.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-25T02:01:26.653",
"Id": "3376",
"Score": "1",
"body": "There are a number of problems with this code. What element in particular are you asking about - the nested try/catch blocks, like Vicente mentions?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-25T01:59:57.180",
"Id": "64501",
"Score": "0",
"body": "Please check: http://stackoverflow.com/questions/5774505/is-it-acceptable-practice-in-java-to-nest-try-catch-statements-for-example"
}
] | [
{
"body": "<p>You hit infamous checked exceptions feature in Java. Here is <a href=\"http://www.mindview.net/Etc/Discussions/CheckedExceptions\" rel=\"nofollow\">one of the basic articles on this</a>, by Bruce Eckel but you can find more by googling \"checked exceptions in Java\".</p>\n\n<p>In most cases it's hard to avoid try/catch blocks but all you need to do in most cases is to rethrow the exception without any processing. In my code I am using the following pattern (using <a href=\"http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/base/Throwables.html\" rel=\"nofollow\">Throwables</a> from <a href=\"http://code.google.com/p/guava-libraries/\" rel=\"nofollow\">Google Guava library</a>):</p>\n\n<pre><code>void myMethod() {\n try {\n APIFunction1();\n APIFunction2();\n } catch (Exception e) { throw Throwables.propagate(e); }\n}\n</code></pre>\n\n<p>I consider this the least necessary evil. You can write similar utility yourself, quite easily. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-25T02:31:19.670",
"Id": "3377",
"Score": "0",
"body": "I forget which language is the \"let it crash\" one, but I wish Java was. :-/"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-25T02:22:43.540",
"Id": "2078",
"ParentId": "2076",
"Score": "1"
}
},
{
"body": "<p>There are a couple of issues.</p>\n\n<ul>\n<li><p>Why is the application pausing for 2 seconds before exiting? Why not just exit straightaway? (And if the answer is that you are running this via Windows 'cmd.exe' then you are better off handling the pausing at that level ...)</p></li>\n<li><p>Given that you do need to pause, then you are better of writing a helper method to do something like \"print a message, pause, and exit with a non-zero exit code\". Then use that in multiple places, as required.</p></li>\n<li><p>You <em>should</em> be setting a <em>non-zero</em> exit code when you exit due to a failure. This allows the script or whatever that launched the java app to detect the failure and (maybe) do something about it; e.g. pause so that the user can see the error message ...</p></li>\n<li><p>The <code>InterruptedException</code> is not a program error, so printing a stacktrace is probably not appropriate. </p></li>\n</ul>\n\n<p>Figuring out what to do with an <code>InterruptedException</code> exception is not straightforward. The exception indicates that something (either the user or the application) has interrupted the application, either before or during the <code>sleep</code>. </p>\n\n<ul>\n<li><p>In this use-case you are just about to exit anyway, so the best strategy is to ignore it an exit anyway.</p></li>\n<li><p>You need to decide what is a sensible thing to do. Some possibilities are:</p>\n\n<ul>\n<li><p>Ignore the interrupt and carry on regardless.</p></li>\n<li><p>Take steps to cause the application to stop what it was doing; e.g. throw a custom unchecked \"stop now\" exception. (You could also call <code>System.exit()</code> directly, but that can also be a bad thing to do, depending on the nature of the code. For instance, calling <code>System.exit()</code> in a library ... or a webapp ... is a big non-no.)</p></li>\n<li><p>Punt: reinstate the \"interrupted\" state by calling <code>Thread.currentThread().interrupt()</code> in the exception handler. For instance, you might do this if some enclosing code is checking the \"interrupted\" flag.</p></li>\n</ul></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-25T03:37:18.037",
"Id": "3378",
"Score": "0",
"body": "My friend's a bit of a trial/error kind of learner. I'll pass this on to him. I get it that Eclipse isn't too beginner friendly then."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-25T04:40:30.943",
"Id": "3379",
"Score": "0",
"body": "@digitxp - these issues are nothing to do with Eclipse."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-25T15:41:28.340",
"Id": "3384",
"Score": "1",
"body": "@Stephen C: I get the feeling the 1997 milliseconds are the grace period given to the user to read the message. :/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-26T00:24:13.033",
"Id": "3392",
"Score": "0",
"body": "@Mr. Disappointment- The message is printed to the console- it won't disappear on System.exit();"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-26T05:58:14.023",
"Id": "3394",
"Score": "0",
"body": "@Mr. Disappointment - I'd already figured that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-26T05:58:23.070",
"Id": "3395",
"Score": "2",
"body": "@Rob Lourens - ... unless you are running it on Windows from a lame \"BAT\" file that closes the console window on exit."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-25T03:07:11.593",
"Id": "2079",
"ParentId": "2076",
"Score": "9"
}
},
{
"body": "<p>Looking at your specific case of <code>Thread.sleep</code>, and knowing other I/O exception-throwing methods (<code>close()</code>, for example), how about using helpful libraries like <a href=\"http://code.google.com/p/guava-libraries/\" rel=\"nofollow\">Google Guava</a>?</p>\n\n<p>For the Files example, you can use <code>Closables.closeQuietly(filehandle)</code>, which does not throw an exception. See: </p>\n\n<p>For your sleep example, you could make similar methods (if you really wanted a thread to sleep ~2 seconds), <code>Sleeper.sleepQuietly(2000)</code>, etc.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-25T05:36:39.590",
"Id": "2080",
"ParentId": "2076",
"Score": "3"
}
},
{
"body": "<p>Not sure on Java since it is a while since I coded with it but in C#, a try-catch block carries a performance overhead that is best limited. A single block is expensive, and best replaced with conditional evaluation to prevent the exception being thrown in the first place, but using nested blocks is okay for basic home projects but if I had to peer review that code I would push it right back to the source developer and ask them to refactor the codefor optimisation. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-25T17:32:20.023",
"Id": "2092",
"ParentId": "2076",
"Score": "0"
}
},
{
"body": "<p>How about :</p>\n\n<pre><code>try {\n double a = Double.parseDouble(secondInput);\n}\ncatch(NumberFormatException nFE) {\n displayNotIntegerErrorAndExit();\n}\n\n[...]\nprivate void displayNotIntegerErrorAndExit() {\n System.out.println(\"The input was not an integer.\");\n sleepFor(1997);\n System.exit(0);\n}\n\nprivate void sleepFor(long delayInMs) {\n try {\n Thread.sleep(delayInMs);\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n}\n</code></pre>\n\n<p>Note: I did not check if it compiles or anything, but that is the way I do it normally. And it makes it easy to see if you are duplicating code (i.e. if you are making 300 sleepFor() methods).</p>\n\n<p>Edit: As an additional point. When handled correctly, the increase in readability and flexibility or the code that comes from exception far outweighs the minor overhead of the exception handling.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-07-29T23:23:20.550",
"Id": "3727",
"ParentId": "2076",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-25T01:58:51.080",
"Id": "2076",
"Score": "8",
"Tags": [
"java",
"error-handling",
"floating-point"
],
"Title": "Aborting a program for invalid floating-point input"
} | 2076 |
<p>I have a simple quantity display function that runs for every product displayed in our catalog. The <code>MaxQtyDisplay</code> value is set in our web.config file. Part of me thinks the function is as streamlined as possible and part of me thinks it can be improved upon somewhere. Because this function is called many, many times in our web application I would like it be optimized as best it could.</p>
<p>What could be done to improve it?</p>
<pre><code>Private Shared Function CalculateQtyDisplay(ByVal x As Double, ByVal y As Double) As Double
Dim q As Double = x - y
If q > 0 And q <= My.Settings.MaxQtyDisplay Then
Return q
ElseIf q > My.Settings.MaxQtyDisplay Then
Return My.Settings.MaxQtyDisplay
Else
Return 0
End If
End Function
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-11T14:19:25.520",
"Id": "392527",
"Score": "0",
"body": "Are the values involved really doubles? Using Integers would help."
}
] | [
{
"body": "<p>I'm sure there will be elements of your application that are of much more concern, performance-wise, than this, but it could certainly be a little more clear, or maybe a little less superfluous...</p>\n\n<ul>\n<li>Evaluation of and work within conditions is only required if <code>q > 0</code></li>\n<li>You really want to use <code>AndAlso</code> to apply short-circuiting in the first condition</li>\n<li><code>q > MaxQtyDisplay</code> is redundant since this condition wouldn't hit otherwise (forgetting negative quantities but we address that by addressing my first point)</li>\n<li><code>Else</code> is likewise not required.</li>\n<li>Only get the value of <code>MaxQtyDisplay</code> from the settings context once (negligible in terms of performance really, since settings are loaded from file into memory on request)</li>\n<li>Naming variables with single character identifiers doesn't optimise anything</li>\n</ul>\n\n<p>So, for example, you can correct these as such:</p>\n\n<pre><code>Private Function CalculateQtyDisplay(ByVal x As Double, ByVal y As Double) As Double\n Dim result = 0.0\n Dim desiredQuantity As Double = x - y\n Dim maxQuantity = My.Settings.MaxQtyDisplay\n If (desiredQuantity > 0) Then\n If (desiredQuantity <= maxQuantity) Then\n result = maxQuantity\n Else\n result = desiredQuantity\n End If\n End If\n Return result\nEnd Function\n</code></pre>\n\n<p>Any other modifications to this code are simply going to be aesthetic and preferential really, as far as I can see. For instance you could do away with maintaining <code>result</code>, this goes against what I recommend in another answer but it clearly boils down to context):</p>\n\n<pre><code>Dim desiredQuantity As Double = x - y\nDim maxQuantity = My.Settings.MaxQtyDisplay\nIf (desiredQuantity > 0) Then\n If (desiredQuantity <= maxQuantity) Then\n Return maxQuantity\n End If\n Return desiredQuantity\nEnd If\nReturn 0\n</code></pre>\n\n<p>A modification that comes to mind which could potentially impact performance, if anything might, is to use the <code>IIf</code> function available to VB.NET (both <code>TruePart</code> and <code>FalsePart</code> of this call are evaluated, though I highly doubt you'll ever have any noticeable degradation with this method anyway, even if you used this method):</p>\n\n<pre><code>Dim quantity As Double = x - y\nDim maxQtyDisplay = 1800 'My.Settings.MaxQtyDisplay\nIf (quantity > 0) Then\n Return IIf(quantity <= maxQtyDisplay, quantity, maxQtyDisplay)\nEnd If\nReturn 0\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-25T18:57:31.327",
"Id": "3389",
"Score": "0",
"body": "WOW. I didn't even think of the solution you proposed. Very well written explanation as well. I actually use `AndAlso` in other functions I have, but didn't even think of using it here."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-25T18:16:00.597",
"Id": "2094",
"ParentId": "2093",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "2094",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-25T17:35:49.197",
"Id": "2093",
"Score": "4",
"Tags": [
"asp.net",
"vb.net"
],
"Title": "Display catalog product quantity"
} | 2093 |
<p>This is a jQuery plug-in I've created that relies on jQuery UI's tabs plug-in. It adds some framework specific logic when setting up tabs:</p>
<ol>
<li>Fixes a bug in jQuery that appears when an id/class contains a "."</li>
<li>Manages the tab state using a framework specific cookie API (does not use the jQuery cookie plugin)</li>
<li>Exposes a couple of options for transition behavior</li>
</ol>
<p>I'd love to get some suggestions on how to improve this, as it'll be used widely in the framework.</p>
<pre><code>(function ($) {
$.fn.dnnTabs = function (options) {
var opts = $.extend({}, $.fn.dnnTabs.defaultOptions, options),
$wrap = this;
$(document).ready(function () {
// Patch for Period in IDs (jQuery bug)
$.ui.tabs.prototype._sanitizeSelector = function (hash) {
// we need this because an id may contain a ":" or a '.'
return hash.replace(/:/g, "\\:").replace(/\./g, "\\\.");
};
var id = 'dnnTabs-' + $wrap.selector.replace('#', '').replace('.', '');
if (opts.selected === -1) {
var tabCookie = dnn.dom.getCookie(id);
if (tabCookie) {
opts.selected = tabCookie;
}
if (opts.selected === -1) {
opts.selected = 0;
}
}
$wrap.tabs({
show: function (event, ui) {
dnn.dom.setCookie(id, ui.index, 1, '/', '', false);
},
selected: opts.selected,
fx: {
opacity: opts.opacity,
duration: opts.duration
}
});
});
return $wrap;
};
$.fn.dnnTabs.defaultOptions = {
opacity: 'toggle',
duration: 'fast',
selected: -1
};
})(jQuery);
</code></pre>
| [] | [
{
"body": "<p>These are probably more comments, but I'll post them as an \"answer\", because it's easier.</p>\n\n<ul>\n<li><p>Could you point out a source or an example for the bug with ids/classes containing <code>.</code> and <code>:</code>, because in a quick test they seem to work fine: <a href=\"http://jsfiddle.net/NSXLc/\" rel=\"nofollow\">http://jsfiddle.net/NSXLc/</a></p></li>\n<li><p>I don't think you should use the document ready event. It should be the plugins user's choice when he wants to apply the tabs.</p></li>\n<li><p>The way you are getting the id for the cookie looks dangerously wrong. You assume the selector is always a simple id or class selector and extending on that you assume, that the selector only matches one element and thus only one one set of tabs are initialized at a time. </p></li>\n</ul>\n\n<p>It's probably better to do something like this:</p>\n\n<pre><code>$wrap.each(function() { // In case the selector matches multiple elements\n var showEvent = null;\n if (this.id) { // only use cookie if ID is set. TODO: use className as alternative\n var id = 'dnnTabs-' + this.id;\n if (opts.selected === -1) {\n // ...\n }\n\n showEvent = (function(cookieId) { // closure for cookie id\n return function (event, ui) {\n dnn.dom.setCookie(cookieId, ui.index, 1, '/', '', false);\n }\n })(id);\n }\n $(this).tabs({\n show: showEvent,\n // ...\n });\n});\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-27T16:06:30.597",
"Id": "3459",
"Score": "0",
"body": "Thanks very much for your feedback, it's very helpful and exactly what I was hoping for. Here is the link to the bug demo - I think you have to try it specifically with the tabs plugin: http://jsfiddle.net/9Mst9/2/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-27T16:29:25.850",
"Id": "3461",
"Score": "0",
"body": "The only thing that's a little weird now is the requirement on each element the plugin is operating on to have an id. I think this is probably fine in general practice, but there will inevitably be an edge case where it will not. Is your suggestion to add fallback logic to use the className when the id is not present? Thanks again."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-28T12:34:06.310",
"Id": "3492",
"Score": "0",
"body": "Ok, that's a real bug the Tabs plugin in. I thought you meant the bug was in jQuery itself. Since you want to store the state of set of tabs in a cookie, id would make sense to give the tabs an id, so that it can use as the cookie name."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-26T10:49:04.670",
"Id": "2103",
"ParentId": "2096",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "2103",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-25T19:51:01.093",
"Id": "2096",
"Score": "3",
"Tags": [
"javascript",
"jquery"
],
"Title": "jQuery Plugin Review - wrapper for jQuery UI's tabs"
} | 2096 |
<p>I am new to the world of coding as well as XHTML and PHP. As a way to gain more experience as well as to put theory into practice including a way to challenge myself, I put together the following code that calculates values a user enters into a form. </p>
<p>This was to test my knowledge regarding PHP's own functions but also creating custom functions. I am sure the code can be improved and would appreciate any advise. </p>
<p>The one thing I was unable to do was to only display the result and to hide the form once it has been posted preferably on the same page i.e. not redirecting the user to another page.</p>
<p>I have also tried to keep business logic and presentation as much as possible.</p>
<p><em>Appreciate any advise as well as constructive criticism.</em></p>
<p><strong>Main Page Code - Calculator.php</strong></p>
<pre><code><?php
require_once('includes/base.php');
require_once('functions.php');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>Calculator</title>
</head>
<body>
<h1>Calculator Instructions</h1>
<p>Below are instructions on using the calculator</p>
<ol>
<li>You must specify 2 values in the fields below</li>
<li>You must select an arithmetic operator which includes the list below
<ul>
<li>Multiply</li>
<li>Divide</li>
<li>Modulus</li>
<li>Add</li>
<li>Subtract</li>
</ul>
</li>
<li>Simply submit the form once you have specified 2 values and selected arithmetic operator</li>
</ol>
<h2>Calculator</h2>
<div>
<?php
if(isset($_POST['submit'])) {
echo mycalculator();
}
?>
</div>
<form name="calculator" method="post" action="calculator.php">
<div>
Field 1: <br />
<input type="input" name="field1" value="<?php if(isset($_POST['field1'])) { echo $_POST['field1']; } ?>" />
</div>
<div>
Field 2: <br />
<input type="input" name="field2" value="<?php if(isset($_POST['field2'])) { echo $_POST['field2']; } ?>" />
</div>
<div>
Select an arithmetic operator: <br />
<select name="field3">
<option value="">Please select an option</option>
<?php
echo myselect();
?>
</select>
</div>
<div>
</div>
<div>
<input type="submit" name="submit" value="submit" />
<input type="reset" name="reset" value="reset" />
</div>
</form>
</body>
</html>
</code></pre>
<p><strong>Define and Set directory and path - Base.php</strong></p>
<pre><code><?php
//Retrieve parent directory
$parentdirectory = dirname(dirname(__FILE__));
$unixpath = str_replace('\\', '/', $parentdirectory);
//Define root directory
define('BASE_DIRECTORY', $parentdirectory);
//Set includes directory
ini_set('include_path', $parentdirectory.'\includes');
?>
</code></pre>
<p><strong>Business Logic - Functions.php</strong></p>
<pre><code><?php
//Generate arithmetic menu
function myselect () {
//Define arithmetic operators
$selectarray = array('multiply', 'divide', 'modulus', 'add', 'subtract');
$status = '';
foreach($selectarray as $seletkey => $selectvalue) {
if($_POST['field3'] == $selectvalue) {
$status = 'selected';
}
else {
$status = '';
}
echo '<option value="'.$selectvalue.'" '.$status.'>'.$selectvalue.'</option>';
}
}
//Validate if form has been submitted
if(isset($_POST['submit'])) {
//Generate errors if form is not completed
function mycalculator() {
//Instatiate form fields, error messages and arithmetic operators
$formfields = array('a' => 'field1', 'b' => 'field2', 'c' => 'field3');
// $formfieldkeys = array_values($formfields);
$formfieldkeys = array_combine(range(1, count($formfields)), array_values($formfields));
//Instantiate error messages array
$errormsg = array();
//Validate if form field has been set
foreach($formfieldkeys as $formfieldkey => $formfieldvalue) {
$formfield = isset($_POST[$formfieldvalue]) ? $_POST[$formfieldvalue] : '';
//Return error message
if(empty($formfield)) {
$errormsg = 'Please specify a value for field '.$formfieldkey.'<br />';
/* Return error message for the specific field concerned using array_values
$errormsg = 'Please specify a value for field '.($formfieldkey + 1).'<br />';
*/
echo $errormsg;
}
//Validate if the values being posted for fields 1 - 2 are numeric
if(in_array($formfieldvalue, array('field1','field2'))) {
if(!is_numeric($formfield)) {
$errormsg = 'You must provide a numeric value for field '.$formfieldkey.'<br />';
/* Return error message for the specific field concerned using array_values
$errormsg = 'You must provide a numeric value for field '.($formfieldkey + 1).'<br />';
*/
echo $errormsg;
}
}
if(!empty($formfield)) {
//Extract individual array values
// extract($formfields);
// $field1 = $_POST[$a];
// $field2 = $_POST[$b];
// $field3 = $_POST[$c];
//Dynamic Variables
${"field{$formfieldkey}"} = $_POST[$formfieldvalue];
if(!empty($field1) && !empty($field2) && !empty($field3)) {
if($field3 == 'multiply') {
$calculate = $field1 * $field2;
// echo $calculate;
}
elseif($field3 == 'divide') {
$calculate = $field1 / $field2;
// echo $calculate;
}
elseif($field3 == 'modulus') {
$calculate = $field1 % $field2;
// echo $calculate;
}
elseif($field3 == 'add') {
$calculate = $field1 + $field2;
// echo $calculate;
}
elseif($field3 == 'subtract') {
$calculate = $field1 - $field2;
// echo $calculate;
}
else {
$calculate = 'error';
}
if($calculate > 0) {
return 'The answer is '.$calculate;
}
}
}
}
}
//Debug
// print_r($_POST);
}
?>
</code></pre>
| [] | [
{
"body": "<p>This is going to have a lot of extensibility concerns. What if I want to add exponentials or scientific notation? What if I want to chain operations? What if I want to ensure someone doesn't put unsafe code that could bork my webserver in the POST variable?</p>\n\n<p><a href=\"https://stackoverflow.com/questions/2401706/where-to-sanitize-php-post-input\">https://stackoverflow.com/questions/2401706/where-to-sanitize-php-post-input</a> </p>\n\n<p>All that said, I'm impressed by how good a job you did of separating your presentation from your business logic. I've seen a lot uglier PHP. The main page code is nicely mainly HTML, and the business logic is separated out.</p>\n\n<p>From here, POA:</p>\n\n<ol>\n<li>Refactor for an Object Oriented Approach</li>\n<li>Sanitize User input</li>\n<li><p>Consider breaking apart pieces of the UI into separate chunks that are added dynamically, which reduced the maintenance burden. For example, you may want to put </p>\n\n<p></p>\n\n<pre><code> Select an arithmetic operator: <br />\n <select name=\"field3\">\n <option value=\"\">Please select an option</option>\n\n <?php\n\n echo myselect();\n\n ?>\n\n </select>\n</div>\n</code></pre></li>\n</ol>\n\n<p>In an operations.php that you include. This allows for easy modification/adding of stuff later.</p>\n\n<p>Also, you'll probably want to look into AJAX. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-26T08:37:25.607",
"Id": "3397",
"Score": "0",
"body": "Software Solution - Thanks for your comments and feedback. I didn't look at extensibility of the code at this stage as I was keen to learn and come to grasps with functions which I must say is still very new to me. Nevertheless, I'll certainly bear in mind about the scalability of my code. What are chain commands? Also I didn't look at sanitizing the data apart from a very basic check of whether the value was numeric."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-26T08:41:35.463",
"Id": "3398",
"Score": "0",
"body": "Software Solution - continued -I assume POA refers to Points of Action. I have no idea how object oriented programming works at this stage but am hoping to touch on it soon. I'll remember about sanitizing user data. How else would you suggest I separate the UI into separate blocks/chunks of code?\n\nFrom a coding perspective, was my code easy to follow? How would you rate it, 1 being absolute crap and 10 being the best of the breed? Where did I make mistakes?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-26T07:59:25.817",
"Id": "4114",
"Score": "0",
"body": "I'd go further and suggest that no html at all should be in your 'business logic'. If your dev team is split front end & server side, then you need to ensure any html is clearly presented and accessible to the other developers. Doing a quick loop and using helper functions such as `set_select()` in CodeIgniter should reduce the visible server side logic."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-26T06:10:04.160",
"Id": "2098",
"ParentId": "2097",
"Score": "2"
}
},
{
"body": "<p>I'm not sure about the function names <code>myselect</code> and <code>mycalculator</code>. They aren't good function names as it stands, but are they just example names that you're planning to change later? Putting the 'my' prefix on a function isn't very useful, since all functions belong to somebody. Often the 'my' prefix is used in example code in books and tutorials to emphasise that this is code written by the user, but it's not good practice in the real world.</p>\n\n<p>Good function names should:</p>\n\n<ul>\n<li>As far as possible, tell you exactly what the function does. This might include things like whether the generated HTML is printed directly or returned to the caller, which is often differentiated as <code>print_foobar</code> and <code>render_foobar</code>.</li>\n<li>Not mention any details of the function that are irrelevant to the caller: who wrote the function, whether it's implemented in PHP or C++, etc.</li>\n<li>Take into account the context in which the function will be called. An object method often needs less context in the name than a free function, because the name of the object will give some context. If you had a free function for rendering a calculator you might call it <code>render_calculator()</code>, but the equivalent method on a <code>Calculator</code> class would probably just need to be <code>render</code>, since you'll typically call it like <code>$calc->render()</code>.</li>\n<li>Follow any (explicit or implicit) naming conventions in (by order of preference) the current class, the current code module, the major libraries you're working with, and the prevailing language style as a whole. PHP is famously bad at adhering to consistent conventions in its standard library functions, but if you're using (say) Zend Framework, you should consider following their conventions.</li>\n</ul>\n\n<p>You will probably want to give your POST variables better names, similar to the way you'd name variables within ordinary code. <code>field3</code> is a bad name, <code>operator</code> might be better. For <code>field1</code> and <code>field2</code> you might be better to emphasise that they are left and right-hand sides of an expression: <code>expr_lhs</code> and <code>expr_rhs</code> might work better.</p>\n\n<p>You want to avoid referring to the <code>$_POST</code> array in more than one place, because it implicitly couples together the various bits of code that refer to it. If you change the keys of your POST data, you don't want to have to update lots of different bits of the code (even worse, you don't want to have trouble tracing where it's referred to, possibly across lots of different files and directories, and fail to update one place). PHP makes it easy to refer to <code>$_POST</code> all over the place, but this doesn't mean it's good practice.</p>\n\n<p>A better option might be to have one piece of code that's responsible for unpacking the $_POST` array and packing it into objects that the rest of the code can use. For example, you could have an expression class:</p>\n\n<pre><code><?php\nclass Expression {\n public $lhs;\n public $rhs;\n public $operator;\n}\n?>\n</code></pre>\n\n<p>And have a function that unpacks <code>$_POST</code> and returns an instance of this.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-26T08:14:58.093",
"Id": "2621",
"ParentId": "2097",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-26T02:31:42.647",
"Id": "2097",
"Score": "3",
"Tags": [
"php"
],
"Title": "PHP and Custom Functions"
} | 2097 |
<p><strong>Edit:</strong></p>
<p>The purpose of this method is to search a specific directory for a given file type, ex. (*.txt, *.pdb, *.exe") then move the file(s) to a given destination directory and delete the original file from the source directory.</p>
<p>Is there a better way to write the following code?:</p>
<pre><code>/// <summary>
/// Moves a specific file type from a given
/// source directory to a destination directory.
/// </summary>
/// <param name="sourceDir">The source directory.</param>
/// <param name="destDir">The destination directory.</param>
/// <param name="fileExt">Type of file to be moved.</param>
private static void MoveFilesToDirectory(string sourceDir, string destDir, string fileExt)
{
try
{
if ( !Directory.Exists(sourceDir) )
{
Console.WriteLine("{0} does not exist.", sourceDir);
return;
}
if ( !Directory.Exists(destDir) )
{
Directory.CreateDirectory(destDir);
}
foreach ( String dir in Directory.GetDirectories(sourceDir) )
{
foreach ( String file in Directory.GetFiles(dir, fileExt) )
{
string fileName = Path.GetFileName(file);
string moveFileTo = Path.Combine(destDir, fileName);
if ( !File.Exists(moveFileTo) )
{
Directory.Move(file, moveFileTo);
}
File.Delete(file);
}
MoveFilesToDirectory(dir, destDir, fileExt);
}
}
catch ( IOException ex )
{
Console.WriteLine(ex.Message);
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-26T11:02:44.037",
"Id": "3401",
"Score": "0",
"body": "Your code does something else than the title indicates?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-26T11:29:54.710",
"Id": "3402",
"Score": "1",
"body": "How so? Look at my edit please."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-26T12:10:48.840",
"Id": "3404",
"Score": "0",
"body": "Is the RemoveFilesFromDirectory call actually meant to be a recursive call to MoveFilesToDirectory?"
}
] | [
{
"body": "<p>From msdn:</p>\n\n<pre><code>string sourceFile = @\"C:\\Users\\Public\\public\\test.txt\";\nstring destinationFile = @\"C:\\Users\\Public\\private\\test.txt\";\n\n// To move a file or folder to a new location:\nSystem.IO.File.Move(sourceFile, destinationFile);\n\n// To move an entire directory. To programmatically modify or combine\n// path strings, use the System.IO.Path class.\nSystem.IO.Directory.Move(@\"C:\\Users\\Public\\public\\test\\\", @\"C:\\Users\\Public\\private\");\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-26T11:31:27.037",
"Id": "3403",
"Score": "1",
"body": "That doesn't have the file searching capability that I have in my above method."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-26T09:33:19.663",
"Id": "2102",
"ParentId": "2101",
"Score": "3"
}
},
{
"body": "<pre><code> static void Main(string[] args)\n {\n String mask = \"*.txt\";\n String source = @\"c:\\source\\\";\n String destination = @\"c:\\destination\\\";\n\n String[] files = Directory.GetFiles(source, mask, SearchOption.AllDirectories);\n foreach (String file in files)\n {\n File.Move(file, destination + new FileInfo(file).Name);\n }\n }\n</code></pre>\n\n<p>Add in your own directory exists verification logic... but this should be all you need at the core. I haven't verified this code, but these built in functions should do what you want.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-26T13:21:45.000",
"Id": "3405",
"Score": "0",
"body": "@schlechtums: Thanks! A buddy of mine just helped me come up with the same solution. I didn't know about the SearchOption.AllDirectories enum."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-26T15:46:30.673",
"Id": "3424",
"Score": "5",
"body": "FYI: .NET 4 introduced a new method called `Directory.EnumerateFiles`. From [MSDN](http://msdn.microsoft.com/en-us/library/dd383458.aspx): \"The EnumerateFiles and GetFiles methods differ as follows: When you use EnumerateFiles, you can start enumerating the collection of names before the whole collection is returned; when you use GetFiles, you must wait for the whole array of names to be returned before you can access the array. Therefore, when you are working with many files and directories, EnumerateFiles can be more efficient.\""
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-26T19:34:42.837",
"Id": "3439",
"Score": "1",
"body": "@Adam Spicer: does enumerate work if you delete a file from the source directory you are enumerating over? With Directory.GetFiles() you first get all source filenames and then delete some of them."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-28T02:21:46.760",
"Id": "3481",
"Score": "0",
"body": "@k3b I haven't researched your question. It would be an interesting test to perform as deleting from enumeration doesn't usually work because it modifies the collection. But since deleting the file isn't removing something from a collection it probably will be ok."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-02T14:29:46.547",
"Id": "3541",
"Score": "1",
"body": "always use Path.Combine(path1, path2) to avoid \"/\" and get valid IO path"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-05-12T21:05:48.273",
"Id": "373751",
"Score": "0",
"body": "You can see it in action https://github.com/kelias/Pillage/blob/master/Pillage/FileScanner.cs\nWhich scans files for the contents inside them.Uses Directory.GetFiles with the SearchSubfolders option."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-26T12:43:46.163",
"Id": "2105",
"ParentId": "2101",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-26T09:23:03.153",
"Id": "2101",
"Score": "7",
"Tags": [
"c#",
".net"
],
"Title": "Is there a better way to search directories for a file or files?"
} | 2101 |
<p>In a controller (PHP, CodeIgniter) I'm adding scripts & css to variables to be used in the view output. My initial coding looked like this:</p>
<pre><code>private function _add_script($path, $where = self::ADD_LAST) {
$html = "<script src='$path'></script>\n";
switch($where) {
case self::ADD_LAST:
array_push($this->_data['script'], $html);
break;
case self::ADD_FIRST:
array_unshift($this->_data['script'], $html);
break;
}
}
private function _add_css($path, self::ADD_LAST) {
$html = " <link rel='stylesheet' href='$path'>\n";
switch($where) {
case self::ADD_LAST:
array_push($this->_data['css'], $html);
break;
case self::ADD_FIRST:
array_unshift($this->_data['css'], $html);
break;
}
}
</code></pre>
<p>Well, I noticed that these two are basically just repeating themselves, so I immediately rewrote them into this format:</p>
<pre><code>private function _add_script($path, $where = self::ADD_LAST) {
$html = "<script src='$path'></script>\n";
$this->_add_external('script', $html, $where);
}
private function _add_css($path, $where = self::ADD_LAST) {
$html = "<link rel='stylesheet' href='$path'>\n";
$this->_add_external('css', $html, $where);
}
private function _add_external($type, $html, $where) {
switch($where) {
case self::ADD_LAST:
array_push($this->_data[$type], $html);
break;
case self::ADD_FIRST:
array_unshift($this->_data[$type], $html);
break;
}
}
</code></pre>
<p>Does the second version seem like the way to go? Or perhaps a 3rd alternative. The requirements call for being able to add elements to the list either before or after all other elements already in the list.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-27T00:39:36.580",
"Id": "3449",
"Score": "0",
"body": "Your rewrite would be good if you were adding many different tags. I.E. more than just the two (script and link)"
}
] | [
{
"body": "<p>I think what you did was a good thing. I also think you could combine the first 2 functions as well. </p>\n\n<p>Something like this: </p>\n\n<pre><code>private function _add_item($path, $type, $where = self::ADD_LAST) {\n $script = \"<script src='$path'></script>\\n\";\n $css = \"<link rel='stylesheet' href='$path'>\\n\";\n\n if ($type == 'script') {\n $html = $script; \n }\n elseif ($type == 'css') {\n $html = $css;\n }\n\n $this->_add_external($type, $html, $where);\n}\n</code></pre>\n\n<p>Or this: </p>\n\n<pre><code>private function _add_item($path, $type, $where = self::ADD_LAST) {\n $script = \"<script src='$path'></script>\\n\";\n $css = \"<link rel='stylesheet' href='$path'>\\n\";\n\n switch($type) {\n case 'script':\n $html = $script; \n break;\n case 'type':\n $html = $css;\n break;\n }\n\n $this->_add_external($type, $html, $where);\n}\n</code></pre>\n\n<p>Or this (My favorite): </p>\n\n<pre><code>private function _add_item($path, $type, $where = self::ADD_LAST) {\n $array['script'] = \"<script src='$path'></script>\\n\";\n $array['css'] = \"<link rel='stylesheet' href='$path'>\\n\";\n\n $html = $array[$type]; \n\n $this->_add_external($type, $html, $where);\n}\n</code></pre>\n\n<p><strong>EDIT:</strong> </p>\n\n<p>And I think this would work too, an all in one solution: </p>\n\n<pre><code>private function _add_item_external($path, $type, $where = self::ADD_LAST) {\n $array['script'] = \"<script src='$path'></script>\\n\";\n $array['css'] = \"<link rel='stylesheet' href='$path'>\\n\";\n\n switch($where) {\n case self::ADD_LAST:\n array_push($this->_data[$type], $array[$type]);\n break;\n case self::ADD_FIRST:\n array_unshift($this->_data[$type], $array[$type]);\n break;\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-27T03:24:18.307",
"Id": "3453",
"Score": "0",
"body": "I don't think you can go \"too far\", can you? So long as what you do saves space and time, I say it is a good thing. It may make your code look sloppy, but just have two versions: one to look at and one for actually running?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-27T19:18:53.933",
"Id": "3470",
"Score": "0",
"body": "@Mr_CryptoPrime That is just begging for insidious bugs to sneak through the discrepancies between the two versions of the code."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-26T15:54:58.143",
"Id": "2113",
"ParentId": "2112",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-26T14:58:45.077",
"Id": "2112",
"Score": "1",
"Tags": [
"php"
],
"Title": "Have I gone too far in factoring out repeated code in this example?"
} | 2112 |
<p>I'm currently using an Open Source FTP library in all my projects as I've never managed to code a decent <strong>FTP Helper Library</strong> based on the C# 4.0 API.</p>
<p>What do you think about this approach? I'm not quite versed in TDD but ideally I'd like to make this class as testable as possible.</p>
<pre><code>public void DownloadFile(string host, string file, string user, string pass, string path)
{
if (!String.IsNullOrWhiteSpace(host) && !String.IsNullOrWhiteSpace(file))
{
Uri addr = new Uri(host + file);
using (WebClient client = new WebClient())
{
if (!String.IsNullOrWhiteSpace(user) && !String.IsNullOrWhiteSpace(pass))
{
client.Credentials = new NetworkCredential(user, pass);
}
if (!String.IsNullOrWhiteSpace(path))
{
client.DownloadFile(addr, path);
}
}
}
}
</code></pre>
| [] | [
{
"body": "<p>Unit testing means that automated tests can run in isolation from any dependencies (such as other classes, but also the environment).</p>\n\n<p>The DownloadFile method has a hard-coded dependency on WebClient and thus on the environment. It can't be used without using the network and (presumably) a remote service. Even if you decide to hit localhost, you'll need to set up an FTP server on your own machine, and that counts as an external dependency as well. Thus the method can't be unit tested as is.</p>\n\n<p>One possible remedy is to hide WebClient behind an appropriate interface (you could call it IWebClient) and inject that into the class holding the DownloadFile method.</p>\n\n<p>In general, however, such methods are better left as <a href=\"http://xunitpatterns.com/Humble%20Object.html\">Humble Objects</a> and perhaps subjected to integration tests.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-27T03:14:35.790",
"Id": "3452",
"Score": "2",
"body": "I agree on all but the idea of IWebClient. If I was going to use dependency injection for testing, I personally would prefer to use a RealProxy based mocking system rather than create an interface & wrapper class (since WebClient already inherits from MarshalByrefObject)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-26T20:18:35.997",
"Id": "2119",
"ParentId": "2114",
"Score": "5"
}
},
{
"body": "<p>1) Your method has no way to tell whether it has downloaded a file or not. You validate input parameters but do not throw exceptions if they are empty which is wrong. Otherwise you simply postpone receiving errors. </p>\n\n<p>2) <code>new Uri(host + file);</code> I don't think concatenation is correct operation for <code>Uri</code> parts, I would look for something like <code>Path.Combine</code> for this purpose. As far as I got <code>Uri(Uri baseUri, string relativeUri)</code> constructor will do the job. </p>\n\n<p>3) If <code>user</code> and <code>pass</code> parameters are optional (you're checking them to be not null) then define them as optional. It will be more clear for users who will use such method that they can omit <code>user</code> and <code>pass</code> parameters if they see that it is optional. Otherwise they will have to guess whether they can pass <code>null</code> or not. </p>\n\n<p>4) There is no point validating <code>path</code> <strong>at the end</strong> of the method. Anyway the method will not do anything if <code>path</code> is empty. Validate it at the beginning together with <code>host</code> and <code>file</code>. </p>\n\n<p>5) I think you should rename your parameters. You have <code>path</code> together with <code>file</code> and it is not that easy to guess which one is local path and which is ftp path. Having <code>path</code> at the end makes it a little bit easier to guess, but still not enough. Name them <code>remotePath</code> or <code>ftpPath</code> and <code>localPath</code> correspondingly. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-26T21:17:43.723",
"Id": "2122",
"ParentId": "2114",
"Score": "3"
}
},
{
"body": "<p>Here's how I would do it, with comments!</p>\n\n<pre><code>public void DownloadFile(string host, string file, string user, string pass, string path)\n{\n // Inverted if-statement to reduce nesting\n if (String.IsNullOrWhiteSpace(host) \n throw new ArgumentNullException(\"host\");\n\n if(String.IsNullOrWhiteSpace(file))\n throw new ArgumentNullException(\"file\");\n\n //Moved path check to forefront because nothing would happen if it's empty\n if(String.IsNullOrWhiteSpace(path)) \n throw new ArgumentNullException(\"path\");\n\n // Changed to UriBuilder. This will handle cases like trailing slashes and whatnot\n UriBuilder address = new UriBuilder();\n address.Host = host;\n address.Path = file;\n\n using (WebClient client = new WebClient())\n {\n if (!String.IsNullOrWhiteSpace(user) && !String.IsNullOrWhiteSpace(pass))\n {\n client.Credentials = new NetworkCredential(user, pass);\n }\n\n // Changed to a try catch so that we can handle the error with a better message\n // If you'd rather have this bubble up, that's fine\n try \n {\n client.DownloadFile(address.Uri, path);\n }\n catch (Exception e)\n {\n throw new InvalidOperationException(\n \"Error downloading file from: \" + address.Uri.ToString(), \n e)\n }\n }\n}\n</code></pre>\n\n<p>I would also change the variable names as Snowbear HIM-compiler said.</p>\n\n<p>I like to keep guard conditions at the top where the cheapest is first. Also, providing exceptions makes it easier for the caller to know why something failed. If you want to switch it to a boolean success/fail, that could work as well, but doesn't provide as much information.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-27T01:51:50.423",
"Id": "2124",
"ParentId": "2114",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "2124",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-26T19:31:02.883",
"Id": "2114",
"Score": "10",
"Tags": [
"c#",
"unit-testing"
],
"Title": "FTP Download Helper Method"
} | 2114 |
<p>I am a newbie to Python and have started object-oriented programming recently. I have implemented a "Rock Paper Scissors" application in OOP. I would like for you to evaluate my code, and tell me where can I improve my code and how I can better organize the functionality.</p>
<pre><code>import random
class RockPaperScissors(object):
def setUserOption(self,val):
self.__option = val
def getValueFromList(self,option):
l = ['rock','scissors','paper']
return l[option]
def __getRandomValue(self,max):
val = random.randint(1,max)
return self.getValueFromList(val-1)
def __getResult(self,t):
self.__d = {('rock','scissors'):'rock breaks scissors - User has won',('rock','paper'):'rock is captured by paper - User has won',('scissors','paper'):'Scissors cut paper - User has won',
('scissors','rock'):'rock breaks scissors - Computer won',('paper','rock'):'rock is captured by paper - Computer won',('paper','scissors'):'Scissors cut paper - Computer won'}
return self.__d[t]
def __computeResult(self,computerOption):
if computerOption == self.__option:
return 'The user and computer choose the same option'
else:
return self.__getResult((self.__option,computerOption))
def printResult(self):
computerOption = self.__getRandomValue(3)
print 'User choice: ',self.__option
print 'Computer choice: ',computerOption
print self.__computeResult(computerOption)
if __name__ == "__main__":
print 'Welcome to rock paper scissors'
print '1. Rock, 2. Paper, 3. Scissor'
val = int(raw_input('Enter your choice Number: '))
if val >=1 and val <= 3:
obj = RockPaperScissors()
obj.setUserOption(obj.getValueFromList(val-1))
obj.printResult()
else:
raise ValueError('You are supposed to enter the choice given in the menu')
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-26T19:53:17.463",
"Id": "3441",
"Score": "0",
"body": "In the future please avoid cross-posting. The moderators will migrate the post to the new site. It helps keep noise across the SE sites down."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-26T20:00:26.400",
"Id": "3442",
"Score": "0",
"body": "@Michael: I was unaware of it, I will not repeat it again. Thank you"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-02T18:00:52.320",
"Id": "3545",
"Score": "0",
"body": "Seems a bit harsh to throw an error when they enter a value not 1,2,3. Perhaps just ask them nicely again to enter a value {1,2,3}?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-07-08T12:04:45.987",
"Id": "175714",
"Score": "0",
"body": "Ohh I thought question is more interesting(something different) from title..but anyways"
}
] | [
{
"body": "<p>All in all, you're looking good!</p>\n\n<p>Here are a few things that stand out to me:</p>\n\n<ul>\n<li>You're using double-underscore name\nmangling, when you probably don't\nneed to. It's not the best habit to\nget into. Single-underscore says \"I\nam private\" without doing the\nhorrendous name obfuscation. Consider\nrenaming your <code>__method()</code> to\n<code>_method()</code>.</li>\n<li>Inside of <code>__getResult()</code> you're\ndefining <code>__d</code>. That means every time\nthat method is called, that\ndictionary is recreated. This\nprobably isn't what you want. \nConsider moving it to a class\nattribute</li>\n<li>Your method (and some variable) names are <code>mixedCase</code>,\nwhich breaks Python convention in\naccordance with the <a href=\"http://www.python.org/dev/peps/pep-0008/\">Python Style\nGuide</a> (aka PEP 8). Consider\nchanging them to\n<code>lower_case_with_underscores</code>.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-26T20:00:23.867",
"Id": "2117",
"ParentId": "2116",
"Score": "8"
}
},
{
"body": "<p>I agree with jathanism - it does look pretty good. It's well organized and doesn't do too much.</p>\n\n<p>You throw an error if an invalid option is selected. Have you considered looping until a correct value is selected?</p>\n\n<pre><code>val = 0\nwhile val < 1 and val > 3\n val = int(raw_input('Enter your choice Number: '))\n</code></pre>\n\n<p>Also, you shift the value down to compensate for the 0 relative array. I'd reccomend changing the array to be artificially 1-relative:</p>\n\n<pre><code>l = ['dummy', 'rock', 'paper', 'scissors']\n</code></pre>\n\n<p>Alternatively you could do the shifting inside <code>getValueFromList</code>. Don't make the caller do it though - they shouldn't have to worry about things like that. Also, you should do some bounds checking - what happens when someone calls <code>getValueFromList(5)</code>? That might be a valid place to throw a <code>ValueError</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-26T20:12:47.470",
"Id": "2118",
"ParentId": "2116",
"Score": "5"
}
},
{
"body": "<p>Along with @jathanism's comments, I would add the following:</p>\n\n<p>I would move the definition of the list of options into a class variable, e.g.: </p>\n\n<pre><code>class RockPaperScissors(object):\n OPTIONS=['rock','paper','scissors']\n ...\n</code></pre>\n\n<p>that way, when you want to extend the game to RockPaperScissorsLizardSpock, you can do so with a simple inheiritance:</p>\n\n<pre><code>class RockPaperScissorsLizardSpock(RockPaperScissors):\n OPTIONS=['rock','paper','scissors','lizard','spock']\n ...\n</code></pre>\n\n<p>The obvious extension/continuation to this comment is that <code>__getResult</code> would then need to be updated to be more generic in a base class.</p>\n\n<p>Also, the logic for printing/making a selection could then be based on the \"OPTIONS\" constant. (e.g.: <code>print ', '.join( '%s. %s' % (i,v) for i in enumerate(RockPaperScissors.OPTIONS) )</code>). Even better, put the selection logic into a method on the class.</p>\n\n<p>I try to apply these kinds of concepts to most classes, as 1) it isn't really any more work to implement, and 2) it allows for subclasses to easily override the behavior of a base class, even when you don't expect inheritance to be used.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-26T20:29:45.407",
"Id": "2120",
"ParentId": "2116",
"Score": "5"
}
},
{
"body": "<p>It would be more pythonic to use properties (or public fields if you don't need any special getter/setter logic) instead of getter/setter methods.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-26T20:53:03.333",
"Id": "2121",
"ParentId": "2116",
"Score": "1"
}
},
{
"body": "<p>Your random function:</p>\n\n<pre><code>def __getRandomValue(self,max):\n val = random.randint(1,max)\n return self.getValueFromList(val-1)\n</code></pre>\n\n<ol>\n<li>You only ever call this function with max = 3, since thats the only sensible argument just assume that and don't make the caller pass it</li>\n<li>You pick a random value between 1 and max, and then subtract one. Better to pick a value between 0 and max-1 (random.randrange make that easy)</li>\n<li>If you make the l list a class attribute, as Chris suggests, then you can use random.choice to select the option.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-27T12:35:16.183",
"Id": "2127",
"ParentId": "2116",
"Score": "4"
}
},
{
"body": "<p>These answers are fantastic, but seem to be focusing on one side of your question. I'm going to focus on object orientation.</p>\n\n<p>I reviewed your code with a couple basic concepts in mind, namely polymorphism and encapsulation.</p>\n\n<h3>Polymorphism</h3>\n\n<p>Where are your objects? A rock, paper, and scissors could all be objects, could they not? And, most importantly, they are all the same kind of object. They are all \"pieces\" of the game.</p>\n\n<p>Here's a pseudo-example:</p>\n\n<pre><code>class Rock inherits from Element\n type = 'rock'\n def compare(Element)\n if type == 'paper'\n return 'LOSE'\n elsif type == 'scissors'\n return 'WIN'\n else\n return 'TIE'\n</code></pre>\n\n<p>Although this is a potential solution, my example is going to go in a different direction simply for the fact that if you wanted to add more elements then you'd have to touch the existing code (re: Chris' example of RPSLS).</p>\n\n<h3>Encapsulation</h3>\n\n<p>A great programming muscle to exercise is encapsulation. The two main areas, in this example, are to hide the user interface from the game code. </p>\n\n<p>The user interface shouldn't care about the inner-workings of the game. The game shouldn't care how it's displayed. What if you wanted to change the interface to something more graphical? Right now, your code relies on the console to know about the pieces of the game and how it works.</p>\n\n<h3>Example</h3>\n\n<p>So, let's return to Chris' example again. The elements of this game are something that may change quite often. How can you handle this to make future programming easier?</p>\n\n<p>One solution is to store the \"data\" of the game elsewhere and dynamically create objects.</p>\n\n<p>The following is Python code to materialize the ideas I've written about here.</p>\n\n<p>Here's code for an abstracted piece of the game, an element:</p>\n\n<pre><code># The goal for an element is to just know when it wins, when it loses, and how to figure that out.\nclass Element:\n _name = \"\"\n _wins = {}\n _loses = {}\n\n def get_name(self):\n return self._name\n\n def add_win(self, losingElementName, action):\n self._wins[losingElementName] = action\n\n def add_loss(self, winningElementName, action):\n self._loses[winningElementName] = action\n\n def compare(self, element):\n if element.get_name() in self._wins.keys():\n return self._name + \" \" + self._wins[element.get_name()] + \" \" + element.get_name()\n elif element.get_name() in self._loses.keys():\n return None\n else:\n return \"Tie\"\n\n def __init__(self, name):\n self._name = name\n self._wins = {}\n self._loses = {}\n</code></pre>\n\n<p>Games have players:</p>\n\n<pre><code># The player's only responsibility is to make a selection from a given set. Whether it be computer or human.\nclass Player:\n _type = ''\n _selection = ''\n\n def make_selection(self, arrayOfOptions):\n index = -1\n if (self._type == 'Computer'):\n index = random.randint(0, len(arrayOfOptions) - 1)\n else:\n index = int(raw_input('Enter the number of your selection: ')) - 1\n self._selection = arrayOfOptions[index]\n return self._type + ' selected ' + self._selection + '.'\n\n def get_selection(self):\n return self._selection\n\n def __init__(self, playerType):\n self._type = playerType\n self._selection = ''\n</code></pre>\n\n<p>Game code:</p>\n\n<pre><code># A game should have players, game pieces, and know what to do with them.\nclass PlayGame:\n _player1 = Player('Human')\n _player2 = Player('Computer')\n\n _elements = {}\n\n def print_result(self, element1, element2):\n val = element1.compare(element2)\n if (val != None):\n print \"YOU WIN! (\" + val + \")\" # win or tie\n else:\n print \"You lose. (\" + element2.compare(element1) + \")\"\n\n\n def fire_when_ready(self):\n counter = 1\n for e in self._elements.keys():\n print str(counter) + \". \" + e\n counter = counter + 1\n print \"\"\n print \"Shoot!\"\n print \"\"\n\n print self._player1.make_selection(self._elements.keys())\n print self._player2.make_selection(self._elements.keys())\n\n element1 = self._elements[self._player1.get_selection()]\n element2 = self._elements[self._player2.get_selection()]\n\n self.print_result(element1, element2)\n\n\n def load_element(self, elementName1, action, elementName2):\n winningElementObject = None\n newElementObject = None\n\n if (elementName1 in self._elements):\n winningElementObject = self._elements[elementName1]\n winningElementObject.add_win(elementName2, action)\n else:\n newElementObject = Element(elementName1)\n newElementObject.add_win(elementName2, action)\n self._elements[elementName1] = newElementObject\n\n if (elementName2 in self._elements):\n losingElementObject = self._elements[elementName2]\n losingElementObject.add_loss(elementName1, action)\n else:\n newElementObject = Element(elementName2)\n newElementObject.add_loss(elementName1, action)\n self._elements[elementName2] = newElementObject\n\n\n def __init__(self, filepath):\n # get elements from data storage\n f = open(filepath)\n for line in f:\n data = line.split(' ')\n self.load_element(data[0], data[1], data[2].replace('\\n', ''))\n</code></pre>\n\n<p>The console code, the user interface:</p>\n\n<pre><code>if __name__ == \"__main__\":\n print \"Welcome\"\n game = PlayGame('data.txt')\n print \"\"\n print \"Get ready!\"\n print \"\"\n game.fire_when_ready()\n</code></pre>\n\n<p>And the data file, data.txt:</p>\n\n<pre><code>scissors cut paper\npaper covers rock\nrock crushes lizard\nlizard poisons spock\nspock smashes scissors\nscissors decapitates lizard\nlizard eats paper\npaper disproves spock\nspock vaporizes rock\nrock crushes scissors\n</code></pre>\n\n<p>The goal for my answer was to show you how you can use some object oriented concepts in solving your problem. In doing so I also left some unresolved problems. One big one is that the player and game objects are still coupled to the user interface. One way to nicely resolve this would be through the use of delegates.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-28T04:26:57.443",
"Id": "2139",
"ParentId": "2116",
"Score": "12"
}
},
{
"body": "<p>Congratulations. You've all managed to write Java in Python.</p>\n\n<p>Try something like:</p>\n\n<pre><code>from random import choice\nif __name__ == \"__main__\":\n while True:\n print \"1. Rock 2. Paper 3. Scissors\"\n val, comp = int(raw_input('Enter your choice Number: ')), choice(range(1,4))\n if val == comp:\n print \"Draw. Try again\"\n elif val == 1:\n if comp == 2:\n print \"You lose\"\n if comp == 3:\n print \"#WINNING\"\n elif val == 2:\n if comp == 3:\n print \"You lose\"\n if comp == 1:\n print \"#WINNING\"\n elif val == 3:\n if comp == 2:\n print \"You lose\"\n if comp == 1:\n print \"#WINNING\"\n</code></pre>\n\n<p>This, even with the ridiculously long if/else statement is better than everything proposed here.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-29T07:18:30.300",
"Id": "8416",
"ParentId": "2116",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "2139",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-26T19:34:37.407",
"Id": "2116",
"Score": "11",
"Tags": [
"python",
"beginner",
"object-oriented",
"game",
"rock-paper-scissors"
],
"Title": "Rock Papers Scissors in Python"
} | 2116 |
<p>This essentially reads a specially-structured file from the scanner and then parses random phrases and prints them:</p>
<pre><code>{
<start>
<greeting> <object>
}
{
<greeting>
hello
bonjour
aloha
}
{
<object>
world
universe
multiverse
}
</code></pre>
<p>Possible random phrases could be: "hello world", "bonjour universe", etc...</p>
<p>Does anyone have some ideas as to how I might decrease the runtime? I heard you could run your code in parallel using multiple threads but was both unsure exactly how to do this and whether it would help at all? The slightest increase in runtime would be beneficial (having a little competition to see who can do it the fastest).</p>
<p>It is not considered cheating so long as I do the majority of the programming, so please just point me in the right direction and provide suggestions.</p>
<pre><code>package comprehensive;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;
import java.util.Scanner;
/**
* Generates random phrases by reading the specified grammar file
* and outputting the number of phrases specified by the user.
* @author Jun Tang and John Newsome
*
*/
public class RandomPhraseGenerator {
public static HashMap<String,ArrayList<String>> map;
public static void main(String[] args) throws FileNotFoundException{
Scanner k = new Scanner(new File(args[0]));
int numPhrases = Integer.parseInt(args[1]);
addKeys(k);
while(numPhrases > 0){
parseStrings();
numPhrases--;
}
}
/**
* Assimilates all of the keys and their associated values into map (a public static hashmap).
* @param scan The scanner that is reading from the specified file.
*/
public static void addKeys(Scanner scan){
map = new HashMap<String, ArrayList<String>>();
while(scan.hasNextLine()){
if(scan.nextLine().equals("{")){
String key = scan.nextLine();
map.put(key, new ArrayList<String>());
String next = scan.nextLine();
while(!next.equals("}")){
map.get(key).add(next);
next = scan.nextLine();
}
}
}
}
/**
* Parses random String phrases from map and prints them.
* Must already have assimilated keys and values prior by using the addKeys() method.
*/
public static void parseStrings(){
Random random = new Random();
StringBuilder strBuf = new StringBuilder((map.get("<start>").get(0)));
int firstInstance = strBuf.indexOf("<", 0);
int secondInstance = strBuf.indexOf(">", firstInstance);
while(firstInstance >= 0 && secondInstance >= 0){
String nonTerminal = strBuf.substring(firstInstance, secondInstance+1);
strBuf.replace(firstInstance, secondInstance+1, (map.get(nonTerminal).get(random.nextInt(map.get(nonTerminal).size()))));
firstInstance = strBuf.indexOf("<", firstInstance);
secondInstance = strBuf.indexOf(">", firstInstance);
}
System.out.println(strBuf);
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-27T04:29:40.683",
"Id": "3454",
"Score": "0",
"body": "If you ask performance questions, you should mention a) what machine you're running on, b) how fast it is now and how fast it has to be. c) What is the sample size? Solutions which are fast with 1000 elements might perform poorly with 1000000 elements. d) Then you have to do some measurements with a profiler, which tells you, where the most amount of time is spent."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-27T04:52:29.663",
"Id": "3455",
"Score": "0",
"body": "Yes, unfortunately my teacher did not disclose the sample size or the grammar file that is to be run...Thanks for trying to help though, appreciate it! :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-27T07:13:06.087",
"Id": "3456",
"Score": "0",
"body": "Your sample file doesn't correspond with the what the program is parsing. The program is obviously looking for curly brackets, which are missing."
}
] | [
{
"body": "<p>I'm no expert in performance optimization or even threads, so my code review will mostly be some style suggestions, but I do have suggestions how I would implement the the phrase building to be faster - purely from my gut :-)</p>\n\n<ul>\n<li><p>A nitpick at the beginning: You should try and clean up your indentations. They are all over the place and make reading the code a bit more difficult</p></li>\n<li><p>You should declare variables to use interfaces where appropriate instead of concrete class. That makes the code more flexible for example in case you get the keys for a different source. In your case declare your map as <code>Map<String,List<String>></code>.</p></li>\n<li><p>Avoid global variables. If would be better to have <code>addKeys</code> return the map (and thus be renamed <code>readKeys</code>) and pass it on to <code>parseString</code> as an argument.</p></li>\n<li><p>In the <code>main</code> function a <code>for</code> loop is probably more appropriate instead of the <code>while</code>.</p></li>\n<li><p>Try to get rid of the duplicate <code>scan.nextLine();</code> in the inner <code>while</code> loop, by moving the exiting condition inside the loop.</p></li>\n</ul>\n\n<p>Now to optimizing the phrase building. There are two main points I would consider here:</p>\n\n<ul>\n<li><p>Avoid copying data. Currently you convert your string with the placeholders into a StringBuilder and insert the text in place of the placeholder. Both creating the StringBuilder and inserting into them requires allot of data copying internally. </p></li>\n<li><p>Don't repeat the parsing of the placeholder text. Instead I would parse the text once into a data structure and then generate the random phrases using that structure.</p></li>\n</ul>\n\n<p>I could write some (pseudo) code to demonstrate, what I mean, but you should be writing it yourself, so I'll wait and see, if you can come up with an implementation based on those two points.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-27T20:20:40.187",
"Id": "3471",
"Score": "0",
"body": "Thanks, that is very helpful! Turns out the competition was actually yesterday, but I will post my updated code and possibly another updated version later."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-27T08:16:37.160",
"Id": "2125",
"ParentId": "2123",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "2125",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-27T00:21:20.530",
"Id": "2123",
"Score": "4",
"Tags": [
"java",
"optimization",
"parsing",
"random",
"file"
],
"Title": "Parsing random phrases from a file"
} | 2123 |
<p>From <a href="http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-18.html" rel="nofollow">SICP</a>:</p>
<blockquote>
<p><strong>Exercise 2.82</strong></p>
<p>Show how to generalize
apply-generic to handle coercion in
the general case of multiple
arguments. One strategy is to attempt
to coerce all the arguments to the
type of the first argument, then to
the type of the second argument, and
so on. Give an example of a situation
where this strategy (and likewise the
two-argument version given above) is
not sufficiently general. (Hint:
Consider the case where there are some
suitable mixed-type operations present
in the table that will not be tried.)</p>
</blockquote>
<p>I wrote this part before:</p>
<pre><code>(define fn-registry '())
(define (get op param-types)
(define (rec entry . rest)
(define (all-equal a b)
(if (symbol? a)
(eq? a b)
(and (= (length a) (length b))
(let loop ((x a) (y b))
(or (null? x)
(and (eq? (car x) (car y))
(loop (cdr x) (cdr y))))))))
(let ((op-entry (car entry))
(param-types-entry (cadr entry))
(function-entry (caddr entry)))
(if (and (eq? op-entry op)
(all-equal param-types-entry param-types))
function-entry
(if (null? rest)
false
(apply rec rest)))))
(apply rec fn-registry))
(define (put op param-types fn)
(set! fn-registry (cons (list op param-types fn) fn-registry)))
</code></pre>
<p>I wrote this coercion-registry code for this exercise:</p>
<pre><code>(define coercion-registry '())
(define (put-coercion t1 t2 fn) (set! coercion-registry (cons (list t1 t2 fn) coercion-registry)))
(define (get-coercion t1 t2)
(define (rec entry . reg)
(define t1-entry car)
(define t2-entry cadr)
(define fn-entry caddr)
(cond ((and (eq? t1 (t1-entry entry))
(eq? t2 (t2-entry entry))) (fn-entry entry))
((null? reg) false)
(else (apply rec reg))))
(apply rec coercion-registry))
</code></pre>
<p>This function takes any set of arguments and coerces them to be the same type:</p>
<pre><code>(define (make-set . args)
(define (rec tested current remains)
(define (coerce-all to-type result items)
(if (null? items)
result
(let ((t1->t2 (get-coercion (type-tag (car items)) to-type)))
(cond ((eq? (type-tag (car items)) to-type)
(coerce-all to-type (cons (car items) result) (cdr items)))
((not t1->t2) false)
(else
(coerce-all to-type (append result (list (t1->t2 (car items)))) (cdr items)))))))
(let ((coerced-all (coerce-all (type-tag current)
'()
(append tested (cons current remains)))))
(cond (coerced-all coerced-all)
((null? remains) false)
(else (rec (append tested (list current)) (car remains) (cdr remains))))))
(rec '() (car args) (cdr args)))
</code></pre>
<p>I made some changes to apply-generic as well:</p>
<pre><code>(define (apply-generic op . args)
(let ((type-tags (map type-tag args)))
(let ((proc (get op type-tags)))
(if proc
(apply proc (map contents args))
(let ((coerced-args (apply make-set args)))
(if coerced-args
(apply apply-generic (cons op coerced-args))
(error "No method found for these types" (list op type-tags))))))))
</code></pre>
<p>This came from a previous activity:</p>
<pre><code>(define (square x) (* x x))
(define (attach-tag type-tag contents)
(if (or (symbol? contents) (number? contents))
contents
(cons type-tag contents)))
(define (type-tag datum)
(cond ((pair? datum) (car datum))
((number? datum) 'scheme-number)
((symbol? datum) 'scheme-symbol)
(else (error "Bad tagged datum -- TYPE-TAG" datum))))
(define (contents datum)
(cond ((pair? datum) (cdr datum))
((or (number? datum)
(symbol? datum)) datum)
(else (error "Bad tagged datum -- CONTENTS" datum))))
(define (add x y) (apply-generic 'add x y))
(define (sub x y) (apply-generic 'sub x y))
(define (mul x y) (apply-generic 'mul x y))
(define (div x y) (apply-generic 'div x y))
(define (equ? x y) (apply-generic 'equ? x y))
(define (=zero? x) (apply-generic '=zero? x))
(define (install-scheme-number-package)
(define (tag x)
(attach-tag 'scheme-number x))
(put 'add '(scheme-number scheme-number)
(lambda (x y) (tag (+ x y))))
(put 'sub '(scheme-number scheme-number)
(lambda (x y) (tag (- x y))))
(put 'mul '(scheme-number scheme-number)
(lambda (x y) (tag (* x y))))
(put 'div '(scheme-number scheme-number)
(lambda (x y) (tag (/ x y))))
(put 'make 'scheme-number
(lambda (x) (tag x)))
(put 'equ? '(scheme-number scheme-number) =)
(put '=zero? '(scheme-number) zero?)
'done)
(define (make-scheme-number n)
((get 'make 'scheme-number) n))
(define (install-rational-package)
;; internal procedures
(define (numer x) (car x))
(define (denom x) (cdr x))
(define (make-rat n d)
(let ((g (gcd n d)))
(cons (/ n g) (/ d g))))
(define (add-rat x y)
(make-rat (+ (* (numer x) (denom y))
(* (numer y) (denom x)))
(* (denom x) (denom y))))
</code></pre>
<p>I added just this one function as part of what I needed in order to test apply-generic: </p>
<pre><code>(put 'add-em '(rational rational rational rational) (lambda (a b c d) (add-rat a (add-rat b (add-rat c d)))))
</code></pre>
<p>More code from a previous activity:</p>
<pre><code> (define (sub-rat x y)
(make-rat (- (* (numer x) (denom y))
(* (numer y) (denom x)))
(* (denom x) (denom y))))
(define (mul-rat x y)
(make-rat (* (numer x) (numer y))
(* (denom x) (denom y))))
(define (div-rat x y)
(make-rat (* (numer x) (denom y))
(* (denom x) (numer y))))
(define (equ?-rat x y)
(and (= (numer x) (numer y))
(= (denom x) (denom y))))
(define (=zero?-rat x) (zero? (numer x)))
;; interface to rest of the system
(define (tag x) (attach-tag 'rational x))
(put 'add '(rational rational)
(lambda (x y) (tag (add-rat x y))))
(put 'sub '(rational rational)
(lambda (x y) (tag (sub-rat x y))))
(put 'mul '(rational rational)
(lambda (x y) (tag (mul-rat x y))))
(put 'div '(rational rational)
(lambda (x y) (tag (div-rat x y))))
(put 'equ? '(rational rational) equ?-rat)
(put '=zero? '(rational) =zero?-rat)
(put 'make 'rational
(lambda (n d) (tag (make-rat n d))))
'done)
(define (make-rational n d)
((get 'make 'rational) n d))
(define (real-part z) (apply-generic 'real-part z))
(define (imag-part z) (apply-generic 'imag-part z))
(define (magnitude z) (apply-generic 'magnitude z))
(define (angle z) (apply-generic 'angle z))
(define (install-complex-package)
;; imported procedures from rectangular and polar packages
(define (make-from-real-imag x y)
((get 'make-from-real-imag 'rectangular) x y))
(define (make-from-mag-ang r a)
((get 'make-from-mag-ang 'polar) r a))
;; internal procedures
(define (add-complex z1 z2)
(make-from-real-imag (+ (real-part z1) (real-part z2))
(+ (imag-part z1) (imag-part z2))))
(define (sub-complex z1 z2)
(make-from-real-imag (- (real-part z1) (real-part z2))
(- (imag-part z1) (imag-part z2))))
(define (mul-complex z1 z2)
(make-from-mag-ang (* (magnitude z1) (magnitude z2))
(+ (angle z1) (angle z2))))
(define (div-complex z1 z2)
(make-from-mag-ang (/ (magnitude z1) (magnitude z2))
(- (angle z1) (angle z2))))
(define (equ?-complex z1 z2)
(and (= (real-part z1) (real-part z2))
(= (imag-part z1) (imag-part z2))))
(define (=zero?-complex z) (and (zero? (real-part z))
(zero? (imag-part z))))
;; interface to rest of the system
(define (tag z) (attach-tag 'complex z))
(put 'add '(complex complex)
(lambda (z1 z2) (tag (add-complex z1 z2))))
(put 'sub '(complex complex)
(lambda (z1 z2) (tag (sub-complex z1 z2))))
(put 'mul '(complex complex)
(lambda (z1 z2) (tag (mul-complex z1 z2))))
(put 'div '(complex complex)
(lambda (z1 z2) (tag (div-complex z1 z2))))
(put 'make-from-real-imag 'complex
(lambda (x y) (tag (make-from-real-imag x y))))
(put 'make-from-mag-ang 'complex
(lambda (r a) (tag (make-from-mag-ang r a))))
(put 'equ? '(complex complex) equ?-complex)
(put '=zero? '(complex) =zero?-complex)
'done)
(define (install-polar-package)
;; internal procedures
(define (magnitude z) (car z))
(define (angle z) (cdr z))
(define (make-from-mag-ang r a) (cons r a))
(define (real-part z)
(* (magnitude z) (cos (angle z))))
(define (imag-part z)
(* (magnitude z) (sin (angle z))))
(define (make-from-real-imag x y)
(cons (sqrt (+ (square x) (square y)))
(atan y x)))
(define (equ? x y)
(and (= (magnitude x) (magnitude y))
(= (angle x) (angle y))))
(define (=zero? x) (zero? (magnitude x)))
;; interface to the rest of the system
(define (tag x) (attach-tag 'polar x))
(put 'real-part '(polar) real-part)
(put 'imag-part '(polar) imag-part)
(put 'magnitude '(polar) magnitude)
(put 'angle '(polar) angle)
(put 'equ? '(polar polar) equ?)
(put '=zero? '(polar) =zero?)
(put 'make-from-real-imag 'polar
(lambda (x y) (tag (make-from-real-imag x y))))
(put 'make-from-mag-ang 'polar
(lambda (r a) (tag (make-from-mag-ang r a))))
'done)
(define (install-rectangular-package)
;; internal procedures
(define (real-part z) (car z))
(define (imag-part z) (cdr z))
(define (make-from-real-imag x y) (cons x y))
(define (magnitude z)
(sqrt (+ (square (real-part z))
(square (imag-part z)))))
(define (angle z)
(atan (imag-part z) (real-part z)))
(define (make-from-mag-ang r a)
(cons (* r (cos a)) (* r (sin a))))
(define (equ? x y)
(and (= (real-part x) (real-part y))
(= (imag-part x) (imag-part y))))
(define (=zero? x) (and (zero? (real-part x))
(zero? (imag-part x))))
;; interface to the rest of the system
(define (tag x) (attach-tag 'rectangular x))
(put 'real-part '(rectangular) real-part)
(put 'imag-part '(rectangular) imag-part)
(put 'magnitude '(rectangular) magnitude)
(put 'angle '(rectangular) angle)
(put 'equ? '(rectangular rectangular) equ?)
(put '=zero? '(rectangular) =zero?)
(put 'make-from-real-imag 'rectangular
(lambda (x y) (tag (make-from-real-imag x y))))
(put 'make-from-mag-ang 'rectangular
(lambda (r a) (tag (make-from-mag-ang r a))))
'done)
(define (make-complex-from-real-imag x y)
((get 'make-from-real-imag 'complex) x y))
(define (make-complex-from-mag-ang r a)
((get 'make-from-mag-ang 'complex) r a))
(install-rational-package)
(install-scheme-number-package)
(install-complex-package)
(install-polar-package)
(install-rectangular-package)
</code></pre>
<p>Register the coercion:</p>
<pre><code>(put-coercion 'scheme-number 'rational (lambda (a) (make-rational a 1)))
</code></pre>
<p>And finally, the test:</p>
<pre><code>(apply-generic 'add-em (make-rational 3 4) 2 3 4)
</code></pre>
<p>There is more code in here than would be necessary to test only the new functionality. I found it easier to test the new apply-generic by including the code from previous examples. I'm sorry that it may make it a bit harder to follow exactly what I'm asking here, but please do your best to give me feedback.</p>
<p>How can I improve this code?</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-27T12:07:22.740",
"Id": "2126",
"Score": "2",
"Tags": [
"lisp",
"scheme",
"sicp"
],
"Title": "Coercion with multiple arguments"
} | 2126 |
<p>I've been rolling around several ideas or approaches in my head, and none seem any more useful or "right" than another. I'm sure this is extremely objective but I'm looking for a close-to-definitive answer on the object oriented approach to large block string storage and output in PHP. Given the following example, how could I change my approach in a way that might cause Zeev Suraski to pat me on the back and say Mazel Tov (beside using HTML5)?</p>
<pre><code><?php
class OutputConstructor extends ContentRetriever // Or whatever I decide to name it
{
protected $htmlHeadBlock;
public function __construct()
{
$this->setHtmlHeadBlock();
}
protected function setHtmlHeadBlock()
{
ob_start();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title><?php echo $this->pageTitle; ?></title>
<link rel="shortcut icon" href="images/favicon.ico" type="image/x-icon" />
<link rel="icon" href="images/favicon.ico" type="image/x-icon" />
<meta name="description" content="<?php echo $this->pageDescription; ?>" />
<meta name="keywords" content="<?php echo $this->pageKeywords; ?>" />
<link type="text/css" rel="stylesheet" href="css/style.css" />
<script type="text/javascript" src="js/functions.js"></script>
</head>
<?php
$this->htmlHeadBlock = ob_get_clean();
}
public function getHtmlHeadBlock()
{
return $this->htmlHeadBlock;
}
} // End of OutputConstructor
?>
</code></pre>
<p>The general theme I'm going with in this example class is that on construction, html is stored in a variable via output buffer and then returned by a public method. When evaluating this code, consider that the html will not be static. Page title, description, keywords and the such will be subbed out with dynamic property references. My overall question is: In object oriented programming, ideally where should the output be stored? PHP's <code>DOMDocument</code> class, however useful, doesn't really answer this question for me. Also in this instance, is there any best practice trade-off between using an output buffer and heredoc syntax? Thanks in advance for your guidance!</p>
| [] | [
{
"body": "<p>Well, I think the most convenient way is to use templates. Your HTML block with variables is actually a template. You can use some template engine like <a href=\"http://www.twig-project.org\" rel=\"nofollow\">Twig</a> or <a href=\"http://www.smarty.net/\" rel=\"nofollow\">Smarty</a> to build your template from the data you supply or you can use PHP extended syntax to do that like this:</p>\n\n<pre><code><html>\n <body>\n <p<?php if ($highlight): ?> class=\"highlight\"<?php endif;?>>This is a paragraph.</p>\n </body>\n</html>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-27T20:24:21.690",
"Id": "3473",
"Score": "0",
"body": "That's good to know, but doesn't really touch my question. There is a lot of literature on how to apply object oriented principles to PHP, but none that really spends any time on object oriented output management or integration. I want to know where in my general design scheme I should be piecing together and formatting my output, and how I should be setting/storing it before output."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-28T06:58:00.070",
"Id": "3484",
"Score": "0",
"body": "@65Fbef05 I don't really understand you. I think you are mixing templating and MVC. HTML is just an HTML, it is not an object itself, it is data. Template engines are object-oriented mostly. And MVC is today's most popular way of structuring web applications."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-28T09:35:06.220",
"Id": "3488",
"Score": "0",
"body": "FractalizeR, please provide a source to your comment \"MVC is today's most popular\"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-28T10:19:58.757",
"Id": "3489",
"Score": "0",
"body": "@RobertPitt http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller Since it became an architectural pattern, I believe one can say, that it's really popular."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-28T12:05:19.903",
"Id": "3490",
"Score": "0",
"body": "I'm not familiar enough with design patterns to name a common pattern that I'm going for, but it's not model-view-controller abstraction. I do intend to have those processes abstracted, but I think you're missing my point altogether. HTML, XML, JSON, plain text... etc; I just used HTML in my example but its use here is irrelevant. Whatever the actual output is, I'm trying to decide how structure my output in an object designed application."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-27T20:05:38.220",
"Id": "2132",
"ParentId": "2128",
"Score": "0"
}
},
{
"body": "<p>The first problem i can see and many other's is that your hardcoding output data, why would you hard code output data on within a language that was built for dynamic content creation.</p>\n\n<p>I would suggest that you restructure your class to combine several entites into one, for example, when creating a html web page, i usually is constructed of 5 major compoinants, for isntance:</p>\n\n<ul>\n<li>Page\n<ul>\n<li>Head</li>\n<li>Body\n<ul>\n<li>Header</li>\n<li>Main</li>\n<li>Footer</li>\n</ul></li>\n</ul></li>\n</ul>\n\n<p>Taking this into consideration i would like to make my code so it would act in the same way, create 6 or so classes called: HTMLPage, HTMLHead, HTMLBody, HTMLBodyHeader, HTMLBodyMain, HTMLBodyFooter</p>\n\n<p>Now each class should be assigned to it's parent, for example:</p>\n\n<p>The Head and Body belong to the Page, and the Header,Main and Fotter belong to the Body, this taken into consideration you should look at the following structure:</p>\n\n<pre><code>/*\n * Create a Page\n*/\n$Page = new Page(\"DOCTYPE\");\n\n/*\n *Create a Head\n*/\n$Head = new Head();\n$Head->title = \"My Practical Home Page\";\n$Head->addScript(\"http://google.com/example.js\");\n$Head->addStyle(\"http://google.com/example.css\");\n$Head->addMeta('blah','..blah..');\n\n/*\n * Create a Body Object\n*/\n$Body = new Body(\"charset\");\n$Body->layout = new HTMLLayout(\"some_file_to_specifiy_the_layout\");\n$Body->SetContent('LeftBlock.Top','Hello World');\n\n/*\n * Create Footer\n*/\n$Footer = new Footer('default_footer.php');\n\n/*\n * Add all the segments to the main page!\n*/\n$Page->head = $Head;\n$Page->body = $Body;\n$Page->body->header = $Header;\n$Page->body->main = \"....\";\n$Page->body->footer= $Footer;\n\n/*\n * Send the page to the browser!\n*/ \n$Page->Display();\n</code></pre>\n\n<p>I will leave it down to you to figure out the classes</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-28T12:23:22.737",
"Id": "3491",
"Score": "0",
"body": "Great example - This really does give me some ideas for the project I'm working on. If it helps you make sense of my code sample, it (with some clear differences) is intended to be used similarly to the `Head` class in your code."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-28T09:33:11.883",
"Id": "2141",
"ParentId": "2128",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "2141",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-27T16:27:47.673",
"Id": "2128",
"Score": "3",
"Tags": [
"php",
"html",
"object-oriented"
],
"Title": "PHP Output Block Defining and Best Practices"
} | 2128 |
<p>I have the following construction in the program:</p>
<pre><code> while(true) {
<...>
try {
JobManager.markJobCompleted(unitOfWork.getSqlFactory(), jobId, dataOut);
} catch (DbLogicException e) {
logger.error(JobManager.CANNOT_MARK_JOB_COMPLETED + jobId, e);
try {
unitOfWork.rollback();
} catch (DbLogicException e1) {
logger.error(UnitOfWork.CANNOT_ROLLBACK_TRANSACTION, e1);
unitOfWork.closeSilently();
return;
}
continue;
}
<...>
}
</code></pre>
<p>So, the logic is the following:</p>
<ol>
<li>Trying to mark the job completed</li>
<li>If we fail, try to rollback transaction and proceed to next job item</li>
<li>If transaction rollback failed, something is seriously wrong here, aborting everything</li>
</ol>
<p>This construction looks a little clumsy to me. Is there a way to refactor it so it would become... beautiful?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-27T17:33:35.203",
"Id": "3462",
"Score": "2",
"body": "You could move the `continue` statement up into the second `try` clause, right after the `rollback()`. Not much of a change, but maybe you like it better?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-27T19:13:04.473",
"Id": "3467",
"Score": "0",
"body": "@Carl, thanks ;) But the whole thing still looks clumsy to me ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-27T23:30:54.083",
"Id": "3479",
"Score": "2",
"body": "Things can be done, but they are only really helpful if the construction appears repeatedly. Does it? Secondly, if I can't roll a transaction back thats a very serious problem. Serious enough that simply returning seems an inappropriate response."
}
] | [
{
"body": "<p>Yes.</p>\n\n<ol>\n<li>Throw specialized exceptions like <code>CannotMarkJobCompletedException</code> and <code>CannotRollbackTransactionException</code>...</li>\n<li>Make your <code>toString()</code> method on exceptions to return something you want what your logger to log</li>\n<li>Instead of doing: <code>...CAN_..._COMPLETED + jobId</code>, you may do: thrown exception already knows this <code>jobId</code></li>\n<li>Store the thrown exception in a variable and call your logger once</li>\n</ol>\n\n<p>By doing all of that you will solve the problem of having nested <code>try-catch</code> blocks.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-27T19:12:10.247",
"Id": "3466",
"Score": "0",
"body": "Can you please demonstrate how will it solve nested try-catch blocks problem? As I understand, I will still need to catch `CannotMarkJobCompletedException` and try to rollback, if it is caught. And again catch `CannotRollbackTransactionException` and cancel all operations if caught."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-27T19:14:55.220",
"Id": "3468",
"Score": "0",
"body": "Also SLF4J `logger.error()` method does not allow to pass single Throwable to it so I still need to provide some error string and pass an exception after."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-27T19:17:20.490",
"Id": "3469",
"Score": "0",
"body": "Oh ;) wait. Did you mean after making distinctive exception classes I should move all logic into a single try-except block and deal with exceptions there?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-28T09:00:38.667",
"Id": "3487",
"Score": "0",
"body": "The main problem is that you need to rollback if marking completed throws an exception, and you need to close silently if rolling back throws an exception. You must either perform these actions in the catch blocks (nested) or alter the control flow in the try blocks (serial)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-28T16:20:40.090",
"Id": "3499",
"Score": "0",
"body": "@FractalizeR I suggested you to make your code readable and maintainable by making your exceptions distinct and by serializing your catch blocks instead of nesting them."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-28T16:22:03.350",
"Id": "3500",
"Score": "0",
"body": "@FractalizeR what logger accepts is a string and you can do that by passing the thrown exception, it will turn your object into string automatically. Btw, you don't need to use an API just as is, you may craft your own and also utilize the existing one by wrapping it, if the situation allows."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-27T18:10:12.587",
"Id": "2131",
"ParentId": "2129",
"Score": "6"
}
},
{
"body": "<p>How about this:</p>\n\n<pre><code>while(true) {\n <...>\n try {\n JobResult const result = JobManager.markJobCompleted(unitOfWork.getSqlFactory(), jobId, dataOut);\n if (JobResult::Fail == result && unitOfWork.rollback())\n {\n unitOfWork.closeSilently();\n }\n }\n catch (DbLogicException1 e) {\n logger.error(JobManager.CANNOT_MARK_JOB_COMPLETED + jobId, e);\n continue;\n }\n catch (DbLogicException2 e) {\n logger.error(UnitOfWork.CANNOT_ROLLBACK_TRANSACTION, e1);\n return;\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-27T21:03:23.877",
"Id": "3474",
"Score": "0",
"body": "Well, that means abandon some exceptions and move to returning results from method? This is a way, but... well, I wanted to do the same beauty but with exceptions ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-27T21:48:48.967",
"Id": "3477",
"Score": "0",
"body": "You're also going to use exceptions, only realization must be by types DbLogicException1, DbLogicException2 etc... Methods unitOfWork.rollback() will throw exception DbLogicException1 and unitOfWork.closeSilently() will throw exception DbLogicException2 (for example)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-27T21:49:01.523",
"Id": "3478",
"Score": "0",
"body": "So, all methods you want will throw exceptions, but catch them in main cycle"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-27T20:54:44.733",
"Id": "2133",
"ParentId": "2129",
"Score": "1"
}
},
{
"body": "<p>I made a quick refactoring to extract a new method <code>UnitOfWork::rollbackOrCloseSilently()</code>, but I'm not sure it really helps.</p>\n\n<pre><code>public boolean rollbackOrCloseSilently() {\n try {\n rollback();\n return true;\n }\n catch (DbLogicException e) {\n logger.error(CANNOT_ROLLBACK_TRANSACTION, e);\n closeSilently();\n return false;\n }\n}\n</code></pre>\n\n<p>While it merely hides the complexity in another method, it does clean up your original loop a little:</p>\n\n<pre><code>while(true) {\n <...>\n try {\n JobManager.markJobCompleted(unitOfWork.getSqlFactory(), jobId, dataOut);\n } catch (DbLogicException e) {\n logger.error(JobManager.CANNOT_MARK_JOB_COMPLETED + jobId, e);\n if (!unitOfWork.rollbackOrCloseSilently()) {\n return;\n }\n continue;\n }\n <...>\n}\n</code></pre>\n\n<p>The problem is that it now hides the logging inside a method that doesn't seem like it should log, and the method returns a success status which is less desirable to exceptions in my view.</p>\n\n<p>Starting over, another simple improvement would be to extract the full code between pairs of <code><...></code> into a new method of the same class. Again you have three possible exits: continue processing normally if the job is marked completed okay, continue the loop early if it fails to be marked but rolls back, or exit the method entirely if it cannot be rolled back. Here's where specific exceptions as İnanç Gümüş recommended could help:</p>\n\n<pre><code>while (true) {\n <...>\n try {\n markJobCompletedOrRollback(unitOfWork, jobId, dataOut);\n }\n catch (MarkCompletedException e) {\n continue;\n }\n catch (RollbackException e) {\n return;\n }\n <...>\n}\n\n...\n\nprivate markJobCompletedOrRollback(UnitOfWork unitOfWork, ? jobId, ? dataOut) {\n try {\n JobManager.markJobCompleted(unitOfWork.getSqlFactory(), jobId, dataOut);\n }\n catch (DbLogicException e) {\n logger.error(JobManager.CANNOT_MARK_JOB_COMPLETED + jobId, e);\n try {\n unitOfWork.rollback();\n }\n catch (DbLogicException e1) {\n logger.error(UnitOfWork.CANNOT_ROLLBACK_TRANSACTION, e1);\n unitOfWork.closeSilently();\n throw new RollbackException();\n }\n throw new MarkCompletedException();\n }\n}\n</code></pre>\n\n<p>While it doesn't address the nested try-catch blocks, it does move them out of the original loop which may improve that method's readability. At least now this new method does one logical thing: mark the job completed or roll it back.</p>\n\n<p>That your original code <code>return</code>s when a unit of work cannot be rolled back makes me suspect that the method should actually throw an exception in this case.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-28T03:45:59.623",
"Id": "3483",
"Score": "0",
"body": "Having a method with \"CloseSilently\" in the name that returns a bool sounds weird to me. Did it close silently? How would you know if it was silent?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-28T08:54:17.537",
"Id": "3486",
"Score": "0",
"body": "@EndangeredMassa - `rollbackOrCloseSilently()` returns `true` if it rolled back or `false` if it closed silently, but I agree it's not very intuitive. That's why I prefer the second refactoring. :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-28T02:20:44.700",
"Id": "2138",
"ParentId": "2129",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "2131",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-27T16:59:26.090",
"Id": "2129",
"Score": "4",
"Tags": [
"java",
"error-handling",
"database",
"exception"
],
"Title": "Making a job completed, rolling back on error"
} | 2129 |
<p>I finished the Ruby chapter in <a href="http://pragprog.com/titles/btlang/seven-languages-in-seven-weeks" rel="nofollow"><em>Seven Languages in Seven Weeks</em></a>. It tries to make you familiar with the core concepts of several languages rather quickly. Dutifully I did all exercises, but most likely they can be improved to be more Ruby-like. I'll post my code samples one by one, so I can apply things learned in previous questions to later questions.</p>
<p>Day 1</p>
<blockquote>
<p>Write a program that picks a random number. Let a player guess the
number, telling the player whether the guess is too low or too high.</p>
</blockquote>
<pre><code>range = (0..10)
to_guess = range.min + rand(range.max - range.min)
guessed = false
while !guessed
puts "Guess a number, between #{range.min} and #{range.max}"
guess = gets
int = guess.to_i
if int == to_guess
puts 'Correct!'
guessed = true
else
puts int > to_guess ? 'Lower' : 'Higher'
end
end
</code></pre>
<hr>
<p>After sepp2k's comments:</p>
<pre><code>class Range
def size
self.end - self.begin
end
end
range = 0..10
to_guess = range.begin + rand(range.size)
guessed = false
until guessed
puts "Guess a number, between #{range.begin} and #{range.end}"
guess = gets
int = guess.to_i
if int == to_guess
puts 'Correct!'
guessed = true
else
puts int > to_guess ? 'Lower' : 'Higher'
end
end
</code></pre>
| [] | [
{
"body": "<p>A couple of minor things:</p>\n\n<p>First of all the convention in the ruby world is to use 2 spaces for indentation, not 4. It doesn't really matter much, but it's generally easier to use the style conventions that everyone uses unless you have a reason not to.</p>\n\n<pre><code>range = (0..10)\n</code></pre>\n\n<p>You don't actually need the parentheses here. Parentheses are not part of range syntax - the reason you usually see ranges wrapped in parentheses is that you can't call methods on ranges without them (because <code>0..10.foo</code> would be interpreter as <code>0..(10.foo)</code>).</p>\n\n<pre><code>to_guess = range.min + rand(range.max - range.min)\n</code></pre>\n\n<p>You should use <code>begin</code> and <code>end</code> or <code>first</code> and <code>last</code> instead of <code>min</code> and <code>max</code>. In ruby 1.8.7 <code>min</code> and <code>max</code> are inherited from <code>Enumerable</code> and will iterate the entire range in order to find the minimum/maximum, making them <code>O(n)</code>. Only in 1.9 (in 1.9.2 at least) they're overridden to work in <code>O(1)</code> time. <code>begin</code> and <code>end</code> work in <code>O(1)</code> time in all ruby versions.</p>\n\n<p>I would also consider putting this into its own method as it seems like it might come in handy more than once.</p>\n\n<pre><code>while !guessed\n</code></pre>\n\n<p>I would write that as <code>until guessed</code> as that reads a bit nicer to me.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-27T23:13:17.723",
"Id": "2136",
"ParentId": "2134",
"Score": "7"
}
},
{
"body": "<p>One thing I noticed is that you have a throwaway variable, <code>guess</code>, in between <code>gets</code> and <code>int</code>. You can reduce some of that by simply using <code>guess = gets.to_i</code> and <code>if guess == to_guess</code>.</p>\n\n<p>Also, you could use <code>break</code> instead of the <code>guessed</code> variable and <code>while</code>/<code>until</code> condition:</p>\n\n<pre><code>loop do\n # ...\n if guess == to_guess\n puts 'Correct!'\n break\n end\n puts int > to_guess ? 'Lower' : 'Higher'\nend\n</code></pre>\n\n<p>But that is more a matter of preference, as both methods have their merits.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-14T22:04:56.843",
"Id": "2412",
"ParentId": "2134",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "2136",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-27T20:55:54.257",
"Id": "2134",
"Score": "7",
"Tags": [
"ruby",
"game"
],
"Title": "Higher lower game in Ruby"
} | 2134 |
<p>As an exercise, I've implemented a simple reader macro in Common Lisp (using SBCL). It converts Octal (unsigned integers only) into numbers.</p>
<p>Usage:</p>
<pre><code>* #z1234
668
</code></pre>
<p>The code:</p>
<pre><code>(defun oct-string-to-number
(string)
"Converts an octal string to a number. Only digits from 0 - 7 are accepted; sign or decimal point symbols will cause oct-to-number to fail"
(setq place 1)
(setq result 0)
(setq digits '(#\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7))
(loop for char across (reverse string)
do
(setq pos (position char digits))
(setq result (+ result (* pos place)))
(setq place (* 8 place)))
result)
(defun slurp-octal-digits
(stream)
(setq string (make-array 0 :element-type 'character :fill-pointer 0 :adjustable t))
"Slurps all digits from 0 - 7 from a stream into a string, stopping at EOF, no data, or a non-digit character."
(setq digits '(#\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7))
(with-output-to-string (out)
(loop do
(setq char (read-char stream))
(setq isnum nil)
(if char
(progn
(setq isnum (find char digits))
(if isnum
(vector-push-extend char string)
(unread-char char stream))))
while (not (eq nil isnum))))
string)
(defun octal-string-transformer
(stream subchar args)
"Slurps an octal number from stream, and converts it to a number. Number must be an unsigned integer."
(setq oct-string (slurp-octal-digits stream))
(oct-string-to-number oct-string))
;; Sets #z to call octal-string-transformer, so e.g. #z1234 will evaluate to 668. Use #z as SBCL has #o already :-)
(set-dispatch-macro-character
#\# #\z
#'octal-string-transformer)
</code></pre>
<p>I'm quite new to Common Lisp, so I'd greatly appreciate feedback on everything: formatting, style, idiom, correctness :-)</p>
<p><em>Edited to add:</em> Actually, the formatting in the pasted code snippet is rendered oddly; indentation that is present when I edit vanishes when I submit. So maybe be a bit gentle with feedback about the formatting ;-)</p>
| [] | [
{
"body": "<p>First of all a note about variables: You're using <code>setq</code> on previously undefined and undeclared variables. This is actually undefined behavior and in most implementations will create global dynamic/special variables. To create local variables (which you presumably intended) use <code>let</code>.</p>\n\n<pre><code>(defun oct-string-to-number \n (string)\n \"Converts an octal string to a number. Only digits from 0 - 7 are accepted; sign or decimal point symbols will cause oct-to-number to fail\"\n</code></pre>\n\n<p>This whole function can be implemented as <code>(parse-integer string :radix 8)</code>. However for the sake of learning let's go through the function anyway:</p>\n\n<pre><code>(setq digits '(#\\0 #\\1 #\\2 #\\3 #\\4 #\\5 #\\6 #\\7))\n...\n(setq pos (position char digits))\n</code></pre>\n\n<p>Iterating through the list of digits to convert a digit to an integer, is neither the most efficient nor the most succinct to do it. You can use the <code>digit-char-p</code> function which returns the digit's int value, if the given char is a digit and nil otherwise. (The same applies in <code>slurp-octal-digits</code> where you do the same thing).</p>\n\n<pre><code>(loop for char across (reverse string)\n do \n (setq pos (position char digits))\n (setq result (+ result (* pos place)))\n (setq place (* 8 place)))\n</code></pre>\n\n<p>Instead of reversing the string and keeping track of a <code>place</code> variable, you can just iterate over the string from the beginning and multiply the result by 8 each step:</p>\n\n<pre><code>(loop for char across string\n do \n (setq result (+ (* 8 result) (digit-char-p char))))\n</code></pre>\n\n<p>That being said, I'd rather use <code>reduce</code> then <code>loop</code> here (that is, if I weren't using <code>parse-integer</code>) - especially as higher order functions are one of the most useful things in lisp that a newcomer should get acquainted to. Using <code>reduce</code> the function would be written like this:</p>\n\n<pre><code>(defun oct-string-to-number (string)\n \"Converts an octal string to a number. Only digits from 0 - 7 are accepted; sign, non-octal digit or decimal point will signal error.\"\n (reduce\n (lambda (sum digit)\n (+ (* 8 sum) (digit-char-p digit 8)))\n string :initial-value 0))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-28T03:23:49.773",
"Id": "3482",
"Score": "1",
"body": "Thank you for being the anti-`setq`, pro-built-in police in my absence."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-28T07:10:45.653",
"Id": "3485",
"Score": "0",
"body": "@Inaimathi: it's good to know about the built-in functionality, but I did this as a learning exercise; otherwise I'd have just used #o in the first place :-)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-28T00:04:48.067",
"Id": "2137",
"ParentId": "2135",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "2137",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-27T22:44:04.573",
"Id": "2135",
"Score": "2",
"Tags": [
"common-lisp"
],
"Title": "Simple octal reader macro in Common Lisp"
} | 2135 |
<p>In <a href="https://stackoverflow.com/questions/5801586/idiomatic-haskell-for-database-abstraction">this</a> post I asked about what would be idiomatic haskell database abstraction. I had been thinking for it a while, and the first answer was similar to what I had in mind, and I wrote a proof-of-concept of it. Discarding the abomination that is the schema, what would you change, and why?</p>
<p>Database.hs</p>
<pre><code>{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Database (
runDB
, quickQuery
, prepare
, execute
, fetchRowAl
, DB (..)
, module Database.HDBC.SqlValue
) where
import qualified Database.HDBC as H
import Database.HDBC.SqlValue
import Database.HDBC.Sqlite3
import Control.Monad.Reader
newtype DB a = D (ReaderT Connection IO a) deriving (Monad, MonadReader Connection, MonadIO)
runDB :: FilePath -> DB b -> IO b
runDB path (D x) = do
c <- connectSqlite3 path
mkSchema c
r <- runReaderT x c
H.disconnect c
return r
mkSchema conn = do
tables <- H.getTables conn
unless ("Location" `elem` tables) $ do
H.handleSqlError $ H.quickQuery' conn "CREATE TABLE Location (location TEXT PRIMARY KEY)" []
return ()
unless ("Person" `elem` tables) $ do
H.handleSqlError $ H.quickQuery' conn (unwords [
"CREATE TABLE Person"
, "(id INTEGER PRIMARY KEY AUTOINCREMENT,"
, "name TEXT NOT NULL,"
, "age INT NOT NULL,"
, "location TEXT,"
, "FOREIGN KEY (location) REFERENCES Location (location))"]) []
return ()
quickQuery :: String -> [SqlValue] -> DB [[SqlValue]]
quickQuery q v = ask >>= \c -> liftIO $ H.quickQuery c q v
prepare :: String -> DB H.Statement
prepare q = ask >>= \c -> liftIO $ H.prepare c q
execute :: H.Statement -> [SqlValue] -> DB Integer
execute stmt v = liftIO $ H.execute stmt v
fetchRowAl :: H.Statement -> DB (Maybe [(String, SqlValue)])
fetchRowAl = liftIO . H.fetchRowAL
</code></pre>
<p>Model.hs</p>
<pre><code>module Model where
import Database
data Person = Person (Maybe Int) String Int Location
newtype Location = Location String deriving (Eq)
instance Eq Person where
(Person _ a b c) == (Person _ a' b' c') = a == a' && b == b' && c == c'
saveLocation :: Location -> DB ()
saveLocation (Location x) = quickQuery "INSERT OR IGNORE INTO Location VALUES (?)" [toSql x] >> return ()
retrieveLocation :: String -> DB (Maybe Location)
retrieveLocation x = do
r <- quickQuery "SELECT location FROM Location WHERE location=?" [toSql x]
case r of
[] -> return Nothing
[[y]] -> return $ Just $ Location $ fromSql y
savePerson :: Person -> DB ()
savePerson (Person _ n a l@(Location loc)) = do
saveLocation l
quickQuery "INSERT INTO Person (name, age, location) VALUES (?, ?, ?)" [toSql n, toSql a, toSql loc]
return ()
retrievePersons name = do
r <- quickQuery "SELECT id, name, age, location FROM Person WHERE name=?" [toSql name]
let persons = map makePerson r
return persons
where
makePerson [sid, sname, sage, slocation] =
Person (fromSql sid) (fromSql sname) (fromSql sage) (Location (fromSql slocation))
</code></pre>
<p>tests.hs</p>
<pre><code>import Test.HUnit
import Test.Framework.Providers.HUnit
import Test.Framework (defaultMain, testGroup)
import System.Directory
import Database.HDBC (quickQuery')
import Control.Monad.Reader
import Control.Applicative
import Data.Maybe
import Database
import Model
runTest f = runDB "/tmp/test.db" f <* removeFile "/tmp/test.db"
testConnected = runTest $ do
c <- ask
r <- liftIO $ quickQuery' c "SELECT 'foo' AS value" []
liftIO $ assertBool "Return value should not be empty" (length r > 0)
testQuickQuery = runTest $ do
[[x]] <- quickQuery "SELECT ? AS value" [toSql "foo"]
liftIO $ assertBool "quickQuery" (fromSql x == "foo")
testPrepared = runTest $ do
stmt <- prepare "SELECT ? AS value"
execute stmt [toSql "foo"]
(Just r) <- fetchRowAl stmt
let (Just x) = lookup "value" r
liftIO $ assertBool "prepared" (fromSql x == "foo")
testRetrieveLocationNothing = runTest $ do
r <- retrieveLocation "Turku"
liftIO $ assertBool "Location nothing" (isNothing r)
testSaveLocation = runTest $ do
let turku = Location "Turku"
saveLocation turku
(Just loc) <- retrieveLocation "Turku"
liftIO $ assertBool "loc == turku" (loc == turku)
testSavePerson = runTest $ do
let person = Person Nothing "Person" 25 $ Location "Turku"
savePerson person
[per] <- retrievePersons "Person"
liftIO $ assertBool "model == db" $ validate person per
where
validate _ (Person Nothing _ _ _) = False
validate a b = a == b
tests = [
testGroup "Database" [
testCase "connected" testConnected
, testCase "quickQuery" testQuickQuery
, testCase "testPrepared" testPrepared
]
, testGroup "Model" [
testCase "saveLocation" testSaveLocation
, testCase "savePerson" testSavePerson
, testCase "testRetrieveLocationNothing" testRetrieveLocationNothing
]
]
main = defaultMain tests
</code></pre>
| [] | [
{
"body": "<p>First of all, I spotted a bug: since HDBC implicitly runs queries in a transaction, and since you never <a href=\"http://hackage.haskell.org/packages/archive/HDBC/latest/doc/html/Database-HDBC.html#v%3acommit\" rel=\"noreferrer\">commit</a>, none of your changes are actually applied to the database. Add a test that opens the file again, to make sure changes persist.</p>\n\n<p>Now, on to code structure.</p>\n\n<p>I definitely like the use of a reader monad. Not only does it keep the user from having to pass a <code>Connection</code> around, but it confines database operations to a single thread (if I understand correctly, SQLite3 does not support concurrent access to a single connection handle, nor does HDBC-sqlite3 provide mutual exclusion). However, since the <code>MonadReader Connection</code> instance is exposed, a user could still get at the underlying <code>Connection</code> and do something to it in another thread. I wouldn't be too worried about that, through.</p>\n\n<p>You may want to leverage the type system some more. For example, consider defining a type class for records that can be stored and retrieved:</p>\n\n<pre><code>class Record r where\n insert :: r -> DB Int -- returns the ID of the inserted row\n get :: Int -> DB (Maybe r)\n</code></pre>\n\n<p>Better yet, use <a href=\"http://www.haskell.org/haskellwiki/Phantom_type\" rel=\"noreferrer\">phantom types</a> to keep ID types distinct:</p>\n\n<pre><code>newtype Id record = Id {unId :: Int}\n deriving (Eq, Ord)\n\nclass Record r where\n insert :: r -> DB (Id r)\n get :: Id r -> DB (Maybe r)\n</code></pre>\n\n<p>However, there's a problem: the <code>Location</code> table's primary key is <code>TEXT</code>, not <code>INT</code>. If it were up to me, I'd give the <code>Location</code> table an integer primary key, so that:</p>\n\n<ul>\n<li><p>All records have a consistent ID type</p></li>\n<li><p>Locations can be renamed without violating the foreign key constraint.</p></li>\n<li><p>The <code>Person</code> table doesn't duplicate location names. You don't want your database blowing up when 200 people take a field trip to <a href=\"http://en.wikipedia.org/wiki/Llanfairpwllgwyngyll\" rel=\"noreferrer\">Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch</a>.</p></li>\n</ul>\n\n<p>I recommend reading the <a href=\"http://www.yesodweb.com/book/persistent\" rel=\"noreferrer\">Persistent</a> chapter of the Yesod book. Even if you don't use Persistent, look at how it's designed.</p>\n\n<p>For example, I noticed you embedded the ID field in your <code>Person</code> type:</p>\n\n<pre><code>data Person = Person (Maybe Int) String Int Location\n</code></pre>\n\n<p>Persistent chooses to keep the ID and data separate. The <a href=\"http://www.yesodweb.com/book/persistent#file337-insert-x1\" rel=\"noreferrer\">Insert section</a> gives a convincing rationale.</p>\n\n<p>Persistent also runs its database monad in a single transaction (<a href=\"http://www.yesodweb.com/book/persistent#file328-persistbackend-bc5\" rel=\"noreferrer\">see the PersistBackend section</a>). HDBC implicitly runs everything in a transaction, so you don't have to do much to follow suit. This approach has a semantic benefit. Sometimes, you need to do a group of operations atomically. Rather than calling BEGIN and COMMIT explicitly (and hoping the caller isn't also doing stuff in a transaction), you use the type system to force the code to run inside of a transaction.</p>\n\n<p><a href=\"http://www.haskell.org/haskellwiki/Software_transactional_memory\" rel=\"noreferrer\">STM</a> does something similar: you can't nest transactions without sidestepping the type system (e.g. with <code>unsafePerformIO</code>).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-12T15:35:44.787",
"Id": "7712",
"ParentId": "2140",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-28T09:33:06.600",
"Id": "2140",
"Score": "8",
"Tags": [
"sql",
"haskell"
],
"Title": "Idiomatic haskell database connectivity"
} | 2140 |
<p>I finished the Ruby chapter in <a href="http://pragprog.com/titles/btlang/seven-languages-in-seven-weeks" rel="nofollow noreferrer">Seven Languages in Seven Weeks</a>. It tries to make you familiar with the core concepts of several languages rather quickly. Dutifully I did all exercises, but most likely they can be improved to be more Ruby-like.</p>
<blockquote>
<p>Write a simple grep that will print the lines of a file having any occurrences of a phrase anywhere in that line (in my example 'bleh'). Include line numbers.</p>
</blockquote>
<pre><code>File.open( 'grepFile.txt', 'r' ) do |file|
lines = []
line_number = 1
file.readlines.each do |line|
lines[line_number] = line
line_number += 1
end
lines.each_index do |i|
line = lines[i]
puts "line #{i.to_s}: #{line}" if line =~ /bleh/
end
end
</code></pre>
| [] | [
{
"body": "<pre><code>File.open( 'grepFile.txt', 'r' ) do |file|\n lines = []\n line_number = 1\n file.readlines.each do |line|\n lines[line_number] = line\n line_number += 1\n end\n lines.each_index do |i| \n line = lines[i]\n puts \"line #{i.to_s}: #{line}\" if line =~ /bleh/\n end\nend\n</code></pre>\n\n<p><code>file.readlines.each</code> should be <code>file.each_line</code>, which will do the same thing (iterate over all the lines) without building an array (and reading the whole file into memory) first. Also instead of keeping track of the <code>line_number</code> manually, you should just use <code>each_with_index</code>. Though actually if you want to append to the end of the array, you actually shouldn't use an index at all, but use <code><<</code> or <code>push</code> instead (if you want the indices to start at 1, you can just insert a <code>nil</code> element first).</p>\n\n<p>That being said if all you want is to read the file into an array, you could just do <code>lines = file.readlines</code> without any loop (or possible <code>[nil] + file.readlines</code>, so that it keeps starting at 1, but I'd rather add 1 to the line number when printing instead of copying the whole array).</p>\n\n<p>Further you can use the methods <code>File.readlines</code> or <code>File.foreach</code> instead of <code>File.open</code> + <code>File#readlines</code> or <code>File.open</code> + <code>File#each_line</code> respectively.</p>\n\n<p>Then when you iterate over <code>lines</code> you should use <code>each_with_index</code> rather than <code>each_index</code>, so you don't have to do <code>lines[i]</code> to get at the value.</p>\n\n<p>As a last note, it's unnecessary to call <code>to_s</code> on an object in <code>#{}</code> - ruby does that automatically.</p>\n\n<hr>\n\n<p>However the whole approach seems needlessly complicated to me. I don't see why you need to build up an array at all. I'd just iterate over the lines once and output them directly. This in addition to being much shorter also has the advantage, that the program runs in <code>O(1)</code> space (assuming the maximum line length is constant) rather than reading the whole file into memory.</p>\n\n<pre><code>File.foreach('grepFile.txt').each_with_index do |line, i|\n puts \"line #{i}: #{line}\" if line =~ /bleh/\nend\n</code></pre>\n\n<p>And of course instead of <code>'grepFile.txt'</code> and <code>/bleh/</code>, you should be using <code>ARGV[1]</code> and <code>Regexp.new(ARGV[0])</code>, as it makes no sense to hardcode these values.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-28T14:59:50.543",
"Id": "3495",
"Score": "1",
"body": "Nice! I was looking for a way to also get the index, but was looking in the wrong place (an overload of each which now I know isn't really supported). The whole reason for the array was to store the line number. ;) Once I read your pointers, I quickly came to the last code sample myself. I just have `#{i+1}` for the line number."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-16T15:19:00.747",
"Id": "28017",
"Score": "1",
"body": "The last bit of code really should be at the top. That's ruby-way structure, and the OPs initial code is just due to their early learning."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-28T13:59:33.490",
"Id": "2143",
"ParentId": "2142",
"Score": "8"
}
},
{
"body": "<p>I am reading the book aswell and I came up with the following solution,</p>\n<pre><code>File.read('text.txt').split(/\\n/).each do |t| \n p t if t =~ /bleh/\nend\n</code></pre>\n<p>Which I think is very nice. I am however also a Ruby-rookie. :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T06:35:19.820",
"Id": "511232",
"Score": "2",
"body": "You did not review the code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T07:20:52.110",
"Id": "511235",
"Score": "0",
"body": "Welcome to Code Review! You have presented an alternative solution, but haven't reviewed the code. Please [edit] to show what aspects of the question code prompted you to write this version, and in what ways it's an improvement over the original. It may be worth (re-)reading [answer]."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T06:13:47.357",
"Id": "259226",
"ParentId": "2142",
"Score": "-1"
}
}
] | {
"AcceptedAnswerId": "2143",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-28T12:40:11.277",
"Id": "2142",
"Score": "8",
"Tags": [
"ruby"
],
"Title": "Custom grep in Ruby"
} | 2142 |
<p>I finished the Ruby chapter in <a href="http://pragprog.com/titles/btlang/seven-languages-in-seven-weeks" rel="nofollow noreferrer">Seven Languages in Seven Weeks</a>. It tries to make you familiar with the core concepts of several languages rather quickly. Dutifully I did all exercises, but most likely they can be improved to be more Ruby-like.</p>
<blockquote>
<p>Given: a CSV file structured with a first line with headers and
subsequent rows with data.</p>
<pre><code>one, two
lions, tigers
</code></pre>
<p>Create a module which loads the header and values from a CSV file,
based on the name of the implementing class. (RubyCSV ->
"rubycsv.txt") Support an <code>each</code> method which returns a <code>CsvRow</code>
object. Use <code>method_missing</code> to return the value for the column for a
given heading. E.g. usage which will print "lions":</p>
<pre><code>m = RubyCsv.new
m.each { |row| p row.one }
</code></pre>
</blockquote>
<p>My implementation:</p>
<pre><code>class CsvRow
attr :row_hash
def initialize( row_hash )
@row_hash = row_hash
end
def method_missing( name, *args )
@row_hash[ name.to_s ]
end
end
module ActsAsCsv
attr_accessor :headers, :csv_contents
def self.included( base )
base.extend ClassMethods
end
module ClassMethods
def acts_as_csv
include InstanceMethods
end
end
module InstanceMethods
def read
@csv_contents = []
filename = self.class.to_s.downcase + '.txt'
file = File.new( filename )
@headers = file.gets.chomp.split( ', ' )
file.each do |row|
@csv_contents << row.chomp.split( ', ' )
end
end
def initialize
read
end
def each
@csv_contents.each do |content|
hash = {}
@headers.zip( content ).each { |i| hash[ i[0] ] = i[1] }
yield CsvRow.new hash
end
end
end
end
class RubyCsv # No inheritance! You can mix it in.
include ActsAsCsv
acts_as_csv
end
</code></pre>
| [] | [
{
"body": "<pre><code>def method_missing( name, *args )\n @row_hash[ name.to_s ]\nend\n</code></pre>\n\n<p>Doing it like this means that if the user calls a row method with arguments, the arguments will silently be ignored. Also if the user calls any method which does not exist and for which no row exists either, he'll just get back nil. I think in both cases an exception should be thrown, so I'd implement <code>method_missing</code> like this:</p>\n\n<pre><code>def method_missing( name, *args )\n if @row_hash.has_key?(name.to_s)\n if args.empty?\n @row_hash[ name.to_s ]\n else\n raise ArgumentError, \"wrong number of arguments(#{ args.size } for 0)\"\n end\n else\n super\n end\nend\n</code></pre>\n\n<hr>\n\n<pre><code>module ActsAsCsv\n # ...\n\n def self.included( base )\n base.extend ClassMethods\n end\n\n module ClassMethods\n def acts_as_csv\n include InstanceMethods\n end\n end\n\n module InstanceMethods\n ...\n end\nend\n</code></pre>\n\n<p>This setup seems needlessly complicated. Since all <code>acts_as_csv</code> does is include the instance methods (except <code>headers</code> and <code>csv_contents</code>, which will be present even if <code>acts_as_csv</code> is not called - which seems a bit arbitrary to me) and there is no reason why a user would want to include <code>ActsAsCsv</code> without getting the instance methods, I see no reason for <code>acts_as_csv</code> to exist at all. The instance methods should be directly in the <code>ActsAsCsv</code> module and the <code>ClassMethods</code> and <code>InstanceMethods</code> modules should not exist.</p>\n\n<p>This way the code will be less complex, and you only need one line <code>include ActsAsCsv</code> instead of two to enable the CSV functionality.</p>\n\n<hr>\n\n<pre><code>def read\n @csv_contents = []\n filename = self.class.to_s.downcase + '.txt'\n file = File.new( filename )\n @headers = file.gets.chomp.split( ', ' )\n\n file.each do |row|\n @csv_contents << row.chomp.split( ', ' )\n end\nend\n</code></pre>\n\n<p>First of all you're opening a file and never closing it. You should use <code>File.open</code> with a block instead.</p>\n\n<p>Second of all you should make use of higher order functions like <code>map</code>. Using <code>map</code> you can create <code>@csv_contents</code> like this instead of appending to it in an <code>each</code> loop:</p>\n\n<pre><code>def read\n filename = self.class.to_s.downcase + '.txt'\n file = File.open( filename ) do |file|\n @headers = file.gets.chomp.split( ', ' )\n @csv_contents = file.map {|row| row.chomp.split( ', ' )}\n end\nend\n</code></pre>\n\n<hr>\n\n<p>That being said I don't think it's a good idea to read the whole file into memory in advance (or at all), as that will make your library unusable on big files (which might not even fit into memory).</p>\n\n<p>So I would get rid of the <code>read</code> method and just open and read through the file in the <code>each</code> method, like this:</p>\n\n<pre><code>def each\n filename = self.class.to_s.downcase + '.txt'\n File.open(filename) do |file|\n headers = file.gets.chomp.split( ', ' )\n file.each do |content| \n hash = {}\n headers.zip( content.chomp.split(', ') ).each { |i| hash[ i[0] ] = i[1] }\n yield CsvRow.new hash\n end\n end\nend\n</code></pre>\n\n<hr>\n\n<p>Lastly, instead of</p>\n\n<pre><code>hash = {}\nheaders.zip( content ).each { |i| hash[ i[0] ] = i[1] }\n</code></pre>\n\n<p>You can also write <code>hash = Hash[ headers.zip( content ) ]</code>.</p>\n\n<hr>\n\n<p>On a more general note, your code does not really correctly parse CSV files. Your code assumes that the fields will be separated by a comma followed by a single space. However it is not required that commas are actually followed by any spaces (and the RFC actually says that any space after a comma is part of the field's content and should not be ignored). You're also not handling quoting (e.g. <code>foo, \"bar, baz\", bay</code>, which is a row containing three, not four, fields) at all.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-28T16:01:13.487",
"Id": "3497",
"Score": "0",
"body": "Actually this question is an adaptation of an example in the book. The `each` and `CsvRow` needed to be added. Now that I heard your explanation I find it a bad example, or ill explained. Others apparently thought the same. I'm definitely going to attempt some more metaprogramming in Ruby to see whether I can grasp its added value. I just need to come up with a nice relatively small exercise. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-28T16:05:40.050",
"Id": "3498",
"Score": "0",
"body": "Found [the authors explanation](http://forums.pragprog.com/forums/147/topics/4654). _\"This was another case of editing an exercise getting the best of me. I wanted to show how Rails acts-as modules work, and initially I had some dynamic capabilities that did some introspection. But in the end, I simplified the application and removed the very capabilities (faster-csv style attribute inspection) that made acts-as a good idea.\n\nI’ll address it in the second edition.\"_"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-28T16:43:22.513",
"Id": "3501",
"Score": "0",
"body": "Thanks for all the pointers! They've been really useful. I fixed some minor mistakes in your updated code samples, but your explanation was great. ;p"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-28T16:48:28.060",
"Id": "3502",
"Score": "0",
"body": "@Steven: Yeah, I wasn't thinking with the `each` instead of `map` ;-) Btw: I've added a paragraph at the end."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-28T15:13:26.133",
"Id": "2145",
"ParentId": "2144",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "2145",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-28T14:37:12.323",
"Id": "2144",
"Score": "5",
"Tags": [
"ruby",
"csv"
],
"Title": "CSV module in Ruby"
} | 2144 |
<p>I have been working with C# for quite some time but relatively new to the concepts of lambdas and Linq. I was working with a Linq To SQL example and trying to write a generic solution for executing a search against a collection of entities (eg. list of <code>Customer</code> objects) where the search parameter will be specified by passing a partially filled object of the entity class itself. I was doing this just to ensure that a person does not have to go on specifying different overloads for different searches based on the entity class attributes and trying to write a generic solution which will cater to any entity class. </p>
<p>Hence I used reflection and an array of predicates to successively apply the Where clauses to the collection.</p>
<h2>Client App</h2>
<pre><code>using (CustomerManager oCustomerManager = new CustomerManager())
{
IEnumerable<Customer> customers = oCustomerManager.Load();
Customer oSearchCustomer = new Customer();
oSearchCustomer.City = "London";
oSearchCustomer.ContactName = "Thomas Hardy";
IEnumerable<Customer> customerList = oCustomerManager.Search(oSearchCustomer);
foreach (Customer customer in customerList)
{
Console.WriteLine(customer.ToString());
}
}
</code></pre>
<h2>Manager Class</h2>
<pre><code>public IEnumerable<Customer> Search(Customer searchObject)
{
IEnumerable<Customer> customers = DataContext.Customers;
List<Func<Customer, bool>> result =
DataContext.Customers.GenerateFilterClause<Customer>(searchObject);
foreach (var item in result)
{
customers = customers.Where(item);
}
return customers;
}
</code></pre>
<h2>Extension Method Utility Class</h2>
<pre><code>public static class UtilityExtensions
{
public static List<Func<T, bool>> GenerateFilterClause<T>(this IEnumerable<T>
collection, T searchEntity)
{
List<Func<T, bool>> whereFilterList = new List<Func<T, bool>>();
Func<T, bool> predicate = null;
var propertyList = searchEntity.GetType().GetProperties();
foreach (PropertyInfo p in propertyList)
{
if (p.GetCustomAttributes(false).OfType<ColumnAttribute>().Count() > 0)
{
string propName = p.Name;
var searchVal =
searchEntity.GetType().GetProperty(propName).GetValue(searchEntity,null);
if (searchVal != null)
{
predicate = new Func<T, bool>(entity => propertyWhereClause(entity,
searchEntity, propName, searchVal));
whereFilterList.Add(predicate);
}
}
}
return whereFilterList;
}
private static bool propertyWhereClause<T>(T obj, T searchEntity, string propertyName, object searchVal)
{
return obj.GetType().GetProperty(propertyName).GetValue(obj,
null).Equals(searchVal);
}
}
</code></pre>
<p>While the solution is working, I have two specific questions:</p>
<ul>
<li>What are the drawbacks of this solution? I was hoping to have inputs regarding performance and cleaner way to rewrite the code.</li>
<li>Can anyone suggest a more efficient and better solution? That would help me to understand the proper way to utilize the power of lambdas and Linq.</li>
</ul>
| [] | [
{
"body": "<p>How much did <a href=\"http://weblogs.asp.net/scottgu/archive/2007/05/19/using-linq-to-sql-part-1.aspx\" rel=\"nofollow\">you look into LINQ to SQL</a>? Unless you have a reason not to expose the <code>DataContext</code>, you can just perform queries on it without using the 'search object'.</p>\n\n<pre><code>from c in DataContext.Customers\nwhere c.City == \"London\" && c.ContactName == \"Thomas Hardy\"\nselect c\n</code></pre>\n\n<p>I haven't used LINQ to SQL myself yet, so I can't really tell much about the best practices and whether or not exposing <code>DataContext</code> is a good idea. Probably it's best to use an existing ORM framework. <a href=\"http://dataobjects.net/\" rel=\"nofollow\">DataObjects.NET</a> looks really nice.</p>\n\n<p>A nice ORM overview can be found on <a href=\"http://ormbattle.net/\" rel=\"nofollow\">ORMbattle</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-29T10:57:23.463",
"Id": "2155",
"ParentId": "2154",
"Score": "3"
}
},
{
"body": "<p>I don't fully understand what you're trying to accomplish, but there's a lot of code here that doesn't make sense.</p>\n<h2>Client app</h2>\n<ul>\n<li>You create a <code>customers</code> object and never use it. Why?</li>\n<li>You create a temporary <code>customerList</code> object only to iterate over it. Why?</li>\n<li><code>WriteLine(object)</code> already calls <code>ToString</code> implicitly.</li>\n</ul>\n<h2>Manager class and the rest</h2>\n<ul>\n<li>You're reinventing the wheel here. This is exactly what LINQ-to-SQL does.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-05-04T03:16:57.040",
"Id": "88746",
"ParentId": "2154",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-29T05:39:21.990",
"Id": "2154",
"Score": "7",
"Tags": [
"c#",
"linq",
"performance"
],
"Title": "Performance optimization for Linq To SQL"
} | 2154 |
<p>Both functions look fairly similar to each other, but they are different in the type of string. I have 6 functions like this and all differ only in the "string cmd". Any ideas on how I can put it all into one?</p>
<pre><code>public void getFrmSingProgTbl(int flg)
{
if (flg == 1)
{
object[] astatus = new object[1];
astatus = td.CheckOk(td.t1snd);
string status = (string)astatus[0];
if (status == "true")
{
string cmd = getCurrTime() + "|" + "part-type" + "|" + t1prtNameTxt.Text + "\n";
cmd += getCurrTime() + "|" + "operation-type" + "|" + t1oprNameTxt.Text + "\n";
string showCmd = "Part Type - " + t1prtNameTxt.Text + "\nOperation - " + t1oprNameTxt.Text;
if (MessageBox.Show(showCmd, "Confirm", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
HandleAfterSend(td.t1snd, td.t1stp, flg, td.t1btn);
sndData(cmd,1);
}
}
else
{
this.ActiveControl = (TextBox)astatus[1];
MessageBox.Show(status, "Error");
}
}
else if (flg == 2)
{
object[] astatus = new object[1];
astatus = td.CheckOk(td.t1stp);
string status = (string)astatus[0];
if (status == "true")
{
string cmd = getCurrTime() + "|" + "part-count-good" + "|" + t1gpTxt.Text + "\n";
cmd += getCurrTime() + "|" + "part-count-bad" + "|" + t1bpTxt.Text + "\n";
string showCmd = "Good Parts - " + t1gpTxt.Text + "\nBad Parts - " + t1bpTxt.Text;
if (td.CheckNumeric(td.t1stp))
{
if (MessageBox.Show(showCmd, "Confirm", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
HandleAfterSend(td.t1stp, td.t1snd, flg, td.t1btn);
sndData(cmd,0);
}
}
else
{
MessageBox.Show("Enter only numbers for Part Count","Error");
}
}
else
{
this.ActiveControl = (TextBox)astatus[1];
MessageBox.Show(status, "Error");
}
}
}
public void getFrmSingFixtTbl(int flg)
{
if (flg == 1)
{
object[] astatus = new object[1];
astatus = td.CheckOk(td.t3snd);
string status = (string)astatus[0];
if (status == "true")
{
string cmd = getCurrTime() + "|" + "part-type" + "|" + t3prtNameTxt.Text + "\n";
cmd += getCurrTime() + "|" + "operation-type" + "|" + t3oprNameTxt.Text + "\n";
cmd += getCurrTime() + "|" + "fixture-positions" + "|" + t3fixPosnTxt.Text + "\n";
string showCmd = "Part Type" + " - " + t3prtNameTxt.Text + "\n";
showCmd += "Operation" + " - " + t3oprNameTxt.Text + "\n";
showCmd += "Parts per Fixture " + " - " + t3fixPosnTxt.Text + "\n";
if (MessageBox.Show(showCmd, "Confirm", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
HandleAfterSend(td.t3snd, td.t3stp, flg, td.t3btn);
sndData(cmd,1);
}
}
else
{
this.ActiveControl = (TextBox)astatus[1];
MessageBox.Show(status, "Error");
}
}
else if (flg == 2)
{
object[] astatus = new object[1];
astatus = td.CheckOk(td.t3stp);
string status = (string)astatus[0];
if (status == "true")
{
string cmd = getCurrTime() + "|" + "part-count-good" + "|" + t3gpTxt.Text + "\n";
cmd += getCurrTime() + "|" + "part-count-bad" + "|" + t3bpTxt.Text + "\n";
string showCmd = "Good Parts" + " - " + t3gpTxt.Text + "\n";
showCmd += "Bad Parts" + " - " + t3bpTxt.Text + "\n";
if (td.CheckNumeric(td.t3stp))
{
if (MessageBox.Show(showCmd, "Confirm", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
HandleAfterSend(td.t3stp, td.t3snd, flg, td.t3btn);
sndData(cmd,0);
}
}
else
{
MessageBox.Show("Enter only numbers for Part Count","Error");
}
}
else
{
this.ActiveControl = (TextBox)astatus[1];
MessageBox.Show(status, "Error");
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-29T23:53:20.563",
"Id": "3506",
"Score": "0",
"body": "How much control do you have over the structure of the td object's type?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-05-04T17:34:07.617",
"Id": "161791",
"Score": "1",
"body": "Please only state the code purpose in the title. I downvoted for the meaningless title"
}
] | [
{
"body": "<p>Quick thoughts off the top of my head.</p>\n\n<ol>\n<li>Use the standard .Net naming convention and don't abbreviate</li>\n<li>Don't change the whole processing of a method by a flag</li>\n<li>If you control td.CheckOk(...) why does it return an array when it isn't used that way? Also, it should return a bool rather than a string \"true\". This should return a specific type rather than a bunch of data in various array indexes.</li>\n<li>Why are you creating a new array astatus = new object[1]; and then immediately replacing it with the value from td.CheckOk?</li>\n<li>Use StringBuilder rather than lots of string concats</li>\n<li><p>Seems like you could replace each function with (ignoring all the changes above):</p>\n\n<pre><code>public void GetResult(Func<string> generateCommand, Func<string> generateSendData) {\nobject[] astatus = td.CheckOk(td.t1snd);\nif (astatus != null && astatus.Length > 0 && (string)astatus[0] == \"true\") {\n string cmd = generateCommand();\n string data = generateSendData();\n if (MessageBox.Show(showCmd, \"Confirm\", MessageBoxButtons.YesNo) == DialogResult.Yes) {\n HandleAfterSend(td.t1snd, td.t1stp, flg, td.t1btn);\n sndData(cmd,1);\n } \n} else {\n this.ActiveControl = (TextBox)astatus[1];\n MessageBox.Show(astatus[0].ToString(), \"Error\");\n}\n}\n</code></pre></li>\n</ol>\n\n<p>And then call it with:</p>\n\n<pre><code>GetResult(\n () => getCurrTime() + \"|\" + \"part-type\" + \"|\" + t1prtNameTxt.Text + \"\\n\" + getCurrTime() + \"|\" + \"operation-type\" + \"|\" + t1oprNameTxt.Text + \"\\n\",\n () => \"Part Type - \" + t1prtNameTxt.Text + \"\\nOperation - \" + t1oprNameTxt.Text\n);\nGetResult(\n () => getCurrTime() + \"|\" + \"part-count-good\" + \"|\" + t1gpTxt.Text + \"\\n\" + getCurrTime() + \"|\" + \"part-count-bad\" + \"|\" + t1bpTxt.Text + \"\\n\",\n () => \"Good Parts - \" + t1gpTxt.Text + \"\\nBad Parts - \" + t1bpTxt.Text\n);\n\n//etc\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-29T16:24:10.510",
"Id": "2158",
"ParentId": "2156",
"Score": "15"
}
},
{
"body": "<ol>\n<li>Do not use <code>int</code> for <code>flag</code>. Use <code>bool</code> or <code>enum</code> </li>\n<li>Do not use <code>string</code> for <code>status</code>. Use <code>bool</code> </li>\n<li>Do not use <code>object[]</code> for <code>astatus</code>. Write own class for that </li>\n<li><strong>Rewrite everything</strong> keeping first 3 points in mind</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-02T19:59:24.833",
"Id": "3547",
"Score": "1",
"body": "Especially the 1, 2, 3 and 4. But it could be nice if you explain the reason for those, isn't?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-29T16:55:56.770",
"Id": "2159",
"ParentId": "2156",
"Score": "14"
}
},
{
"body": "<p>To add to akmad's answer you can simplify your string handling by using a string mask and the <code>String.Format()</code> function.</p>\n\n<p>For example:</p>\n\n<pre><code>string cmd = getCurrTime() + \"|\" + \"part-count-good\" + \"|\" + t1gpTxt.Text + \"\\n\";\ncmd += getCurrTime() + \"|\" + \"part-count-bad\" + \"|\" + t1bpTxt.Text + \"\\n\";\nstring showCmd = \"Good Parts - \" + t1gpTxt.Text + \"\\nBad Parts - \" + t1bpTxt.Text;\n</code></pre>\n\n<p>could be replaced with:</p>\n\n<pre><code>string cmdFormat = \"{0}|part-count-good|{1}\\n{0}|part-count-bad|{2}\\n\";\nstring cmd = String.format(cmdFormat, getCurrTime(), tlgp.Text, tlbp.Text);\n\nstring showFormat = \"Good Parts - {0}\\nBad Parts - {1}\";\nstring showCmd = String.Format(showFormat, tlgpTxt.Text, tlbpTxt.Text);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-29T21:06:36.463",
"Id": "2160",
"ParentId": "2156",
"Score": "5"
}
},
{
"body": "<p>Method names that start with \"Get\" just sound wrong for methods that return void.</p>\n\n<p>Depending on how these methods are used, you may be able to extract them to command objects with the common portion implemented in a common base class and the differences further extracted to abstract methods.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-30T00:13:33.363",
"Id": "2163",
"ParentId": "2156",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "2158",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-29T15:11:29.057",
"Id": "2156",
"Score": "7",
"Tags": [
"c#",
"strings"
],
"Title": "Managing part types and counts"
} | 2156 |
<p>I have small Class which handles user's information. (name, surname, login, hash of password). Also this class can activate, register and login the user. This means I should connect to DB. Is it normal? I'm using Pear MDB2 to connect to DB. </p>
<p>Does it mean that every instance of User will have MDB2 object initialised?</p>
<pre><code>class User {
private $login;
private $hash;
private $name;
/* some getters and setters */
//
// public function get_name() { return $this->name }
// ..
//
private $connect; // MDB2 connection
private $dsn = ""; // connection config
public function exists() { // return true if User exists
require ('MDB2.php');
$this->connect = MDB2::connect($this->dsn);
// check
}
}
</code></pre>
<p>Should I make $connect and $dsn variables static? Or may be I should use some pattern for this idea?</p>
<p>Update: (kind of decision)</p>
<p>I store database connection in static variable:</p>
<pre><code>class DataBase {
// connections options
static public $connect = NULL; // MDB2 connection variable
static public $dsn = "pgsql://user:pass@IP/database";
static public $connected = false;
static function reportError() {
if (PEAR::isError(self::$connect)) {
$res["success"]=false;
$res["errors"][] = self::$connect->getMessage();
echo json_encode($res);
exit;
}
} //: reportError
} //: Class DataBase
</code></pre>
<p>So If I want to connect to DB I write:</p>
<pre><code>// connect only if it's not connected
if (!DataBase::$connected) {
require_once('MDB2.php'); // Pear MDB2 class
DataBase::$connect = MDB2::factory(DataBase::$dsn); // connection
DataBase::$connected = true; // Flag that we're already connected
}
</code></pre>
<p>It's normal? Or I should make it another way?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-02T17:58:32.460",
"Id": "3544",
"Score": "0",
"body": "What is MDB2.php doing?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-02T19:16:40.847",
"Id": "3546",
"Score": "0",
"body": "MDB2.php is Pear MDB2 class. It helps to connect to database of any type (mysql, pqsql, sqlite, etc). To change database it requires only changing of one variable ($dsn)"
}
] | [
{
"body": "<blockquote>\n<p>Also this class can activate, register and login the user. This means I should connect to DB. Is it normal?</p>\n</blockquote>\n<p>It's up to you and your requirements. Personally I am trying to make all domain specific objects simple as possible and use it only as <a href=\"http://en.wikipedia.org/wiki/Data_transfer_object\" rel=\"nofollow noreferrer\">Value Object</a>. So, in this case all actions such as checking for existance, creation, activation, registration etc should go to another class, for example, UserManager or similar. And in this class I will hold reference to DB and doing all SQL-queries.</p>\n<blockquote>\n<p>Should I make $connect and $dsn variables static?</p>\n</blockquote>\n<p>Again, it's depends from your requirements. But from my point of view -- no, you shouldn't. When you doing this you cannot have two different connections for MySQL and PostgreSQL, for example.</p>\n<p>In any case, I suggest to change <code>public</code> modifier to <code>private</code> (or <code>protected</code>) for <code>$connect</code>, <code>$dsn</code> and <code>$connected</code> memebers.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-03T04:52:19.357",
"Id": "2206",
"ParentId": "2157",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "2206",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-29T15:46:52.153",
"Id": "2157",
"Score": "4",
"Tags": [
"php",
"object-oriented",
"database"
],
"Title": "User php class. Should I connect to DB in this class?"
} | 2157 |
<p>I'm giving a lecture on basic programming to first-year mathematics students. The programming language is Java (defined by curriculum).</p>
<p>Last week I gave the following task:</p>
<blockquote>
<p>Write a program, that reads in the date of birth of the user separated into year, month and day and subsequently calculates the days the user has lived until today.<br>
Do consider leap years.</p>
</blockquote>
<p>This task seems not to be too hard, but there are some restrictions (as they are first-year students and never had had any experiences in programming):</p>
<ol>
<li>only the basic data types are known (<code>int</code>, <code>double</code>, <code>boolean</code>, <code>String</code> etc.)</li>
<li>arrays are <em>not</em> known</li>
<li>writing own functions is <em>not</em> known (i.e. everything is within the <code>main</code>)</li>
<li>except of <code>System.out.print</code>/<code>ln</code> none of the Java API functions are known</li>
<li>user input is realised through a provided method <code>readInteger(String promt)</code> (the students just use it, but don't know why and how it works)</li>
</ol>
<p>Here I present my sample solution and would like to know, whether there are some more possibilities of "smoothing" the code, optimising it or just increasing the readability. Only tweaks and tricks are allowed, which can be done given the knowledge-restrictions above.</p>
<pre><code>public static void main(String[] args) {
// define today's day
final int TODAY_YEAR = 2011, TODAY_MONTH = 4, TODAY_DAY = 29;
// define a leapyear in the past
final int LEAPYEAR = 1904;
// is the current year a leapyear?
boolean todayIsLeapyear = false;
// get user input
int birthYear = readInteger("Please enter the year of your birth:");
int birthMonth = readInteger("Please enter the month of your birth:");
int birthDay = readInteger("Please enter the day of your birth:");
// check input for validity
boolean inputOK = true;
int birthYearLeapShift = 0;
boolean birthYearWasLeap = false;
if (birthYear > 2011 || birthMonth > 12) {
System.out.println("Your input was not correct.");
if (birthYear > 2011) {
System.out.println("You are from the future! How is it there?");
} else {
System.out.println("We will calculate in the usual gregorian calendar.");
}
inputOK = false;
} else {
// calculate shift of year of birth to the prior leapyear
birthYearLeapShift = (birthYear - LEAPYEAR) % 4;
birthYearWasLeap = (birthYearLeapShift == 0);
// check the input of the month of birth for validity
switch (birthMonth) {
case 1: //january
inputOK = (birthDay <= 31);
break;
case 2: //february
inputOK = (birthDay <= 28);
inputOK = (birthDay <= 29 && birthYearWasLeap);
break;
case 3: //march
inputOK = (birthDay <= 31);
break;
case 4: //april
inputOK = (birthDay <= 30);
break;
case 5: //may
inputOK = (birthDay <= 31);
break;
case 6: //june
inputOK = (birthDay <= 30);
break;
case 7: //july
inputOK = (birthDay <= 31);
break;
case 8: //august
inputOK = (birthDay <= 31);
break;
case 9: //september
inputOK = (birthDay <= 30);
break;
case 10: //october
inputOK = (birthDay <= 31);
break;
case 11: //november
inputOK = (birthDay <= 30);
break;
case 12: //december
inputOK = (birthDay <= 31);
break;
}
}
if (inputOK) {
// calculate the days fo the current year
int daysInCurrYear = TODAY_DAY;
switch (TODAY_MONTH - 1) {
case 11:
daysInCurrYear += 30;
case 10:
daysInCurrYear += 31;
case 9:
daysInCurrYear += 30;
case 8:
daysInCurrYear += 31;
case 7:
daysInCurrYear += 31;
case 6:
daysInCurrYear += 30;
case 5:
daysInCurrYear += 31;
case 4:
daysInCurrYear += 30;
case 3:
daysInCurrYear += 31;
case 2:
daysInCurrYear += todayIsLeapyear ? 29 : 28;
case 1:
daysInCurrYear += 31;
}
// calculate the lived (full) days in the year of birth
int daysInBirthYear = 0;
switch (birthMonth) {
case 1:
daysInBirthYear += 31 - birthDay;
case 2:
if (birthYearWasLeap) {
daysInBirthYear += (birthMonth == 2) ? (29 - birthDay) : 29;
} else {
daysInBirthYear += (birthMonth == 2) ? (28 - birthDay) : 28;
}
case 3:
daysInBirthYear += (birthMonth == 3) ? (31 - birthDay) : 31;
case 4:
daysInBirthYear += (birthMonth == 4) ? (30 - birthDay) : 30;
case 5:
daysInBirthYear += (birthMonth == 5) ? (31 - birthDay) : 31;
case 6:
daysInBirthYear += (birthMonth == 6) ? (30 - birthDay) : 30;
case 7:
daysInBirthYear += (birthMonth == 7) ? (31 - birthDay) : 31;
case 8:
daysInBirthYear += (birthMonth == 8) ? (31 - birthDay) : 31;
case 9:
daysInBirthYear += (birthMonth == 9) ? (30 - birthDay) : 30;
case 10:
daysInBirthYear += (birthMonth == 10) ? (31 - birthDay) : 31;
case 11:
daysInBirthYear += (birthMonth == 11) ? (30 - birthDay) : 30;
case 12:
daysInBirthYear += (birthMonth == 12) ? (31 - birthDay) : 31;
}
// calculate the full lived years since birth
int fullYearsSinceBirth = TODAY_YEAR - birthYear - 1;
// ... and considere the leapyears lived
int leapyearsLived = (fullYearsSinceBirth + birthYearLeapShift) / 4;
// and calculate the lived days in the lived full years
int daysInFullYears = fullYearsSinceBirth * 365 + leapyearsLived;
// add everything together
int daysLived = daysInBirthYear + daysInFullYears + daysInCurrYear;
// and finally return the result
System.out.println("You have been living for " + daysLived
+ " days now.");
System.out.println("In addition, this is approximately "
+ (daysLived / 30) + " full months and "
+ fullYearsSinceBirth + " full years.");
System.out.println("Congratulations!");
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-03T11:21:30.010",
"Id": "3563",
"Score": "0",
"body": "Do they know loops?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-04T12:17:04.463",
"Id": "3577",
"Score": "0",
"body": "@HosamAly: Yes, they do know loops."
}
] | [
{
"body": "<p>Wow, arrays would be really nice for this, but I suppose you can give a \"rewrite that first problem using arrays\" once they learn them. :)</p>\n\n<p>What happens if they enter zero or negative values?</p>\n\n<p>Anyone born in February is automatically invalid:</p>\n\n<pre><code>case 2: //february\n inputOK = (birthDay <= 28);\n inputOK = (birthDay <= 29 && birthYearWasLeap);\n</code></pre>\n\n<p>This forces <code>inputOk</code> to <code>false</code> when the birth year isn't a leap year, even if <code>birthDay</code> is 5. It should be combined using or logic.</p>\n\n<pre><code>case 2: //february\n inputOK = (birthDay <= 28) || (birthDay <= 29 && birthYearWasLeap);\n</code></pre>\n\n<p>I would add an error message when the input is not okay. If they know about <code>return</code> or <code>System.exit(1)</code> I would use them after displaying an error message. Better yet, loop until the input is acceptable if they know about looping.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-30T05:43:34.933",
"Id": "3511",
"Score": "0",
"body": "Oh, yes. I totally missed the logical error of these two lines. Thanks a lot for pointing me on this! I must admit, that I really forgot the last error message (wrong day of birth) and haven't caught input <= 0."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-30T00:40:54.753",
"Id": "2166",
"ParentId": "2161",
"Score": "5"
}
},
{
"body": "<p>The code contains a number of things that would be considered bad style ... and you should not be requiring students to learn/practice bad style. Some of the big problems are:</p>\n\n<ul>\n<li><p>A <code>main</code> method that is 100's of line long is in dire need of refactoring.</p></li>\n<li><p>Drop through in switch statements is considered to be bad style. Certainly, it is rarely used in real applications. You've done it 2 or 3 times.</p></li>\n<li><p>Hard wiring today's date into a program is a terrible idea. Teaching students to hard wire environmental information is a really bad idea. </p></li>\n</ul>\n\n<p>I'd say that the task that you have set is <em>way too complicated</em> given the restrictions. At the very least, students need to understand static methods and method calls to undertake a task like this. They also need to be told about <code>System.currentTimeMillis()</code>.</p>\n\n<hr>\n\n<p>Given that the problem is set in concrete, and the students' knowledge is as stated, there's not much you can do to improve the readability of the solution, I'm afraid.</p>\n\n<p>The best you could do would be to show them what the ideal solution would look like ... if they were using a larger subset of Java. (And then maybe \"fess up\" to the fact that the problem was too hard.)</p>\n\n<hr>\n\n<p>Drop-through switch cases are bad style because drop-through is easy to miss. (And in fact, it is usually an error.) If you really want to use it, you should have a comment at each point where drop through is intended to occur; see <a href=\"http://www.oracle.com/technetwork/java/codeconventions-142311.html#468\" rel=\"nofollow\">http://www.oracle.com/technetwork/java/codeconventions-142311.html#468</a></p>\n\n<p>I will grant you that yours is an elegant solution ... but a more elegant one would be to use array lookup; e.g.</p>\n\n<pre><code> final static int[] DAYS_TO_START_OF_MONTH = {\n // Line them up neatly so that it is trivial to manually inspect\n // the constant expressions ...\n 0,\n 31,\n 31 + 28,\n 31 + 28 + 31,\n ...\n };\n\n public int daysToStartOfMonth(int month, boolean isLeapYear) {\n return DAYS_TO_START_OF_MONTH[month] + (month >= 2 && isLeapYear ? 1 : 0);\n }\n</code></pre>\n\n<p>Teaching people bad programming style is a bad idea period. A lot of students who graduate with a mathematics degree <strong>do</strong> end up in programming jobs ... and need remedial mentoring to help them unlearn their bad programming habits.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-30T05:53:52.113",
"Id": "3512",
"Score": "0",
"body": "Thank you for commenting on style issues. That was some of the answers I was waiting for here.\nThe fact, that dropping through switch-statements is bad style is new to me. I thought, that it might be an elegant way of doing this kind of stuff in this case.\nThough I don't want to teach them bad style, I have to say, that these are mathematics students and most of them will never ever use Java in there live again, but MATLAB, R and SAS."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-04T12:26:09.367",
"Id": "3581",
"Score": "0",
"body": "Once again, thank you for your suggestions and critical comments. I'll revise my sample code and include your points and finally explain it to my students. Your definition of that final array is a good idea. I'll take your answer as the accepted one -- though I'd like to take all of them as accepted."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-30T00:41:05.940",
"Id": "2167",
"ParentId": "2161",
"Score": "7"
}
},
{
"body": "<p>I would hardly agree to give such an exercise to first-year students at the knowledge level you describe. That's not how people <em>love</em> programming. But anyway, here are some suggestions:</p>\n\n<ul>\n<li><p>You can check the validity of the birth date in a much easier way:</p>\n\n<pre><code>if (month == 2) {\n inputOK = inputOK && (birthDay <= 28 ||\n birthYearWasLeap && birthDay <= 29);\n} else if (month == 1 || month == 3 || month == 5 || month == 7 ||\n month == 8 || month == 10 || month == 12) {\n inputOK = inputOK && (birthDay <= 31);\n} else if (month <= 12) {\n inputOK = inputOK && (birthDay <= 30);\n} else {\n inputOK = false; // month > 12\n}\n</code></pre>\n\n<p>or using <code>switch</code>:</p>\n\n<pre><code>int daysInMonth;\nswitch (month) {\n case 2:\n daysInMonth = (birthYearWasLeap ? 29 : 28);\n break;\n case 1:\n case 3:\n case 5:\n case 7:\n case 8:\n case 10:\n case 12:\n daysInMonth = 31;\n break;\n case 4:\n case 6:\n case 9:\n case 11:\n daysInMonth = 30;\n break;\n default: // invalid month\n daysInMonth = -1; // error value\n break;\n}\n\ninputOK = (birthDay <= daysInMonth); // fails if daysInMonth == -1\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-04T12:24:14.173",
"Id": "3580",
"Score": "0",
"body": "Doing it with a loop was one of my initial ideas, however I've chosen the switch-statement. Your cleaned switch is probably more readable than mine. Thank you for this."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-03T11:35:14.803",
"Id": "2207",
"ParentId": "2161",
"Score": "4"
}
},
{
"body": "<p>Given the restrictions of the problem, it looks a reasonable, but could definitely do with some improving:</p>\n\n<ul>\n<li>Are you sure none of the students have ever programmed before? Or may have asked for help from someone who has programmed before? Most of the maths students I was at university with knew at least a little bit of programming, and most went on to do jobs involving programming. That's less likely if this is an introductory course, but you want to make sure that if any of them HAVE heard about arrays and functions, you make it clear that your example is BAD without being more streamlined.</li>\n<li>Even without arrays, you can reduce duplication: collect the \"case\" statements together as Hosam Aly suggests; used named constants for the lengths of the months if they are used more than once</li>\n<li>Use comments to introduce NOW the things the students should be doing right from the start. Eg. if you DO fall through from a \"case\" statement, comment every time. Eg. If you hardcode the date, put a \"TODO: get date from system\" to make it clear that hardcoding the date is bad. Eg. If you don't validate every input, put another \"TODO:\" in. Etc. This can be valuable in teaching them to work towards a better program, but without it it may encourage them NOT to.</li>\n<li>Do NOT encourage the students to simplify leap year calculations. You're right, assuming a leap year every four years works, unless someone over 110 uses the program (since 1900, 1800 and 1700 are not leap years), but you should (if you must) explicitly validate and disallow anyone that old, or (preferably) calculate leap years correctly every time even in sample programs. You want to teach people to do it right from the start[1].</li>\n</ul>\n\n<p>[1] I assume you know this as you chose 1904 as the sample leap year, but not everyone reading may know for sure. FWIW, the correct rule is on wikipedia; it is every year divisible by four is a leap year, except that every year divisuble by 100 is NOT a leap year, except that every year divisible by 400 IS a leap year. But if you're not sure, don't take my word for it, CHECK. These people may never write code that needs to handle dates before 1900 or after 2100, but they should still be taught not to make assumptions without checking them clearly, and it will only confuse anyone who has dim or better memories of how to do it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-04T12:22:42.693",
"Id": "3579",
"Score": "0",
"body": "Thank you very much for these comments. I will revise my sample code and explain it to my students. Your suggestions of the TODO-comments is great. I asked the students and almost none of them have ever done some programming. The leap year rule has been made clear to all students in the task."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-03T11:51:56.380",
"Id": "2208",
"ParentId": "2161",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "2167",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-29T22:46:27.720",
"Id": "2161",
"Score": "3",
"Tags": [
"java",
"datetime"
],
"Title": "Days of life calculator for first-year mathematics students"
} | 2161 |
<blockquote>
<p>I remember once going to see [Srinivasa Ramanujan] when he was ill at Putney. I had ridden in taxi cab number 1729 and remarked that the number seemed to me rather a dull one, and that I hoped it was not an unfavorable omen. "No," he replied, "it is a very interesting number; it is the smallest number expressible as the sum of two cubes in two different ways." [G. H. Hardy as told in <a href="http://en.wikipedia.org/wiki/1729_%28number%29" rel="nofollow noreferrer">"1729 (number)"</a>]</p>
</blockquote>
<p>In <a href="http://www.forbes.com/2009/02/06/math-archimedes-churchill-opinions-contributors_0207_joseph_tartakovsky.html" rel="nofollow noreferrer">"Math Wrath"</a> Joseph Tartakovsky says about this feat:</p>
<blockquote>
<p>So what? Give me two minutes and my calculator watch, and I'll do the same without exerting any little gray cells.</p>
</blockquote>
<p>I don't know how Mr. Tartakovsky would accomplish that proof on a calculator watch, but the following is my scheme function that enumerates numbers starting at 1 and stops when it finds a number that is expressable in two seperate ways by summing the cubes of two positive numbers. And it indeeds returns 1729.</p>
<p>There are two areas where I would appreciate suggestions for improvement. One area is, being new to scheme, style and idiom. The other area is around the calculations. Sisc does not return exact numbers for roots, even when they could be.</p>
<p>For example <code>(expt 27 1/3)</code> yields 2.9999999999999996. But I do get exact results when cubing an exact number, <code>(expt 3 3)</code> yields <code>27</code>. My solution was to get the exact floor of a cube root and then test against the cube of the floor and the cube of the floor plus one, counting as a match if either match. This solution seems messy and hard to reason about. Is there a more straightforward way?</p>
<pre><code>; Find the Hardy-Ramanujan number, which is the smallest positive
; integer that is the sum of the cubes of two positivie integers in
; two seperate ways.
(define (hardy-ramanujan-number)
(let ((how-many-sum-of-2-positive-cubes
; while i^3 + 1 < n/1
; tmp := exact_floor(cube-root(n - i^3))
; if n = i^3 + tmp^3 or n = i^3 + (tmp + 1) ^3 then count := count + 1
; return count
(lambda (n)
(let ((cube (lambda (n) (expt n 3)))
(cube-root (lambda (n) (inexact->exact (expt n 1/3)))))
(let iter ((i 1) (count 0))
(if (> (+ (expt i 3) 1) (/ n 2))
count
(let* ((cube-i (cube i))
(tmp (floor (cube-root (- n cube-i)))))
(iter (+ i 1)
(+ count
(if (or (= n (+ cube-i (cube tmp)))
(= n (+ cube-i (cube (+ tmp 1)))))
1
0))))))))))
(let iter ((n 1))
(if (= (how-many-sum-of-2-positive-cubes n) 2)
n
(iter (+ 1 n))))))
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-19T14:21:53.743",
"Id": "7333",
"Score": "0",
"body": "give more examples on the topic"
}
] | [
{
"body": "<p>Your code looks mostly fine, I see a few very minor things to comment on:</p>\n\n<ul>\n<li><p>There's no need to define <code>cube</code> and <code>cube-root</code> at the innermost scope,</p></li>\n<li><p>Using <code>define</code> for internal functions makes it look a little clearer,</p></li>\n<li><p>This is related to the second part of your question: you're using <code>inexact->exact</code> on a floating point number which can lead to large rationals (in the sense that you allocate a pair of two big integers) -- it would be better to avoid this,</p></li>\n<li><p>Doing that still doesn't solve the extra test that you do -- but that's only because you're not certain if you have the right number of if you missed by 1. Given that it should be <em>close</em> to an integer, you can just use <code>round</code> and then do one check, saving you one test.</p></li>\n</ul>\n\n<p>Fixing the above, and doing it in one function that returns the number when it's found, and using some more \"obvious\" identifier names, I get this:</p>\n\n<pre><code>(define (hardy-ramanujan-number n)\n (define (cube n) (expt n 3))\n (define (cube-root n) (inexact->exact (round (expt n 1/3))))\n (let iter ([i 1] [count 0])\n (if (> (+ (cube i) 1) (/ n 2))\n (hardy-ramanujan-number (+ n 1))\n (let* ([i^3 (cube i)]\n [j^3 (cube (cube-root (- n i^3)))]\n [count (if (= n (+ i^3 j^3)) (+ count 1) count)])\n (if (= count 2) n (iter (+ i 1) count))))))\n</code></pre>\n\n<p>I'm running this on Racket, and it looks like it's about 10 times faster (50ms vs 5ms).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-30T02:02:11.673",
"Id": "3509",
"Score": "0",
"body": "+1 for not overengineering your solution. I was originally planning to write a solution that micro-optimised a couple of things, but your answer is very concise, and obviously plenty fast enough. Yay for simplicity!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-30T01:24:52.767",
"Id": "2169",
"ParentId": "2162",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "2169",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-29T23:55:04.117",
"Id": "2162",
"Score": "8",
"Tags": [
"scheme"
],
"Title": "Find the Hardy–Ramanujan number using R5RS scheme"
} | 2162 |
<p>The objective was the following to be solved in Python:</p>
<blockquote>
<p>Given a string, def a function that
returns another string with the vowels
(upper or lowercase) replaced by
0,1,2,3,4 respectively.</p>
<hr>
<p>Example input:</p>
<pre><code>"bB nN aei ou AEIOU"
</code></pre>
<p>Desired Output:</p>
<pre><code>"bB nN 012 34 01234"
</code></pre>
<hr>
</blockquote>
<p>This is in fact quite trivial and can be solved in several ways, one way may be this:</p>
<pre><code>def crypt(s):
vow = ["a","e","i","o","u"]
stringL = []
for x in s:
if x in vow or x.lower() in vow:
stringL.append(str(vow.index(x.lower())))
else:
stringL.append(x)
return "".join(stringL)
</code></pre>
<p>I was told this was over-complicated for such a simple task, that code like this would be difficult to debug etc.</p>
<p>Would you consider this approach a "bad" one, which way would you have gone instead, is it unclear?</p>
| [] | [
{
"body": "<p>The calls to append, index, join, str are just noise.</p>\n\n<p>Here's the same idea but with a map and a generator expression:</p>\n\n<pre><code>def crypt(s):\n m = {\"A\": \"0\", \"E\": \"1\", \"I\": \"2\", \"O\": \"3\", \"U\": \"4\"}\n return \"\".join(m[c.upper()] if c.upper() in m else c for c in s)\n</code></pre>\n\n<p>It's a little less noisy.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-30T01:36:20.253",
"Id": "3508",
"Score": "2",
"body": "Use the dictionary .get() method instead the m[x] if x in m else y bit."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-30T00:40:31.740",
"Id": "2165",
"ParentId": "2164",
"Score": "6"
}
},
{
"body": "<p>Use <a href=\"https://docs.python.org/2/library/string.html#string.maketrans\" rel=\"nofollow noreferrer\"><code>string.maketrans()</code></a>.</p>\n\n<pre><code>from string import maketrans \n\ninput = \"aeiouAEIOU\"\noutput = '0123401234'\ntrans = maketrans(input,output)\nstr = 'This is a Q&A site, not a discussiOn forUm, so please make sure you answer the question.'\nprint str.translate(trans)\n</code></pre>\n\n<p>Output:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>Th2s 2s 0 Q&0 s2t1, n3t 0 d2sc4ss23n f3r4m, s3 pl10s1 m0k1 s4r1 y34 0nsw1r th1 q41st23n.\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-30T01:14:56.297",
"Id": "2168",
"ParentId": "2164",
"Score": "14"
}
},
{
"body": "<p>I think in this case you're best off just writing out the mapping -- there are only ten letter/digit pairs, and writing code to generate that mapping doesn't buy you much.</p>\n\n<pre><code>def crypt(s):\n substitutions = {\n 'a' : '0',\n 'e' : '1',\n 'i' : '2',\n 'o' : '3',\n 'u' : '4',\n 'A' : '0',\n 'E' : '1',\n 'I' : '2',\n 'O' : '3',\n 'U' : '4'\n }\n\n for before, after in substitutions.items():\n s = s.replace(before, after)\n\n return s\n</code></pre>\n\n<p>If you were writing a more general transliteration tool, say, with more complicated <code>substitution</code> rules, then the situation would be different. It's fun to come up with neat ways to build that mapping... for instance:</p>\n\n<pre><code>substitutions = dict(zip('aeiou','01234') + zip('AEIOU', '01234'))\n</code></pre>\n\n<p>Cute, except it isn't -- you're going to hate yourself in a couple weeks (or days!) when someone comes along with \"AND SOMETIMES Y!!!\", right?</p>\n\n<p>Given the small scale of the problem statement, I'd say just spit out the mapping and be done with it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-30T06:06:51.617",
"Id": "3514",
"Score": "0",
"body": "Nice answer thanks! `just spit out the mapping and be done with it.` agreed! This was a quick exercise we did on class, just got hung up with it. Thanks again."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-30T02:05:37.973",
"Id": "2170",
"ParentId": "2164",
"Score": "2"
}
},
{
"body": "<p>Yet another way to do this using duck typing.</p>\n\n<pre><code>def crypt(s):\n LUT = {\"A\": \"0\", \"E\": \"1\", \"I\": \"2\", \"O\": \"3\", \"U\": \"4\"}\n ns = \"\"\n for x in s:\n try:\n ns += LUT[x.upper()]\n except KeyError:\n ns += x\n return ns\n</code></pre>\n\n<hr>\n\n<p>Just for the sake of it I decided to run each method presented here for 100000 cycles with timeit.</p>\n\n<p>The results were interesting, learnCodes was the fastest by a long shot.</p>\n\n<pre><code> mine 1.431309\n\n ribby 1.314431\n\n pat 0.631507\n\n learnCode 0.124485\n</code></pre>\n\n<hr>\n\n<pre><code>#my method\ndef crypt(s):\n LUT = {\"A\": \"0\", \"E\": \"1\", \"I\": \"2\", \"O\": \"3\", \"U\": \"4\"}\n ns = \"\"\n for x in s:\n try:\n ns += LUT[x.upper()]\n except:\n ns += x\n return ns\n\n#ribbys method\ndef crypt2(s):\n m = {\"A\": \"0\", \"E\": \"1\", \"I\": \"2\", \"O\": \"3\", \"U\": \"4\"}\n return \"\".join(m[c.upper()] if c.upper() in m else c for c in s)\n\n#pats method\ndef crypt3(s):\n substitutions = {\n 'a' : '0',\n 'e' : '1',\n 'i' : '2',\n 'o' : '3',\n 'u' : '4',\n 'A' : '0',\n 'E' : '1',\n 'I' : '2',\n 'O' : '3',\n 'U' : '4'\n }\n for before, after in substitutions.items():\n s = s.replace(before, after)\n return s\n\n#learnCodes method\nfrom string import maketrans \ndef crypt4(s):\n input = \"aeiouAEIOU\"\n output = '1234512345'\n trans = maketrans(input,output)\n return s.translate(trans)\n\nimport timeit\nprint \"volting %f\" %timeit.Timer(\"crypt('bB nN aei ou AEIOU')\", \"from __main__ import crypt\").timeit(100000)\nprint \"ribby %f\" %timeit.Timer(\"crypt2('bB nN aei ou AEIOU')\", \"from __main__ import crypt2\").timeit(100000)\nprint \"pat %f\" %timeit.Timer(\"crypt3('bB nN aei ou AEIOU')\", \"from __main__ import crypt3\").timeit(100000)\nprint \"learnCode %f\" %timeit.Timer(\"crypt4('bB nN aei ou AEIOU')\", \"from __main__ import crypt4\").timeit(100000)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-30T13:48:17.870",
"Id": "3524",
"Score": "1",
"body": "Please don't use except: you'll catch any exception. Catch the KeyError specifically."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-30T14:32:55.457",
"Id": "3527",
"Score": "0",
"body": "I usually don't... it slipped my mind!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-30T21:54:59.767",
"Id": "3530",
"Score": "0",
"body": "That's interesting, thanks for doing the comparison. :) I wonder why `maketrans` is so fast?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-01T00:41:57.980",
"Id": "3531",
"Score": "0",
"body": "Thank you for another giving another approach and for taking the time for timing them all! +1! (BTW which machine did you run it in? It's so much faster than mine!)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-01T11:59:47.650",
"Id": "3533",
"Score": "0",
"body": "@Trufa your welcome! The test machine is nothing special just an [E8500](http://ark.intel.com/Product.aspx?id=33911) with 8GB RAM running Windows 7 x64"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-30T12:15:45.317",
"Id": "2181",
"ParentId": "2164",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "2168",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-30T00:24:30.360",
"Id": "2164",
"Score": "11",
"Tags": [
"python",
"strings"
],
"Title": "Change upper or lowercase vowels to [0,1,2,3,4] respectively and leave the rest the same"
} | 2164 |
<p>I have been using the following function (in the kohana html class in a table) to generate tables.</p>
<pre><code>function table($columns,$reverse=false,$fill=false,array $attr=null){
$c = '';
//ugly hack, looking for fix
$max=sizeof(max($columns));
for($i=0;$i<sizeof($columns);$i++){
$column = $columns[$i];
if($fill==true){
$l = ($max-sizeof($column));
for($ii=0;$ii<$l;$ii++){
array_push($column,'');
}
}
if($reverse==true){
$columns[$i] = array_reverse($column);
}else{
$columns[$i] = $column;
}
}
for($i=0,$l=sizeof($columns);$i<$l;$i++){
$column = $columns[$i];
$c.="<tr>";
for($ii=0,$ll=sizeof($column);$ii<$ll;$ii++){
$c.="<td>".$column[$ii]."</td>";
}
$c.="</tr>";
}
return "<table".html::attributes($attr).">".$c."</table>";
}
</code></pre>
<p>And then I have been calling it like so:</p>
<pre><code>echo html::table(array(
array('colunm 1 row 1','colunm 2 row 1'),
));
</code></pre>
<p>And a reversed table that auto fills the columns.</p>
<pre><code>echo html::table(array(
array('colunm 1 row 1','colunm 2 row 1'),
array('column 1 row 2','column 2 row 2')
),true,true);
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-31T00:06:42.447",
"Id": "4230",
"Score": "0",
"body": "There's also [PEAR's HTML_Table](http://pear.php.net/package/HTML_Table) package, if you're into that sort of thing. :-)"
}
] | [
{
"body": "<ul>\n<li>Some of the variable names could benefit from being slightly less terse.</li>\n<li>Aren't you passing in an array of rows? Each element in the array is then an array of columns.</li>\n<li>What is max? Is it trying to find the row with the most columns? Either rename to something more self-documenting or add a comment.</li>\n<li>array_map may be worth a look and could feasibly allow for reverse to be replaced with a callback function.</li>\n<li><p>Consider changing the last lines of the function to:</p>\n\n<pre><code>return \"<table\".html::attributes($attr).\">\".$c.\"</table>\";\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-06T02:39:19.593",
"Id": "3647",
"Score": "0",
"body": "I'm not sure what I was thinking for the return statement. Or rather I wasn't thinking %). Also, yes I'm passing in an array of rows which contains an array of columns."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-06T02:42:17.347",
"Id": "3648",
"Score": "0",
"body": "Yes max is attempting to find the max number of columns. Basically if you reverse a table with out all the rows having the same number of columns, the table will fill to the left. By passing in true to `$fill` it adds additional empty cells to the end of table so it doesn't fill to the left. What would you advise for a naming alternative to `$max`? That's the php function name so I thought it was well suited."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-06T12:51:46.867",
"Id": "3658",
"Score": "0",
"body": "Perhaps $max could be called $num_tbl_columns since it's the number of columns in the table."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-01T14:24:10.200",
"Id": "2188",
"ParentId": "2171",
"Score": "3"
}
},
{
"body": "<p>replace for loops with <a href=\"http://php.net/manual/en/control-structures.foreach.php\" rel=\"nofollow\">foreach</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-06T02:52:28.667",
"Id": "3651",
"Score": "0",
"body": "I would love to use foreach, but I am unsure how to use it in place of the first for loop. I am reassigning itself as a reversed array at the end of the loop. I don't believe php allows you to reassign the looping variable inside a foreach."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-06T17:03:32.327",
"Id": "3662",
"Score": "0",
"body": "Actually, you can using foreach($array as $key => &$value)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-05T20:53:12.720",
"Id": "2264",
"ParentId": "2171",
"Score": "1"
}
},
{
"body": "<p>Didn't test, but I would write it something like this:</p>\n\n<pre><code>function table($rows, $reverse = false, $fill = false, array $attr = null) {\n $c = '';\n $max_cols = sizeof(max($columns));\n\n foreach ($rows as $columns) {\n if ($fill && sizeof($columns) < $max_cols) {\n $columns = array_merge($columns, array_fill(0, $max_cols - sizeof($columns), ''));\n }\n if ($reverse) {\n $columns = array_reverse($columns);\n }\n $c .= '<tr><td>' . implode('</td><td>', $columns) . '</td></tr>';\n }\n\n return '<table>' . $c . '</table>';\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-06T21:36:23.647",
"Id": "3667",
"Score": "0",
"body": "Sweet, I wasn't aware of `array_fill` or `implode`. Very convenient and it shortens the function by a lot. There was one bug `$fill_to` should be `$max_cols`. I decided to change some of the naming from `$columns` to `$rows`. Here is the edited version: http://codepad.org/UQyynzqW Thanks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-07T07:26:40.197",
"Id": "3671",
"Score": "0",
"body": "that's what i get for not testing. fixed the variable, and naming to make more sense."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-06T17:09:43.113",
"Id": "2288",
"ParentId": "2171",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "2288",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-30T02:44:51.897",
"Id": "2171",
"Score": "6",
"Tags": [
"php",
"php5"
],
"Title": "PHP Table generation"
} | 2171 |
<p>In the situation where I am looping through a collection looking for an item, is it better practice to <code>break</code> before I <code>return</code> or should I <code>break</code> and then <code>return</code>?</p>
<p>Return during loop:</p>
<pre><code>foreach(string item in items)
{
string[] split = item.Split('|');
if(split[0] == searchFor)
return split[1];
}
return null;
</code></pre>
<p>Break then return:</p>
<pre><code>string result = null;
foreach(string item in items)
{
string[] split = item.Split('|');
if(split[0] == searchFor)
{
result = split[1];
break;
}
}
return result;
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-29T19:58:25.763",
"Id": "3515",
"Score": "3",
"body": "`return (from split in items.Select(item => item.Split('|')) where split[0] == searchFor select split[1]).FirstOrDefault();`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-29T20:11:19.283",
"Id": "3516",
"Score": "0",
"body": "I like the second because it would be easier to add logging."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-30T06:07:09.457",
"Id": "3517",
"Score": "0",
"body": "'Better' or 'Best' is quite subjective."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-04T20:25:29.237",
"Id": "3603",
"Score": "0",
"body": "`return (from item in items where item.StartsWith(searchFor + '|') select item.Split('|')[1]).FirstOrDefault();` is even shorter — but is it more readable? Doubtful."
}
] | [
{
"body": "<p>If you break, you need to introduce an additional variable. In my opinion, it's more clear to return as soon as possible from any function.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-29T19:57:52.540",
"Id": "3518",
"Score": "1",
"body": "Unless of course you have objects which need to be cleaned up before returning."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-29T20:01:07.687",
"Id": "3519",
"Score": "3",
"body": "@McMinton: In which case you probably want a `try/finally` anyway so that they will be cleaned up if an exception is thrown."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-29T20:01:21.237",
"Id": "3520",
"Score": "0",
"body": "@McMinton: I use `using` or `finally` blocks for those."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-29T19:56:12.567",
"Id": "2173",
"ParentId": "2172",
"Score": "18"
}
},
{
"body": "<p>No main difference, and as far as I'm concerned no real advantage of using one or the other, besides readability, purism.</p>\n\n<p>Check out this quote I found:</p>\n\n<blockquote>\n <p>True purists will say that a function\n should only have a single entry (at\n the top) and exit (at the bottom)\n point.</p>\n \n <p>Really, it gets down to whether or not\n you want to continue executing your\n code after a certain loop condition\n has happened. Those that use returns\n within a loop (and I am guilty of the\n occasional usage myself) simply want a\n quick way to exit the function without\n writing additional logic to support\n the \"single exit\" philosophy.</p>\n \n <p>Remember, they do have different\n purposes as BREAK will only exit the\n loop that you are in but execution of\n the function continues.</p>\n</blockquote>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-29T19:56:28.900",
"Id": "2174",
"ParentId": "2172",
"Score": "0"
}
},
{
"body": "<p>I would return directly, it's more direct and more clear. You dont need to add an extra variable and have less possibilty to make a mistake.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-29T19:56:46.383",
"Id": "2175",
"ParentId": "2172",
"Score": "0"
}
},
{
"body": "<p>If you know that that is the end of the function then by all means return. There is no nead to do a single exit point. That is old school nonsense.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-30T10:43:28.397",
"Id": "3522",
"Score": "0",
"body": "\"No need to do a single exit point\" - that is ridiculous. Stick that code into a function with > 200 lines and then try to make that statement. It is by all means a best practice to have a single exit point. It makes for cleaner code and forces you to think about the structure of the program in terms of readability."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-23T08:41:57.493",
"Id": "58685",
"Score": "1",
"body": "@AdamSpicer if you're concerned about readability you shouldn't be writing 200-line functions in the first place"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-29T19:57:13.630",
"Id": "2176",
"ParentId": "2172",
"Score": "0"
}
},
{
"body": "<p>I think there's no \"best practice\" on this - you'll find people supporting both possibilities.</p>\n\n<p>I personally would take the first approach as the control flow is better expressed using the return. You simply know, that if the condition is true, no further code will be executed after the loop.<br>\nAnd code which is clearer and thus easier to understand should be more maintable.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-29T19:57:29.167",
"Id": "2177",
"ParentId": "2172",
"Score": "0"
}
},
{
"body": "<p>Best practice is to return as early as you can. The first example is clearer to read and you're not dragging around a variable you don't actually need.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-29T19:59:11.500",
"Id": "2178",
"ParentId": "2172",
"Score": "3"
}
},
{
"body": "<p>Often, the specific problem dictates the solution.</p>\n\n<ul>\n<li><p>Immediately returning can save levels of nested conditions, greatly improving legibility of the code.</p></li>\n<li><p>Waiting until the end allows for simpler logging, and sometimes simpler debugging.</p></li>\n<li><p>If there's a non-trivial probability you'll want to add further logic to the function later, then don't return until the end.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-01T22:22:32.820",
"Id": "2192",
"ParentId": "2172",
"Score": "4"
}
},
{
"body": "<p>Ummm... use Linq?</p>\n\n<pre><code>return items.Select(item => item.Split('|'))\n .Where(split => (split[0] == searchFor))\n .Select(split => split[1])\n .FirstOrDefault();\n</code></pre>\n\n<p>or</p>\n\n<pre><code>searchFor += \"|\";\nreturn items.Where(item => (item.StartsWith(searchFor)))\n .Select(item => item.Substring(searchFor.Length))\n .FirstOrDefault();\n</code></pre>\n\n<p>BTW the second implementation is about 17% faster than the OP's explicit loop.</p>\n\n<p>I realize this doesn't directly answer the question, but I thought I'd post it here for completeness. And to be cool. All the kids are replacing loops with LINQ these days.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-23T01:53:27.020",
"Id": "35956",
"ParentId": "2172",
"Score": "2"
}
},
{
"body": "<p>For this trivial example, it hardly matters, but if the function were much more complicated it would make more sense to return as quickly as possible, handling any cleanup activity in a finally block. </p>\n\n<p>Opportunistic return is an important practice for avoiding the <a href=\"http://lostechies.com/chrismissal/2009/05/27/anti-patterns-and-worst-practices-the-arrowhead-anti-pattern/\" rel=\"nofollow\">arrow anti-pattern</a> (see technique #4 described <a href=\"http://www.codinghorror.com/blog/2006/01/flattening-arrow-code.html\" rel=\"nofollow\">in this article</a>). Using opportunistic return allows you to transform nested ifs into parallel/progressive ifs and gates, which reduces <a href=\"http://en.wikipedia.org/wiki/Cyclomatic_complexity\" rel=\"nofollow\">cyclomatic complexity</a> and (it's fairly well established) the likelihood of logic errors.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-23T03:15:15.253",
"Id": "35959",
"ParentId": "2172",
"Score": "0"
}
},
{
"body": "<p>Which is better is fairly subjective and depends upon context.</p>\n\n<p>But...your code looks like it is the body of a procedure that looks like this...</p>\n\n<pre><code>public string Search(string searchFor, IEnumerable<string>items){\n foreach(string item in items) {\n string[] split = item.Split('|');\n if(split[0] == searchFor)\n return split[1];\n }\n return null;\n}\n</code></pre>\n\n<p>Which is quite common, but IMO also quite wrong. By returning <code>null</code> when the value is not found, you are giving two semantic (and entirely opposite) meanings to the returned value: the value found, and no value was found.</p>\n\n<pre><code>public boolean TrySearch(string searchFor, IEnumerable<string>items, \n out string stringFound){\n stringFound=null;\n foreach(string item in items) {\n string[] split = item.Split('|');\n if(split[0] == searchFor){\n stringFound=split[0];\n return true;\n }\n }\n return false;\n}\n</code></pre>\n\n<p>Is much safer and clearer because it lets the caller know that the return value may or may not be usable and encourages the check for <code>null</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-23T03:58:01.660",
"Id": "35962",
"ParentId": "2172",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "2173",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-29T19:54:07.993",
"Id": "2172",
"Score": "14",
"Tags": [
"c#",
"strings"
],
"Title": "Looping through a collection"
} | 2172 |
<p>I managed to get something up and running, but I've no idea whether there are better ways to do this. I've spent all morning trying to figure out the best way to use parameters (allowing objects from the pipeline, or to be passed in, allowing overriding the <code>modelName</code>, etc.) and trying to understand differences between a Cmdlet and just a function, so feedback in that area in particular would be good.</p>
<p><a href="http://code.dantup.com/PSRazor" rel="noreferrer">Bitbucket</a></p>
<pre><code>function Format-Razor()
{
<#
.SYNOPSIS
Formats a set of objects using the Razor Engine.
.DESCRIPTION
The Format-Razor function formats a set of objects using a supplied template using the Razor Engine created for ASP.NET.
.NOTES
Author: Danny Tuppeny (DanTup)
.LINK
http://code.dantup.com/PSRazor
.PARAMETER templateText
The Razor template text to be processed for each object.
.PARAMETER modelName
The name to use for access the data object in the template. Defaults to "Model".
.EXAMPLE
Get-Command | Select -Last 10 | Format-Razor "Command name: @Model.Name Loop: @for (int i = 0; i < 5; i++) { <y>@i</y> }"
.EXAMPLE
Get-Command | Select -Last 10 | Format-Razor "Command name: @Data.Name (@Data.CommandType)" -modelName "Data"
.EXAMPLE
Format-Razor "Command name: @Peter.Name Loop: @for (int i = 0; i < 5; i++) { <y>@i</y> }" $host -modelName "Peter"
#>
[CmdletBinding()]
PARAM(
[Parameter(Mandatory=$true)] [string] $templateText,
[Parameter(Mandatory=$true, ValueFromPipeline=$true)] [PSObject] $model,
[Parameter(Mandatory=$false)] [string] $modelName = "Model"
)
BEGIN
{
# Load the MVC assembly so we can access the Razor classes
[System.Reflection.Assembly]::LoadWithPartialName("System.Web.Razor") | Out-Null
# Create a StringReader for the template, which we'll need to pass into the Razor Engine
$stringReader = New-Object System.IO.StringReader($templateText)
$engine = CreateRazorTemplateEngine
$razorResult = $engine.GenerateCode($stringReader)
$results = CompileCode($razorResult);
# If the template doesn't compile, we can't continue
if ($results.Errors.HasErrors)
{
throw $results.Errors
}
# Create an instance of the Razor-generated template class that will be used in PROCESS for formatting
$template = CreateTemplateInstance($results)
}
PROCESS
{
# Set the model to the current object, using the $modelName param so the user can customise it
$template.$modelName = $model
# Execute the code, which writes the output to our buffer
$template.Execute()
# "Return" the output for this item
$template.Buffer.ToString()
# Clear the buffer ready for the next object
$template.Buffer.Clear() | Out-Null
}
}
# Export the fuction for use by the user
Export-ModuleMember -Function Format-Razor
function CreateRazorTemplateEngine()
{
# Create an instance of the Razor engine for C#
$language = New-Object System.Web.Razor.CSharpRazorCodeLanguage
$host = New-Object System.Web.Razor.RazorEngineHost($language)
# Set some default properties for the Razor-generated class
$host.DefaultBaseClass = "TemplateBase" # This is our base class (created below)
$host.DefaultNamespace = "RazorOutput"
$host.DefaultClassName = "Template"
# Add any default namespaces that will be useful to use in the templates
$host.NamespaceImports.Add("System") | Out-Null
New-Object System.Web.Razor.RazorTemplateEngine($host)
}
function CompileCode($razorResult)
{
# HACK: To avoid shipping a DLL, we're going to just compile our TemplateBase class here
$baseClass = @"
using System.IO;
using System.Text;
public abstract class TemplateBase
{
public StringBuilder Buffer { get; set; }
public StringWriter Writer { get; set; }
public dynamic $modelName { get; set; }
public TemplateBase()
{
this.Buffer = new StringBuilder();
this.Writer = new StringWriter(this.Buffer);
}
public abstract void Execute();
public virtual void Write(object value)
{
WriteLiteral(value);
}
public virtual void WriteLiteral(object value)
{
Buffer.Append(value);
}
}
"@
# Set up the compiler params, including any references required for the compilation
$codeProvider = New-Object Microsoft.CSharp.CSharpCodeProvider
$assemblies = @(
[System.Reflection.Assembly]::LoadWithPartialName("System.Core").CodeBase.Replace("file:///", ""),
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.CSharp").CodeBase.Replace("file:///", "")
)
$compilerParams = New-Object System.CodeDom.Compiler.CompilerParameters(,$assemblies)
# Compile the template base class
$templateBaseResults = $codeProvider.CompileAssemblyFromSource($compilerParams, $baseClass);
# Add the (just-generated) template base assembly to the compile parameters
$assemblies = $assemblies + $templateBaseResults.CompiledAssembly.CodeBase.Replace("file:///", "")
$compilerParams = New-Object System.CodeDom.Compiler.CompilerParameters(,$assemblies)
# Compile the Razor-generated code
$codeProvider.CompileAssemblyFromDom($compilerParams, $razorResult.GeneratedCode)
}
function CreateTemplateInstance($results)
{
# Grab the assembly that contains the Razor-generated classes
$assembly = $results.CompiledAssembly
# Create an instance of our Razor-generated class (this name is hard-coded above)
$type = $assembly.GetType("RazorOutput.Template")
[System.Activator]::CreateInstance($type)
}
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-30T11:54:51.267",
"Id": "2180",
"Score": "18",
"Tags": [
"shell",
"powershell",
"razor"
],
"Title": "PowerShell module for formatting objects using Razor"
} | 2180 |
<p>I've never been satisfied with any of the possible <code>sprintf()</code>-like functions in C++:</p>
<ul>
<li><code>sprintf()</code> is a C function and it's very unsafe and dangerous to use (undefined behavior all over the place)</li>
<li><code>boost::format</code> is too slow and awkward to use (think of the <code>%</code> syntax)</li>
<li><code>iostream</code> is <strong>extremely</strong> awkward to use</li>
</ul>
<p>So I came up with my own. Those are my requirements:</p>
<ul>
<li>Inspired by C#'s format function</li>
<li>Must never fail at run time, never crash and never have undefined behavior, no matter what you call it with. Should fail at compile time whenever possible instead.</li>
<li>Must be expandable (if you create a class <code>Person</code>, then you can pass a <code>Person</code> object to the function)</li>
<li>Must be fast</li>
<li>The format string must be easy to localize</li>
<li>The format string must not have placeholders whose syntax depends on the argument type (ie, no <code>%s</code> vs <code>%d</code>)</li>
<li>Must have a fairly "normal" syntax (no % like boost::format)</li>
</ul>
<p>I'm interested in reviews on the satisfaction of the requirements above. I'm especially interested in reviews from the end-user perspective and less about the internals of the code (i.e., the code that is hidden from the end user).</p>
<p>A few examples:</p>
<pre><code>// Returns a string containing "Hello my name is Andreas and I'm 22 years old".
Format("Hello my name is {0} and I'm {1} years old.", "Andreas", 22);
// Returns "Hex: 0xA"
Format("Hex: {0:x}", 10);
// Fails to compile: Person is not a built in type and doesn't have any function to convert to string
struct Person {};
Person p;
Format("Person: {0}", p);
// "Person: Andreas Bonini" [Note: if it was {0:abc}, then Person::ToString("abc") would have been called]
struct Person {
Person(string first, string last) : First(first), Last(last) {}
string ToString(const string &options) const { return Format("{0} {1}", First, Last); }
string First, Last;
};
Person p("Andreas", "Bonini");
Format("Person: {0}", p);
</code></pre>
<p>These are my unit tests:</p>
<pre><code>TEST(Format)
{
CHECK_EQUAL(Format("Testing {0} test {0}{0} test", 123), "Testing 123 test 123123 test");
CHECK_EQUAL(Format("{0}", (const char *)NULL), "{null}");
CHECK_EQUAL(Format("Test double {0} - {1}", 0, 1), "Test double 0 - 1");
CHECK_EQUAL(Format("Test options: {0:x}", 0xABC), "Test options: 0xABC");
CHECK_EQUAL(Format("Test malformed: {0:x", 0xABC), "Test malformed: {0:x");
CHECK_EQUAL(Format("Check stupid: {0:bmkldmbkglmbgk902 r iko4om wkl lfs s,gf, gfsdg fsd ! @ G}", "stupid"), "Check stupid: stupid");
CHECK_EQUAL(Format("Check missing: {1}", 0), "Check missing: {Argument 1}");
CHECK_EQUAL(Format("Master format test {0} {1} {2 {2:2} {3} {4:e} {5:x} {0}", 0, 1234.55566f, 1.11111f, "lolz", "a'b", 0xABCDEFABCDEFULL),
"Master format test 0 1234.56 {2 1.11 lolz 'a\\'b' 0xABCDEFABCDEF 0");
CHECK_EQUAL(Format("{0:x}", 0xFFFFFFFF), "0xFFFFFFFF");
}
</code></pre>
<p>Note that due to C++ limitations (lack of variadic templates) the code isn't exactly pretty. Also the code is part of a bigger library so it won't compile of its own.</p>
<pre><code>/****************************************************************************************
* Prism
* File Name: Format.h
* Added on: 2010/09/26 14:09:52
*/
/***************************************************************************************/
#pragma once
#include <boost/type_traits.hpp>
/***************************************************************************************/
/* This is the main formatting function; it is 100% type safe and hopefully fast. It's inspired
* by C#'s String.Format() function and has pretty much the base syntax:
*
* string format = Format("Hello {0}, my name is {1}.", "you", "me");
*
* More precisely the placeholder can be:
* {n[,a][:o]}
*
* n = Number of argument, starting from 0
* a = Alignment; if it's positive it is right aligned, otherwise left aligned
* o = Options
*
* The arguments themselves to the conversion and handle the options. For each passed argument the
* .ToString(options) function will be called, and the returned value will be used for replacing the
* placeholder.
*
* Of course this won't work with built in types such as int. The conversion for those is implemented
* in the library, which supports the following types (and options).
*
* The 'a' option means alternative.
*
* -- bool --
* - No options: prints "true" or "false".
* - a: prints "yes" or "no".
*
* -- char --
* - No options: prints the character normally
* - a: prints the character as a number.
*
* -- short, int, long --
* - No options: prints the number normally
* - b: prints the number as binary
* - x: prints the number as hex, prepending "0x"
* - X: prints the number as hex, without "0x"
* - ,: prints the number with a comma as thousands separator
*
* -- float, double --
* - No options: prints the number normally
* - A number (N): equivalent to %.Nf
* - %: multiplies by 100, adds a % sign
*
* -- string --
* - No options: prints the string normally
* - e: Escapes the string for use in MySQL queries.
*
* >>> Error handling <<<
* - Not enough arguments: FATAL() is called
* - Too many arguments: not an error; extra arguments are ignored
* - Unknown options: not an error; unknown options may not be implemented yet
*/
/***************************************************************************************/
namespace Prism
{
namespace Text
{
namespace Conversion
{
template<class T>
string IntToString(T _val, bool hasSign, const string &options)
{
typename boost::make_signed<T>::type valSigned = _val;
typename boost::make_unsigned<T>::type valUnsigned = _val;
if(options == ",")
return GetCommaNumber(hasSign ? valSigned : valUnsigned);
static const char itoa_tab[10] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
static const char xtoa_tab[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
static const char btoa_tab[2] = { '0', '1' };
int base;
string ret;
const char *tab;
char tmp[128];
char *ptr = &tmp[sizeof(tmp) - 1];
*ptr = 0;
/* Parse options, set up variables */
if (options == "b") {
base = 2;
ret.reserve(64 + 1);
hasSign = false;
tab = btoa_tab;
} else if (options == "x") {
base = 16;
ret.reserve(16 + 2 + 1);
ret.push_back('0');
ret.push_back('x');
hasSign = false;
tab = xtoa_tab;
} else if (options == "X") {
base = 16;
ret.reserve(16 + 2);
hasSign = false;
tab = xtoa_tab;
} else {
base = 10;
ret.reserve(22);
tab = itoa_tab;
}
/* If it's negative */
if(hasSign && valSigned < 0)
{
ret.push_back('-');
valSigned = Math::Abs(valSigned);
valUnsigned = valSigned;
}
do {
*--ptr = tab[valUnsigned % base];
valUnsigned /= base;
} while (valUnsigned);
while(*ptr)
ret.push_back(*ptr++);
return ret;
}
inline string ToString(const char *s, const string &options)
{
if(!s)
s = "{null}";
if(options == "e")
return SqlSafeCopy(s);
return s;
}
inline string ToString(char *s, const string &options)
{
return ToString((const char *)s, options);
}
template<typename T>
string ToString(const T &val, const string &options) { return val.ToString(options); }
template<> string ToString(const char &val, const string &options);
template<> string ToString(const bool &val, const string &options);
template<> string ToString(const float &val, const string &options);
template<> string ToString(const double &val, const string &options);
template<> inline string ToString(const int64 &val, const string &options) { return IntToString(val, true, options); }
template<> inline string ToString(const uint64 &val, const string &options) { return IntToString(val, false, options); }
template<> inline string ToString(const int32 &val, const string &options) { return IntToString(val, true, options); }
template<> inline string ToString(const uint32 &val, const string &options) { return IntToString(val, false, options); }
template<> inline string ToString(const int16 &val, const string &options) { return IntToString(val, true, options); }
template<> inline string ToString(const uint16 &val, const string &options) { return IntToString(val, false, options); }
template<> inline string ToString(const float &val, const string &options) { return ToString(static_cast<double>(val), options); }
template<> inline string ToString(const string &s, const string &options)
{
if(options == "e")
return SqlSafeCopy(s);
return s;
}
}
}
}
/***************************************************************************************/
namespace Prism
{
namespace Text
{
struct PlaceholderData
{
PlaceholderData(int start, int end, const string &argument, int &final_length) : Start(start), End(end), Argument(argument)
{
final_length = final_length - (End - Start) + Argument.length();
}
int Start;
int End;
string Argument;
};
extern string _FinalizeFormat(const string &str, const vector<PlaceholderData> &placeholders, int final_length);
extern bool _FindPlaceholder(const char *str, int &start, const int &end, int &num, int &placeholder_length, string &options);
#include "FormatNoVariadicTemplates.h"
}
}
/***************************************************************************************/
</code></pre>
<pre><code>/****************************************************************************************
* Prism
* File Name: Format.cpp
* Added on: 2010/09/26 14:56:35
*/
/***************************************************************************************/
#include "Prism.h"
#include "Format.h"
#include "Text.h"
#if COMPILER == COMPILER_MSVC
#pragma warning (disable: 4996)
#endif
namespace Prism
{
namespace Text
{
/***************************************************************************************/
namespace Conversion
{
template<>
string ToString(const char &val, const string &options)
{
const bool alternative = (options == "a");
if (!alternative)
return string(1, val);
else
return ToString((int)val, "");
}
template<>
string ToString(const bool &val, const string &options)
{
static const char *normalStrings[] = { "true", "false" };
static const char *alternativeStrings[] = { "yes", "no" };
const bool alternative = (options == "a");
const char **strings = alternative ? alternativeStrings : normalStrings;
if (val)
return strings[0];
else
return strings[1];
}
template<>
string ToString(const double &val, const string &options)
{
if (options[0] == '%')
return ToString(val * 100, options.substr(1)) + "%";
char ret[128];
if (IsDigit(options[0]) && !options[1]) {
char format[5];
format[0] = '%';
format[1] = '.';
format[2] = options[0];
format[3] = 'f';
format[4] = '\0';
sprintf(ret, format, val);
} else
sprintf(ret, "%g", val);
return ret;
}
}
/***************************************************************************************/
string _FinalizeFormat(const string &str, const vector<PlaceholderData> &placeholders, int final_length)
{
if(placeholders.empty())
return str;
string ret;
ret.reserve(final_length);
int current_position = 0;
const char *ptr = str.data();
foreach (const PlaceholderData &placeholder, placeholders) {
if (placeholder.Start != current_position) {
const int bytes = (placeholder.Start - current_position);
ret.append(ptr + current_position, bytes);
current_position += bytes;
}
ret.append(placeholder.Argument);
current_position += (placeholder.End - placeholder.Start);
}
const int remaining_bytes = str.size() - current_position;
if (remaining_bytes > 0)
ret.append(ptr + current_position, remaining_bytes);
return ret;
}
/***************************************************************************************/
static bool ReadPlaceholder(const char *str, int &start, const int &end, int &num, int &placeholder_length, string &options)
{
const char *placeholder_number = &str[start + 1];
char *endStr;
if (!IsDigit(*placeholder_number))
return false;
num = strtoul(placeholder_number, &endStr, 10);
if (!endStr)
return false;
if (*endStr == ':') {
/* Read options */
++endStr;
const char *begin = endStr;
while (endStr < &str[end] && *endStr != '}')
++endStr;
if (endStr == &str[end])
return false;
options.assign(begin, endStr - begin);
} else
options = "";
if (*endStr != '}')
return false;
++endStr;
placeholder_length = endStr - &str[start];
return true;
}
/***************************************************************************************/
bool _FindPlaceholder(const char *str, int &start, const int &end, int &num, int &placeholder_length, string &options)
{
/* Find the '{' */
for (int i = start; i < end; ++i)
{
if (str[i] != '{')
continue;
/* Check if there is enough space for the minimum spaceholder length, 3: {.} */
if (end - i < 3)
continue;
if (ReadPlaceholder(str, i, end, num, placeholder_length, options))
{
start = i;
return true;
}
}
/* If we reach here, we reached the end of the string */
start = end;
return false;
}
/***************************************************************************************/
}
}
</code></pre>
<pre><code>/****************************************************************************************
* Prism
* File Name: FormatNoVariadicTemplates.h
* Added on: 2010/09/26 21:04:33
*/
/***************************************************************************************/
#pragma once
/***************************************************************************************/
/* Here we go.. */
#define FNVT_BEGIN vector<PlaceholderData> placeholders; \
int final_length = str.length(); \
int start = 0; \
const int end = str.length(); \
int num, placeholder_length; \
string argument, options; \
while (start < end) { \
if (!_FindPlaceholder(str.c_str(), start, end, num, placeholder_length, options)) \
continue; \
switch(num) {
#define FNVT_END default: \
argument = Format("{Argument {0}}", num); \
break; \
} \
placeholders.push_back(PlaceholderData(start, start + placeholder_length, argument, final_length)); \
start += placeholder_length; \
} \
return _FinalizeFormat(str, placeholders, final_length);
#define ARGUMENT(n) case n: \
argument = Conversion::ToString(_ ## n, options); \
break; \
/***************************************************************************************/
template<typename A>
string Format(const string &str, const A &_0)
{
FNVT_BEGIN;
ARGUMENT(0);
FNVT_END;
}
template<typename A, typename B>
string Format(const string &str, const A &_0, const B &_1)
{
FNVT_BEGIN;
ARGUMENT(0);
ARGUMENT(1);
FNVT_END;
}
template<typename A, typename B, typename C>
string Format(const string &str, const A &_0, const B &_1, const C &_2)
{
FNVT_BEGIN;
ARGUMENT(0);
ARGUMENT(1);
ARGUMENT(2);
FNVT_END;
}
template<typename A, typename B, typename C, typename D>
string Format(const string &str, const A &_0, const B &_1, const C &_2, const D &_3)
{
FNVT_BEGIN;
ARGUMENT(0);
ARGUMENT(1);
ARGUMENT(2);
ARGUMENT(3);
FNVT_END;
}
template<typename A, typename B, typename C, typename D, typename E>
string Format(const string &str, const A &_0, const B &_1, const C &_2, const D &_3, const E &_4)
{
FNVT_BEGIN;
ARGUMENT(0);
ARGUMENT(1);
ARGUMENT(2);
ARGUMENT(3);
ARGUMENT(4);
FNVT_END;
}
template<typename A, typename B, typename C, typename D, typename E, typename F>
string Format(const string &str, const A &_0, const B &_1, const C &_2, const D &_3, const E &_4, const F &_5)
{
FNVT_BEGIN;
ARGUMENT(0);
ARGUMENT(1);
ARGUMENT(2);
ARGUMENT(3);
ARGUMENT(4);
ARGUMENT(5);
FNVT_END;
}
template<typename A, typename B, typename C, typename D, typename E, typename F, typename G>
string Format(const string &str, const A &_0, const B &_1, const C &_2, const D &_3, const E &_4, const F &_5, const G &_6)
{
FNVT_BEGIN;
ARGUMENT(0);
ARGUMENT(1);
ARGUMENT(2);
ARGUMENT(3);
ARGUMENT(4);
ARGUMENT(5);
ARGUMENT(6);
FNVT_END;
}
template<typename A, typename B, typename C, typename D, typename E, typename F, typename G, typename H>
string Format(const string &str, const A &_0, const B &_1, const C &_2, const D &_3, const E &_4, const F &_5, const G &_6, const H &_7)
{
FNVT_BEGIN;
ARGUMENT(0);
ARGUMENT(1);
ARGUMENT(2);
ARGUMENT(3);
ARGUMENT(4);
ARGUMENT(5);
ARGUMENT(6);
ARGUMENT(7);
FNVT_END;
}
template<typename A, typename B, typename C, typename D, typename E, typename F, typename G, typename H, typename I>
string Format(const string &str, const A &_0, const B &_1, const C &_2, const D &_3, const E &_4, const F &_5, const G &_6, const H &_7, const I &_8)
{
FNVT_BEGIN;
ARGUMENT(0);
ARGUMENT(1);
ARGUMENT(2);
ARGUMENT(3);
ARGUMENT(4);
ARGUMENT(5);
ARGUMENT(6);
ARGUMENT(7);
ARGUMENT(8);
FNVT_END;
}
template<typename A, typename B, typename C, typename D, typename E, typename F, typename G, typename H, typename I, typename J>
string Format(const string &str, const A &_0, const B &_1, const C &_2, const D &_3, const E &_4, const F &_5, const G &_6, const H &_7, const I &_8, const J &_9)
{
FNVT_BEGIN;
ARGUMENT(0);
ARGUMENT(1);
ARGUMENT(2);
ARGUMENT(3);
ARGUMENT(4);
ARGUMENT(5);
ARGUMENT(6);
ARGUMENT(7);
ARGUMENT(8);
ARGUMENT(9);
FNVT_END;
}
template<typename A, typename B, typename C, typename D, typename E, typename F, typename G, typename H, typename I, typename J, typename K>
string Format(const string &str, const A &_0, const B &_1, const C &_2, const D &_3, const E &_4, const F &_5, const G &_6, const H &_7, const I &_8, const J &_9, const K &_10)
{
FNVT_BEGIN;
ARGUMENT(0);
ARGUMENT(1);
ARGUMENT(2);
ARGUMENT(3);
ARGUMENT(4);
ARGUMENT(5);
ARGUMENT(6);
ARGUMENT(7);
ARGUMENT(8);
ARGUMENT(9);
ARGUMENT(10);
FNVT_END;
}
template<typename A, typename B, typename C, typename D, typename E, typename F, typename G, typename H, typename I, typename J, typename K, typename L>
string Format(const string &str, const A &_0, const B &_1, const C &_2, const D &_3, const E &_4, const F &_5, const G &_6, const H &_7, const I &_8, const J &_9, const K &_10, const L &_11)
{
FNVT_BEGIN;
ARGUMENT(0);
ARGUMENT(1);
ARGUMENT(2);
ARGUMENT(3);
ARGUMENT(4);
ARGUMENT(5);
ARGUMENT(6);
ARGUMENT(7);
ARGUMENT(8);
ARGUMENT(9);
ARGUMENT(10);
ARGUMENT(11);
FNVT_END;
}
template<typename A, typename B, typename C, typename D, typename E, typename F, typename G, typename H, typename I, typename J, typename K, typename L, typename M>
string Format(const string &str, const A &_0, const B &_1, const C &_2, const D &_3, const E &_4, const F &_5, const G &_6, const H &_7, const I &_8, const J &_9, const K &_10, const L &_11, const M &_12)
{
FNVT_BEGIN;
ARGUMENT(0);
ARGUMENT(1);
ARGUMENT(2);
ARGUMENT(3);
ARGUMENT(4);
ARGUMENT(5);
ARGUMENT(6);
ARGUMENT(7);
ARGUMENT(8);
ARGUMENT(9);
ARGUMENT(10);
ARGUMENT(11);
ARGUMENT(12);
FNVT_END;
}
template<typename A, typename B, typename C, typename D, typename E, typename F, typename G, typename H, typename I, typename J, typename K, typename L, typename M, typename N>
string Format(const string &str, const A &_0, const B &_1, const C &_2, const D &_3, const E &_4, const F &_5, const G &_6, const H &_7, const I &_8, const J &_9, const K &_10, const L &_11, const M &_12, const N &_13)
{
FNVT_BEGIN;
ARGUMENT(0);
ARGUMENT(1);
ARGUMENT(2);
ARGUMENT(3);
ARGUMENT(4);
ARGUMENT(5);
ARGUMENT(6);
ARGUMENT(7);
ARGUMENT(8);
ARGUMENT(9);
ARGUMENT(10);
ARGUMENT(11);
ARGUMENT(12);
ARGUMENT(13);
FNVT_END;
}
template<typename A, typename B, typename C, typename D, typename E, typename F, typename G, typename H, typename I, typename J, typename K, typename L, typename M, typename N, typename O>
string Format(const string &str, const A &_0, const B &_1, const C &_2, const D &_3, const E &_4, const F &_5, const G &_6, const H &_7, const I &_8, const J &_9, const K &_10, const L &_11, const M &_12, const N &_13, const O &_14)
{
FNVT_BEGIN;
ARGUMENT(0);
ARGUMENT(1);
ARGUMENT(2);
ARGUMENT(3);
ARGUMENT(4);
ARGUMENT(5);
ARGUMENT(6);
ARGUMENT(7);
ARGUMENT(8);
ARGUMENT(9);
ARGUMENT(10);
ARGUMENT(11);
ARGUMENT(12);
ARGUMENT(13);
ARGUMENT(14);
FNVT_END;
}
template<typename A, typename B, typename C, typename D, typename E, typename F, typename G, typename H, typename I, typename J, typename K, typename L, typename M, typename N, typename O, typename P>
string Format(const string &str, const A &_0, const B &_1, const C &_2, const D &_3, const E &_4, const F &_5, const G &_6, const H &_7, const I &_8, const J &_9, const K &_10, const L &_11, const M &_12, const N &_13, const O &_14, const P &_15)
{
FNVT_BEGIN;
ARGUMENT(0);
ARGUMENT(1);
ARGUMENT(2);
ARGUMENT(3);
ARGUMENT(4);
ARGUMENT(5);
ARGUMENT(6);
ARGUMENT(7);
ARGUMENT(8);
ARGUMENT(9);
ARGUMENT(10);
ARGUMENT(11);
ARGUMENT(12);
ARGUMENT(13);
ARGUMENT(14);
ARGUMENT(15);
FNVT_END;
}
template<typename A, typename B, typename C, typename D, typename E, typename F, typename G, typename H, typename I, typename J, typename K, typename L, typename M, typename N, typename O, typename P, typename Q>
string Format(const string &str, const A &_0, const B &_1, const C &_2, const D &_3, const E &_4, const F &_5, const G &_6, const H &_7, const I &_8, const J &_9, const K &_10, const L &_11, const M &_12, const N &_13, const O &_14, const P &_15, const Q &_16)
{
FNVT_BEGIN;
ARGUMENT(0);
ARGUMENT(1);
ARGUMENT(2);
ARGUMENT(3);
ARGUMENT(4);
ARGUMENT(5);
ARGUMENT(6);
ARGUMENT(7);
ARGUMENT(8);
ARGUMENT(9);
ARGUMENT(10);
ARGUMENT(11);
ARGUMENT(12);
ARGUMENT(13);
ARGUMENT(14);
ARGUMENT(15);
ARGUMENT(16);
FNVT_END;
}
template<typename A, typename B, typename C, typename D, typename E, typename F, typename G, typename H, typename I, typename J, typename K, typename L, typename M, typename N, typename O, typename P, typename Q, typename R>
string Format(const string &str, const A &_0, const B &_1, const C &_2, const D &_3, const E &_4, const F &_5, const G &_6, const H &_7, const I &_8, const J &_9, const K &_10, const L &_11, const M &_12, const N &_13, const O &_14, const P &_15, const Q &_16, const R &_17)
{
FNVT_BEGIN;
ARGUMENT(0);
ARGUMENT(1);
ARGUMENT(2);
ARGUMENT(3);
ARGUMENT(4);
ARGUMENT(5);
ARGUMENT(6);
ARGUMENT(7);
ARGUMENT(8);
ARGUMENT(9);
ARGUMENT(10);
ARGUMENT(11);
ARGUMENT(12);
ARGUMENT(13);
ARGUMENT(14);
ARGUMENT(15);
ARGUMENT(16);
ARGUMENT(17);
FNVT_END;
}
template<typename A, typename B, typename C, typename D, typename E, typename F, typename G, typename H, typename I, typename J, typename K, typename L, typename M, typename N, typename O, typename P, typename Q, typename R, typename S>
string Format(const string &str, const A &_0, const B &_1, const C &_2, const D &_3, const E &_4, const F &_5, const G &_6, const H &_7, const I &_8, const J &_9, const K &_10, const L &_11, const M &_12, const N &_13, const O &_14, const P &_15, const Q &_16, const R &_17, const S &_18)
{
FNVT_BEGIN;
ARGUMENT(0);
ARGUMENT(1);
ARGUMENT(2);
ARGUMENT(3);
ARGUMENT(4);
ARGUMENT(5);
ARGUMENT(6);
ARGUMENT(7);
ARGUMENT(8);
ARGUMENT(9);
ARGUMENT(10);
ARGUMENT(11);
ARGUMENT(12);
ARGUMENT(13);
ARGUMENT(14);
ARGUMENT(15);
ARGUMENT(16);
ARGUMENT(17);
ARGUMENT(18);
FNVT_END;
}
template<typename A, typename B, typename C, typename D, typename E, typename F, typename G, typename H, typename I, typename J, typename K, typename L, typename M, typename N, typename O, typename P, typename Q, typename R, typename S, typename T>
string Format(const string &str, const A &_0, const B &_1, const C &_2, const D &_3, const E &_4, const F &_5, const G &_6, const H &_7, const I &_8, const J &_9, const K &_10, const L &_11, const M &_12, const N &_13, const O &_14, const P &_15, const Q &_16, const R &_17, const S &_18, const T &_19)
{
FNVT_BEGIN;
ARGUMENT(0);
ARGUMENT(1);
ARGUMENT(2);
ARGUMENT(3);
ARGUMENT(4);
ARGUMENT(5);
ARGUMENT(6);
ARGUMENT(7);
ARGUMENT(8);
ARGUMENT(9);
ARGUMENT(10);
ARGUMENT(11);
ARGUMENT(12);
ARGUMENT(13);
ARGUMENT(14);
ARGUMENT(15);
ARGUMENT(16);
ARGUMENT(17);
ARGUMENT(18);
ARGUMENT(19);
FNVT_END;
}
template<typename A, typename B, typename C, typename D, typename E, typename F, typename G, typename H, typename I, typename J, typename K, typename L, typename M, typename N, typename O, typename P, typename Q, typename R, typename S, typename T, typename U>
string Format(const string &str, const A &_0, const B &_1, const C &_2, const D &_3, const E &_4, const F &_5, const G &_6, const H &_7, const I &_8, const J &_9, const K &_10, const L &_11, const M &_12, const N &_13, const O &_14, const P &_15, const Q &_16, const R &_17, const S &_18, const T &_19, const U &_20)
{
FNVT_BEGIN;
ARGUMENT(0);
ARGUMENT(1);
ARGUMENT(2);
ARGUMENT(3);
ARGUMENT(4);
ARGUMENT(5);
ARGUMENT(6);
ARGUMENT(7);
ARGUMENT(8);
ARGUMENT(9);
ARGUMENT(10);
ARGUMENT(11);
ARGUMENT(12);
ARGUMENT(13);
ARGUMENT(14);
ARGUMENT(15);
ARGUMENT(16);
ARGUMENT(17);
ARGUMENT(18);
ARGUMENT(19);
ARGUMENT(20);
FNVT_END;
}
template<typename A, typename B, typename C, typename D, typename E, typename F, typename G, typename H, typename I, typename J, typename K, typename L, typename M, typename N, typename O, typename P, typename Q, typename R, typename S, typename T, typename U, typename V>
string Format(const string &str, const A &_0, const B &_1, const C &_2, const D &_3, const E &_4, const F &_5, const G &_6, const H &_7, const I &_8, const J &_9, const K &_10, const L &_11, const M &_12, const N &_13, const O &_14, const P &_15, const Q &_16, const R &_17, const S &_18, const T &_19, const U &_20, const V &_21)
{
FNVT_BEGIN;
ARGUMENT(0);
ARGUMENT(1);
ARGUMENT(2);
ARGUMENT(3);
ARGUMENT(4);
ARGUMENT(5);
ARGUMENT(6);
ARGUMENT(7);
ARGUMENT(8);
ARGUMENT(9);
ARGUMENT(10);
ARGUMENT(11);
ARGUMENT(12);
ARGUMENT(13);
ARGUMENT(14);
ARGUMENT(15);
ARGUMENT(16);
ARGUMENT(17);
ARGUMENT(18);
ARGUMENT(19);
ARGUMENT(20);
ARGUMENT(21);
FNVT_END;
}
template<typename A, typename B, typename C, typename D, typename E, typename F, typename G, typename H, typename I, typename J, typename K, typename L, typename M, typename N, typename O, typename P, typename Q, typename R, typename S, typename T, typename U, typename V, typename W>
string Format(const string &str, const A &_0, const B &_1, const C &_2, const D &_3, const E &_4, const F &_5, const G &_6, const H &_7, const I &_8, const J &_9, const K &_10, const L &_11, const M &_12, const N &_13, const O &_14, const P &_15, const Q &_16, const R &_17, const S &_18, const T &_19, const U &_20, const V &_21, const W &_22)
{
FNVT_BEGIN;
ARGUMENT(0);
ARGUMENT(1);
ARGUMENT(2);
ARGUMENT(3);
ARGUMENT(4);
ARGUMENT(5);
ARGUMENT(6);
ARGUMENT(7);
ARGUMENT(8);
ARGUMENT(9);
ARGUMENT(10);
ARGUMENT(11);
ARGUMENT(12);
ARGUMENT(13);
ARGUMENT(14);
ARGUMENT(15);
ARGUMENT(16);
ARGUMENT(17);
ARGUMENT(18);
ARGUMENT(19);
ARGUMENT(20);
ARGUMENT(21);
ARGUMENT(22);
FNVT_END;
}
template<typename A, typename B, typename C, typename D, typename E, typename F, typename G, typename H, typename I, typename J, typename K, typename L, typename M, typename N, typename O, typename P, typename Q, typename R, typename S, typename T, typename U, typename V, typename W, typename X>
string Format(const string &str, const A &_0, const B &_1, const C &_2, const D &_3, const E &_4, const F &_5, const G &_6, const H &_7, const I &_8, const J &_9, const K &_10, const L &_11, const M &_12, const N &_13, const O &_14, const P &_15, const Q &_16, const R &_17, const S &_18, const T &_19, const U &_20, const V &_21, const W &_22, const X &_23)
{
FNVT_BEGIN;
ARGUMENT(0);
ARGUMENT(1);
ARGUMENT(2);
ARGUMENT(3);
ARGUMENT(4);
ARGUMENT(5);
ARGUMENT(6);
ARGUMENT(7);
ARGUMENT(8);
ARGUMENT(9);
ARGUMENT(10);
ARGUMENT(11);
ARGUMENT(12);
ARGUMENT(13);
ARGUMENT(14);
ARGUMENT(15);
ARGUMENT(16);
ARGUMENT(17);
ARGUMENT(18);
ARGUMENT(19);
ARGUMENT(20);
ARGUMENT(21);
ARGUMENT(22);
ARGUMENT(23);
FNVT_END;
}
template<typename A, typename B, typename C, typename D, typename E, typename F, typename G, typename H, typename I, typename J, typename K, typename L, typename M, typename N, typename O, typename P, typename Q, typename R, typename S, typename T, typename U, typename V, typename W, typename X, typename Y>
string Format(const string &str, const A &_0, const B &_1, const C &_2, const D &_3, const E &_4, const F &_5, const G &_6, const H &_7, const I &_8, const J &_9, const K &_10, const L &_11, const M &_12, const N &_13, const O &_14, const P &_15, const Q &_16, const R &_17, const S &_18, const T &_19, const U &_20, const V &_21, const W &_22, const X &_23, const Y &_24)
{
FNVT_BEGIN;
ARGUMENT(0);
ARGUMENT(1);
ARGUMENT(2);
ARGUMENT(3);
ARGUMENT(4);
ARGUMENT(5);
ARGUMENT(6);
ARGUMENT(7);
ARGUMENT(8);
ARGUMENT(9);
ARGUMENT(10);
ARGUMENT(11);
ARGUMENT(12);
ARGUMENT(13);
ARGUMENT(14);
ARGUMENT(15);
ARGUMENT(16);
ARGUMENT(17);
ARGUMENT(18);
ARGUMENT(19);
ARGUMENT(20);
ARGUMENT(21);
ARGUMENT(22);
ARGUMENT(23);
ARGUMENT(24);
FNVT_END;
}
template<typename A, typename B, typename C, typename D, typename E, typename F, typename G, typename H, typename I, typename J, typename K, typename L, typename M, typename N, typename O, typename P, typename Q, typename R, typename S, typename T, typename U, typename V, typename W, typename X, typename Y, typename Z>
string Format(const string &str, const A &_0, const B &_1, const C &_2, const D &_3, const E &_4, const F &_5, const G &_6, const H &_7, const I &_8, const J &_9, const K &_10, const L &_11, const M &_12, const N &_13, const O &_14, const P &_15, const Q &_16, const R &_17, const S &_18, const T &_19, const U &_20, const V &_21, const W &_22, const X &_23, const Y &_24, const Z &_25)
{
FNVT_BEGIN;
ARGUMENT(0);
ARGUMENT(1);
ARGUMENT(2);
ARGUMENT(3);
ARGUMENT(4);
ARGUMENT(5);
ARGUMENT(6);
ARGUMENT(7);
ARGUMENT(8);
ARGUMENT(9);
ARGUMENT(10);
ARGUMENT(11);
ARGUMENT(12);
ARGUMENT(13);
ARGUMENT(14);
ARGUMENT(15);
ARGUMENT(16);
ARGUMENT(17);
ARGUMENT(18);
ARGUMENT(19);
ARGUMENT(20);
ARGUMENT(21);
ARGUMENT(22);
ARGUMENT(23);
ARGUMENT(24);
ARGUMENT(25);
FNVT_END;
}
/***************************************************************************************/
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-30T14:26:32.517",
"Id": "3526",
"Score": "0",
"body": "PS: comments in the code talk about alignment, the {0,10} syntax, which is not implemented yet. Also I wrote my examples (but not the unit tests) without trying to run them first."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-20T00:30:54.030",
"Id": "88339",
"Score": "0",
"body": "You might be interested in the C++ Format library http://cppformat.github.io/. It is based on Python's str.format which uses very similar format string syntax. It is also very fast, depending on format string it can even be faster than sprintf."
}
] | [
{
"body": "<p>In my opinion:</p>\n\n<ul>\n<li>Use fullscope names (like <code>std::vector</code>, <code>boost::shared_ptr</code>)</li>\n<li>Don't use <code>const &</code> for simple types (for example <code>int</code> or <code>double</code>)</li>\n<li>Write <code>const</code> after the type: <code>std::string const&</code></li>\n<li>For <code>string IntToString(...)</code> and <code>ToString(const double &val...)</code> why you don't use <code>std::ostringstream</code>?</li>\n<li>In <code>FormatNoVariadicTemplates.h</code> why you don't use functions for <code>FNVT_BEGIN</code> and <code>FNVT_END</code>?</li>\n</ul>\n\n<p>Have you any some benchmark results?</p>\n\n<p>PS: good idea ;)\nI'm usually use to Qt functions, we are using this library in our projects or stl.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-01T15:57:31.580",
"Id": "3534",
"Score": "0",
"body": "For point 1), I prefer to use names without the namespace, it really bothers me having to type it every time 2) I sometimes use it mostly for consistency; can't hurt 3) That's a personal preference 4) std::ostringstreams is extremely slow, and it's the main reason boost::format is over 10 times slower than printf(), even with optimizations on 5) It cannot be converted to a function because of the ## preprocessor trick (see ARGUMENT())"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-01T16:45:21.860",
"Id": "3535",
"Score": "0",
"body": "Few links about some points, it's not very important, but i use it.\n1) http://www.gotw.ca/publications/c++cs.htm (59)\n3) http://www.codeproject.com/KB/cpp/complex_declarations.aspx#right_left_rule\nAnd\n5) It can be template functions, i think."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-02T12:24:31.760",
"Id": "3539",
"Score": "1",
"body": "The thing about `using` in headers _is_ important."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-30T15:57:04.397",
"Id": "2183",
"ParentId": "2182",
"Score": "7"
}
},
{
"body": "<p>There are some serious portability-issues with the code:</p>\n\n<ul>\n<li>You do not have proper header guards. <code>#pragma</code> is non-standard.</li>\n<li>You do not have proper includes (because of a precompiled header, I presume).</li>\n<li>Names beginning with an underscore followed by an uppercase letter (e.g. <code>_FinalizeFormat</code>, <code>_FindPlaceholder</code>) are reserved by the compiler.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-02T12:57:08.750",
"Id": "3540",
"Score": "1",
"body": "For first point i use to\n#ifndef LIKE_THIS\n#define LIKE_THIS\n...\n#endif // LIKE_THIS"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-29T20:01:25.987",
"Id": "11395",
"Score": "0",
"body": "@siquell Ditto :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-02T12:28:28.123",
"Id": "2194",
"ParentId": "2182",
"Score": "11"
}
},
{
"body": "<p>I have a few comments, in no particular order.</p>\n\n<p>It seems to me like you can't decide between <code>std::string</code> and <code>const char*</code>. Pick one.</p>\n\n<p>(Maybe I'll get flamed for this one.) You say you care about performance, but your use of <code>vector</code> and <code>string</code> tell a different story. It seems to me like heap allocation is completely unneccessary for most of this, and for this reason I would avoid STL and C++ strings. Or, if not avoiding them entirely, I would avoid using so many <code>std::string</code>s as temporaries while formatting. The functions that do this should maybe take a destination buffer as a parameter.</p>\n\n<p>It seems strange that your internal representation of options remains a string at all times. For example:</p>\n\n<pre><code>static const char *normalStrings[] = { \"true\", \"false\" };\nstatic const char *alternativeStrings[] = { \"yes\", \"no\" };\nconst bool alternative = (options == \"a\");\nconst char **strings = alternative ? alternativeStrings : normalStrings;\n</code></pre>\n\n<p>This itself is a bit hard for an outsider to follow as written, but aside from that, do you really want<code>options == \"a\"</code>? What if you want more than one option? Wouldn't a check for <code>a</code> be more like <code>strchr(options, 'a')</code>? In which case I would say do you really want O(n) lookup for options? Maybe this doesn't make sense as a string. Maybe you want to store them internally as flags in an integer. Even if you don't want to combine options it still might look less weird as an enum or constant. There are a lot of magic literals floating around in this code.</p>\n\n<p>There's lots of code that's more verbose than it has to be, for example:</p>\n\n<pre><code>/* Find the '{' */\nfor (int i = start; i < end; ++i)\n{\n if (str[i] != '{')\n continue;\n\n /* Check if there is enough space for the minimum spaceholder length, 3: {.} */\n if (end - i < 3)\n continue;\n</code></pre>\n\n<p>The <code>for</code> loop seems to be reinventing <code>strchr</code>. I would much prefer something like this:</p>\n\n<pre><code>char *current, *end;\n\nwhile ((current=strchr(str, '{')) &&\n (end=strchr(current, '}')))\n{\n //\n // TODO: do something with placeholder at (current, end)\n //\n\n str = end + 1;\n}\n</code></pre>\n\n<p>Or perhaps more C-like (though I realize you're writing C++ it looks like you've already rejected some of its idioms) would be something like this:</p>\n\n<pre><code>while (*str)\n{\n if (*str == '{' &&\n (end=strchr(str, '}')))\n {\n //\n // TODO: evaluate placeholder at (str, end) into dst\n //\n\n str = end+1;\n }\n else\n {\n // TODO: make sure this doesn't overflow :-)\n *dst++ = *str++;\n }\n}\n</code></pre>\n\n<p><code>IntToString</code> could have a lot of improvements... One trivial stylistic thing is that <code>\"0123456789\"</code> is a lot easier on the eyes than <code>{ '0', '1', '2', ... }</code>. More importantly, do you have to do this with a separate heap allocation? Maybe it should be passed a destination buffer. The <code>reserve</code> method being called with a constant also looks a bit weird because you've just done the conversion inside <code>tmp</code>, so you know the exact length...</p>\n\n<p>Lastly, as a matter of habit, if you're going to use <code>sprintf</code> -- well don't. Use <code>snprintf</code> instead. (If you happen to be using a version of Visual Studio that doesn't have that, there's also <code>sprintf_s</code> or <code>StringCchPrintf</code>.)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-06T11:00:08.560",
"Id": "2281",
"ParentId": "2182",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-30T14:11:00.527",
"Id": "2182",
"Score": "12",
"Tags": [
"c++",
"reinventing-the-wheel",
"formatting"
],
"Title": "My own C++ Format function"
} | 2182 |
<p>I am writing a wrapper for dynamic behavior in C#. If I use <code>GetMethod()</code>, then an exception is thrown when there is more than one method (overloads). I figure it will become apparent at runtime that if there is an argument mismatch anyway. Is this a good way to solve the problem?</p>
<pre><code>public class StaticMembersDynamicWrapper : DynamicObject
{
private Type _type;
public StaticMembersDynamicWrapper(Type type) { _type = type; }
// Handle static methods
public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
{
var methods = _type
.GetMethods(BindingFlags.FlattenHierarchy | BindingFlags.Static | BindingFlags.Public)
.Where(methodInfo => methodInfo.Name == binder.Name);
var method = methods.FirstOrDefault();
if (method != null)
{
result = method.Invoke(null, args);
return true;
}
result = null;
return false;
}
}
</code></pre>
| [] | [
{
"body": "<p>The order the method infos are returned in dose not appear to be a defined one, I would suggest filtering on argument types to avoid the risk of it all crumbling to dust when the order changes.</p>\n\n<p>Also you may want to consider the case when a method is defined on both the base class and the subclass.</p>\n\n<pre><code>class A\n{\n public static void DoAwsomeStuff()\n {\n // really awsome stuff.\n }\n}\n\nclass B : A\n{\n public static void DoAwsomeStuff()\n {\n // different but still awsome stuff.\n }\n}\n</code></pre>\n\n<p>Hiding static methods like this should probably be frowned upon, but all the same I would suggest selecting the method with the most specific declaring type. Just to be safe.</p>\n\n<pre><code>MethodInfo method = null;\n\nforeach(var current in methods)\n{\n if(method == null || current.DeclaringType.IsAssignableFrom(method.DeclaringType))\n {\n method = current;\n }\n}\n</code></pre>\n\n<hr>\n\n<p>Edit:</p>\n\n<p>Another possibility worth exploring is the use of Type.InvokeMember(). This already takes the argument types and method hiding into account for you.</p>\n\n<pre><code>try\n{\n result = _type.InvokeMember(\n binder.Name,\n BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy | BindingFlags.InvokeMethod,\n null,\n null,\n args\n );\n\n return true;\n}\ncatch(MissingMethodException)\n{\n result = null;\n return false;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-01T01:14:54.817",
"Id": "3532",
"Score": "0",
"body": "I am using this with simple value types, such as int or double. This means that the inheritance scenario is not a plausible one. Sounds like a good thing to guard for with, possibly, a code contract. I am much more interested in the aspect of multiple overloads. But that sounds more like a StackOverflow question."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-01T00:37:15.167",
"Id": "2186",
"ParentId": "2184",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "2186",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-04-30T17:18:28.257",
"Id": "2184",
"Score": "4",
"Tags": [
"c#"
],
"Title": "Wrapper for dynamic behavior"
} | 2184 |
<p>I am seeing it more and more.</p>
<p>Which do you think works best and why?</p>
<p>This:</p>
<pre><code>$config = array(
'param1'=>'abc'
'param2'=>'dfg'
);
new Class($config);
</code></pre>
<p>Or:</p>
<pre><code>new Class('abc','dfg');
</code></pre>
| [] | [
{
"body": "<p>I'd always use the second version, since one could use type-hinting. The array style is less transparent.</p>\n\n<p>At least the array style should read like this:</p>\n\n<pre><code>$config = array(\n Class::PARAM_1_INFO =>'abc'\n Class::PARAM_1_SOMETHING =>'dfg'\n);\n</code></pre>\n\n<p>This way, Class is the single point, where the keys get defined. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-01T17:09:31.280",
"Id": "2190",
"ParentId": "2189",
"Score": "2"
}
},
{
"body": "<p>Not sure if \"work's best\" is appropriate, but I know variations of the array approach (including formatted arg strings) are popular on some C projects, because of the issues with varargs and stack corruption.</p>\n\n<p>I quite like the array approach (not all PHP-specific reasons) because:</p>\n\n<ul>\n<li>Caller doesn't need to know all the possible args for a given function.</li>\n<li>Caller doesn't need to guess at sensible defaults</li>\n<li>Caller automatically gains when recommended defaults change</li>\n<li>Implementer doesn't need to write lots of variations of a function clogging up the stack with nested calls adding 1 arg.</li>\n<li>Merging arrays to get defaults is^H^Hcan be fairly painless</li>\n</ul>\n\n<p>With the con:</p>\n\n<ul>\n<li>Caller automatically breaks when defaults change</li>\n</ul>\n\n<p>The thing to consider is, without looking into what Class actually does, what is easier to understand in the calling code?</p>\n\n<pre><code>$x = new Class(array('needle'=>'abc','haystack'=>'gagagabcfasfgaf'))\n</code></pre>\n\n<p>or</p>\n\n<p><code>$x = new Class('abc','gagagabcfasfgaf')</code></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-14T21:06:41.323",
"Id": "4527",
"Score": "2",
"body": "Another pro is \"Caller doesn't need to know the order to list the arguments\". Any time PHP has a `foo_function($needle, $haystack)` it seems like they just flip a coin to determine the argument order."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-01T22:13:16.583",
"Id": "2191",
"ParentId": "2189",
"Score": "0"
}
},
{
"body": "<p>if there are many args, use 3rd option. a config class to pass in as an arg. if there are many args, it may be a sign that something is wrong however. generally the fewer arguments, the better.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-18T08:51:24.853",
"Id": "2461",
"ParentId": "2189",
"Score": "2"
}
},
{
"body": "<p>I've had this come up a couple of times recently, and each time ended up realising that the arguments being passed in were actually all attributes of the entity being created. So I've followed the following pattern:</p>\n\n<pre><code>$theObject = new TheClass();\n$theObject->setParam1('abc');\n$theObject->setParam2('def');\n$theObject->doSomething();\n</code></pre>\n\n<p>Which means that you can force the types of the various attributes, but also validate them further within the <code>set</code> methods, as well as gain a bunch of other benefits such as easier testing etc.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-30T05:41:18.790",
"Id": "2706",
"ParentId": "2189",
"Score": "0"
}
},
{
"body": "<p>My advice is to mix both styles: pass the required and important properties directly as parameters, and keep a hash table for optional properties.</p>\n\n<p>For example:</p>\n\n<pre><code>$c = new Class(ImportantRelatedInterface $obj, $options = array(..));\n</code></pre>\n\n<p>If you <strong>really</strong> need to set/change some properties after the instantiation, then you can provide some setters, but avoid it to simplify the code if possible.\nFor options, you can provide general setter/getter: </p>\n\n<pre><code>function setOption(..);\nfunction getOption(..);\n</code></pre>\n\n<p>And even:</p>\n\n<pre><code>function hasOption(..);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-13T20:11:30.857",
"Id": "2934",
"ParentId": "2189",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-01T17:00:32.253",
"Id": "2189",
"Score": "4",
"Tags": [
"php"
],
"Title": "single array or many single argument to call a constructor with params?"
} | 2189 |
<p><a href="http://en.wikipedia.org/wiki/Trie" rel="noreferrer">http://en.wikipedia.org/wiki/Trie</a></p>
<p>The basic idea is to support fast searches via prefix matching. In my implementation, I allow each node to store all of the words that match its given prefix, and then if the word length exceeds the length of the node's prefix, it passes the word into its children for further storage.</p>
<pre><code>public class TrieNode
{
private string Prefix { get; set; }
private IList<string> Items { get; set; }
private IDictionary<string, TrieNode> ChildNodes { get; set; }
private IEqualityComparer<string> Comparer { get; set; }
public TrieNode() : this(StringComparer.CurrentCulture) { }
public TrieNode(IEqualityComparer<string> comparer) : this(comparer, string.Empty) { }
private TrieNode(IEqualityComparer<string> comparer, string prefix)
{
if (prefix == null)
throw new ArgumentNullException("Invalid prefix");
this.Prefix = prefix;
this.Items = new List<string>();
this.ChildNodes = new Dictionary<string, TrieNode>(comparer);
this.Comparer = comparer;
}
public void Add(string word)
{
if (word == null)
throw new InvalidOperationException("Cannot add null to list");
if (word.Length < this.Prefix.Length
|| !this.Comparer.Equals(word.Substring(0, this.Prefix.Length), this.Prefix))
{
throw new ArgumentException("Parameter does not match prefix.");
}
this.Items.Add(word);
if (word.Length > this.Prefix.Length)
{
string childKey = word.Substring(0, this.Prefix.Length + 1);
if (!this.ChildNodes.ContainsKey(childKey))
{
this.ChildNodes.Add(childKey, new TrieNode(this.Comparer, childKey));
}
this.ChildNodes[childKey].Add(word);
}
}
public void AddRange(IEnumerable<string> words)
{
foreach (string word in words)
this.Add(word);
}
public ReadOnlyCollection<string> FindMatches(string searchPrefix)
{
if (searchPrefix == null)
throw new InvalidOperationException("Cannot search on null strings");
if (this.Comparer.Equals(searchPrefix, this.Prefix))
{
return new ReadOnlyCollection<string>(this.Items);
}
else
{
string childKey = searchPrefix.Substring(0, this.Prefix.Length + 1);
if (this.ChildNodes.ContainsKey(childKey))
return this.ChildNodes[childKey].FindMatches(searchPrefix);
else
return new ReadOnlyCollection<string>(new string[0]); // empty list for no matches
}
}
}
</code></pre>
<p>...</p>
<pre><code>TrieNode trie = new TrieNode(StringComparer.CurrentCultureIgnoreCase);
trie.AddRange(new string[] { "Apple", "Banana", "BANANA", "Bar", "Berry", "Cherry", "Coconut", "Date" });
ReadOnlyCollection<string> matches = trie.FindMatches("BA"); // BANANA, banana, Bar
</code></pre>
<p>The slight concern I have is that each node contains its list of matching words, it's not an aggregation from its children. I call it <em>slight</em>, because it allows for easy logic when performing searches, as once a match is found, there's no need to further poll children and aggregate responses. On the other hand, I end up storing the same word in <em>n</em> lists, where <em>n</em> is the length of the word. </p>
<p><strong>Edit</strong> An answer suggested returning an <code>IEnumerable<string></code> to allow lazy streaming of results as well as to eliminate unnecessary copying. The tradeoff is that ordering is not preserved<strike>, and the code logic (at least, the way I tried it) is a bit less simple</strike>. But the quick changes I made to allow such a sequence are the following. First, inside the <code>Add</code> method, only storing matches to the specific prefix </p>
<pre><code>if (this.Comparer.Equals(word, this.Prefix))
{
// keep each match - preserves number of matches as well as differences
// if the comparer allows insensitive equality
this.Items.Add(word);
}
</code></pre>
<p>And then the <code>FindMatches</code> method</p>
<pre><code>public IEnumerable<string> FindMatches(string searchPrefix)
{
if (searchPrefix == null)
throw new InvalidOperationException("Cannot search on null strings");
if (this.Comparer.Equals(searchPrefix, this.Prefix))
{
return this.Items.Concat(this.ChildNodes.SelectMany(n => n.Value.FindMatches(n.Key)));
}
else
{
string childKey = searchPrefix.Substring(0, this.Prefix.Length + 1);
if (this.ChildNodes.ContainsKey(childKey))
{
return this.ChildNodes[childKey].FindMatches(searchPrefix);
}
else
{
return Enumerable.Repeat(string.Empty, 0);
}
}
}
</code></pre>
| [] | [
{
"body": "<p>Instead of returning a collection, why not return an IEnumerable? Then you would perform no list copying, and it would be low cost to return an Enumerable that actually recurses through all the children lists.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-02T23:28:46.213",
"Id": "3555",
"Score": "0",
"body": "If you have a coding suggestion for the `IEnumerable<string>` approach, I would welcome it. I wrote such an implementation, found it a bit more messy in terms of code and logic, but I recognize the tradeoff. For example, in my approach, order is preserved, logic is relatively simple, but there is more memory utilized and results cannot be lazily streamed. +1, though."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-03T13:22:43.647",
"Id": "3564",
"Score": "0",
"body": "If the order you want to preserve is sort order, then as long as you traverse the childNodes in sort order, and maintain the child lists in sort order, you should get the results in sort order. ab[cde] all come before ac[abf]."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-03T17:19:51.850",
"Id": "3567",
"Score": "0",
"body": "@Phil, I was thinking more of preserving a non-sorted original order, such that if the original input was \"million\", \"millimeter\", \"milan\", then a search for \"mil\" would return the results in the same order. I have an idea for how to still arrive at that result even with an `IEnumerable` approach and without excessive copies, which is basically to keep a single copy of the original list as an ordering mechanism for the otherwise decentralized output."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-07T17:52:47.407",
"Id": "3675",
"Score": "0",
"body": "@Anthony, consider keeping the position of each occurrence as a list of integers at each node. Then do an insertion sort into a new list as you pick up new items."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-02T22:57:45.097",
"Id": "2202",
"ParentId": "2195",
"Score": "6"
}
},
{
"body": "<p>Consider just storing a single character at each node. Currently, you are storing this:</p>\n\n<pre><code>given abc, abdfa, abdfb, bcd, efg\n\na : abc, abdfa, abdfb\n. ab : abc, abdfa, abdfb\n.. abc : abc\n.. abd : abdfa, abdfb\nb : bcd\n. bc : bcd\n.. bcd : bcd\ne : efg\n. ef : efg\n.. efg : efg\n</code></pre>\n\n<p>However, just storing the character and a boolean for whether the cumulative prefix has been found:</p>\n\n<pre><code>a : F\n. b : F\n.. c : T\n.. d : F\n... f : F\n.... a : T\n.... d : T\nb : F\n. c : F\n.. d : T\ne : F\n. f : F\n.. g : T\n</code></pre>\n\n<p>Thus your add code would be:</p>\n\n<pre><code>public void Add(string wordExcess)\n{\n /* validation etc here */\n\n if (wordExcess == \"\")\n this.Seen = true;\n else\n {\n // child key is just a char\n string childKey = wordExcess[0];\n if (!this.ChildNodes.ContainsKey(childKey)) \n this.ChildNodes.Add(childKey, new TrieNode(this.Comparer, childKey)); \n\n string childExcess = wordExcess.Substring(1,wordExcess.Length-1);\n this.ChildNodes[childKey].Add(childExcess);\n }\n}\n</code></pre>\n\n<p>Then iterating to find matches:</p>\n\n<pre><code>public IEnumerator FindMatches(string searchExcess)\n{\n /** validation etc here **/\n\n if (searchExcess == \"\" && this.Seen)\n yield return this.Prefix;\n\n if (searchExcess.Length > 0)\n {\n string childKey = searchExcess[0];\n if (this.ChildNodes.ContainsKey(childKey))\n {\n string childExcess = searchExcess.Substring(1,childExcess.Length-1);\n foreach(string match in this.ChildNodes[childKey].FindMatches(searchExcess)\n yield return this.Prefix+match;\n }\n }\n else\n {\n foreach(KeyValuePair <string,TrieNode> pair in this.ChildNodes)\n foreach(string match in pair.Value.FindMatches(\"\"))\n yield return this.Prefix+match;\n }\n}\n</code></pre>\n\n<p>Here we are appending the current prefix to the matches as you return them, and a parent call will do the same. So the a.b.c.d node matches \"\" and returns \"d\" to the c.match, which returns \"c\"+\"d\" to the b.match which returns \"b\"+\"cd\" etc.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-03T17:20:44.547",
"Id": "3568",
"Score": "0",
"body": "Thanks for the suggestion, I will attempt to perform a similar modification when I get a chance this evening."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-09-11T20:51:53.777",
"Id": "114349",
"Score": "1",
"body": "+1 Is there any reason why storing a character is better than a word (at each node)?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-03T13:22:47.780",
"Id": "2209",
"ParentId": "2195",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "2202",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-02T18:13:02.800",
"Id": "2195",
"Score": "5",
"Tags": [
"c#",
"search"
],
"Title": "Is this a reasonable Trie implementation?"
} | 2195 |
<p>I have this python code that compares merge sort and selection sort, but it is taking "forever."</p>
<pre><code>import time
import random
# Selection Sort Code #
def maxIndex(J):
return J.index(max(J))
def swap(LCopy, i, j):
temp = LCopy[i]
LCopy[i] = LCopy[j]
LCopy[j] = temp
# Implementation of selection sort
def selectionSort(L):
for i in range(len(L)-1, 1, -1):
j = maxIndex(L[0:i+1])
swap(L, i, j)
# Merge Sort Code #
# Assumes that L[first:mid+1] is sorted and also
# that L[mid: last+1] is sorted. Returns L with L[first: last+1] sorted
def merge(L, first, mid, last):
i = first # index into the first half
j = mid + 1 # index into the second half
tempList = []
# This loops goes on as long as BOTH i and j stay within their
# respective sorted blocks
while (i <= mid) and (j <= last):
if L[i] <= L[j]:
tempList.append(L[i])
#print L[i], "from the first block"
i += 1
else:
tempList.append(L[j])
#print L[j], "from the second block"
j += 1
# If i goes beyond the first block, there may be some elements
# in the second block that need to be copied into tempList.
# Similarly, if j goes beyond the second block, there may be some
# elements in the first block that need to be copied into tempList
if i == mid + 1:
tempList.extend(L[j:last+1])
#print L[j:last+1], "some elements in second block are left over"
elif j == last+1:
tempList.extend(L[i:mid+1])
#print L[i:mid+1], "some elements from first block are left over"
L[first:last+1] = tempList
#print tempList
# The merge sort function; sorts the sublist L[first:last+1]
def generalMergeSort(L, first, last):
# Base case: if first == last then it is already sorted
# Recursive case: L[first:last+1] has size 2 or more
if first < last:
# divide step
mid = (first + last)/2
# conquer step
generalMergeSort(L, first, mid)
generalMergeSort(L, mid+1, last)
# combine step
merge(L, first, mid, last)
# Wrapper function
def mergeSort(L):
generalMergeSort(L, 0, len(L)-1)
m = 10
n = 100000
n_increments = 9
baseList = [ random.randint(0,100) for r in range(n) ]
i = 0
while i < n_increments:
j = 0
sel_time = 0
mer_time = 0
while j < m:
# Do a Selection Sort #
x = time.clock()
selectionSort( baseList)
y = time.clock()
sel_time += ( y - x )
random.shuffle( baseList )
# Do a Merge Sort #
x = time.clock()
mergeSort( baseList )
y = time.clock()
mer_time += ( y - x )
random.shuffle( baseList )
j += 1
print "average select sort time for a list of", n, "size:", sel_time / m
print "average merge sort time for a list of", n, "size:", mer_time / m
j = 0
i += 1
n += 10000
</code></pre>
| [] | [
{
"body": "<p>The first reason that your code is slow is because you are implementing a selection sort which will be slow in any implementation. It has to scan through a large list looking for the values for each iteration. That's gonna be slow.</p>\n\n<p>The second problem is that you freely create new lists. For example:</p>\n\n<pre><code>j = maxIndex(L[0:i+1])\n</code></pre>\n\n<p>The slice creates a new list and copies the elements in L into it. That works fine when you are dealing with small lists, but in the lists you are playing with here, thats gonna be a significant speed drain. For the most efficiency in cases like this you need to avoid creating new lists altogether and just move stuff between elements in the same list.</p>\n\n<p>All in all, it isn't really much slower then I'd expect the algorithm you are implementing to be in Python. Nothing you are doing should produce pathologically bad performance. However, there is a reason why we use a sort implementation in C. If you are just interested in implementing algorithms for the learning experience, I suggest you use smaller lists. Thats a lot of data to sort with a bad algorithm.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-03T14:11:48.330",
"Id": "3565",
"Score": "0",
"body": "Winston is right, the maxIndex list slice will be perform a copy. Try islice from the itertools module: j=maxIndex(islice(L,0,i+1))."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-03T14:52:55.513",
"Id": "3566",
"Score": "0",
"body": "@Phil H, I thought about suggesting that, but maxIndex passes over the list twice which makes use of an iterator problematic."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-04T07:55:17.097",
"Id": "3575",
"Score": "0",
"body": "Ah, I didn't read that function properly. In that case import itertools and do max(itertools.izip(islice(L,0,i+1),itertools.count())) - it is a pure iterator version with a single pass."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-04T14:45:26.197",
"Id": "3587",
"Score": "0",
"body": "@Phil H, yeah, you can do that. But I didn't think the complexity worth introducing here."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-02T21:30:53.303",
"Id": "2200",
"ParentId": "2199",
"Score": "10"
}
}
] | {
"AcceptedAnswerId": "2200",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-02T20:41:38.680",
"Id": "2199",
"Score": "7",
"Tags": [
"python",
"performance",
"sorting",
"mergesort"
],
"Title": "Merge sort and selection sort comparison taking too long"
} | 2199 |
<p>In order to avoid the user having to explicitly prefix a script with <code>sudo</code> or <code>su --command</code>, I wrote the following:</p>
<pre><code>import sys
import os
if os.getuid():
root = "/usr/bin/sudo"
if not os.path.exists("/usr/bin/sudo"):
root = "/bin/su --command"
command = "{} {}".format(root, sys.argv[0])
command = command.split()
retcode = subprocess.call(command)
if retcode:
print("something wrong happened")
else:
action_that_needs_admin_rights()
</code></pre>
<p>It feels like a hack to me, so am looking forward to better approaches.</p>
| [] | [
{
"body": "<p>The last time I checked (which admittedly has been a while) all major Linux distributions except Ubuntu have a default setup in which sudo is installed, but not configured to be able to start arbitrary applications. So on those your script will fail.</p>\n\n<p>Apart from that I think it's a bad idea to use split like this. This will break if the python file (or the path to it if it was invoked with a path) contains spaces. I'd do it like this instead:</p>\n\n<pre><code>if sudo:\n root = [\"/usr/bin/sudo\"]\nelse:\n root = [\"/bin/su\", \"--command\"]\ncommand = root + [ sys.argv[0] ]\n</code></pre>\n\n<p>A further problem is that you're requiring the script to be marked as executable. I think it'd be a better idea to use <code>sys.executable</code> to get the python interpreter and invoke that.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-03T02:21:19.230",
"Id": "3558",
"Score": "0",
"body": "What's wrong with requiring the script executable?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-03T02:32:43.767",
"Id": "3559",
"Score": "0",
"body": "@Tshepang: It's not wrong as such, it just means that it won't work in cases in which it otherwise would (i.e. in the case where the user invokes the script with `python script.py` rather than making it executable)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-03T08:30:55.540",
"Id": "3561",
"Score": "0",
"body": "Even in that case it should work, because `sys.argv[0]` is always the script filename."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-03T08:40:00.323",
"Id": "3562",
"Score": "3",
"body": "@Tshepang: Yes, that's the point. `sudo filename.py` does not work, if the file is not executable. You need to do `sudo python filename.py`."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-03T02:06:21.273",
"Id": "2205",
"ParentId": "2203",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "2205",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-03T01:18:16.187",
"Id": "2203",
"Score": "7",
"Tags": [
"python"
],
"Title": "Becoming root from Python"
} | 2203 |
<p>Just for the heck of it, I wrote a simple little interpreter that takes in inputs in the form of Polish Notation.</p>
<p>The user will input something like</p>
<blockquote>
<p><code>+ 5 6</code></p>
</blockquote>
<p>And it will then output</p>
<blockquote>
<p><code>11</code></p>
</blockquote>
<p>Here's another sample input:</p>
<blockquote>
<p><code>+ 5 * 2 3</code></p>
</blockquote>
<p>And the output:</p>
<blockquote>
<p><code>11</code></p>
</blockquote>
<p>Users can even define their own variables, like this:</p>
<blockquote>
<p><code>def myVar 10</code></p>
</blockquote>
<p>and like this:</p>
<blockquote>
<p><code>def anotherVar + 5 6</code></p>
</blockquote>
<p>And then of course reuse those variables. So let's say you type</p>
<blockquote>
<p><code>myVar</code></p>
</blockquote>
<p>it will ouput</p>
<blockquote>
<p><code>10</code></p>
</blockquote>
<p>or</p>
<blockquote>
<p><code>anotherVar</code></p>
</blockquote>
<p>which outputs</p>
<blockquote>
<p><code>11</code></p>
</blockquote>
<p>Furthermore, you type in</p>
<blockquote>
<p><code>+ myVar anotherVar</code></p>
</blockquote>
<p>you would then get</p>
<blockquote>
<p><code>21</code></p>
</blockquote>
<hr>
<p>I'm a total newbie to well-formatted and readable code. What would be a good way to refactor this?</p>
<pre><code>#include <iostream>
#include <vector>
#include <string>
#include <sstream>
using namespace std;
class Variable
{
public:
Variable(const string& name, double val)
{
this->name = name;
this->val = val;
}
inline const string& get_name() const { return name; }
inline double get_val() const { return val; }
private:
string name;
double val;
};
//----------------------------------
double operate(const string& op, istringstream& iss, vector<Variable>& v);
double perform_addition(istringstream& iss, vector<Variable>& v);
double perform_subtraction(istringstream& iss, vector<Variable>& v);
double perform_division(istringstream& iss, vector<Variable>& v);
double perform_multiplication(istringstream& iss, vector<Variable>& v);
void define_new_var(vector<Variable>& v, istringstream& iss);
bool is_number(const string& op)
{
int char_to_int = op[0];
if (char_to_int >= 48 && char_to_int <= 57)
return true;
return false;
}
void print_var_list(vector<Variable>& v)
{
int size = v.size();
for (int i = 0; i < size; i++)
{
cout << v[i].get_name() << ", " << v[i].get_val() << endl;
}
cout << endl;
}
int main()
{
cout << endl << "LeRPN Programming Language" << endl;
vector<Variable> v;
string temp;
while (cin)
{
cout << endl << "> ";
getline(cin, temp);
istringstream iss(temp);
string op;
iss >> op;
if (op == "quit")
break;
else if (op == "def")
define_new_var(v, iss);
else if (op == "show_vars")
print_var_list(v);
else
cout << endl << operate(op, iss, v) << endl;
}
}
double perform_addition(istringstream& iss, vector<Variable>& v)
{
string left;
iss >> left;
string right;
iss >> right;
return operate(left, iss, v) + operate(right, iss, v);
}
double perform_subtraction(istringstream& iss, vector<Variable>& v)
{
string left;
iss >> left;
string right;
iss >> right;
return operate(left, iss, v) - operate(right, iss, v);
}
double perform_division(istringstream& iss, vector<Variable>& v)
{
string left;
iss >> left;
string right;
iss >> right;
return operate(left, iss, v) / operate(right, iss, v);
}
double perform_multiplication(istringstream& iss, vector<Variable>& v)
{
string left;
iss >> left;
string right;
iss >> right;
return operate(left, iss, v) * operate(right, iss, v);
}
double get_variable(const string& op, vector<Variable>& v)
{
int size = v.size();
for (int i = 0; i < size; i++)
{
if (op == v[i].get_name())
return v[i].get_val();
}
}
double operate(const string& op, istringstream& iss, vector<Variable>& v)
{
double value;
if (op == "+")
value = perform_addition(iss, v);
else if (op == "-")
value = perform_subtraction(iss, v);
else if (op == "/")
value = perform_division(iss, v);
else if(op == "*")
value = perform_multiplication(iss, v);
else if (is_number(op))
value = atof(op.c_str());
else
value = get_variable(op, v);
return value;
}
void define_new_var(vector<Variable>& v, istringstream& iss)
{
string name;
iss >> name;
string temp;
iss >> temp;
double value = operate(temp, iss, v);
v.push_back(Variable(name, value));
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-26T20:50:20.423",
"Id": "67422",
"Score": "1",
"body": "You've described [Polish notation](http://en.wikipedia.org/wiki/Polish_notation), not [Reverse Polish notation](http://en.wikipedia.org/wiki/Reverse_Polish_notation)."
}
] | [
{
"body": "<p>If you look at the similarity of your various perform_xxx functions, it suggests there is duplication that could be removed. One way to do this would be to extract Operator classes, one for each operation, where the common behavior of extracting left and right values from the stream was expressed in the superclass and the individual operations of multiplication, addition, etc. was left to the subclasses.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-03T18:43:16.833",
"Id": "2212",
"ParentId": "2211",
"Score": "1"
}
},
{
"body": "<ol>\n<li><p><code>double get_variable(const string& op, vector<Variable>& v)</code> -\nmust return default value (0.0), for example if <code>op</code> is empty. Alternatively, you can show an error message.</p></li>\n<li><p><code>double operate(const string& op, istringstream& iss, vector<Variable>& v)</code> - \nAlways initialize variables, like this:</p>\n\n<pre><code>double value(0.0); OR\ndouble value = 0.0;\n</code></pre>\n\n<p>and you must check this <code>op</code> in vector, if it doesn't exist - show error.</p></li>\n<li><p><code>void define_new_var(vector<Variable>& v, istringstream& iss)</code> -\nif variable already exists, set new value or show error.</p></li>\n<li><p><code>bool is_number(const string& op)</code></p>\n\n<pre><code>int char_to_int = op[0];\n</code></pre>\n\n<p>if <code>op</code> is empty.</p></li>\n<li><p>For this functions:</p>\n\n<pre><code>double perform_addition(istringstream& iss, vector<Variable>& v);\ndouble perform_subtraction(istringstream& iss, vector<Variable>& v);\ndouble perform_division(istringstream& iss, vector<Variable>& v);\ndouble perform_multiplication(istringstream& iss, vector<Variable>& v);\n</code></pre>\n\n<p>Define common function who get left and right.</p>\n\n<p>I think you can define some <code>enum</code>s and functions, like this:</p>\n\n<pre><code>double perform_operator(istringstream& iss, vector<Variable>& v, OperatorType type)\n{\n std::string lhs, rhs;\n GetValues(iss, lhs, rhs); // fill them\n switch(type)\n {\n case Minus\n {\n return operate(left, iss, v) - operate(right, iss, v);\n }\n break;\n }\n}\n</code></pre></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-03T19:00:07.997",
"Id": "2213",
"ParentId": "2211",
"Score": "2"
}
},
{
"body": "<pre><code>#include <iostream>\n#include <vector>\n#include <string>\n#include <sstream>\n#include <cstdlib> // mmocny: I needed to add this to use atof\n#include <functional>\n\nusing namespace std;\n\n//----------------------------------\n\nclass Variable\n{\npublic:\n Variable(const string& name, double val)\n : name_(name), val_(val) // mmocny: Use initializer lists\n {\n }\n\n // mmocny: get_* syntax is less common in C++ than in java etc.\n const string& name() const { return name_; } // mmocny: Don't mark as inline (they already are, and its premature optimization)\n double val() const { return val_; } // mmocny: Again, don't mark as inline\nprivate:\n string name_; // mmocny: suggest renaming name_ or _name: Easier to spot member variables in method code, and no naming conflicts with methods\n double val_;\n};\n\n//----------------------------------\n\n// mmocny: Replace print_* methods with operator<< so that other (non cout) streams can be used.\n// mmocny: Alternatively, define to_string()/str() methods which can also be piped out to different streams\nstd::ostream & operator<<(std::ostream & out, Variable const & v)\n{\n return out << v.name() << \", \" << v.val() << endl;\n}\n\nstd::ostream & operator<<(std::ostream & out, vector<Variable> const & v)\n{\n for (vector<Variable>::const_iterator it = v.begin(), end = v.end(); it != end; ++it ) // mmocny: Use iterators rather than index access\n {\n out << *it << endl;\n }\n return out;\n}\n\n//----------------------------------\n\ndouble get_variable(const string& op, vector<Variable>& v)\n{\n // mmocny: instead of using a vector<Variable> you should be using a map/unordered_map<string,double> and doing a key lookup here\n int size = v.size();\n for (int i = 0; i < size; i++)\n { \n if (op == v[i].name())\n return v[i].val();\n }\n // mmocny: what do you do if you don't find the variable?\n throw std::exception(); // mmocny: You should do something better than throw a generic exception()\n}\n\n//----------------------------------\n\nbool is_number(const string& op)\n{\n // mmocny: someone else already mentioned: what if op is empty?\n int char_to_int = op[0];\n // mmocny: couple notes here:\n // 1) chars are actually numbers you can reference directly, and not need \"magic\" constants\n // 2) functions in the form \"if (...) return true; else return false;\" should just be reduced to \"return (...);\"\n // 3) is_number functionality already exists in libc as isdigit()\n // 4) long term, you are probably going to want to improve this function.. what about negative numbers? numbers in the form .02? etc..\n //return (char_to_int >= '0' && char_to_int <= '9');\n return isdigit(char_to_int);\n}\n\n//----------------------------------\n\n// mmocny: replace istringstream with istream\n// mmocny: you only need to predeclare this one function\ndouble operate(const string& op, istream& in, vector<Variable>& v);\n\n//----------------------------------\n/*\n * mmocny: All of your perform_* functions have identical code other than the operator being used.\n * You can turn all of these functions into a single function template where you pass the operator to be used.\n * Luckily, <functional> already has plus minus multiplies divides function objects (functors)\n */\n\ntemplate< class Operator >\ndouble perform_action(istream& in, vector<Variable>& v, Operator op)\n{\n string left;\n in >> left;\n\n double result = operate(left, in, v); // mmocny: This is a big one: for correctness, you must calculate result of left BEFORE you read right\n\n string right;\n in >> right;\n\n return op(result, operate(right, in, v));\n}\n\n//----------------------------------\n\ndouble operate(const string& op, istream& in, vector<Variable>& v)\n{ \n double value;\n if (op == \"+\")\n value = perform_action(in, v, plus<double>());\n else if (op == \"-\")\n value = perform_action(in, v, minus<double>());\n else if(op == \"*\")\n value = perform_action(in, v, multiplies<double>());\n else if (op == \"/\")\n value = perform_action(in, v, divides<double>());\n else if (is_number(op))\n value = atof(op.c_str()); // mmocny: consider using boost::lexical_cast<>, or strtod (maybe)\n else\n value = get_variable(op, v);\n\n return value;\n}\n\n//----------------------------------\n\nvoid define_new_var(vector<Variable>& v, istream& in)\n{\n string name;\n in >> name;\n\n string temp;\n in >> temp;\n\n double value = operate(temp, in, v);\n\n v.push_back(Variable(name, value));\n}\n\n//----------------------------------\n\nint main()\n{\n cout << endl << \"LeRPN Programming Language\" << endl;\n\n vector<Variable> v;\n\n string temp;\n while (cin)\n {\n cout << endl << \"> \";\n\n getline(cin, temp);\n\n if (temp.empty()) // mmocny: This also handles the case of CTRL+D\n continue;\n\n istringstream iss(temp);\n string op;\n iss >> op;\n\n if (op == \"quit\")\n break;\n else if (op == \"def\")\n define_new_var(v, iss);\n else if (op == \"show_vars\")\n std::cout << v << std::endl;\n else\n cout << endl << operate(op, iss, v) << endl;\n }\n}\n</code></pre>\n\n<p>Those are my changes, with comments inline. I would make more changes, but thats enough for now :)</p>\n\n<p>Notice one BIG change: you have a serious correctness bug in your perform_* functions. Not that I've tested my modified code above for all edge cases, but the original code was flat out always wrong for any nested calculations.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-03T19:39:21.037",
"Id": "2216",
"ParentId": "2211",
"Score": "5"
}
},
{
"body": "<p>As a minor aside, I've renamed it to <code>PN</code> instead of <code>RPN</code>. The form you've give (with operators preceding the operands) is Polish Notation as Jan Łukasiewicz invented it. RPN is when you reverse that, and have the operands first, followed by the applicable operator.</p>\n\n<p>As to why they decided to call that RPN: because English speakers had a hard enough time figuring out that his last name was pronounced roughly like \"Wookashayvitch\", not to mention trying to figure out how to say that backwards.</p>\n\n<p>In any case, I think I'd write the code more like this:</p>\n\n<pre><code>#include <iostream>\n#include <vector>\n#include <string>\n#include <sstream>\n#include <map>\n#include <iterator>\n\nusing namespace std; // really would *not* normally do this, but...\n\nvoid define_var(map<string, int> &v, istringstream& iss) {\n std::string name;\n int value;\n iss >> name >> value;\n v[name] = value;\n} \n\nint do_op(char op, int val1, int val2) { \n switch (op) { \n case '+': return val1 + val2;\n case '-': return val1 - val2;\n case '*': return val1 * val2;\n case '/': return val1 / val2;\n default: \n string error(\"Unknown operator: \");\n error += op;\n throw runtime_error(error);\n }\n}\n\nbool isoperator(char ch) { \n return ch == '+' || ch == '-' || ch == '*' || ch == '/';\n}\n\nchar getop(istream &is) {\n char ch;\n while (isspace(ch = is.peek()))\n is.get(ch);\n ch = is.peek();\n return ch;\n}\n\nint eval(istream &is, map<string, int> const &v) { \n // evaluate an expression. It consists of:\n // an operator followed by operands, or\n // a number, or\n // a variable.\n // \n\n char ch = getop(is);\n\n if (isoperator(ch)) {\n is.get(ch);\n int val1 = eval(is, v);\n int val2 = eval(is, v);\n return do_op(ch, val1, val2);\n }\n if (isdigit(ch)) {\n int val;\n is >> val;\n return val;\n }\n\n string var_name;\n is >> var_name;\n map<string, int>::const_iterator p = v.find(var_name);\n if (p==v.end()) {\n string problem(\"Unknown variable: \");\n problem +=var_name;\n throw runtime_error(problem.c_str());\n }\n return p->second;\n}\n\n// used only for dumping out the variables.\nnamespace std { \n ostream &operator<<(ostream &os, pair<string, int> const &v) {\n return os << v.first << \": \" << v.second;\n }\n}\n\nint main() {\n cout << endl << \"LePN Programming Language\" << endl;\n\n map<string, int> v;\n\n string temp;\n cout << endl << \"> \";\n while (getline(cin, temp)) {\n istringstream iss(temp);\n\n string op;\n iss >> op;\n\n if (op == \"quit\")\n break;\n else if (op == \"def\") \n define_var(v, iss);\n else if (op == \"show_vars\")\n std::copy(v.begin(), v.end(), ostream_iterator<pair<string, int> >(cout, \"\\n\"));\n else {\n // Technically, this isn't right -- it only ungets one \n // character, not the whole string.\n // For example, this would interpret \"this+ 2 3\" as \"+ 2 3\"\n // and give 5 instead of an error message. Shouldn't affect \n // correct input though.\n // \n iss.unget();\n cout << endl << eval(iss, v) << endl;\n }\n cout << endl << \"> \";\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-04T02:38:57.987",
"Id": "3570",
"Score": "1",
"body": "You throw a string in do_op instead of std::runtime_error(), though i imagine that was just overlooked as you do the right thing later... I believe that the ch = is.peek() is not needed in getop() after the loop... i like that you wrote a getop() function that doesn't require op to precede whitespace..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-04T02:45:01.583",
"Id": "3572",
"Score": "0",
"body": "@mmocny: Oops, thanks for pointing out the silly mistake in do_op. Perhaps a first: a time that an exception specification might have actually been useful! I think you're right and the `ch=is.peek()` is technically unnecessary, but at least to me it seemed clearer this way."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-04T23:17:22.747",
"Id": "3605",
"Score": "1",
"body": "Totally unrelated: depends on your notion of \"reverse\": a phonemic reversal such as Cziveisakuł would be [tʂiveisakuw], but a phonetic reversal would be [ʂtivejɕakuw], roughly Sztiveiśakuł."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-15T23:27:38.020",
"Id": "94773",
"Score": "0",
"body": "Adding an overload to namespace std? :'( Edit: woah.. this is old.. didn't see that"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-03T23:49:46.983",
"Id": "2219",
"ParentId": "2211",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "2216",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-03T17:30:11.730",
"Id": "2211",
"Score": "6",
"Tags": [
"c++",
"calculator",
"math-expression-eval"
],
"Title": "Polish notation interpreter/calculator"
} | 2211 |
<p>Is it good or bad practice (or, when is it appropriate) to use shorthand methods?</p>
<p>Lets pretend we're using jQuery here, because it has a lot of them.:</p>
<pre><code>jQuery.ajax()
jQuery.get()
jQuery.getJSON()
jQuery.getScript()
.load()
jQuery.post()
</code></pre>
<p>These are all really just shorthand forms for the ajax function, with the exception of load which combines another function later on.</p>
<p>I can use <code>$.ajax( dataType: 'script',)</code> to do the same thing as <code>getScript</code>, but why?</p>
<p>This to me seems insane, and overly complicates the API. Is this good, or bad, or what? Why isn't there a getCSS and a PostCSS and a postScript and a putScript too?</p>
| [] | [
{
"body": "<p>Hm, good question. I guess I would say that the number one rule of programming is DRY: Don't Repeat Yourself. You could argue that any function is \"just shorthand for\" whatever it does. But whenever you find yourself typing the same thing over and over and over, even if that thing is only two or three lines, it's worth at least asking yourself, should I make this into a function?</p>\n\n<p>Now the authors of JQuery don't know exactly what kind of code you're writing, they just have a general idea of what JavaScript code out there in the world looks like. So maybe they originally just had <code>$.ajax()</code> and then over time they realized, you know, 99% of the time, people are either doing always GETs or always POSTs, it's rare that you do something like:</p>\n\n<pre><code>var method;\nif (someComplicatedThing()) method = 'GET';\nelse method = 'POST';\n$.ajax({method:method});\n</code></pre>\n\n<p>so why not shorten it up a little bit?</p>\n\n<p>I agree it's possible to overdo it though, and have a zillion little functions that are all variants of the same idea, making the API seem overwhelming. So it's a question of finding the right balance, I guess.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-11T23:42:08.950",
"Id": "3766",
"Score": "0",
"body": "+1 for the balance. This seems to be an issue for my work right now also. My general rule of thumb is if I am going to want to change all of them at some point then I'll make it a function or if I am using it a dozen times (approx.) then I'll make it a function."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-23T19:09:41.530",
"Id": "4044",
"Score": "2",
"body": "I would add to that that, as jQuery is a library, from a library perspective you want an API that is readable and helps elucidate what it is doing. As programmers, I think we often read method/function calls and ignore parameters when scanning code, as it gives us an overview of what is happening. With descriptive function calls (that are simply shorthand methods), results in more informative code. This can be taken too far, but, as you've said, it's often about balance."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-05T05:52:10.847",
"Id": "2245",
"ParentId": "2214",
"Score": "3"
}
},
{
"body": "<p>There is DRY, and there is readability. Every function is a black box from the call, the tendency is to DRY when you are 'one with the code' and the black boxes are fresh in your mind. Then, when you come back to the code later - you are trying to infer what is happening inside the boxes simply from the function names.</p>\n\n<p>Congratulations, you have just atomized your code. And when you did it, you probably were using some type of naming convention that was conducive to typing instead of describing -- using short names that allowed you to 'zoom out' on the code line.</p>\n\n<p>When you come back to it, your ego will be stroked with thoughts of \"I must have been a genius the day I wrote this!\" -- because you can't understand it now without sitting in the lotus position and meditating deeply.</p>\n\n<p>There is a lot to be said in favor of 'flat coding' and copy/paste extensibility. On the other hand, you have the power of a well-developed framework.</p>\n\n<p>You have to ask yourself, 'what am I making here' -- is any of this a framework that I can extract and formalize? Will I do it? What is my deadline?</p>\n\n<p>So you have a tension along the spectrum of modularity/frameworks and flat code that says what it does right in your face. Don't take DRY and other best practices as a religion, look at your real-world goals and tackle the problem like an infantryman -- your job is to kill the deadline and not leave too many innocent corpses in your wake.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-14T00:54:23.797",
"Id": "7789",
"ParentId": "2214",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "2245",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-03T19:02:08.923",
"Id": "2214",
"Score": "5",
"Tags": [
"javascript",
"jquery"
],
"Title": "shorthand methods"
} | 2214 |