body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<pre><code>import random
from random import choice
import os
import time
import texttable
class Stack():
def __init__(self, replay, winnings):
self.start_amount = 100
self.stored_bet = 0
self.stored_end = 0
self.replay = replay
if self.replay == 0:
self.stored_end = 0 #needs to be initialized
else:
self.stored_end = self.stored_end + winnings
def load_account(self):
self.stored_end = self.start_amount
def account(self, begin, change):
end = float(begin) + float(change)
self.stored_end = end # store class variable??
return(begin, change, end)
def bet_test(self, miss_type):
# collect's bet and check input
# miss_type should start as 0
possible_bets = ['5', '10', '15', '20', '25']
while True:
print "\nWhat is your bet? (5, 10, 15, 20, 25)"
bet = raw_input(' >')
if bet in possible_bets:
bet = int(bet)
if self.replay == 1:
begin = self.stored_end
self.stored_bet = int(bet)
break
else:
if bet > self.stored_end:
print "You don't have enough for that bet."
time.sleep(2)
else:
begin = self.stored_end
self.stored_bet = bet
break
class DECK():
def __init__(self):
suite = ('Spades', 'Hearts', 'Diamonds', 'Clubs')
rank = ('2', '3', '4', '5', '6', '7', '8', '9', '10', "Jack", "Queen", "King", "Ace")
self.full_deck = {}
n = 0
i = 0
for n in range(6):
for s in suite:
for r in rank:
self.full_deck[i + n] = "%s of %s" % (r, s)
i += 1
n += 1
self.values = {'Ace':11, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '10': 10, 'Jack': 10, 'Queen': 10, 'King': 10}
self.test_hand1 = {0: 'Ace of Spades', 1: 'Jack of Clubs' } # for testing
self.test_hand2 = {0: 'Ace of Clubs', 1: '10 of Diamonds' } # for testing
self.test_hand3 = {0: '8 of Spades', 1: '8 of Hearts'} # for testing splits
self.hand_dict = {} # this will be a dict of all the hand instances created by Hand.
self.incomplete_hands = {} # hands yet to be played
self.compltete_hands = {} # hands done being played
# re-split hands and counters
self.split_counter = 0
def hand_table(self):
# show table of hands
hands_dict = {}
bets_dict = {}
points_dict = {}
for hand in Hand.instances:
hands_dict.setdefault(hand.name, hand.hand_a)
bets_dict.setdefault(hand.name, hand.bet)
points_dict.setdefault(hand.name, hand.hand_points)
first_cards = []
second_cards = []
third_cards = []
fourth_cards = []
fifth_cards = []
bets_list = []
points_list = []
for hand in hands_dict:
first_cards.append(hands_dict[hand].get(0))
second_cards.append(hands_dict[hand].get(1))
third_cards.append(hands_dict[hand].get(2))
fourth_cards.append(hands_dict[hand].get(3))
fifth_cards.append(hands_dict[hand].get(4))
bets_list.append("Bet is %r" % bets_dict[hand])
points_list.append("Points are %r" % points_dict[hand])
print "\n"
header = hands_dict.keys()
table = texttable.Texttable()
table.header(header)
table.add_rows([first_cards, second_cards, third_cards, fourth_cards, fifth_cards, points_list, bets_list], header = False)
print table.draw()
def dhos(self):
# dealer hit or stick
os.system("clear")
#show table of hands
self.hand_table()
print " _ " * 10
game.deck.d_hand.show_hand()
time.sleep(1.5)
dpoints, d_raw_points = game.deck.d_hand.points()
if dpoints < 17:
new_card = game.deck.full_deck.pop(random.choice(game.deck.full_deck.keys()))
print new_card
hl = len(game.deck.d_hand.hand_a.keys()) # hl is hand length
game.deck.d_hand.hand_a[hl] = new_card # insert new hard into the given hand
self.dhos()
else:
game.deck.d_hand.hand_points = dpoints
game.end_game()
def deal(self):
# deal two cards each to dealer and player
dhand = {}
phand = {}
for i in range (2):
phand[i] = game.deck.full_deck.pop(random.choice(game.deck.full_deck.keys()))
dhand[i] = game.deck.full_deck.pop(random.choice(game.deck.full_deck.keys()))
# actual hand
# creat instance of Hand for player's starting hand
self.start_hand = Hand(phand, game.deck.full_deck, 0, "Opening Hand")
# start_hand instance is now a member of the deck object.
# creat instance of Hand for dealer's starting hand
self.d_hand = Hand(dhand, game.deck.full_deck, 0, "Dealer")
# d_hand instance is now a member of the deck object.
def split_algo(self, hand):
print hand.hand_a
# old cards
card1 = hand.hand_a[0]
card2 = hand.hand_a[1]
print card1
print card2
# new cards
card_a = self.full_deck.pop(random.choice(self.full_deck.keys()))
card_b = self.full_deck.pop(random.choice(self.full_deck.keys()))
print card_a
print card_b
#two new hands
new_hand_a = {0: card1, 1: card_a}
new_hand_b = {0: card2, 1: card_b}
if game.deck.split_counter == 0:
self.split_1 = Hand(new_hand_a, game.deck.full_deck, 0, 'Split 1')
self.split_2 = Hand(new_hand_b, game.deck.full_deck, 0, 'Split 2')
# load bets: equal to bet on first hand
self.split_1.bet = game.deck.start_hand.bet
self.split_2.bet = game.deck.start_hand.bet
split_hands_dict = {0: self.split_1, 1: self.split_2}
# find the staring hand 'test split' in this case and delete it
for x in range(len(Hand.instances)):
if Hand.instances[x-1].name == 'Opening Hand':
del Hand.instances[x-1]
game.deck.split_counter += 1
return split_hands_dict
class Hand():
instances = [] # used to keep track of hand instances
def __init__(self, hand_a, play_deck, split_count, name): # hand_a for hand actual
Hand.instances.append(self)
self.hand_a = hand_a # the actual hand when instance created
# self.play_deck = play_deck # need to move this to deck class
self.split_count = split_count
self.name = name
self.hand_points = 0
self.raw_points = 0
self.aces = 0
self.testy = self
self.status = 'incomplete'
self.bet = 0
self.stack_change = 0
self.outcome = ''
self.black_jack = 0
def show_hand(self):
print "%r hand is:" % self.name
for i in range(len(self.hand_a.keys())):
print self.hand_a[i]
print "\n"
def show_card(self, key):
return self.hand_a[key]
def points(self):
ln = len(self.hand_a.keys())
tpoints = 0
# add up all the cards with aces = 11
self.aces = 0
for i in range(ln):
card, rank = self.card_and_rank(self.hand_a[i])
# add up all the aces
if rank == 'Ace':
self.aces += 1
# deck is an object of game
tpoints = game.deck.values[rank] + tpoints
raw_points = tpoints
# check to see if there are aces in the hand.
if self.aces > 0:
for n in range(self.aces):
# check to see if the total points are more than 21.
if tpoints > 21:
# subtract 10 points for each ace.
tpoints = tpoints - 10
return (tpoints, raw_points)
def card_and_rank(self, card):
z = card.split()
rank = z[0]
return (card, rank)
def split_test(self):
card_a, rank_a = self.card_and_rank(self.hand_a[0])
card_b, rank_b = self.card_and_rank(self.hand_a[1])
val_a = game.deck.values[rank_a]
val_b = game.deck.values[rank_b]
if self.bet * 2 > stack.stored_end:
print "You don't have enough cash to split."
time.sleep(2)
return 'no'
elif game.deck.split_counter == 1:
return 'no'
elif val_a == val_b:
return 'split'
else:
return 'no'
def hos(self):
# hos = hit or stick
os.system("clear")
self.hand_points, self.raw_points = self.points()
print "\n"
# show dealer's hand
print "Dealer's up card is:\n%r\n" % game.deck.d_hand.show_card(0)
# show starting hand
self.show_hand()
self.softness(self.hand_points, self.raw_points)
print "\nYou're bet is $%d." % stack.stored_bet
print "Your stack is (less your current bet) $%d" % (stack.stored_end - stack.stored_bet)
x = self.black_jack_check()
if x == 'black_jack':
self.black_jack = 1
answer = 'stick'
self.check_hand(answer)
if self.split_test() == 'split':
answers = ['hit', 'stick', 'double', 'split']
while True:
print "\nWould you like to 'hit', 'stick', 'double' down or 'split'?"
if self.hand_points == 21:
answer = 'stick'
print "You have 21!"
time.sleep(.5)
break
else:
answer = raw_input(' >')
if answer in answers:
print "end of hos func"
break
else:
answers = ['hit', 'stick', 'double']
while True:
print "\nWould you like to 'hit', 'stick' or 'double'?"
if self.hand_points == 21:
answer = 'stick'
print "You have 21!"
time.sleep(.5)
break
else:
answer = raw_input(' >')
if answer in answers:
print "end of hos func"
break
self.check_hand(answer)
def check_hand(self, answer):
print "\nYou said %r." % answer
# hit
if answer == 'hit':
self.hit()
if self.hand_points > 21:
self.status = 'completed'
print "Your busted"
print "need to go to end game"
self.status = 'completed'
return 'done'
hl = len(self.hand_a.keys())
if hl == 5:
self.status = 'completed'
return 'done'
self.hos()
# stick
elif answer == 'stick':
self.status = 'completed'
print "need to call dhos and end the game"
# double
elif answer == 'double':
t_bet = stack.stored_bet # temp bet
t_end = stack.stored_end # temp stack balance (before bet)
t_bal = t_end - t_bet # what would the stack be if bet subtracted?
if t_bet > t_bal:
print "You don't have enough to doule down."
print "need to continue with hand - should check this when asking the question."
raw_input("Please hit enter to continue")
else:
print "\nYou doubled down."
stack.stored_bet = stack.stored_bet * 2
self.bet = self.bet * 2
print "Your bet is now $%d." % stack.stored_bet
self.hit()
self.show_hand()
self.status = 'completed'
time.sleep(3)
# split
elif answer == 'split':
if game.deck.split_counter == 0:
split_hands_dict = game.deck.split_algo(game.deck.start_hand)
ln = len(split_hands_dict)
for x in range(ln):
split_hands_dict[x].hos()
else:
print "Sorry, but no more splits."
time.sleep(2)
else:
print "something went horribly wrong."
exit(0)
def softness(self, points, raw_points):
# returns soft hand if hand is soft
if self.aces > 0:
nap = raw_points - (self.aces * 11) # = non-ace - points
if nap + 11 < 21:
print "\n%s has a soft %d" % (self.name, points)
print " _ " * 10
else:
print "%s has %d points. a" % (self.name, points)
print " _ " * 10
else:
print "%s has %d points." % (self.name, points)
print " _ " * 10
def black_jack_check(self):
# print " _ " * 10
# print "\n"
zz = {}
for i in range(len(self.hand_a.keys())):
card, rank = self.card_and_rank(self.hand_a[i])
# print "card is %r and rank is %r" % (card, rank)
zz[i] = rank
i += 1
if zz[0] == 'Ace' and zz[1] == "Jack":
# print "zz[0] is %r and zz[1] is %r a " % (zz[0], zz[1])
print "\nBlack Jack! You Win!\n"
time.sleep(1.5)
return "black_jack"
elif zz[0] == 'Jack' and zz[1] == 'Ace':
# print "zz[0] is %r and zz[1] is %r b" % (zz[0], zz[1])
print "\nBlack Jack! You Win!\n"
time.sleep(1.5)
return "black_jack"
else:
return 0
def hit(self):
print "hit method"
k = len(game.deck.full_deck.keys())
print k
new_card = game.deck.full_deck.pop(random.choice(game.deck.full_deck.keys()))
# hl = len(game.deck.start_hand.hand_a.keys()) # hl is hand length
hl = len(self.hand_a.keys()) # hl is hand length
print hl
# add new card tto hand
self.hand_a[hl] = new_card # insert new hard into hand of the given instance.
# add new opints to self.hand_points
self.hand_points, self.raw_points = self.points()
class Game():
def __init__(self):
self.hand_dict = {} # this will be a dict of all the hand instances created by Hand.
self.incomplete_hands = [] # hands yet to be played
self.compltete_hands = {} # hands done being played
def collect_hands(self):
# loops trough Hand.instances and unpacks into indivudual hands
print "\nbegin collect_hands\n"
i = 0
for handy in Hand.instances:
self.hand_dict.setdefault(handy.name, handy.hand_a)
i += 1
print self.hand_dict
print "\n"
for player in self.hand_dict:
print player
n = 0
for n in range(len(self.hand_dict[player])):
print self.hand_dict[player][n]
n += 1
print "print card rows"
# list of rows
first_cards = []
second_cards = []
third_cards = []
fourth_cards = []
fifth_cards = []
list_of_rows_raw = [first_cards, second_cards, third_cards, fourth_cards, fifth_cards]
for x in self.hand_dict:
first_cards.append(self.hand_dict[x][0])
for y in self.hand_dict:
second_cards.append(self.hand_dict[y][1])
table = texttable.Texttable()
header = self.hand_dict.keys()
table.header(header)
table.add_rows([first_cards, second_cards], header=False)
print table.draw()
def end_game(self):
# check to see how each completed hand did against the dealer
dpoints = self.deck.d_hand.hand_points
for hand in Hand.instances:
hand.stack_change = 0
if hand.status == 'completed':
# print "hand is %r" hand.name
print "hand points are %r" % hand.hand_points
print "dpoints are %r" % dpoints
print "bet is %r" % hand.bet
if hand.hand_points == 21:
if hand.black_jack == 1:
hand.stack_change = hand.stack_change + ((float(3)/2) * hand.bet)
hand.outcome = "Black Jack!!"
else:
hand.stack_change += hand.bet
hand.outcome = "Win"
elif hand.hand_points > 21:
hand.stack_change -= hand.bet
hand.outcome = "Lose"
elif dpoints > 21:
hand.stack_change += hand.bet
hand.outcome = "Win"
elif hand.hand_points < dpoints:
hand.stack_change -= hand.bet
hand.outcome = "Lose"
elif hand.hand_points > dpoints:
hand.stack_change += hand.bet
hand.outcome = "Win"
elif hand.hand_points == dpoints:
hand.stack_change + 0
hand.outcome = "Push"
else:
print "not sure what to tell you"
exit(0)
self.check_score()
def check_score(self):
#check to see if player has money to play again
total_winnings = 0
for hand in Hand.instances:
total_winnings = total_winnings + hand.stack_change
if stack.stored_end + total_winnings < 0:
print "You're out of cash. Goodbye!"
exit(0)
else:
stack.stored_end += total_winnings
self.replay(0, total_winnings)
def replay(self, miss_type, total_winnings):
# show table of hands
os.system("clear")
print "Your hands: \n"
hands_dict = {}
bets_dict = {}
outcomes_dict = {}
points_dict = {}
for hand in Hand.instances:
hands_dict.setdefault(hand.name, hand.hand_a)
bets_dict.setdefault(hand.name, hand.bet)
outcomes_dict.setdefault(hand.name, hand.outcome)
points_dict.setdefault(hand.name, hand.hand_points)
first_cards = []
second_cards = []
third_cards = []
fourth_cards = []
fifth_cards = []
bets_list = []
outcomes_list = []
points_list = []
for hand in hands_dict:
first_cards.append(hands_dict[hand].get(0))
second_cards.append(hands_dict[hand].get(1))
third_cards.append(hands_dict[hand].get(2))
fourth_cards.append(hands_dict[hand].get(3))
fifth_cards.append(hands_dict[hand].get(4))
bets_list.append("Bet is %r" % bets_dict[hand])
points_list.append("Points are %r" % points_dict[hand])
outcomes_list.append(outcomes_dict[hand])
header = hands_dict.keys()
table = texttable.Texttable()
table.header(header)
table.add_rows([first_cards, second_cards, third_cards, fourth_cards, fifth_cards, points_list, bets_list, outcomes_list], header = False)
print table.draw()
print "\n"
self.deck.d_hand.show_hand()
print "Dealer's points are %r." % self.deck.d_hand.hand_points
print "\nYou won $%r" % total_winnings
print "Your stack is now $%r\n" % stack.stored_end
if stack.stored_end <=0:
print "You're out of cash. Better luck next time!"
exit(0)
while True:
print "\nWould you like to play again?"
a = raw_input(' >')
if a == 'no':
print "Thanks for playing."
print "You ended up with $%d\n" % stack.stored_end
exit(0)
elif a =='yes':
hil = len(Hand.instances) # hil = hand instances length
for x in range(hil):
del Hand.instances[x-1]
time.sleep(1)
game.play_game(1, total_winnings)
break
else:
print "just 'yes' or 'no' please."
time.sleep(1)
def load_inc_hands(self):
# load first opening hand into incomplete hadns dict.
# remove dealer hand
lnth = len(Hand.instances)
for x in range(lnth):
if Hand.instances[x-1].name == 'Dealer':
del Hand.instances[x-1]
lnth = len(Hand.instances)
for z in range(lnth):
self.incomplete_hands.append(Hand.instances[z].name)
def play_game(self, replay, total_winnings):
# start
self.deck = DECK()
if replay == 1:
self.stack = Stack(1 , total_winnings)
os.system("clear")
print "Let's play!\n"
print " _ " * 10
begin = stack.stored_end # need this here for when game is replayed
begin, change, end = stack.account(0, begin) #laod account func with initical balance
print "You have $%d in your stack.\n" % end
print " _ " * 10
time.sleep(0.5)
play_deck = self.deck.full_deck
# bet
stack.bet_test(0)
bet = stack.stored_bet
# deal
self.deck.deal()
# attach the bet to the starting hand
self.deck.start_hand.bet = bet
os.system("clear")
print "deck has %r cads" % len(play_deck.keys())
print "play_game method of Game class\n"
# load incomeplete hands dict
self.load_inc_hands()
# go thorugh each hand and hit or stick
for hand in Hand.instances:
if hand.status == 'incomplete':
print "you're stuck in the hos loop"
hand.hos()
# go to dealer's hand
self.deck.dhos()
exit(0)
if __name__ == '__main__':
game = Game()
stack = Stack(0, 0)
stack.load_account()
game.play_game(0, 0)
</code></pre>
<p>First, if there's a better way to get the code in here than copy and paste, please let me know. Checking all the indents in python is a bit of a pain.</p>
<p>Second, please rip up this code! I'm trying to learn Python on my own and need all the feedback I can get. Please comment on everything: best practices, conventions...etc. Any and all comments welcome.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-30T19:55:30.220",
"Id": "24693",
"Score": "0",
"body": "about `DECK()` class; [it is convention to use CapWords for class names](http://www.python.org/dev/peps/pep-0008/#class-names)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T23:56:38.060",
"Id": "63221",
"Score": "1",
"body": "You should either remove `from random import choice` or replace all instances of `random.choice` with `choice`"
}
] |
[
{
"body": "<ol>\n<li>Python convention is to name classes with CamelCase, not ALL_CAPS</li>\n<li>Don't use 1 and 0 for boolean values, use True and False</li>\n<li>Don't mix UI and logic. You should have some classes/functions that implement the rules for the game, and completely different classes/functions for the user interface.</li>\n<li>Avoid the use of mutable class variable like <code>Hand.instances</code></li>\n<li>Your classes don't seem to have a defined identity. Your <code>Stack</code> class seems like it should represent a stack of chips. But it also seems to be keeping track of past history a little bit? I'm really not quite sure what the replay logic is doing.</li>\n<li>The rules of the game seem to be strewn all over the code. Look at the number of places that have 21.</li>\n</ol>\n\n<p>Let's take a detailed look at one function:</p>\n\n<pre><code>def bet_test(self, miss_type):\n # collect's bet and check input\n # miss_type should start as 0\n possible_bets = ['5', '10', '15', '20', '25']\n</code></pre>\n\n<p>Constant lists like this should be global constants. </p>\n\n<pre><code> while True:\n print \"\\nWhat is your bet? (5, 10, 15, 20, 25)\"\n bet = raw_input(' >')\n if bet in possible_bets:\n bet = int(bet)\n</code></pre>\n\n<p>I don't like reusing variables for different things. i.e. the text and number version of the bet. I'd store them in different names.</p>\n\n<pre><code> if self.replay == 1:\n</code></pre>\n\n<p>Use <code>if self.replay:</code> for boolean values</p>\n\n<pre><code> begin = self.stored_end\n</code></pre>\n\n<p>You set begin, but you don't seem to do anything with it...</p>\n\n<pre><code> self.stored_bet = int(bet)\n</code></pre>\n\n<p>bet is already an int</p>\n\n<pre><code> break\n else:\n if bet > self.stored_end:\n</code></pre>\n\n<p>Why not use an <code>elif</code> here to force, </p>\n\n<pre><code> print \"You don't have enough for that bet.\"\n time.sleep(2)\n else:\n begin = self.stored_end\n self.stored_bet = bet\n break\n</code></pre>\n\n<p>You've done this twice. You should rearrange the code so that it happens only once.</p>\n\n<p>Here's my reworking of that function:</p>\n\n<pre><code>def bet_test(self, miss_type):\n # collect's bet and check input\n # miss_type should start as 0\n possible_bets = range(5, min(25, self.stored_end+1), 5)\n while True:\n print \"\\nWhat is your bet? (%s)\" % (\", \".join(possible_bets))\n try:\n bet = int(raw_input(' >'))\n except ValueError:\n pass # make them try again\n else:\n if bet in possible_bets:\n self.stored_bet = bet\n break\n self.stored_bet = bet\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-31T02:06:36.250",
"Id": "15225",
"ParentId": "15219",
"Score": "11"
}
},
{
"body": "<p>Some other points:</p>\n\n<ul>\n<li><code>from random import choice</code>, but you only ever use <code>random.choice</code> not <code>choice</code>.</li>\n<li>You often use something like: <code>full_deck.pop(random.choice(full_deck.keys()))</code>.\nRather than this, consider using a list rather than a dictionary and using <code>random.shuffle</code> to shuffle the pack at the start. Then it's just a case of popping one.</li>\n<li><p>You're holding the hands as dictionaries as well, for no purpose other than indexing them with 0, 1 etc. Don't forget that you can use lists for this!</p></li>\n<li><p>In Deck.init:</p>\n\n<pre><code>n = 0\ni = 0\nfor n in range(6):\n for s in suite:\n for r in rank:\n self.full_deck[i + n] = \"%s of %s\" % (r, s)\n i += 1\n n += 1\n</code></pre>\n\n<p><code>n</code> seems to be part of some leftover code, <code>n = 0</code> and <code>n += 1</code> are redundant, its values are directly taken from the range object. For that matter, I don't know why that loop is there at all.</p></li>\n<li><p>Use full variable/function names. There's nothing wrong with using <code>dealer_hit_or_stick</code> as a name rather than <code>dhos</code>.</p></li>\n<li><p>For asking questions, since you're picking from a defined list of responses, separate it into a function, which will simplify your code a bit. <code>get_player_response( question, options )</code></p></li>\n<li><p>Try to avoid using strings as return values (<em>e.g.</em> in <code>split_test</code>) - there's always a possibility of a hard-to-track spelling mistake. If you can't use a boolean return, make up some constants for them. This also applies to get_player_response - if you pass a dictionary (string:constant) as the options, you can test against the keys and return the value.</p></li>\n<li><p>In the place where you're using split_test (which should really be renamed is_split_allowed), you can avoid the repeated 21 test with a bit of rearrangement.</p></li>\n<li><p>Printing the hands should be put into a separate function (avoid repeated code!)</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-31T07:09:35.303",
"Id": "15230",
"ParentId": "15219",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "15225",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-30T19:43:45.973",
"Id": "15219",
"Score": "8",
"Tags": [
"python",
"game",
"playing-cards"
],
"Title": "Blackjack game in Python"
}
|
15219
|
<p>I am practicing using the Prototype pattern and to do so, I am building a simple CRUD app that allows me to view, add, and delete customers.</p>
<p><a href="http://jsfiddle.net/phillipkregg/cfafr/146/" rel="nofollow">Here</a> is a JsFiddle for you to see what I've got so far.</p>
<pre><code>// Create customer 'class' and store state here
var Customer = function(el) {
this.el = document.getElementById(el);
this.first_name = $("#input_first_name").val();
this.last_name = $("#input_last_name").val();
this.name = ""
}
var customers = [];
// In the Customer prototype store methods
Customer.prototype = {
// utility to log customer array
logCustomers: function() {
console.log(customers);
},
fullName: function() {
this.name = this.first_name + " " + this.last_name;
return this.name;
},
addCustomer: function() {
// clear out the current html to make room for the append later
this.el.innerHTML = "";
// create new customer instance
var cust = new Customer();
// add customer to the array
customers.push(cust);
// iterate through the array and add each customer to a row in the table
$.each(customers, function() {
$("#el").append("<tr><td>" + this.fullName() + "</td><td><a id='btn_remove_cust' class='btn btn-mini btn-danger'>delete</a></td></tr>");
})
// Clear out the text boxes
$("#input_first_name").val("");
$("#input_last_name").val("");
},
// Remove customer from array and hide the row that contained them
removeCustomer: function(e) {
$(e.target).closest('tr').hide();
customers.splice(e.target, 1);
}
}
// Default customer object has to be created in order for unobtrusive calls to work
var cust = new Customer("el");
// unobtrusive jQuery event handling below
$("#btn_add_customer").click(function() {
cust.addCustomer();
});
$("#btn_remove_cust").live("click", cust.removeCustomer);
$("#btn_log_customers_array").click(cust.logCustomers)
</code></pre>
<p>There are a few things that I'm concerned about:</p>
<ol>
<li><p>I'm using jQuery to handle events and I'm trying to make everything as unobtrusive as possible. In doing so, I wasn't exactly sure where I needed to place the event-handling code so I created a separate block below the prototype code to contain the button click events. I'm not sure if this is the best way to go.</p></li>
<li><p>The events are being passed a function from the prototype - so in order for anything to work I have to new-up an instance of the 'Customer' before the user actually creates a new customer. Seems like there might be a better way - but since I'm using a constructor function, I'm not sure if there is any other way around that. If I change the constructor to an object literal, than I've just got a singleton.</p></li>
<li><p>Am I handling the removal of 'customers' from the array properly? I created a simple utility function that is wired up to a button so that I could check and make sure that objects were being removed - as well as hidden in the DOM.</p></li>
</ol>
|
[] |
[
{
"body": "<p>Here's are a few things that I noticed.</p>\n\n<h1>1</h1>\n\n<p>The control and flow of the application needs to be seperated into smaller logical groups.\nThe <code>customers</code> should be a container and controller for the customers, not the otherway around. \nFor example, <code>Customer.prototype.addCustomer</code> should be associated with <code>Customers.prototype.addCustomer</code>, since Customers is a container for customer objects.</p>\n\n<h1>2</h1>\n\n<p><code>this.id</code> should be a property inside the Customer constructor. Ideally, the id value should be set to null until it is added to the Customers container.</p>\n\n<h1>3</h1>\n\n<p>Setting an object's prototype to an object over-writes the entire prototype, which means that you lose the reference to the constructor object.\nSo it's better if you add values and functions to the prototype one at a time like so.</p>\n\n<pre><code>// ok but you lost a few values.\nCustomer.prototype = {\n method1: function(){\n //...\n }\n};\n\n//best\nCustomer.prototype.method1 = function(){\n //...\n};\n</code></pre>\n\n<h1>4</h1>\n\n<p>Pass values to the constructor rather than have the constructor go out and find them.</p>\n\n<pre><code>// ok\nvar Customer = function(el) {\n this.el = document.getElementById(el); \n this.first_name = $(\"#input_first_name\").val();\n this.last_name = $(\"#input_last_name\").val();\n this.name = \"\"\n}\n\n// best\nvar Customer = function(el, firstName, lastName ) {\n this.el = document.getElementById(el); \n this.first_name = firstName;\n this.last_name = lastName;\n this.name = \"\";\n this.id;\n} \n</code></pre>\n\n<p>Here's a free online book to help you to understand MVC\n<a href=\"http://addyosmani.github.com/backbone-fundamentals/\" rel=\"nofollow\">http://addyosmani.github.com/backbone-fundamentals/</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-03T11:28:08.667",
"Id": "15302",
"ParentId": "15220",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-30T20:29:22.417",
"Id": "15220",
"Score": "2",
"Tags": [
"javascript",
"jquery",
"crud"
],
"Title": "CRUD app for managing customers"
}
|
15220
|
<p>I've written this code to convert an integer number into its word representation. I've tested it for many cases and it seems to be working as expected.</p>
<p>For example:</p>
<ul>
<li>1000 displayed as "One Thousand"</li>
<li>99999 displayed as "Ninety nine thousand nine hundred ninety nine"</li>
<li>999999999 displayed as "Nine hundred ninety nine million nine hundred ninety nine thousand nine hundred ninety nine"</li>
</ul>
<p>However, I think it could be improved especially because I'm doing some checks repeatedly. Can someone suggest some refactoring for this? </p>
<pre><code>import java.util.HashMap;
public class NumberToWord {
static HashMap<Integer,String> numberMap = new HashMap<Integer,String>();
static{
numberMap.put(0,"Zero");
numberMap.put(1,"One");
numberMap.put(2,"Two");
numberMap.put(3,"Three");
numberMap.put(4,"Four");
numberMap.put(5,"Five");
numberMap.put(6,"Six");
numberMap.put(7,"Seven");
numberMap.put(8,"Eight");
numberMap.put(9,"Nine");
numberMap.put(10,"Ten");
numberMap.put(11,"Eleven");
numberMap.put(12,"Twelve");
numberMap.put(13,"Thirteen");
numberMap.put(14,"Fourteen");
numberMap.put(15,"Fifteen");
numberMap.put(16,"Sixteen");
numberMap.put(17,"Seventeen");
numberMap.put(18,"Eighteen");
numberMap.put(19,"Nineteen");
numberMap.put(20,"Twenty");
numberMap.put(30,"Thirty");
numberMap.put(40,"Forty");
numberMap.put(50,"Fifty");
numberMap.put(60,"Sixty");
numberMap.put(70,"Seventy");
numberMap.put(80,"Eighty");
numberMap.put(90,"Ninety");
numberMap.put(100,"Hundred");
numberMap.put(1000,"Thousand");
}
public static String numberToWord(int number)
{
String wordForm = "";
int quotient =0;
int remainder = 0;
int divisor = 0;
if(number<1000000000 && number>=1000000)
{
divisor = 1000000;
quotient = number/divisor;
remainder = number % divisor;
if(quotient!=0)
wordForm += numberToWord(quotient) + " " + "Million";
if(remainder!=0)
wordForm+= " " + numberToWord(remainder);
}
else if(number<1000000 && number>=10000)
{
divisor = 1000;
quotient = number/divisor;
remainder = number % divisor;
if(quotient!=0)
wordForm += numberToWord(quotient) + " " + "Thousand";
if(remainder!=0)
wordForm+= " " + numberToWord(remainder);
}
else if(number<10000 && number>=1000)
{
divisor = 1000;
quotient = number/divisor;
remainder = number % divisor;
if(quotient!=0)
wordForm += numberMap.get(quotient) + "Thousand";
if(remainder!=0)
wordForm+= numberToWord(remainder);
}else if(number<1000 && number>=100)
{
divisor = 100;
quotient = number/divisor;
remainder = number % divisor;
if(quotient!=0)
wordForm += numberMap.get(quotient) + " " + "Hundred";
if(remainder!=0)
wordForm +=numberToWord(remainder);
}else if(number<100 && number>=10)
{
divisor = 10;
quotient = number/divisor;
remainder = number % divisor;
if(quotient!=0)
wordForm+= numberMap.get(quotient*divisor);
if(remainder!=0)
wordForm+= numberMap.get(remainder);
}else if(number<10 && number>=0)
{
wordForm += numberMap.get(number);
}
return wordForm;
}
public static void main(String[] args)
{
System.out.println(numberToWord(100000));
System.out.println(numberToWord(999999));
System.out.println(numberToWord(678900));
System.out.println(numberToWord(0));
System.out.println(numberToWord(100567));
System.out.println(numberToWord(4589));
System.out.println(numberToWord(3333));
System.out.println(numberToWord(67500));
System.out.println(numberToWord(72));
System.out.println(numberToWord(172346));
System.out.println(numberToWord(890000));
System.out.println(numberToWord(600700));
System.out.println(numberToWord(67));
System.out.println(numberToWord(999999999));
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-31T01:04:16.057",
"Id": "24698",
"Score": "1",
"body": "Although this is targeting c# and may be slighter different you might find this Code Review question useful - http://codereview.stackexchange.com/questions/14033/convert-number-to-words-web-application"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-31T03:13:46.447",
"Id": "24702",
"Score": "1",
"body": "This is a duplicate of http://stackoverflow.com/questions/3911966/how-to-convert-number-to-words-in-java"
}
] |
[
{
"body": "<p>Some notes:</p>\n\n<ol>\n<li><p><code>wordForm</code> should be <code>StringBuilder</code>: <a href=\"https://stackoverflow.com/questions/73883/string-vs-stringbuilder\">https://stackoverflow.com/questions/73883/string-vs-stringbuilder</a> Actually, I'd rename it to <code>result</code> too to make it clear that this object stores the result of the method.</p></li>\n<li><p>Instead of the <code>System.out.println</code>s, use a parametrized unit test:</p>\n\n<pre><code>import static org.junit.Assert.assertEquals;\n\nimport java.util.Arrays;\nimport java.util.Collection;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.junit.runners.Parameterized;\nimport org.junit.runners.Parameterized.Parameters;\n\n@RunWith(value = Parameterized.class)\npublic class NumberToWordTest extends NumberToWord {\n\n private final String expected;\n private final int input;\n\n public NumberToWordTest(final String expected, final int input) {\n this.expected = expected;\n this.input = input;\n }\n\n @Parameters\n public static Collection<Object[]> data() {\n final Object[][] data = new Object[][] {\n { \"One Hundred Thousand\", 100000 },\n { \"Nine HundredNinetyNine Thousand Nine HundredNinetyNine\", 999999 },\n { \"Six HundredSeventyEight Thousand Nine Hundred\", 678900 },\n { \"Zero\", 0 },\n { \"One Hundred Thousand Five HundredSixtySeven\", 100567 },\n { \"FourThousandFive HundredEightyNine\", 4589 },\n { \"ThreeThousandThree HundredThirtyThree\", 3333 },\n { \"SixtySeven Thousand Five Hundred\", 67500 },\n { \"SeventyTwo\", 72 },\n { \"One HundredSeventyTwo Thousand Three HundredFortySix\", 172346 },\n { \"Eight HundredNinety Thousand\", 890000 },\n { \"Six Hundred Thousand Seven Hundred\", 600700 },\n { \"SixtySeven\", 67 },\n { \"Nine HundredNinetyNine Million Nine HundredNinetyNine Thousand Nine HundredNinetyNine\", 999999999 } };\n return Arrays.asList(data);\n }\n\n @Test\n public void test() {\n assertEquals(expected, NumberToWord.numberToWord(input));\n }\n\n}\n</code></pre>\n\n<p>See: <a href=\"http://junit.sourceforge.net/doc/faq/faq.htm#best_6\" rel=\"nofollow noreferrer\">Why not just use System.out.println()?</a> in the JUnit FAQ.</p></li>\n<li><p>The <code>number</code> parameter could be <code>final</code>. It would help readers, because they know that the value does not change later. <a href=\"https://softwareengineering.stackexchange.com/questions/115690/why-declare-final-variables-inside-methods\">https://softwareengineering.stackexchange.com/questions/115690/why-declare-final-variables-inside-methods</a> but you can find other questions on Programmers.SE in the topic.</p></li>\n<li><p>According to the <a href=\"http://www.oracle.com/technetwork/java/codeconventions-142311.html#430\" rel=\"nofollow noreferrer\">Code Conventions for the Java Programming Language</a></p>\n\n<blockquote>\n <p>if statements always use braces {}.</p>\n</blockquote>\n\n<p>Omitting them is error-prone.</p></li>\n<li><p>Numbers like <code>1000000000</code>, <code>1000000</code> etc. are magic numbers. You should use named constants.</p>\n\n<pre><code>private static final int ZERO = 0;\nprivate static final int TEN = 10;\nprivate static final int ONE_HUNDRED = 100;\nprivate static final int ONE_THOUSAND = 1000;\nprivate static final int TEN_THOUSANDS = 10000;\nprivate static final int ONE_BILLION = 1000000000;\nprivate static final int ONE_MILLION = 1000000;\n</code></pre></li>\n<li><p>The method does not handle negative numbers. In this case you should throw an <code>IllegalArgumentException</code> instead of returning an empty string. (See: <em>Effective Java, 2nd edition, Item 38: Check parameters for validity</em>)</p></li>\n<li><p>The reference type of <code>numberMap</code> should be simply <code>Map<Integer, String></code>. See: <em>Effective Java, 2nd edition</em>, <em>Item 52: Refer to objects by their interfaces</em></p></li>\n<li><p><code>numberMap</code> could be <code>private</code> and unmodifiable. It would prevent accidental modification.</p>\n\n<pre><code>private static final Map<Integer, String> numberMap = createNumberMap();\n\nprivate static Map<Integer, String> createNumberMap() {\n final Map<Integer, String> numberMap = new HashMap<Integer, String>();\n numberMap.put(0, \"Zero\");\n numberMap.put(1, \"One\");\n ...\n return Collections.unmodifiableMap(numberMap);\n}\n</code></pre>\n\n<p><a href=\"https://stackoverflow.com/questions/7959129/whats-the-deal-with-javas-public-fields\">What's the deal with Java's public fields?</a></p></li>\n<li><p>I'd try to extract out a few methods:</p>\n\n<pre><code>private static void calc(final StringBuilder result, final int number, \n final int divisor, final String postfix) {\n final int quotient = number / divisor;\n final int remainder = number % divisor;\n if (quotient != 0) {\n result.append(numberToWord(quotient));\n result.append(\" \");\n result.append(postfix);\n }\n if (remainder != 0) {\n result.append(\" \");\n result.append(numberToWord(remainder));\n }\n}\n\nprivate static void calc2(final StringBuilder result, final int number, \n final int divisor, final String postfix) {\n final int quotient = number / divisor;\n final int remainder = number % divisor;\n if (quotient != 0) {\n result.append(numberMap.get(quotient));\n result.append(postfix);\n }\n if (remainder != 0) {\n result.append(numberToWord(remainder));\n }\n}\n\nprivate static void calc3(final StringBuilder result, final int number, \n final int divisor) {\n final int quotient = number / divisor;\n final int remainder = number % divisor;\n if (quotient != 0) {\n result.append(numberMap.get(quotient * divisor));\n }\n if (remainder != 0) {\n result.append(numberMap.get(remainder));\n }\n}\n</code></pre>\n\n<p>It would remove some code duplication. Maybe you can find a better names for them.</p>\n\n<p>Then, the <code>numberToWord</code> looks like this:</p>\n\n<pre><code>public static String numberToWord(final int number) {\n if (number < 0) {\n throw new IllegalArgumentException(\"Number can't be negative: \" + number);\n }\n final StringBuilder result = new StringBuilder();\n if (number < ONE_BILLION && number >= ONE_MILLION) {\n calc(result, number, ONE_MILLION, \"Million\");\n } else if (number < ONE_MILLION && number >= TEN_THOUSANDS) {\n calc(result, number, ONE_THOUSAND, \"Thousand\");\n } else if (number < TEN_THOUSANDS && number >= ONE_THOUSAND) {\n calc2(result, number, ONE_THOUSAND, \"Thousand\");\n } else if (number < ONE_THOUSAND && number >= ONE_HUNDRED) {\n calc2(result, number, ONE_HUNDRED, \" Hundred\");\n } else if (number < ONE_HUNDRED && number >= TEN) {\n calc3(result, number, TEN);\n } else if (number < TEN && number >= ZERO) {\n result.append(numberMap.get(number));\n\n }\n return result.toString();\n}\n</code></pre></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-01T19:12:24.383",
"Id": "24758",
"Score": "0",
"body": "palacsint do you think the code is easy to maintain and readable?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-02T07:49:10.423",
"Id": "24763",
"Score": "0",
"body": "@Phoenix: I think it's fine, I didn't have any big problem during the review/refactoring. I'd not consider any of my comment serious."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-01T09:50:37.083",
"Id": "15260",
"ParentId": "15224",
"Score": "8"
}
},
{
"body": "<p>Here is a sample I played with. Hope it's useful.</p>\n\n<p>I'd consider decomposing this into reusable functions.</p>\n\n<pre><code>package com.bluenoteandroid.experimental.ints;\n\nimport static com.google.common.base.Optional.*;\nimport static com.google.common.base.Preconditions.*;\nimport static java.lang.Math.*;\n\nimport java.util.Arrays;\nimport java.util.LinkedList;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.Joiner;\nimport com.google.common.base.Optional;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Lists;\n\npublic final class Ints {\n\n public static final int BASE_10 = 10;\n\n public static final String MINUS = \"minus\"; \n\n public static final ImmutableMap<Integer, String> NUMBERS = ImmutableMap.<Integer, String>builder()\n .put(0,\"zero\")\n .put(1,\"one\")\n .put(2,\"two\")\n .put(3,\"three\")\n .put(4,\"four\")\n .put(5,\"five\")\n .put(6,\"six\")\n .put(7,\"seven\")\n .put(8,\"eight\")\n .put(9,\"nine\")\n .put(10,\"ten\")\n .put(11,\"eleven\")\n .put(12,\"twelve\")\n .put(13,\"thirteen\")\n .put(14,\"fourteen\")\n .put(15,\"fifteen\")\n .put(16,\"sixteen\")\n .put(17,\"seventeen\")\n .put(18,\"eighteen\")\n .put(19,\"nineteen\")\n .put(20,\"twenty\")\n .put(30,\"thirty\")\n .put(40,\"forty\")\n .put(50,\"fifty\")\n .put(60,\"sixty\")\n .put(70,\"seventy\")\n .put(80,\"eighty\")\n .put(90,\"ninety\")\n .put(100,\"hundred\")\n .put(1000,\"thousand\")\n .put(1000000,\"million\")\n .put(1000000000,\"billion\")\n .build();\n\n private Ints() { /* disabled */ }\n\n public static boolean allZeros(int[] range) {\n for (int n : range) {\n if (n != 0) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * Counts digits in an integer\n * @param number\n * @return digits count in the number\n */\n public static int digitCount(final int number) {\n return (int) ((number == 0) ? 1 : log10(abs(number)) + 1);\n }\n\n /**\n * Sums digits in an integer\n * @param number number\n * @return sum of the n's digits\n */\n public static int digitSum(final int number) {\n int _n = abs(number);\n int sum = 0;\n do {\n sum += _n % BASE_10;\n } while ((_n /= BASE_10) > 0);\n return sum;\n }\n\n /**\n * Gets digit index in an integer, counting from right \n * @param number number\n * @param index (from right)\n * @return index-th digit from n\n */\n public static int digitFromRight(final int number, final int index) {\n checkElementIndex(index, digitCount(number));\n return (int) ((abs(number) / pow(BASE_10, index)) % BASE_10);\n }\n\n /**\n * Gets digit of index in an integer, counting from left \n * @param number\n * @param index (from left)\n * @return index-th digit from n\n */\n public static int digitFromLeft(final int number, final int index) {\n checkElementIndex(index, digitCount(number));\n return digitFromRight(number, digitCount(number) - index - 1);\n }\n\n /**\n * Converts a number to the array of it's digits\n * @param number number\n * @return array of digits\n */\n public static int[] digits(final int number) {\n return digits(number, digitCount(number));\n }\n\n /**\n * Converts a number to a reversed array of it's digits\n * @param number number\n * @return reversed array of digits\n */\n public static int[] digitsReversed(final int number) {\n return digitsReversed(number, digitCount(number));\n }\n\n private static int[] digits(final int number, final int digitCount) {\n final int[] digits = new int[digitCount];\n\n int _n = abs(number);\n int i = digitCount - 1;\n do {\n digits[i--] = _n % BASE_10;\n } while ((_n /= BASE_10) > 0);\n return digits;\n }\n\n /**\n * Converts a number to a reversed array of it's digits\n * @param number number\n * @param digitCount digit count\n * @return reversed array of digits\n */\n private static int[] digitsReversed(final int number, final int digitCount) {\n final int[] reversedDigits = new int[digitCount];\n\n int _n = abs(number);\n int i = 0;\n do {\n reversedDigits[i++] = _n % BASE_10;\n } while ((_n /= BASE_10) > 0);\n return reversedDigits;\n }\n\n public static int fromDigits(final int[] digits) {\n int n = 0;\n int i = 0;\n do { \n n += digits[i++];\n if (i >= digits.length) {\n break;\n }\n n *= BASE_10;\n } while (true);\n return n;\n }\n\n public static int fromDigitsReversed(final int[] reversedDigits) {\n int n = 0;\n int i = reversedDigits.length;\n do { \n n += reversedDigits[--i];\n if (i <= 0) {\n break;\n }\n n *= BASE_10;\n } while (true);\n return n;\n }\n\n @Beta\n public static String numberInWords(final int number) {\n Optional<String> name = fromNullable(NUMBERS.get(number));\n if (name.isPresent()) {\n return name.get();\n } else {\n return numberToName(number);\n } \n }\n\n private static String numberToName(int number) { \n final LinkedList<String> words = Lists.newLinkedList();\n final int[] digits = digitsReversed(number); \n for (int factor = 0; factor < digits.length; factor += 3) {\n final int[] range = Arrays.copyOfRange(digits, factor, factor + 3);\n if (allZeros(range)) {\n continue;\n }\n\n switch (factor) {\n case 0: /* nothing */\n break;\n case 3: /* thousand */\n words.addFirst(NUMBERS.get((int) pow(BASE_10, 3)));\n break;\n case 6: /* million */\n words.addFirst(NUMBERS.get((int) pow(BASE_10, 6)));\n break;\n case 9: /* billion */\n words.addFirst(NUMBERS.get((int) pow(BASE_10, 9)));\n break;\n default:\n throw new IllegalStateException(\"Unknown factor: \" + factor);\n }\n\n String part = tripletToWords(range);\n words.addFirst(part);\n }\n\n if (number < 0) { // negative\n words.addFirst(MINUS);\n }\n\n return Joiner.on(' ').join(words);\n }\n\n private static String tripletToWords(final int[] reversedDigits) {\n checkArgument(reversedDigits.length == 3, \"This is not a triplet of digits, size: \" + reversedDigits.length);\n\n final int number = fromDigitsReversed(reversedDigits);\n\n final int[] range = Arrays.copyOfRange(reversedDigits, 0, 2);\n final String dubletWords = dubletToWords(range);\n\n if (number >= 100) {\n final int thirdDigit = reversedDigits[2];\n final int factor = BASE_10 * BASE_10;\n final String dublet = allZeros(range) ? null : dubletWords;\n return Joiner.on(' ').skipNulls().join(\n NUMBERS.get(thirdDigit),\n NUMBERS.get(factor),\n dublet);\n } else {\n return dubletWords;\n }\n }\n\n private static String dubletToWords(final int[] reversedDigits) {\n checkArgument(reversedDigits.length == 2, \"This is not a dublet of digits, size: \" + reversedDigits.length);\n\n final int number = fromDigitsReversed(reversedDigits);\n\n Optional<String> name = fromNullable(NUMBERS.get(number));\n if (name.isPresent()) {\n return name.get();\n } else {\n final int firstDigit = reversedDigits[0];\n final int secondDigit = reversedDigits[1];\n final int tens = BASE_10 * secondDigit;\n return Joiner.on('-').join(\n NUMBERS.get(tens),\n NUMBERS.get(firstDigit));\n }\n }\n}\n</code></pre>\n\n<p>With unit tests:</p>\n\n<pre><code>package com.bluenoteandroid.experimental.ints;\n\nimport static com.bluenoteandroid.experimental.ints.Ints.*;\nimport static org.hamcrest.Matchers.*;\nimport static org.junit.Assert.*;\n\nimport java.util.Arrays;\nimport java.util.Collection;\n\nimport org.junit.Test;\nimport org.junit.experimental.categories.Categories;\nimport org.junit.runner.RunWith;\nimport org.junit.runners.Parameterized;\nimport org.junit.runners.Parameterized.Parameters;\nimport org.junit.runners.Suite.SuiteClasses;\n\nimport com.bluenoteandroid.experimental.ints.IntsTests.*;\n\n@RunWith(Categories.class)\n@SuiteClasses({ \n CountTest.class, \n SumTest.class, \n GetDigitRightTest.class, \n GetDigitRightPeconditionsTest.class,\n GetDigitLeftTest.class, \n GetDigitLeftPeconditionsTest.class,\n DigitArrayTest.class,\n FromDigitArrayTest.class,\n ReverseDigitArrayTest.class,\n FromReverseDigitArrayTest.class,\n NumberToWordTest.class\n})\npublic class IntsTests {\n\n @RunWith(value = Parameterized.class) \n public static class CountTest {\n\n private final int input;\n private final int expected;\n\n public CountTest(final int input, final int expected) {\n this.input = input;\n this.expected = expected;\n }\n\n @Parameters\n public static Collection<Integer[]> data() {\n return Arrays.asList(new Integer[][] {\n { 0, 1 }, /* input, expected */\n { -1, 1 },\n { 900003245, 9 },\n });\n }\n\n @Test\n public void shouldCountDigits() {\n assertThat(digitCount(input), is(expected));\n }\n }\n\n @RunWith(value = Parameterized.class)\n public static class SumTest {\n\n private final int input;\n private final int expected;\n\n public SumTest(final int input, final int expected) {\n this.input = input;\n this.expected = expected;\n }\n\n @Parameters\n public static Collection<Integer[]> data() {\n return Arrays.asList(new Integer[][] {\n { 0, 0 }, /* input, expected */\n { -1, 1 },\n { 1001, 2 },\n { 1234, 1+2+3+4 }\n });\n }\n\n @Test\n public void shouldSumDigits() {\n assertThat(digitSum(input), is(expected));\n }\n }\n\n @RunWith(value = Parameterized.class)\n public static class GetDigitRightTest {\n\n private final int input;\n private final int index;\n private final int expected;\n\n public GetDigitRightTest(final int input, final int index, final int expected) {\n this.input = input;\n this.index = index;\n this.expected = expected;\n }\n\n @Parameters\n public static Collection<Integer[]> data() {\n return Arrays.asList(new Integer[][] {\n { 0, 0, 0 }, /* input, expected */\n { -1004, 0, 4 },\n { 1234, 1, 3 },\n { -1234, 2, 2 },\n { 1234, 3, 1 },\n });\n }\n\n @Test\n public void shouldGetDigits() {\n assertThat(digitFromRight(input, index), is(expected));\n }\n }\n\n public static class GetDigitRightPeconditionsTest {\n\n @Test(expected=IndexOutOfBoundsException.class)\n public void shouldNotAllowNegativeIndex() {\n digitFromRight(1234, -1);\n }\n\n @Test(expected=IndexOutOfBoundsException.class)\n public void shouldNotAllowToBigIndex() {\n digitFromRight(1234, 4);\n }\n }\n\n @RunWith(value = Parameterized.class)\n public static class GetDigitLeftTest {\n\n private final int input;\n private final int index;\n private final int expected;\n\n public GetDigitLeftTest(final int input, final int index, final int expected) {\n this.input = input;\n this.index = index;\n this.expected = expected;\n }\n\n @Parameters\n public static Collection<Integer[]> data() {\n return Arrays.asList(new Integer[][] {\n { 0, 0, 0 }, /* input, expected */\n { -1004, 0, 1 },\n { 1234, 1, 2 },\n { -1234, 2, 3 },\n { 1234, 3, 4 },\n });\n }\n\n @Test\n public void shouldGetDigits() {\n assertThat(digitFromLeft(input, index), is(expected));\n }\n }\n\n public static class GetDigitLeftPeconditionsTest {\n\n @Test(expected=IndexOutOfBoundsException.class)\n public void shouldNotAllowNegativeIndex() {\n digitFromLeft(1234, -1);\n }\n\n @Test(expected=IndexOutOfBoundsException.class)\n public void shouldNotAllowToBigIndex() {\n digitFromLeft(1234, 4);\n }\n }\n\n public static class DigitArrayTest {\n\n @Test\n public void shouldGetAllDigits() {\n final int[] result = digits(-1234);\n final int[] expected = new int[] {1,2,3,4};\n assertThat(result, is(expected));\n }\n }\n\n public static class FromDigitArrayTest {\n\n @Test\n public void shouldConvertDigits() {\n final int result = fromDigits(new int[] {1,2,3,4});\n final int expected = 1234;\n assertThat(result, is(expected));\n }\n }\n\n public static class ReverseDigitArrayTest {\n\n @Test\n public void shouldGetAllDigits() {\n final int[] result = digitsReversed(-1234);\n final int[] expected = new int[] {4,3,2,1};\n assertThat(result, is(expected));\n }\n }\n\n public static class FromReverseDigitArrayTest {\n\n @Test\n public void shouldConvertDigits() {\n final int result = fromDigitsReversed(new int[] {4,3,2,1});\n final int expected = 1234;\n assertThat(result, is(expected));\n }\n }\n\n @RunWith(value = Parameterized.class)\n public static class NumberToWordTest {\n\n private final int input;\n private final String expected;\n\n public NumberToWordTest(final int input, final String expected) {\n this.input = input;\n this.expected = expected;\n }\n\n @Parameters\n public static Collection<Object[]> data() {\n return Arrays.asList(new Object[][] {\n { 0, \"zero\" },\n { 1, \"one\" },\n { 10, \"ten\" },\n { 15, \"fifteen\" },\n { 60, \"sixty\" },\n { 67, \"sixty-seven\" },\n { 72, \"seventy-two\" },\n { 101, \"one hundred one\" },\n { 205, \"two hundred five\" },\n { 4589, \"four thousand five hundred eighty-nine\" },\n { 3333, \"three thousand three hundred thirty-three\" },\n { 67500, \"sixty-seven thousand five hundred\" },\n { 100000, \"one hundred thousand\" },\n { 100567, \"one hundred thousand five hundred sixty-seven\" },\n { 172346, \"one hundred seventy-two thousand three hundred forty-six\" },\n { 600700, \"six hundred thousand seven hundred\" },\n { 678900, \"six hundred seventy-eight thousand nine hundred\" },\n { 890000, \"eight hundred ninety thousand\" },\n { 999999, \"nine hundred ninety-nine thousand nine hundred ninety-nine\" },\n { 999999999, \"nine hundred ninety-nine million nine hundred ninety-nine thousand nine hundred ninety-nine\" },\n { 1999999999, \"one billion nine hundred ninety-nine million nine hundred ninety-nine thousand nine hundred ninety-nine\" },\n { -21239, \"minus twenty-one thousand two hundred thirty-nine\"},\n });\n }\n\n @Test\n public void test() {\n assertEquals(expected, numberInWords(input));\n }\n\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-02T20:46:51.600",
"Id": "15285",
"ParentId": "15224",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-31T00:56:28.350",
"Id": "15224",
"Score": "7",
"Tags": [
"java",
"converting",
"numbers-to-words"
],
"Title": "Converting an integer number into its word representation"
}
|
15224
|
<p>I'm trying to build simple pattern matching in a string.</p>
<p>ie., Given a <code>template</code> of: <code>"Hello ${1}"</code> and an <code>input</code> of <code>"Hello world"</code>, I'd like to be able to return a map of <code>1='world'</code>.</p>
<p>This test demonstrates what I'm trying to acheive:</p>
<pre><code>@Test
public void detectsTokenValues()
{
Properties properties = formatter.getTokenValues("${1}/andThen/${2}/followedBy/${3}","start/andThen/middle/followedBy/end");
assertThat((String) properties.get("1"), equalTo("start"));
assertThat((String) properties.get("2"), equalTo("middle"));
assertThat((String) properties.get("3"), equalTo("end"));
}
</code></pre>
<p>Here's my implementation. It works, but I feel like it's convoluted, and I suspect there's Regex or other JDK native features I could be using to make it simpler.</p>
<pre><code>// Matches ${0} - ${9999} etc., But not ${variblesWithWords}
private static final Pattern NUMERIC_VARIABLES = Pattern.compile("\\$\\{([0-9]+?)\\}");
Properties getTokenValues(String template, String input) {
Properties properties = new Properties();
Matcher matcher = NUMERIC_VARIABLES.matcher(sourcestring);
final int variableWrapperLength = "${}".length();
int accumulativeOffset = 0;
while (matcher.find())
{
String variableName = matcher.group(1);
String value = null;
if (matcher.end() >= template.length())
{
value = input.substring(matcher.start() + accumulativeOffset);
} else {
// Find the character after the variable in the template.
// This serves as the end-delimeter in the input string.
String endDelimiter = template.substring(matcher.end(),matcher.end()+1);
int variableEndIndex = findEndDelimiterIndex(input, matcher.start() + 1,
endDelimiter);
value = input.substring(matcher.start() + accumulativeOffset, variableEndIndex);
// Adjust the accumulative offset to account for the difference
// in lengths between the variableName (eg., ${1})
// and the the actual value (eg., 'foo')
accumulativeOffset += value.length() - (variableWrapperLength + variableName.length());
}
if (value != null)
properties.put(variableName, value);
}
return properties;
}
private int findEndDelimiterIndex(String input, int fromIndex,
String endDelimiter) {
// Find the first instance of the delimiter in the input string
// that occurs after the start of our matches variable.
if (fromIndex > input.length())
{
return Integer.MAX_VALUE;
}
int variableEndIndex = input.indexOf(endDelimiter,fromIndex);
return variableEndIndex;
}
</code></pre>
<p>How can I improve this method?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-31T19:56:15.350",
"Id": "24732",
"Score": "0",
"body": "`NUMERIC_VARIABLES.matcher(sourcestring);` shouldn't be `NUMERIC_VARIABLES.matcher(template)`?"
}
] |
[
{
"body": "<p>Just a side note: You could avoid the <code>(String)</code> casting if you used a <code>Map</code> (a <code>HashMap</code>, for example) instead of <code>Properties</code>. <code>Properties</code> has a design flaw: it should not extend <code>Hashtable</code>. </p>\n\n<p><em>Effetcive Java, 2nd Edition</em> mentions it in its <em>Item 16: Favor composition over inheritance</em>:</p>\n\n<blockquote>\n <p>In the case of <code>Properties</code>, the designers intended that only strings be\n allowed as keys and values, but direct access to the underlying <code>Hashtable</code> allows\n this invariant to be violated. Once this invariant is violated, \n it is no longer possible\n to use other parts of the <code>Properties</code> API (<code>load</code> and <code>store</code>). \n By the time this problem \n was discovered, it was too late to correct it because clients depended on the\n use of nonstring keys and values.</p>\n</blockquote>\n\n<hr>\n\n<p>Here is an alternate implementation based on <em>@barjak</em>'s idea:</p>\n\n<pre><code>private static final String NON_GROUP_REGEX = \".*?\";\nprivate static final String GROUP_REGEX = \"(.*?)\";\n\npublic Map<String, String> getTokenValues2(final String template, final String input) {\n final Map<String, String> result = new LinkedHashMap<String, String>();\n\n final List<String> variableNames = getVariableNames(template);\n // TODO: check duplicated variables here\n\n for (final String variableName: variableNames) {\n final String value = getValueForVariable(template, input, variableName);\n result.put(variableName, value);\n }\n return result;\n}\n\nprivate List<String> getVariableNames(final String template) {\n final List<String> result = new ArrayList<String>();\n final Matcher matcher = NUMERIC_VARIABLES.matcher(template);\n while (matcher.find()) {\n final String variableName = matcher.group(1);\n result.add(variableName);\n }\n return result;\n}\n\nprivate String getValueForVariable(final String template, final String input, \n final String variableName) {\n final String variableRegex = createVariableRegex(template, variableName);\n final Matcher variableMatcher = Pattern.compile(variableRegex).matcher(input);\n if (!variableMatcher.matches()) {\n throw new IllegalStateException(\"template: \" + template + \", input: \" \n + input + \", variableName \" + variableName);\n }\n final String value = variableMatcher.group(1);\n return value;\n}\n\nprivate String createVariableRegex(String template, \n final String groupMatcherVariableName) {\n template = replaceNumericVariableToGroupMatcher(template, groupMatcherVariableName);\n template = replaceNumericVariablesToNonGroupMatchers(template);\n return template;\n}\n\nprivate String replaceNumericVariablesToNonGroupMatchers(final String template) {\n return NUMERIC_VARIABLES.matcher(template)\n .replaceAll(Matcher.quoteReplacement(NON_GROUP_REGEX));\n}\n\nprivate String replaceNumericVariableToGroupMatcher(final String template, \n final String variableName) {\n final Pattern variableNamePattern = Pattern.compile(Pattern\n .quote(\"${\" + variableName + \"}\"));\n final String quotedVariableNameReplacementRegexp = \n Matcher.quoteReplacement(GROUP_REGEX);\n return variableNamePattern.matcher(template)\n .replaceFirst(quotedVariableNameReplacementRegexp);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-31T04:40:29.237",
"Id": "15227",
"ParentId": "15226",
"Score": "2"
}
},
{
"body": "<p>The function <code>getTokenValues</code> is actually a pattern matching function. It just uses a different syntax than the pattern format of <code>java.util.regex</code>.</p>\n\n<p>I suggest you to convert your pattern string (the one with <code>$</code> signs) into a valid <code>Pattern</code>.</p>\n\n<pre><code>${1}/andThen/${2}/followedBy/${3}\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>(.+?)/andThen/(.+?)/followedBy/(.+?)\n</code></pre>\n\n<p>And then you can use <code>Pattern.matcher</code> to find the content of the groups. There is still one thing missing : the fact that the numbering of the original pattern is lost. For that, you can parse the original pattern string to extract those numbers, to create a mapping table.</p>\n\n<p>When you convert your pattern string into a Pattern, be careful to escape the substrings between the <code>$</code> using <code>Pattern.quote()</code>.</p>\n\n<p>I don't know if this solution would be an improvement of yours, but it's an alternative to consider.</p>\n\n<h2>Edit</h2>\n\n<p>The implementation of my solution :</p>\n\n<pre><code>Map<String, String> getTokenValues(String pattern, String str) {\n Map<String, String> res = new HashMap<String, String>();\n List<String> identifiers = new ArrayList<String>();\n\n Pattern dollarRgx = Pattern.compile(\"\\\\$\\\\{([0-9]+?)\\\\}\");\n Matcher dollarMatcher = dollarRgx.matcher(pattern);\n StringBuilder convRgxBd = new StringBuilder();\n int lastEnd = 0;\n while(dollarMatcher.find()) {\n String before = pattern.substring(lastEnd, dollarMatcher.start());\n convRgxBd.append(Pattern.quote(before));\n convRgxBd.append(\"(.+?)\");\n lastEnd = dollarMatcher.end();\n identifiers.add(dollarMatcher.group(1));\n }\n String after = pattern.substring(lastEnd, pattern.length());\n convRgxBd.append(Pattern.quote(after));\n\n Pattern convRgx = Pattern.compile(convRgxBd.toString());\n Matcher convMatcher = convRgx.matcher(str);\n if(convMatcher.matches()) {\n for(int i = 0; i < convMatcher.groupCount(); i++) {\n String id = identifiers.get(i);\n res.put(id, convMatcher.group(i+1));\n }\n }\n\n return res;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-31T10:05:37.997",
"Id": "15233",
"ParentId": "15226",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-31T03:20:33.147",
"Id": "15226",
"Score": "2",
"Tags": [
"java",
"regex"
],
"Title": "String pattern matching - method needs improving"
}
|
15226
|
<p>Here is my solution to <a href="http://www.reddit.com/r/dailyprogrammer/comments/z3a4y/8302012_challenge_93_easy_twoway_morse_code/" rel="nofollow">reddit.com/r/dailyprogrammer #93 (easy)</a>., which is a Python script that translates between English and Morse code.</p>
<p>Is <code>String_To_Translate</code> a good example of a class? Am I violating convention? How can I improve this code and make it more readable and pythonic?</p>
<pre><code>import re
morse_code_dict = { 'a':'.-',
'b':'-...',
'c':'-.-.',
'd':'-...',
'e':'..-.',
'f':'..-.',
'g':'--.',
'h':'....',
'i':'..',
'j':'.---',
'k':'-.-',
'l':'.-..',
'm':'--',
'n':'-.',
'o':'---',
'p':'.--.',
'q':'--.-',
'r':'.-.',
's':'...',
't':'-',
'u':'..-',
'v':'...-',
'w':'.--',
'x':'-..-',
'y':'-.--',
'z':'--..',
'1':'.----',
'2':'..---',
'3':'...--',
'4':'....-',
'5':'.....',
'6':'-....',
'7':'--...',
'8':'---..',
'9':'----.',
'0':'-----',
',':'--..--',
'.':'.-.-.-',
'?':'..--..',
'/':'-..-.',
'-':'-....-',
'(':'-.--.',
')':'-.--.-',
' ':' ',
}
class String_To_Translate:
def __init__(self, string):
self.string = string
self.Translated = ''
self.lang = ''
def determine_lang(self):
exp = r'[a-zA-Z\,\?\/\(\)]'#regexp for non morse code char
if re.search(exp, self.string) == None:
self.lang = 'm'
else:
self.lang = 'eng'
def prep(self):
if self.lang == 'eng':
#get rid of whitespace & warn user
(self.string, numWhitespaceReplacements) = re.subn(r'\s', ' ', self.string)
if numWhitespaceReplacements > 0:
print 'Some whitespace characters have been replaced with spaces.'
#get rid of characters not in dict & warn user
(self.string, numReplacements) = re.subn(r'[^a-zA-Z\,\?\/\(\)\.\-\s]', ' ', self.string)
if numReplacements > 0:
print 'Some ({0}) characters were unrecognized and could not be translated, they have been replaced by spaces.'.format(numReplacements)
#convert to lowercase
self.string = self.string.lower()
def translate_from_morse(self):
eng_dict = dict([(v, k) for (k, v) in morse_code_dict.iteritems()])
def split_morse(string):
d = ' '
charList = [[char for char in word.split() + [' ']] for word in string.split(d) if word != '']
charList = [item for sublist in charList for item in sublist]
print charList
return charList
charList = split_morse(self.string)
for char in charList:
self.Translated += eng_dict[char]
def translate_from_eng(self):
charList=list(self.string)
for char in charList:
self.Translated += morse_code_dict[char] + ' '
def translate(self):
self.determine_lang()
if self.lang == 'm':
self.translate_from_morse()
elif self.lang == 'eng':
self.prep()
self.translate_from_eng()
else:
print 'shit'
if __name__=="__main__":
translateme = String_To_Translate(raw_input('enter a string: '))
translateme.translate()
print translateme.Translated
print 'translating back'
test = String_To_Translate(translateme.Translated)
test.translate()
print test.Translated
</code></pre>
|
[] |
[
{
"body": "<p>Minor points:</p>\n\n<ol>\n<li><code>self.Translated</code> should be <code>self.translated</code>.</li>\n<li>The use of <code>re</code> may be bit of overkill for what you want it for.</li>\n<li>If you use a space in the text, you get told that it's being replaced by a space.</li>\n<li>Create constants instead of using 'm' and 'eng' </li>\n</ol>\n\n<p>Points to consider (as in, what I would do!):</p>\n\n<ol>\n<li>Rather than having a single class, create separate classes for each direction, then select which in a function. The two directions share no code in common.</li>\n<li>Rather than storing the result, return it directly.</li>\n</ol>\n\n<p>So I might end up with something like:</p>\n\n<pre><code>class TranslationToMorse:\n def __init__( self, str ):\n self.src_lang = ENGLISH\n self.lang_dict = morse_code_dict\n self.str = str\n def prep( self, str ):\n #etc\n def translate( self ):\n #etc\n return trans\n\nclass TranslationToEnglish:\n def __init__( self, str ):\n self.src_lang = MORSE\n self.lang_dict = dict([(v, k) for (k, v) in morse_code_dict.iteritems()])\n self.str = str\n def translate( self ):\n #etc\n return trans\n\n\ndef get_translator( str ): \n exp = r'[a-zA-Z\\,\\?\\/\\(\\)]'#regexp for non morse code char\n if re.search( exp, str ) == None:\n return TranslationToEnglish( str )\n else:\n return TranslationToMorse( str )\n</code></pre>\n\n<p>and:</p>\n\n<pre><code>print get_translator( msg ).translate()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-31T09:54:02.950",
"Id": "24708",
"Score": "1",
"body": "I'd avoid comparing `None` using the `==` operator.\nEither use `if re.search(exp, str):` or `if re.search(exp, str) is None:`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-31T09:06:09.000",
"Id": "15231",
"ParentId": "15228",
"Score": "1"
}
},
{
"body": "<ol>\n<li><p>The first thing that stands out from your code is the big table giving the morse code: it's lengthy, hard to read, and hard to check. (And consequently, it contains two mistakes.) I would write something like this:</p>\n\n<pre><code>from itertools import izip\n\ndef pairwise(s):\n \"\"\"\n Generate pairs from the sequence `s`.\n\n >>> list(pairwise('abcd'))\n [('a', 'b'), ('c', 'd')]\n \"\"\"\n it = iter(s)\n return izip(it,it)\n\nmorse_encoding = dict(pairwise('''\n a .- b -... c -.-. d -.. e . f ..-. \n g --. h .... i .. j .--- k -.- l .-..\n m -- n -. o --- p .--. q --.- r .-.\n s ... t - u ..- v ...- w .-- x -..-\n y -.-- z --..\n\n 1 .---- 2 ..--- 3 ...-- 4 ....- 5 ..... \n 6 -.... 7 --... 8 ---.. 9 ----. 0 -----\n\n , --..-- . .-.-.- ? ..--.. / -..-. - -....-\n ( -.--. ) -.--.- ' .----. ! -.-.-- & .-...\n : ---... ; -.-.-. = -...- + .-.-. _ ..--.-\n \" .-..-. $ ...-..- @ .--.-.\n'''.split()))\n\nmorse_decoding = {v:k for k,v in morse_encoding.iteritems()}\n</code></pre></li>\n<li><p>You rebuild the decoding table every time you start a new translation. This seems wasteful: I suggest building it only once, as above.</p></li>\n<li><p><em>Not everything needs to be a class</em>. A class is a data abstraction whose instances represent some <em>thing</em> together with methods for operating on that thing. You don't actually have any persistent data here: all you are using the class for is to store the temporary state for a single translation). It makes more sense to structure this code as functions.</p></li>\n<li><p>Your classes and methods have no docstrings and no doctests. Even a small doctest or two might have caught the mistakes in your Morse code table.</p></li>\n<li><p>In your <code>determine_lang</code> method, you use a regular expression that matches strings that are not Morse code. It would be simpler to do the test the other way round: to determine that the string <em>is</em> Morse code (because Morse code contains only dots, dashes and spaces). Python's sets provide a clear and concise way to express this test:</p>\n\n<pre><code>def is_morse_code(s):\n \"\"\"\n Return True if the string `s` resembles Morse code (contains only\n dots, dashes and spaces), False otherwise.\n\n >>> is_morse_code('... --- ...')\n True\n >>> is_morse_code('abc')\n False\n \"\"\"\n return set(s) <= set('.- ')\n</code></pre></li>\n<li><p>The original challenge may have referred to \"English\", but there's nothing actually English-specific about Morse code. It translates any language that can be written in the Latin alphabet. So I would prefer names that didn't presume that we were translating English.</p></li>\n<li><p>When a character cannot be encoded or decoded, you print a message to inform the user. The usual approach in Python is to raise an exception.</p></li>\n<li><p>Your translation code seems very complex for what it is doing. All you need to do is split the string into words, split each word into letters, translate each letter, join the translated letters into words, and then join the translated words into the result. This can be done neatly and concisely using <code>split</code> and <code>join</code> and a couple of loops:</p>\n\n<pre><code>def morse_encode(s):\n \"\"\"\n Encode the string `s` in Morse code and return the result. \n Raise KeyError if it cannot be encoded.\n\n >>> morse_encode('morse code')\n '-- --- .-. ... . -.-. --- -.. .'\n \"\"\"\n return ' '.join(' '.join(morse_encoding[l] for l in word)\n for word in s.lower().split(' '))\n\ndef morse_decode(s):\n \"\"\"\n Decode the string `s` from Morse code and return the result.\n Raise KeyError if it cannot be decoded.\n\n >>> morse_decode('-- --- .-. ... . -.-. --- -.. .')\n 'morse code'\n \"\"\"\n return ' '.join(''.join(morse_decoding[l] for l in word.split(' '))\n for word in s.split(' '))\n</code></pre></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-31T11:33:14.953",
"Id": "24711",
"Score": "0",
"body": "and for extra fun, return a function from determine_lang: `return lambda: morse_encode( str ) if re.search( exp, str ) else lambda: morse_decode( str )`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-04T01:13:44.887",
"Id": "24825",
"Score": "0",
"body": "An excellent, thorough response. thank you Gareth."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-31T10:19:37.983",
"Id": "15234",
"ParentId": "15228",
"Score": "10"
}
}
] |
{
"AcceptedAnswerId": "15234",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-31T05:23:31.903",
"Id": "15228",
"Score": "5",
"Tags": [
"python",
"morse-code"
],
"Title": "Python implementation of a Morse code translator"
}
|
15228
|
<p>I was wondering if anyone could give me a little bit of help with optimizing a tree-structure in C++. I'm currently developing a dictionary program for a school project but want to take it a bit further in my spare time.</p>
<p>A little bit of info: The dictionary is a simple class which contains a node. Each node in the class contains an array of 26 pointers to sub-nodes. Each node can contain a single letter (<code>char</code>) and a single definition (of <code>std::string</code>-type). Traversal is based solely on what letter of the alphabet needs to be looked up.</p>
<p>Basically, if I want to search for the definition of "programming," the dictionary class will look at each letter in the requested word and go directly to a sub-node representing the letter (a=0, b=1, c=2, and so on...). When it finally reaches the final letter "g" in "programming" then it returns a user-defined definition.</p>
<p>What I was wondering was if I could get help in optimizing any of the subroutines in this class. Currently, looking up words is in \$O(n)\$ time (where n is the number of letters in the requested word). Copying words in the dictionary is in \$O(m+n)\$ where 'm' is the number of preexisting words in the destination dictionary and 'n' is the number of words in the source dictionary.</p>
<p>Hopefully the source is easy enough to understand (I'm not used to sharing my code and this site seems to mess up my formatting).</p>
<pre><code>#ifndef DICTIONARY_H
#define DICTIONARY_H
#include <string>
using namespace std;
typedef const char* cstr;
int toLower(char c) {
//Return a lowercase letter if its within A-Z (65-90) on the ASCII table;
//Otherwise return 'c' as it is (don't bother with non-alphabetical characters).
return (c > 64 && c < 91) ? c+26 : c;
}
class dictionary {
private:
struct node {
char letter;
string definition;
node* alphabet[26];
explicit node();
explicit node(const node& nodeCopy);
~node();
node& operator = (const node& nodeCopy);
void clear();
void copy(const node& src);
};
node mainNode;
int getArrayIndex(char c);
node* iterateToNode(cstr nodeName);
public:
dictionary() {}
dictionary (const dictionary& dictionCopy) {mainNode.copy( dictionCopy.mainNode );}
~dictionary() {}
dictionary& operator = (const dictionary& dictCopy);
cstr getDefinition (cstr word);
void defineWord (cstr word, cstr inDefinition);
bool knowWord (cstr word);
bool knowDefinition (cstr word);
void addWord (cstr word);
void clear () {mainNode.clear();}
};
//-----------------------------------------------------------------------------
// Node Structure
//-----------------------------------------------------------------------------
dictionary::node::node() :
letter(0),
definition("")
{
//NULL-ify all of the elements in the array
int iter(26);
while (iter--) alphabet[iter] = 0;
}
dictionary::node::node(const node& nodeCopy) {
copy(nodeCopy);
}
dictionary::node::~node() {
clear();
}
dictionary::node& dictionary::node::operator = (const node& nodeCopy) {
copy(nodeCopy);
return *this;
}
void dictionary::node::clear() {
int iter(26);
while (iter--) {
if (alphabet[iter]) {
delete alphabet[iter];
alphabet[ iter ] = 0;
}
}
}
void dictionary::node::copy(const node& src) {
clear();
letter = src.letter;
definition = src.definition;
int iter(26);
while (iter--) {
if (src.alphabet[ iter ]) {
alphabet[ iter ] = new node; //memory-safe operation. The destination node has already been cleared
alphabet[ iter ]->copy(*src.alphabet[ iter ]); //begin recursive awesomeness!
}
}
}
//-----------------------------------------------------------------------------
// Utilities
//-----------------------------------------------------------------------------
dictionary& dictionary::operator =(const dictionary& dictCopy) {
mainNode = dictCopy.mainNode;
return *this;
}
dictionary::node* dictionary::iterateToNode(cstr nodeName) {
int pos(0), index(0);
node* nodeTracker(&mainNode); //dictionary iterator
do {
index = getArrayIndex( nodeName[pos] );
if (index == -1 || !nodeTracker->alphabet[ index ]) return 0;
nodeTracker = nodeTracker->alphabet[index];
++pos;
} while (nodeName[ pos ]); //end the loop when a null-termination is reached
return nodeTracker; //return the position of the requested node
}
int dictionary::getArrayIndex(char c) {
//make sure the letter in question actually is a letter
if ((c < 'a') && (c > 'Z') || (c < 'A') || (c > 'z')) return -1;
return (c < 'a') ? c - 'A' : c - 'a'; //convert all uppercase letters to lowercase (See asciitable.com)
//get the index of the next letter in dictionary::alphabet[]
}
//-----------------------------------------------------------------------------
// Definitions
//-----------------------------------------------------------------------------
cstr dictionary::getDefinition(cstr word) {
node* nodeTracker( iterateToNode(word) );
return (nodeTracker) ? nodeTracker->definition.c_str() : '\0';
}
void dictionary::defineWord(cstr word, cstr inDefinition) {
node* nodeTracker( iterateToNode(word) );
if (nodeTracker)
nodeTracker->definition = inDefinition;
}
bool dictionary::knowWord(cstr word) {
node* nodeTracker( iterateToNode(word) );
return (nodeTracker) ? true : false;
}
bool dictionary::knowDefinition(cstr word) {
node* nodeTracker( iterateToNode(word) );
return (nodeTracker && nodeTracker->definition.size()) ? true : false;
}
void dictionary::addWord(cstr word) {
int pos(0), index(0);
node* nodeTracker(&mainNode); //dictionary iterator
do {
index = getArrayIndex( word[ pos ] ); //get the index of the next letter in dictionary::alphabet[]
if (index == -1) return;
if (nodeTracker->alphabet[ index ] == 0) {
nodeTracker->alphabet[ index ] = new node; //add a new word to the dictionary if possible
nodeTracker->letter = word[ pos ];
}
nodeTracker = nodeTracker->alphabet[index]; //move to the next letter in dictionary::alphabet
++pos;
} while (word[ pos ]); //end when a null-termination is reached
}
#endif /* DICTIONARY_H */
</code></pre>
<p>Sample program that I've been using to test everything:</p>
<pre><code>//prototyping a dictionary lookup (uses lowercase ASCII only)
#include <iostream>
#include "dictionary.h"
using namespace std;
int main() {
dictionary testDict;
dictionary testDict2;
string input;
string def;
while (true) {
cout << "What would you like to do?" << endl;
cout << "\t1. Look up a word" << endl;
cout << "\t2. Check if a word is in the dictionary" << endl;
cout << "\t3. Add a word to the dictionary" << endl;
cout << "\t4. Define a word" << endl;
cout << "\t5. Quit" << endl;
getline(cin, input);
cout << endl;
if (input == "1") {
cout << "What would you like to lookup?" << endl;
getline(cin, input);
if (testDict.knowDefinition(input.c_str())) {
cout << "\tThe definition is: " << testDict.getDefinition(input.c_str()) << endl;
}
else {
cout << "\tSorry, I don't know that word's definition." << endl;
}
}
else if (input == "2") {
cout << "What word would you like to check?" << endl;
getline(cin, input);
if (testDict.knowWord(input.c_str())) {
cout << "\tI have definitely seen that before." << endl;
}
else {
cout << "\tSorry, I don't know that word." << endl;
}
}
else if (input == "3") {
cout << "What word would you like to add?" << endl;
getline(cin, input);
testDict.addWord(input.c_str());
cout << "\tAdded the word: " << input.c_str() << endl;
//memory-copying checks
testDict2 = testDict;
if (!testDict2.knowWord(input.c_str())) {
cout << "\tERROR: Unable to copy memory!" << endl;
}
}
else if (input == "4") {
cout << "What word would you like to define?" << endl;
getline(cin, input);
if (!testDict.knowWord(input.c_str())) {
cout << "I'm sorry, I've never even seen that word" << endl;
continue;
}
cout << "What's the definition of \"" << input.c_str() << "\"?" << endl;
getline(cin, def);
testDict.defineWord(input.c_str(), def.c_str());
cout << "\"" << input << "\" is now defined as: " << endl;
cout << "\t" << testDict.getDefinition(input.c_str()) << endl;
def.clear();
}
else if (input == "5") {
cout << "GOODBYE!" << endl;
break;
}
else {
cout << "I'm sorry, I don't understand that." << endl;
}
cout << endl;
input.clear();
}
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-31T16:57:45.637",
"Id": "24723",
"Score": "0",
"body": "Your analyses of complexity is wrong; :-) The complexity is O(ln(n)) for both search and insert. As n is based on the size of the dictionary not the word length. I don't think I have a worry about doing 29 inserts `floccinaucinihilipilification` into the tree when there are 50,000 words in the dictionary. That is pretty good."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-31T20:05:21.243",
"Id": "24734",
"Score": "0",
"body": "@LokiAstari I'm not sure I understand where you're coming from. The traversing is based on the characters in the word, not comparing the word to what is already in the tree. Take, icdae's example of programming. You can have a million words in the tree, but programming is still going to be 11 traversals to search for (worst case). `O(n)` with n defined as the number of characters in a word for searching/inserting sounds correct to me."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-31T20:40:04.580",
"Id": "24736",
"Score": "0",
"body": "@Corbin: The complexity of the insert should be related to the data set size (the size of the dictionary) not the size of the word. If the complexity of inserting a word is linear O(n) then you would need to scan through the dictionary from start to end to locate the insertion point. What is happening here is that on each letter you are basically doing a 1/26 chop of the dictionary at each letter this is O(log<26>(n)) => O(ln(n)) operation. Looking at it another way it will take you 11 tests with a million entries that's not linear (linear on average would require 1/2 million tests)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-31T20:44:12.670",
"Id": "24737",
"Score": "0",
"body": "If you want to say it is linear over the size of the word sure that is a measurement. But not really a useful measurement. Even if the cost was exponentiation across the size of the word I would not worry that much if the upper bound is only 8 -> 11 characters (longest English word 29 characters (still not worried).http://en.wikipedia.org/wiki/Longest_word_in_English"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-31T20:48:40.440",
"Id": "24738",
"Score": "0",
"body": "@LokiAstari I understand that the word length is not a useful metric, but neither is the number of entries already in the tree. With a normal tree, yes, letting n be the number of links, you are cutting n away from the possibilities. In this case though, the number of items in the tree does not affect the current item (unless I'm not understanding the algorithm?). The way I understand it, if we're cosnidering only n, number of items in the tree, then searching is O(1). \"dog\" for example means you always go root[d]->links[o]->links[g]. That happens no matter what is already in place."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-31T20:51:47.950",
"Id": "24739",
"Score": "0",
"body": "@Corbin: http://en.wikipedia.org/wiki/Big_O_notation"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-31T20:53:25.143",
"Id": "24740",
"Score": "0",
"body": "@LokiAstari Yes, I understand what big O notation is. My question is, what does the run time of the search operating look like? It's not a function of what is already in the tree. Looking for \"dog\" in a tree with 4 billion elements and looking for dog in an tree with only \"dog\" in it will be the exact same. (Edit: it actually does depend on the items (not number of items) in the tree, but only because of the potential to short circuit. For example, if root->links[d] is null, then there's no need to keep going down for dog.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-31T21:16:16.407",
"Id": "24741",
"Score": "0",
"body": "Its not the cost of finding a specific element. It is the cost of the worst case of the average element. The cost of this is related to the data set size. **But** if you really need to understand this; This is a good question for [programmers](http://programmers.stackexchange.com) or maybe [mathematics](http://math.stackexchange.com/). Not a prolonged discussion in comments."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-31T21:53:21.067",
"Id": "24742",
"Score": "0",
"body": "@LokiAstari Afraid I still don't get how the size of the input set growing affects the run-time of `iterateToNode`, but I think I've abused the comments enough for one day, so I'll drop it and go find my algorithms book :)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-31T23:48:24.260",
"Id": "24746",
"Score": "0",
"body": "@Corbin had it right, The algorithm jumps directly to the definition of a word by jumping between the letters. If I want the definition of \"Dog\", then the dictionary will jump like this: Root->node[D]->node[O]->node[G]->definition. The problem isn't necessarily with searching, but copying, clearing, and adding to the dictionary. (BTW, I'm relatively new to Big O notation, so thanks for helping me out with that)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-01T06:22:42.920",
"Id": "24750",
"Score": "0",
"body": "@icdae: I think you misunderstood the discussion. The complexity for search/insert is still O(ln(n)). If I picked a word at random the complexity of finding that word is relative to the size of the dictionary."
}
] |
[
{
"body": "<p>Dictionary is a very common word. I am thinking that there may be high possibility of clashing with existing software. I tend to try an make my include guards unique by including the namespace as part of the guard (My base namespace is also my website name so it is unique).</p>\n\n<pre><code>#ifndef DICTIONARY_H\n#define DICTIONARY_H\n</code></pre>\n\n<p>Please stop doing this:</p>\n\n<pre><code>using namespace std;\n</code></pre>\n\n<p>Never do this in a header file you will pollute the global namespace (potentially without the user knowing) thus causing all sorts of side-affects). Even in source files you should probably not do it so that you don't pollute the global namespace for yourself. The reason it is called <code>std</code> rather than <code>standard</code> is so that it would not be painful to prefix things with it.</p>\n\n<pre><code>std::string x; // A string from the standard namespace.\n</code></pre>\n\n<p>OK. Not a real problem:</p>\n\n<pre><code>typedef const char* cstr;\n</code></pre>\n\n<p>But I would prefer not to see it as it implies you are using C-Strings (rather than C++ strings). Whose real type is actually <code>char const*</code> if you get them from literals so this can be a potentially dangerous typedef. Also once the data goes into your dictionary do you expect to mutate it? If not then I would like to see the const in the typedef.</p>\n\n<p>There is already a std::tolower() that does exactly what you expect.</p>\n\n<pre><code>int toLower(char c) {\n //Return a lowercase letter if its within A-Z (65-90) on the ASCII table;\n //Otherwise return 'c' as it is (don't bother with non-alphabetical characters).\n return (c > 64 && c < 91) ? c+26 : c;\n}\n</code></pre>\n\n<p>And is implemented in an optimal way for your platform.</p>\n\n<p>Trying to be too clever and shot your self in the foot.</p>\n\n<pre><code>int iter(26);\nwhile (iter--) alphabet[iter] = 0;\n</code></pre>\n\n<p>It works. But it is very awkward way of writing it. Thus every maintainer that comes across this code will go \"what?\". and need to validate that it actually works</p>\n\n<p>Your copy constructor calls <code>copy()</code> which calls <code>clear()</code> which relies on the <code>alphabet</code> array being already initialized with <code>NULL</code>. This is not the case. Thus this will result in undefined behavior.</p>\n\n<pre><code>dictionary::node::node(const node& nodeCopy) {\n copy(nodeCopy);\n}\n</code></pre>\n\n<p>The reason for copy seems that you put common code from the copy constructor and assignment operator in a single place. I would change this up. I would put all the copy code in the copy constructor without the call to <code>clear()</code>. Thenuse the copy and swap idiom to implement the assignment operator (now there is no reason for the <code>copy()</code> method).</p>\n\n<p>Use copy and swap idiom to implement the assignment operator:</p>\n\n<pre><code>dictionary::node& dictionary::node::operator = (const node& nodeCopy) {\n copy(nodeCopy);\n return *this;\n}\n</code></pre>\n\n<p>This implementation is not exception safe (and does not handle self assignment). When doing assignment you need to do in three stages:</p>\n\n<pre><code>1) Copy src (nodeCopy) (without altering the current object).\n If you generate an exception during the copy you need to be able\n to leave the object in a valid state preferably unchanged.\n By doing the copy without altering the current object makes this\n easier.\n2) Swap the current data with the copies data.\n `swapping` is an exception safe activity so you can atomically change\n the state of the object without any exceptions being generated.\n3) Destroy the old data.\n It does not matter if you generate exceptions now the object is in\n a consistent state.\n</code></pre>\n\n<p>These three stages are automatically achieved using the copy and swap idiom.</p>\n\n<p>No need to check for NULL before deleting.</p>\n\n<pre><code> if (alphabet[iter]) {\n delete alphabet[iter];\n alphabet[ iter ] = 0;\n }\n</code></pre>\n\n<p>Just use the copy constructor here it is much clearer:</p>\n\n<pre><code> alphabet[ iter ] = new node; //memory-safe operation. The destination node has already been cleared\n alphabet[ iter ]->copy(*src.alphabet[ iter ]); //begin recursive awesomeness!\n\n // can be written a:\n alphabet[ iter ] = new node(*src.alphabet[iter]);\n</code></pre>\n\n<p>I will be back with more:</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-01T00:26:19.403",
"Id": "24748",
"Score": "0",
"body": "I always thought the delete operator required a non-NULL pointer, but after looking at the C++ standard, I can remove that \"if\" statement in the clear() function. Thanks for the help, I implemented those changes you pointed out and the code definitely looks much cleaner (copy() function replaced with the \"=\" operator, NULL-ifying values in the construction)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-31T19:14:09.897",
"Id": "15248",
"ParentId": "15229",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "11",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-31T05:26:31.067",
"Id": "15229",
"Score": "3",
"Tags": [
"c++",
"optimization",
"tree",
"hash-map",
"lookup"
],
"Title": "Dictionary tree optimization"
}
|
15229
|
<p>I made a function that returns the number displayed for pagination. I want to get something like this (parentheses is the only show where the active site):</p>
<p>if pages < 10</p>
<pre><code>1 2 3 4 5 6 7 8 9 10
</code></pre>
<p>if pages > 10</p>
<pre><code>1 2 3 ... 20 [30] 40 ... 78 79 80
</code></pre>
<p>where [30] is active page. If active page < 3</p>
<pre><code>1 2 [3] 4 ... 20 30 40 ... 78 79 80
</code></pre>
<p>etc. My code:</p>
<pre><code> count_all - number of all items
items_on_page - items displayed on one page
page - current page
countpages = int(float(count_all+(items_on_page-1))/float(items_on_page))
linkitems = 10
if countpages > (linkitems-1):
countpagesstr = list()
for i in range(1,int(float(linkitems+(2))/float(3))):
countpagesstr += [str(i)]
countpagesstr += ['...']
sr = int(countpages/2)
for i in range(sr-1, sr+1):
countpagesstr += [str(i)]
countpagesstr += ['...']
for i in range(countpages-3, countpages):
countpagesstr += [str(i)]
else:
cp = list()
for c in range(1,countpages+1):
cp.append(str(c))
countpagesstr = cp
return countpagesstr
</code></pre>
<p>How to do it better?</p>
|
[] |
[
{
"body": "<ol>\n<li><p>Your code doesn't run as written. It needs a function definition.</p></li>\n<li><p>Your design needs work. Suppose the current page is 30 and the list of pages says \"... 20 [30] 40 ...\" as in your example. How do I get to page 29 or page 31? It doesn't look as if these page numbers will ever appear in the list.</p>\n\n<p>The more usual design is to always show a small number of pages at the beginning and end, and a small number of pages adjacent to the current page. So that the list of pages would look more like \"1 2 3 ... 28 29 [30] 31 32 ... 78 79 80\".</p></li>\n<li><p>The expression</p>\n\n<pre><code>int(float(count_all+(items_on_page-1))/float(items_on_page))\n</code></pre>\n\n<p>is unnecessarily complex. You can use Python's floor division operator (<code>//</code>) to achieve the same thing without converting to floats and back again:</p>\n\n<pre><code>(count_all + items_on_page - 1) // items_on_page\n</code></pre></li>\n<li><p>Your variables are poorly and unsystematically named. <code>count_all</code>, for example. All what? Or <code>countpagesstr</code>, which sounds like it might be a string, but is in fact a list. You use underscores in some cases (<code>count_all</code>) but not in others (<code>countpages</code>).</p></li>\n<li><p>It is easiest conceptually to separate the two steps of <em>deciding which page numbers to show</em> and <em>showing them in order with ellipses</em>.</p>\n\n<p>In the code below I build the set of the page numbers from the first three pages, the five pages around the current page, and the last three pages. I use Python's sets so that I can take this union without having to worry about duplicate page numbers.</p>\n\n<pre><code>def abbreviated_pages(n, page):\n \"\"\"\n Return a string containing the list of numbers from 1 to `n`, with\n `page` indicated, and abbreviated with ellipses if too long.\n\n >>> abbreviated_pages(5, 3)\n '1 2 [3] 4 5'\n >>> abbreviated_pages(10, 10)\n '1 2 3 4 5 6 7 8 9 [10]'\n >>> abbreviated_pages(20, 1)\n '[1] 2 3 ... 18 19 20'\n >>> abbreviated_pages(80, 30)\n '1 2 3 ... 28 29 [30] 31 32 ... 78 79 80'\n \"\"\"\n assert(0 < n)\n assert(0 < page <= n)\n\n # Build set of pages to display\n if n <= 10:\n pages = set(range(1, n + 1))\n else:\n pages = (set(range(1, 4))\n | set(range(max(1, page - 2), min(page + 3, n + 1)))\n | set(range(n - 2, n + 1)))\n\n # Display pages in order with ellipses\n def display():\n last_page = 0\n for p in sorted(pages):\n if p != last_page + 1: yield '...'\n yield ('[{0}]' if p == page else '{0}').format(p)\n last_page = p\n\n return ' '.join(display())\n</code></pre></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-31T14:26:51.063",
"Id": "15239",
"ParentId": "15235",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "15239",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-31T10:57:40.653",
"Id": "15235",
"Score": "5",
"Tags": [
"python"
],
"Title": "how to generate numbers for pagination?"
}
|
15235
|
<p>I have been working on a class to use Reflection to interrogate other PHP classes and interfaces, what I want to know from anyone with more experience of this is, is there anything else I can add, or is there a better way of doing the things I am trying to do.</p>
<p>In essence I want to be able to use the interrogator to tell me everything it can about a class I give it, interfaces, parents, methods etc etc. When working on large multi-file projects this would give you an idea of the structure of the code and where to find things you need or want to change, eg you change a method in a parent only to find it was overridden by a child class, this should tell you if methods etc are overridden.</p>
<p>thoughts / comments etc welcome.</p>
<pre><code><?php
/* Test / Dummy classes and interfaces for testing */
interface i1
{
const interface_i1_version = '1.0.0';
public function fred();
}
interface i2 extends i1
{
const interface_i2_version = '2.0.0';
}
interface i3
{
const interface_i3_version = '3.0.0';
}
class c1
{
const class_c1_version = '1.0.0';
private $test1;
var $test2;
var $test3 = 'fred';
public function __construct()
{
}
public function foo()
{
}
}
class c2 extends c1 implements i3
{
const class_c2_version = '2.0.0';
public function bar()
{
}
}
class c3 extends c2 implements i1,i2
{
const class_c3_version = '3.0.0';
public static $Test = "sub";
public function foo($bob = 1)
{
}
public function fred()
{
}
}
class c4 extends c3
{
const class_c4_version = '3.0.0';
public static $Test = "bob";
public function foo($bob = 1)
{
}
}
/* The real class to do the work */
class interogate
{
private $constants = Array();
private function get_type($ro)
{
return implode(' ', Reflection::getModifierNames($ro->getModifiers()));
}
private function in_array_r($needle, $haystack, $strict = true)
{
foreach ($haystack as $item)
{
if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && $this->in_array_r($needle, $item, $strict)))
{
return true;
}
}
return false;
}
private function check_parent($name, $parent)
{
foreach ($parent as $p)
{
if ($name == $p['name'])
{
return $p;
}
}
return false;
}
private function update_global_constants($name, $location)
{
foreach ($this->constants as $constant)
{
if ($constant['name'] === $name)
{
return;
}
}
$constant = Array('name' => $name, 'location' => $location);
$this->constants[] = $constant;
}
private function get_global_constants($name)
{
foreach ($this->constants as $constant)
{
if ($constant['name'] === $name)
{
return ($constant['location']);
}
}
return (false);
}
private function constants_from_interfaces($interface_name)
{
$results = Array();
try
{
$ro = new ReflectionClass($interface_name);
}
catch (ReflectionException $re)
{
return($results);
}
foreach ($ro->getConstants() as $name => $value)
{
$this->update_global_constants($name, $interface_name);
$location = $this->get_global_constants($name);
$results[] = Array('name' => $name, 'value' => $value, 'location' => $location);
}
return ($results);
}
private function interogate_interfaces($ro)
{
$results = Array();
foreach ($ro->getInterfaceNames() as $in)
{
if (!($this->in_array_r($in, $results)))
{
$constants = $this->constants_from_interfaces($in);
$results[] = Array('name' => $in, 'constants' => $constants);
}
}
asort($results);
return ($results);
}
private function interogate_statics($ro)
{
$results = Array();
foreach ($ro->getStaticProperties() as $name => $value)
{
$results[] = Array('name' => $name, 'value' => $value);
}
return ($results);
}
private function interogate_constants($ro, $class_name)
{
$results = Array();
foreach ($ro->getConstants() as $name => $value)
{
$this->update_global_constants($name, $class_name);
$location = $this->get_global_constants($name);
$results[] = Array('name' => $name, 'value' => $value, 'location' => $location);
}
return ($results);
}
private function interogate_properties($ro)
{
$results = Array();
foreach ($ro->getProperties() as $p)
{
$name = $p->name;
$results[] = Array('name' => $p->name, 'value' => 'todo');
}
return ($results);
}
public function interogate_methods($ro, $name, $parent, $interface)
{
$results = Array();
$results['local'] = Array();
$results['inherited'] = Array();
foreach ($ro->getMethods() as $m)
{
$local = $this->check_parent($m->name, (isset($parent['methods']['local']))?$parent['methods']['local']:Array());
$inherited = $this->check_parent($m->name, (isset($parent['methods']['inherited']))?$parent['methods']['inherited']:Array());
$overridden = 0;
$overridden_from = 0;
if ((($local !== false) || ($inherited !== false)) && ($m->class == $name))
{
$overridden = 1;
if ($local !== false)
{
$overridden_from = $local['class'];
}
elseif ($inherited !== false)
{
$overridden_from = $inherited['class'];
}
}
if ($interface)
{
$location = 'local';
}
elseif ($m->class == $name)
{
$location = 'local';
}
else
{
$location = 'inherited';
}
$type = $this->get_type($m);
$inheritable = 0;
if (($m->isProtected()) || ($m->isPublic()))
{
$inheritable = 1;
}
if (($inheritable == 0) && ($location == 'inherited'))
{
// Skip ??
}
else
{
$parameters = Array();
foreach ($m->getParameters() as $p)
{
if ($p->isOptional())
{
$optional = 'Yes';
try
{
$default = $p->getDefaultValue();
}
catch (ReflectionException $re)
{
$default = 'Built In';
}
}
else
{
$optional = 'No';
$default = 'none';
}
$position = $p->getPosition();
$parameters[] = Array('name' => $p->name, 'optional' => $optional, 'default' => $default, 'position' => $position);
}
$results[$location][] = Array('name' => $m->name, 'class' => $m->class, 'overridden' => $overridden, 'overridden_from' => $overridden_from, 'inheritable' => $inheritable, 'modifier' => $type, 'parameters' => $parameters);
}
}
return ($results);
}
public function interogate_object($name)
{
$results = Array();
try
{
$rc1 = new ReflectionClass($name);
}
catch (ReflectionException $re)
{
return($results);
}
if ($rc1->isInterface())
{
$type = 'interface';
$interface = 1;
}
else
{
$type = 'class';
$interface = 0;
}
$results['name'] = $name;
$results['type'] = $type;
$filename = $rc1->getFileName();
$start_line = $rc1->getStartLine();
$end_line = $rc1->getEndLine();
$results['filename'] = ($filename == FALSE)?'Unknown':$filename;
$results['details'] = (($start_line == FALSE) || ($end_line == FALSE))?'Unknown':'Between lines: ' . $start_line . ' and ' . $end_line;
$parent = (array) $rc1->getParentClass();
if (array_key_exists('name', $parent))
{
$parent = $parent['name'];
$results['parent'] = $this->interogate_object($parent);
}
$results['interfaces'] = $this->interogate_interfaces($rc1);
$results['methods'] = $this->interogate_methods($rc1, $name, (isset($results['parent']))?$results['parent']:Array(), $interface);
$results['statics'] = $this->interogate_statics($rc1);
$results['constants'] = $this->interogate_constants($rc1, $name);
$results['properties'] = $this->interogate_properties($rc1);
return ($results);
}
}
$i = new interogate();
//$results = $i->interogate_object('ReflectionClass');
$results = $i->interogate_object('c4');
print_r($results);
?>
</code></pre>
<p>I am not sure if anyone else has done this already, or if I am making some bad assumptions, but this is my first play with Reflection so this is as much a learning exercise as anything else.</p>
<p>The completed class (once complete of course), will be available for free (release GPL v3) for anyone to make use of.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-31T13:47:29.093",
"Id": "24717",
"Score": "1",
"body": "If you are doing this project for the experience, that's fine. But if you are doing it for those reasons you gave, then a much better, and easier, solution would be to adopt a good IDE. For instance, my favorite IDE, Netbeans, does all of this natively via the Navigator pane and \"find usages\" tool. As for determining if a method is overriden in a child? Well, a gray circle next to the parent method will tell you that, and a green circle next to the child method will confirm it. Ctrl+Click to follow to source, etc... I'll look over the code and give you my opinion in a few."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-31T13:51:39.117",
"Id": "24718",
"Score": "0",
"body": "I am fine with using a decent IDE but I like to write code to benefit not just myself but other people if possible. So a good IDE would benefit me directly but what about others? This is a valid point of course, but I like a challenge so I want to push this and see how far I can go with it :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-31T13:53:30.003",
"Id": "24719",
"Score": "0",
"body": "The idea is to have a decent output rather than a var_dump for the final version, so you can do full interrogation of a class, as I say mostly a coding exercise to learn something new."
}
] |
[
{
"body": "<p>There are a few things that stood out. I understand this is prototype code, but some of the things I am seeing shouldn't even be present in prototypes. So, I'm just going to treat this as a normal review and point out everything, just in case. As for helping everyone, a good IDE still does this and more. So it is more likely to be installed before some random report generating API. Please do not take offense, I am merely explaining it as others will see it. The benefits of an IDE, that allows seamless integration into the current environment, far outweigh that of a simple \"report\" that distracts from the code the user is attempting to write. There would have to be some reason or feature that would drive someone to use this API over an IDE. And then you would be better off developing it as a plugin for your favorite IDE. Of course, a couple of things you said make me think that this is mostly just a challenge for you, so that is fine, I just wanted to make sure you understood that this is not likely to become the next PHPUnit. Then again, I've been known to be wrong. If you want an accurate assessment, then I would request input from the community on various forums to determine if there is a need. But in the mean time...</p>\n\n<p>Your interfaces could use some work. Again, I understand this might be because you are just prototyping it, but even prototype interfaces should be better fleshed out. If all you are going to do is add constants to them, then you might as well not use interfaces. An interface is supposed to inform the person implementing it what methods and properties are available. As it stands, you would be better off just assigning those constants in the class you wanted to use them in, it would save the overhead at least. Its good to use interfaces, but only if they are being used properly.</p>\n\n<p>Those old-fashioned properties, <code>var</code>, while not deprecated any more, are likely to become deprecated again before too long. It is the old way of declaring a <code>public</code> property. If your version of PHP still requires this syntax, then it is safe to say that you should upgrade it. I'll demonstrate the proper way below, I'll also sneak in the multideclaration syntax.</p>\n\n<pre><code>public\n $test2,\n $test3 = 'fred'\n;\n</code></pre>\n\n<p>What is <code>$ro</code>? Be descriptive with your variables, especially if you are planning on sharing this with others as you mentioned. Sure I can guess what it is supposed to be, but if it were any deeper or more abstracted, this might become a challenge. Besides, I shouldn't have to guess. Well written code is self documenting code. Always remove the uncertainty. Not only will this help others use your code, but it will make it easier for you to return to your code later.</p>\n\n<p>Why do you have a Ternary in an if statement? For one, I didn't even know that was possible; I mean I guess I knew it was, but I've never thought about doing it. Two, why would you do it? You are only making your code more difficult to read. Even after I abstracted the ternary operation from this statement it is still hard to read. This is usually a sign that you are trying to do too much. Try to see how you can simplify it. Here's the ternary abstracted.</p>\n\n<pre><code>$stringCompare = $strict ? $item === $needle : $item == $needle;\nif( $stringCompare || ( is_array( $item ) && $this->in_array_r( $needle, $item, $strict ) ) ) {\n</code></pre>\n\n<p>And here is a simplified version.</p>\n\n<pre><code>private function in_array_r( $needle, $haystack, $strict = TRUE ) {\n if( ! is_array( $haystack ) ) {\n return $strict ? $item === $needle : $item == $needle;\n }\n\n foreach( $haystack AS $item ) {\n if( $this->in_array_r( $needle, $item, $strict ) ) {\n return true;\n }\n }\n\n return false;\n}\n</code></pre>\n\n<p>A better notation for <code>foreach</code> loops is to use the plural as the array and the singular as element. This follows that \"self documenting\" rule and is pretty intuitive to follow. Using single letter variables will only confuse the matter. The only single letter variables should be incrementals or throw away variables, example <code>$i</code> or <code>$x</code>.</p>\n\n<pre><code>foreach( $parents AS $parent ) {\n</code></pre>\n\n<p>You should not use try/catch blocks to control the flow of your program. They are meant to be used for error checking. Either throw a new exception, or do something with the current one. If the program fails, you should inform the user, just returning a value is misleading.</p>\n\n<p>Why are your ternary operations getting harder and harder to read? Be consistent in your style. Also, ternary statements are still statements. A good convention to follow states that there should only be one statement per line, so ternary should declared on its own line and defined to a variable. This helps with legibility, and ensures that your lines do not become excessively long.</p>\n\n<pre><code>$localMethods = isset( $parent[ 'methods' ] [ 'local' ] ) ? $parent[ 'methods' ] [ 'local' ] : array();\n$local = $this->check_parent( $m->name, $localMethods );\n</code></pre>\n\n<p>Of course, even some ternary statements are too long and would be better written as plain if statements. Ternary should not be used if it makes your code harder to read.</p>\n\n<pre><code>$localMethods = array();\nif( isset( $parent[ 'methods' ] [ 'local' ] ) {\n $localMethods = $parent[ 'methods' ] [ 'local' ];\n}\n</code></pre>\n\n<p>Don't use excessive parenthesis. They are not necessary for every comparison, only for those that would return a different value because of precedence. The more parenthesis there are, the harder the statement is to follow. So only use them where they are necessary.</p>\n\n<pre><code>if( ( $local !== false || $inherited !== false ) && $m->class == $name ) {\n</code></pre>\n\n<p>And again, simplify your statements. Don't do a comparison more than once.</p>\n\n<pre><code>if( $m->class == $name ) {\n $overridden = 1;\n\n if( $local !== FALSE ) {\n $overridden_from = $local[ 'class' ];\n } else if( $inherited !== FALSE ) {\n $overridden_from = $inherited[ 'class' ];\n } else {\n $overridden = 0;\n $overridden_from = 0;\n }\n}\n</code></pre>\n\n<p>Additionally, don't recreate booleans. If you have a variable that toggles between a TRUE/FALSE state, then use a boolean. A boolean does not always need to be a boolean, just for the FALSE state. That's why you always see <code>=== FALSE</code> and rarely see <code>=== TRUE</code>. The first is necessary, the second is redundant. For example, both <code>$overridden</code> and <code>$overridden_from</code> both have a FALSE state where their value is zero, and a TRUE state where their value contains the overriding method. The first state is misleading, the second state is natural. When I first saw those variables being declared with zero values, I thought you were setting up a counter to determine how many times it was being overridden. It wasn't until I read on that I figured out what you were trying to do. It is much more intuitive and natural to read <code>$overridden = FALSE;</code> rather than <code>$overridden = 0;</code>. Its also much easier to do a proper comparison.</p>\n\n<p>PHP is very nice in that it does not care about whitespace. So your long array declarations, or method parameters, can be pushed to multiple lines. This makes your code much easier to read.</p>\n\n<pre><code>$parameters[] = array(\n 'name' => $p->name,\n 'optional' => $optional,\n 'default' => $default,\n 'position' => $position\n);\n</code></pre>\n\n<p>Just a couple more things. First, your methods should be shorter. Those last couple were extremely large. I didn't read over them completely, so I can't describe how exactly, but keep in mind the Single Responsibility Principle, and you should be ok. Second, when you are appending a bunch of data onto an array, all at once, do so in a new array and then merge that array onto the old. For example:</p>\n\n<pre><code>$temp = array(\n 'statics' => $this->interogate_statics( $rc1 );\n 'constants' => $this->interogate_constants( $rc1, $name );\n 'properties' => $this->interogate_properties( $rc1 );\n);\n\n$results = array_merge( $results, $temp );\n</code></pre>\n\n<p>Hope this helps</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-31T17:16:56.440",
"Id": "24724",
"Score": "0",
"body": "The opening paragraph of my post is the most important to read, I am looking for feedback on the logic of the code not the layout/style/format. This was a 30 min hack over lunch, so it will get cleaned up prior to release. I am more concerned that the code logic and functionality is right."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-31T18:33:47.400",
"Id": "24727",
"Score": "0",
"body": "@Tim'Wolf'Gurney: As is the opening paragraph of my post. In it I stated that I understood this and that even so there were some things that were concerning even in the prototyping stage. As such I reviewed the whole thing to ensure everything was covered. Is the logic sound? Asides from the things I pointed out, sure. Though, as I mentioned, I fail to see the benefits of such a class, so I cannot extrapolate from it and be more detailed. Can it be done better? Sure, but you'll actually have to write the code before I can do anything more."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-01T10:04:02.223",
"Id": "24752",
"Score": "0",
"body": "Ok that makes sense, and sorry if I sounded ungrateful before because I am not you gave a lot of useful feedback which I will take into account when I clean it up. As for the point of it? I doubt there is one to be honest other than a learning exercise. So thank you for the complete feedback it will be taken on board while I finish it off."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-31T16:52:38.937",
"Id": "15243",
"ParentId": "15236",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-31T12:33:03.723",
"Id": "15236",
"Score": "1",
"Tags": [
"php",
"reflection"
],
"Title": "PHP class and interface interrogation using reflection"
}
|
15236
|
<p>I began programming recently. I am trying to implement a simple trial-division algorithm for finding all primes up to some number (it is much more "primitive" algorithm than the Sieve of Eratosthenes). Can you please find what's wrong with my code?</p>
<pre><code>#range function:
range = function (a,b,c){
var range1=[]
for (i=a; i<b; i=i+c){
range1.push(i);
}
return range1;
}
#The algorithm:
n=prompt("n");
var numbers=range(2,n,1);
var primes=[];
for (number in numbers){
var sublist=range(2,number,1);
console.log(sublist);
for (x in sublist){
if (number%x ===0){
break;
}
primes.push(number);
}
}
</code></pre>
<p>Thanks in advance!</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-18T23:26:38.243",
"Id": "25576",
"Score": "1",
"body": "Is this code working? I'm a little confused at the request \"Can you please find what's wrong with my code?\""
}
] |
[
{
"body": "<p>Try using this instead.</p>\n\n<pre><code>// `isPrime` adopted from http://www.javascripter.net/faq/numberisprime.htm\nvar isPrime = function (n) {\n if (isNaN(n) || !isFinite(n) || n % 1 || n < 2) {\n return false;\n }\n if (n % 2 === 0){\n return (n === 2);\n }\n if (n % 3 === 0){\n return (n === 3);\n }\n for (var i = 5, m = Math.sqrt(n); i <= m; i += 6) {\n if ((n % i === 0) || (n % (i + 2) === 0)){\n return false;\n }\n }\n return true;\n}\nvar getPrimesUntilN = function (n) {\n n = Math.abs(n);\n var primes = (1 < n) ? [2] : [];\n if (isNaN(n) || !isFinite(n)) {\n return primes;\n }\n for (var i = 3; i <= n; i+=2) {\n if (isPrime(i)) {\n primes.push(i);\n }\n }\n return primes;\n};\n</code></pre>\n\n<h1>Input:</h1>\n\n<p><code>getPrimesUntilN(50);</code></p>\n\n<h1>Output:</h1>\n\n<p><code>[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]</code></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-31T18:22:02.400",
"Id": "15246",
"ParentId": "15240",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-31T15:07:52.017",
"Id": "15240",
"Score": "0",
"Tags": [
"javascript"
],
"Title": "Simple trial division in JavaScript"
}
|
15240
|
<p>I am doing my research about scheduling by using Matlab. I am a new Matlab user and I have a problem with time execution of my following code:</p>
<pre><code>clc
clear all
A=8;
B=12;
C=10;
ProcessTime= [ 11 11 11 11 4 4 4 4 4 4 4 2 ]; %Converting Matrice
RandomMatriceA=zeros(A,B,C);
RandomMatriceB=zeros(A,B,C);
SumRandomMatriceB=zeros(1,A,C);
ConvertMatriceA=zeros(A,B,C);
ProcessRandomMatriceA=zeros(A,B,C);
StartProcess=zeros(A,B,C);
EndProcess=zeros(A,B,C);
StartPost=zeros(A,B,C);
for ii=1:C;
for x=1:2:A-1;
%make first random matrice
[vals RandomMatriceA(x,:,ii)]=sort(rand(1,B),2); %batasan tidak boleh satu kelompok melakukan lebih dari satu aktivitas dalam satu waktu
done=false;
while ~done,
%make row of second random matrice
NewRowRandomMatriceB=randi([0 2],1,B);
%Make sure sum all element per row in RandomMatriceB <=11
done=sum(NewRowRandomMatriceB)<12;
end
RandomMatriceB(x,:,ii)=NewRowRandomMatriceB;
%After making RandomMatriceA and RandomMatriceB, then Make New
%Matrice
%To know varible of new matrice which is result of combining
%RandomMatriceA,RandomMatriceB and ProcessTime
for y=1:B,
ConvertMatriceA(x,y,ii)=ProcessTime(RandomMatriceA(x,y,ii));%FirstVarible:Consecutive The Number of value in all element of RandomMatriceA
end
ProcessRandomMatriceA(x,:,ii)=ProcessTime(RandomMatriceA(x,:,ii))+RandomMatriceB(x,:,ii);
EndProcess(x,:,ii)=cumsum(ProcessRandomMatriceA(x,:,ii),2);%secondVaribale:to know in which column The Consecutive value RandomMatrice will be end
StartProcess(x,:,ii)=EndProcess(x,:,ii)-(ProcessTime(RandomMatriceA(x,:,ii))-1);%ThirdVariable:to know in which column The Consecutive Value will be start
for yy=1:B;
N=RandomMatriceA(x,yy,ii);
StartPost(x,N,ii)=StartProcess(x,yy,ii);
end
end
for h=2:2:A;
doneA=false;
while ~doneA,
[vals RandomMatriceA(h,:,ii)]=sort(rand(1,B),2);
doneB=false;
while ~doneB,
NewRowRandomMatriceB=randi([0 2],1,B);
doneB= sum(NewRowRandomMatriceB)<12;
end
RandomMatriceB(h,:,ii)=NewRowRandomMatriceB;
for y=1:B;
ConvertMatriceA(h,y,ii)=ProcessTime(RandomMatriceA(h,y,ii));
end
ProcessRandomMatriceA(h,:,ii)=ProcessTime(RandomMatriceA(h,:,ii))+RandomMatriceB(h,:,ii);
EndProcess(h,:,ii)=cumsum(ProcessRandomMatriceA(h,:,ii),2);%secondVaribale:to know in which column The Consecutive value RandomMatrice will be end
StartProcess(h,:,ii)=EndProcess(h,:,ii)-(ProcessTime(RandomMatriceA(h,:,ii))-1);%ThirdVariable:to know in which column The Consecutive Value will be start
for z=1:B;
N=RandomMatriceA(h,z,ii);
StartPost(h,N,ii)=StartProcess(h,z,ii);
end
doneA =all(ismember(StartPost(h,1:4,ii),StartPost(h-1,1:4,ii)));
end
%arrange value in column 1 until 4 in order that it will have same
%value
StartPost(h,1:4,ii)=StartPost(h-1,1:4,ii);
end
end
</code></pre>
<p>After using the profile viewer, I know that my problem is in this following code. This part takes too much execution time.</p>
<pre><code>....
end
doneA =all(ismember(StartPost(h,1:4,ii),StartPost(h-1,1:4,ii)));
end
%arrange value in column 1 until 4 in order that it will have same
%value
StartPost(h,1:4,ii)=StartPost(h-1,1:4,ii);
end
</code></pre>
<p>How can I improve it and make it run faster?</p>
|
[] |
[
{
"body": "<p>My best guess given the information:\nYou are doing some expensive ismember operations. You can try to get rid of them by tracking Done in a different way.</p>\n\n<p>Perhaps you can use a more efficent way to do it in the same location, or perhaps you need to move it inside the loop and do it in a very cheap way there.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-16T17:45:16.087",
"Id": "29810",
"Score": "0",
"body": "+1 - ismember is one of the slowest things you can do in matlab. ismember inside a loop is a real performance killer. Anyway all this code is not properly vectorized."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-16T15:13:02.787",
"Id": "18708",
"ParentId": "15242",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-31T16:50:31.583",
"Id": "15242",
"Score": "5",
"Tags": [
"optimization",
"performance",
"beginner",
"matrix",
"matlab"
],
"Title": "Processing random matrices"
}
|
15242
|
<p>Just seeing if there is anyway to shorten these for statements?</p>
<pre><code>...
fillMonthSelect: function() {
var month = new Date().getMonth() + 1;
for (var i = 1; i <= 12; i++) {
$('.card-expiry-month').append($('<option value="'+i+'" '+(month === i ? "selected" : "")+'>'+i+'</option>'));
}
},
fillYearSelect: function() {
var year = new Date().getFullYear();
for (var i = 0; i < 12; i++) {
$('.card-expiry-year').append($("<option value='"+(i + year)+"' "+(i === 0 ? "selected" : "")+">"+(i + year)+"</option>"));
}
},
...
</code></pre>
|
[] |
[
{
"body": "<p>String building in code is typically messy, especially without a native <code>String.Format()</code> or <code>sprintf()</code> in Javascript. Building HTML is the worst offender, too.</p>\n\n<p>Other than using a templating engine, like <a href=\"http://icanhazjs.com/\" rel=\"nofollow\">ICanHaz.js</a> (which this use case alone doesn't really justify), you could also build a helper function for creating option tags.</p>\n\n<pre><code>function buildOption(value, isSelected) {\n return \"<option value='\"+value+\"' \"+(isSelected ? \"selected\" : \"\")+\">\"+value+\"</option>\";\n}\n</code></pre>\n\n<p>If you're building a lot of these drop-down options, it might makes things more readable:</p>\n\n<pre><code>for (var i = 0; i < 12; i++) {\n var option = buildOption(i + year, i === 0);\n $('.card-expiry-year').append(option);\n}\n</code></pre>\n\n<p>It's a good idea to avoid long lines/sections of code which have a simple purpose, but have to be read carefully to understand what they do (complicated regular expressions are a good example).</p>\n\n<p>Extracting that functionality into a function avoids this, because the function signature is all someone would need to read to understand what it does.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-31T21:07:41.160",
"Id": "15252",
"ParentId": "15249",
"Score": "3"
}
},
{
"body": "<p>There are a couple of things I'd do to pretty up the code. First, you are looking up the same element with every loop iteration. I know it's common, but it is very inefficient and leads towards long lines. </p>\n\n<p>I moved a couple of things into variables, with also split up those long lines and made the code far more readable, IMHO.</p>\n\n<p>Try something like this instead: </p>\n\n<pre><code> fillMonthSelect: function() {\n var month = new Date().getMonth() + 1;\n var el = $('.card-expiry-month');\n var selectedFlag;\n\n for (var i = 1; i <= 12; i++) {\n selectedFlag = (month === i ? \"selected\" : \"\");\n el.append($('<option value=\"'+i+'\" '+ selectedFlag +'>'+i+'</option>'));\n }\n },\n</code></pre>\n\n<p>The next step would be to get a formatString function, so you could simply write something like:</p>\n\n<pre><code> formatString(\"<option value='{0}' {1}>{0}</option>\", i, selectedFlag);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-31T23:10:18.863",
"Id": "15254",
"ParentId": "15249",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-31T19:53:49.927",
"Id": "15249",
"Score": "3",
"Tags": [
"javascript",
"jquery"
],
"Title": "Anyway to shorten these for statements?"
}
|
15249
|
<p>I'm trying to implement a lexer in Haskell. For easy console input and output, I've used an intermediate data type <strong>Transition Table</strong>.</p>
<pre><code>type TransitionTable = [(Int, Transitions String Int)]
type Transitions a b = [(a, b)]
</code></pre>
<p>I want to take input from the user for all the states and transitions. I do not want to take the total number of states before hand. I want it to keep taking input for the transitions of each state until the user types <em>"--"</em> . If the user types <em>"---"</em>, the current state is discarded and the input terminates.</p>
<p>After a lot of attempts I came up with this, which I think is horrible code.</p>
<pre><code>-- |A function to emulate the while loop for easy IO functionality.
-- Defination:- while @comparator @func @start:
-- *comparator @arg: A function which returns True or False on the basis of @arg.
-- The loop stops when False is returned.
-- *func: The function which is executed repeadly.
-- It is responsible for returning the next @arg for the comparator on the basis of the current @arg.
-- *start: The starting value of @arg to pass to the comparator.
while :: (Monad m) => (a -> Bool) -> (a -> m a) -> a -> m a
while comparator func start =
if comparator start then do
nxt <- func start
while comparator func nxt
else
return start
-- |A modification of putStr which flushes out stdout. Corrents buffer problems.
myPutStr :: String -> IO ()
myPutStr str = putStr str >> hFlush stdout >> return ()
</code></pre>
<hr>
<pre><code>-- Takes input from the console to generate a TransitionTable.
inputTransitionTable :: IO TransitionTable
inputTransitionTable = do
putStrLn "Type -- for next state and --- for completing input entering."
retVal <- while notFinished takeInfo (0, [])
return (snd retVal)
where
-- Returns True when input entry is over.
notFinished (i, _) = i > -1
-- Takes the current state number and the incomplete corrosponding transition table which is populated
-- with user input. Input ends when user enters "---". State number is set to -1 when input is over.
takeInfo (i, states) = do
putStrLn ("Adding transitions to state " ++ show i ++ ": ")
retVal <- while entryNotFinished takeStateInfo ("", [])
let (inpStr, stateInfo) = retVal
case inpStr == "---" of
True -> return (-1, states)
False -> return (i+1, states ++ [(i, stateInfo)])
-- Checks if input entry is over. Returns False if finished.
entryNotFinished (s, _)
| s == "--" || s == "---" = False
| otherwise = True
-- Takes the input state number along with the corresponding transitions.
-- Input ends when the user enters "--".
takeStateInfo (str, state_info) = do
myPutStr "\tEnter transitions symbol: "
symbol <- getLine
if symbol == "--" || symbol == "---" then
return (symbol, state_info)
else do
myPutStr "\t\tEnter the transition state number: "
state' <- getLine
let state = read state' :: Int
return (str, (symbol, state):state_info)
</code></pre>
<p>Basically this is how it runs:</p>
<pre><code>*Main> x <- inputTransitionTable
Type -- for next state and --- for completing input entering.
Adding transitions to state 0:
Enter transitions symbol: a
Enter the transition state number: 1
Enter transitions symbol: b
Enter the transition state number: 2
Enter transitions symbol: --
Adding transitions to state 1:
Enter transitions symbol: a
Enter the transition state number: 2
Enter transitions symbol: b
Enter the transition state number: 3
Enter transitions symbol: --
Adding transitions to state 2:
Enter transitions symbol: a
Enter the transition state number: 3
Enter transitions symbol: --
Adding transitions to state 3:
Enter transitions symbol: --
Adding transitions to state 4:
Enter transitions symbol: ---
(0.03 secs, 344420 bytes)
-- Output
*Main> prettyPrintTransitionTable x
State Transitions
0 ("b",2) ("a",1)
1 ("b",3) ("a",2)
2 ("a",3)
3
</code></pre>
<p>Is there a better way to do this?</p>
|
[] |
[
{
"body": "<p>In order to repeat an action ad nauseum, you can use <a href=\"http://hackage.haskell.org/packages/archive/base/latest/doc/html/Control-Monad.html#v%3aforever\" rel=\"nofollow\"><code>forever</code></a>. But you don't really need to use that here, you can just do it the way you've done it so far. Though I'd think that your <code>while</code> function could be written with guards instead.</p>\n\n<pre><code>while :: (Monad m) => (a -> Bool) -> (a -> m a) -> a -> m a\nwhile comparator func start | comparator start = func start >>= while comparator func\n | otherwise = return start\n</code></pre>\n\n<p>You could also look into using\n<a href=\"http://hackage.haskell.org/package/loop-while\" rel=\"nofollow\"><code>Control.Monad.LoopWhile</code></a>,\nthough I've never used it before.</p>\n\n<p>Note that you don't need <code>>> return ()</code>, since <code>hFlush :: Handle -> IO ()</code> already returns <code>()</code> in the <code>IO</code> Monad. Actually, you never really need <code>return ()</code>. I find it preferable to use <code>void action</code> or <code>_ <- action</code> in order to throw away the result of <code>action</code>.</p>\n\n<p>Your <code>inputTransitionTable</code> function is… not very idiomatic. Threading state\nyourself is unnecessary, you can use the <code>State</code> monad.</p>\n\n<p>Instead of this interactive process, it might actually be easier for a user to\njust specify the transition table as a list of ordered pairs, pretty much the\nway you're printing it after the thing is done. This would probably also require\nyou to <em>parse</em> the user input properly, which is good opportunity to learn the\nropes with <code>parsec</code>. If you want to keep the interactive model, then I'd\nrecommend stacking the <code>IO</code> and <code>State</code> Monads together into an action of type\n<code>State IO TransitionTable</code>.</p>\n\n<p>You can read up on all this stuff in the corresponding chapters of\n<em>RealWorldHaskell</em>. <a href=\"http://book.realworldhaskell.org/read/using-parsec.html\" rel=\"nofollow\">Chapter 16 on\nParsec</a>, and <a href=\"http://book.realworldhaskell.org/read/monad-transformers.html\" rel=\"nofollow\">Chapter\n18 on Monad\nTransformers</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-31T20:55:05.887",
"Id": "15251",
"ParentId": "15250",
"Score": "2"
}
},
{
"body": "<p>There sure is a cleaner way to write it!</p>\n\n<pre><code>import Control.Monad\nimport Control.Monad.Trans.Class\nimport Control.Monad.Trans.Maybe\nimport Control.Monad.Trans.Writer\nimport System.IO\n\ntype TransitionTable = [(Int, Transitions String Int)]\ntype Transitions a b = [(a, b)]\n\ninputTransitionTable :: IO TransitionTable\ninputTransitionTable = execWriterT $ runMaybeT $ forM_ [0..] $ \\i -> do\n -- Monad transformer stack at this point is:\n -- MaybeT <= Outer loop\n -- (WriterT TransitionTable <= Outer writer\n -- IO ) r\n let liftIO = lift . lift\n tellOuter = lift . tell\n liftIO $ putStrLn $ \"Adding transitions to state \" ++ show i ++ \": \"\n t <- execWriterT $ runMaybeT $ forever $ do\n -- Monad transformer stack at this point is:\n -- MaybeT <= Inner loop\n -- (WriterT (Transitions String Int) <= Inner writer\n -- (MaybeT <= Outer loop\n -- (WriterT TransitionTable <= Outer writer\n -- IO ) ) ) r\n let liftIO = lift . lift . lift . lift\n breakOuter = lift . lift $ mzero\n tellInner = lift . tell\n breakInner = mzero\n liftIO $ putStr \"\\tEnter transitions symbol: \"\n symbol <- liftIO getLine\n case symbol of\n \"--\" -> breakInner\n \"---\" -> breakOuter\n _ -> return ()\n liftIO $ putStr \"\\t\\tEnter the transition state number: \"\n state' <- liftIO getLine\n tellInner [(symbol, read state')]\n tellOuter [(i, t)]\n\nprettyPrintTransitionTable table\n = forM_ table $ \\(n, transitions) -> do\n putStr $ show n ++ \" \"\n forM_ transitions $ \\(symbol, state) -> do\n putStr $ \"{\" ++ symbol ++ \"→\" ++ show state ++ \"} \"\n putStrLn \"\"\n\nmain = do\n hSetBuffering stdout NoBuffering -- <= Auto-flushes all \"putStr\"s\n t <- inputTransitionTable\n prettyPrintTransitionTable t\n</code></pre>\n\n<p>The following is how I would actually write it in my own code, so you can compare the size of the code a fluent Haskell programmer writes and compare to your favorite language:</p>\n\n<pre><code>inputTransitionTable = execWriterT $ runMaybeT $ forM_ [0..] $ \\i -> do\n let liftIO = lift . lift\n liftIO $ putStrLn $ \"Adding transitions to state \" ++ show i ++ \": \"\n t <- execWriterT $ runMaybeT $ forever $ do\n let liftIO = lift . lift . lift . lift\n liftIO $ putStr \"\\tEnter transitions symbol: \"\n symbol <- liftIO getLine\n case symbol of\n \"--\" -> mzero\n \"---\" -> lift . lift $ mzero\n _ -> return ()\n liftIO $ putStr \"\\t\\tEnter the transition state number: \"\n state' <- liftIO getLine\n lift $ tell [(symbol, read state')]\n lift $ tell [(i, t)]\n</code></pre>\n\n<p>Test output from the program:</p>\n\n<pre><code>./transitions\nAdding transitions to state 0:\n Enter transitions symbol: a\n Enter the transition state number: 1\n Enter transitions symbol: b\n Enter the transition state number: 2\n Enter transitions symbol: --\nAdding transitions to state 1: \n Enter transitions symbol: a\n Enter the transition state number: 2\n Enter transitions symbol: b\n Enter the transition state number: 3\n Enter transitions symbol: --\nAdding transitions to state 2: \n Enter transitions symbol: a\n Enter the transition state number: 3\n Enter transitions symbol: --\nAdding transitions to state 3: \n Enter transitions symbol: --\nAdding transitions to state 4: \n Enter transitions symbol: ---\n0 {a→1} {b→2} \n1 {a→2} {b→3} \n2 {a→3} \n3\n</code></pre>\n\n<p>If you don't know very much about monad transformers, the best starting point is <a href=\"http://www.grabmueller.de/martin/www/pub/Transformers.pdf\" rel=\"nofollow\">this paper</a>. Don't be put off by the fact that it's a paper. It's written towards beginners and it's very readable and understandable.</p>\n\n<p>To understand the trick I use for breaking out of loops, I recommend you read <a href=\"http://www.haskellforall.com/2012/07/breaking-from-loop.html\" rel=\"nofollow\">this post</a> explaining how you can use <code>MaybeT</code> and <code>EitherT</code> to easily break from loops on the fly the same way you would in an imperative language.</p>\n\n<p>Also, note that I use the <code>WriterT</code> monad transformer to collect results. <code>WriterT</code> commonly arises any time you need to fold or collect data interactively.</p>\n\n<p>I use <code>hSetBuffering</code> to set the output buffering to auto-flush everything. This is an alternative to writing your own <code>putStr</code> function.</p>\n\n<p>I want to also point out the nice <code>forM_</code> combinator which you can use to mimic <code>foreach</code> in other languages. I show it off in the pretty printer function to write code that is almost indistinguishable from the equivalent imperative code.</p>\n\n<p>Also, if you are new to monad transformers, I recommend you stick to the <code>transformers</code> library whenever possible and try to use the <code>mtl</code> only sparingly. This means using <code>Control.Monad.Trans.Class</code> instead of <code>Control.Monad.Trans</code> and <code>Control.Monad.Trans.XXX</code> for the monad transformers. The need to manually <code>lift</code> things might seem off-putting at first, but you gain the ability to equationally reason about your code. That might not seem like much to you now, but as you become a better Haskell programmer you will value that a lot more, so it's a good habit to build early on.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-31T23:11:08.393",
"Id": "15255",
"ParentId": "15250",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "15255",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-08-31T20:02:53.507",
"Id": "15250",
"Score": "4",
"Tags": [
"haskell",
"functional-programming"
],
"Title": "Writing an infinitely running( while(true) { } ) user input function in haskell"
}
|
15250
|
<p>For <a href="http://tour.golang.org/#60" rel="noreferrer">this exercise</a> I have done this:</p>
<pre><code>func between(start, end, value byte) bool{
if value > end {
return false
} else if value < start {
return false
}
return true
}
func (r rot13Reader) Read(p []byte) (n int, err error) {
s, err := r.r.Read(p)
if err != nil {
return s, err
}
for i,v := range p {
if between(97,122, v) {
new := v + 13
if new > 122 {
new -= 26
}
p[i] = new
} else if between(65, 90, v) {
new := v + 13
if new > 90 {
new -= 26
}
p[i] = new
}
}
return s, err
</code></pre>
<p>It works correctly, but it feels like too much code for something like this. Can I improve this code?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-01T12:32:36.703",
"Id": "24753",
"Score": "0",
"body": "Incidentally, this code assumes that the input string contains no character code > 127, otherwise it won’t work. That’s not necessarily a problem though. Just pointing it out."
}
] |
[
{
"body": "<p>I don’t know Go but here are a few general things that I noticed:</p>\n\n<pre><code>func between(start, end, value byte) bool {\n if value > end {\n return false\n } else if value < start {\n return false\n }\n return true\n}\n</code></pre>\n\n<p>As a general pattern, don’t write <code>if condition return true else return false</code> or any permutation thereof. Instead, return the condition directly. In your case, you need to rewrite the condition ever so slightly:</p>\n\n<pre><code>func between(start, end, value byte) bool {\n return ! (value > end) && ! (value < start)\n}\n</code></pre>\n\n<p>Which is the same as (and which can also derived intuitively from the expected semantics of <code>between</code>):</p>\n\n<pre><code>func between(start, end, value byte) bool {\n return value >= start && value <= end\n}\n</code></pre>\n\n<p>In general, <em>only use boolean constants <code>true</code> and <code>false</code> to initialise variables (or parameters)</em>. This is their only use.</p>\n\n<hr>\n\n<p>In your main code, you are essentially doing the same thing twice, once for upper-case and once for lower-case letters. Avoid redundancy and make these cases into one:</p>\n\n<pre><code>is_upper := between(65, 90, v)\nis_lower := between(97, 122, v)\n\nif is_upper || is_lower {\n new := v + 13\n if (is_upper && new > 90) || (is_lower && new > 122) {\n new -= 26\n }\n p[i] = new\n}\n</code></pre>\n\n<p>But this code is still cryptic: what are these weird numbers? Substitute them by named constants or use character constants (since it’s clear what <code>'a'</code> means).</p>\n\n<p>Furthermore, you can get rid of <code>between</code> since Go has functions to test whether a <code>byte</code> is an upper-case or lower-case letter (requires the package <code>unicode</code>):</p>\n\n<pre><code>is_upper := unicode.IsUpper(rune(v))\nis_lower := unicode.IsLower(rune(v))\n</code></pre>\n\n<p>Finally, the logic of rot-13 transforming a character can be simplified by the use of the modulus operation:</p>\n\n<pre><code>c := (c + 13) % 26\n</code></pre>\n\n<p>Obviously, this assumes that <code>c</code> is a value from 0 to 25; so the real logic should be something along these lines: <sup>(Seriously, Go? No conditional operator?!)</sup></p>\n\n<pre><code>if is_upper || is_lower {\n a := byte('a')\n if is_upper { a = byte('A') }\n p[i] = (v - a + 13) % 26 + a\n}\n</code></pre>\n\n<p>The last line here first puts the value of <code>v</code> into the range 0–25 by subtracting <code>a</code>, then does the rot-13 transformation, and then translates it back into a letter by adding the value of <code>a</code> back.</p>\n\n<p>Notice how much shorter the logic of this code has become: the whole loop body is now only seven lines long.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-04-25T20:37:02.140",
"Id": "236721",
"Score": "0",
"body": "I don't have enough reputation points on this site to post an answer, but a shorter version of the for loop is: \n` for k := range(b) {\n if b[k]<'n' {b[k]+=13} else {\n b[k]-=13\n }\n }`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-04-25T21:44:30.180",
"Id": "236734",
"Score": "0",
"body": "@ArnaudAmzallag That omits the entire sanity checking logic, which makes up the bulk of the code (and the logic), and assumes that the string consists entirely of lowercase letters."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-04-26T14:54:38.177",
"Id": "236863",
"Score": "0",
"body": "fair enough. Not sure if shorter now. for k := range(b) {\n if (b[k] >= 'a' && b[k] <= 'm') || (b[k] >= 'A' && b[k] <= 'M') {b[k]+=13} else {\n if (b[k] > 'm' && b[k] <= 'z') || (b[k] > 'M' && b[k] <= 'Z') {b[k]-=13}\n }}"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-01T12:20:29.620",
"Id": "15261",
"ParentId": "15256",
"Score": "15"
}
},
{
"body": "<p>I used a lookup table, keeping the reader code short and uncoding the cipher in O(n).</p>\n\n<pre><code>var rot13lot = map[byte]byte{\n 'A': 'N',\n /* ... */\n 'z': 'm',\n}\n\nfunc (rot13r rot13Reader) Read(p []byte) (n int, err error) {\n n, err = rot13r.r.Read(p)\n for i := 0; i < n; i++ {\n rot, isRot := rot13lot[p[i]]\n if isRot {\n p[i] = rot\n }\n }\n return\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-09-16T09:02:31.457",
"Id": "115071",
"Score": "0",
"body": "The other algorithms also run in O(n), no need for the lookup table to achieve that. The lookup table may *still* be faster, of course."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-16T16:30:09.863",
"Id": "50937",
"ParentId": "15256",
"Score": "2"
}
},
{
"body": "<p>I used similar logic to the original, but made it simpler using modulus operation: </p>\n\n<pre><code>func (self rot13Reader) Read(p []byte) (n int, err error) {\n n, err = self.r.Read(p)\n for i,v := range p {\n switch {\n case v > 64 && v < 91:\n p[i] = (v - 65 + 13) % 26 + 65\n case v > 96 && v < 123:\n p[i] = (v - 97 + 13) % 26 + 97\n }\n }\n return\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-05T17:48:55.143",
"Id": "59142",
"ParentId": "15256",
"Score": "3"
}
},
{
"body": "<p>This improves slightly on Keeth's answer by making the source of the magic numbers more clear.</p>\n\n<pre><code>func (r *rot13Reader) Read(p []byte) (n int, err error) {\n n, err = r.r.Read(p)\n for i := 0; i < n; i++ {\n c := p[i]\n switch {\n case 'a' <= c && c <= 'z':\n p[i] = (c-'a'+13)%26 + 'a'\n case 'A' <= c && c <= 'Z':\n p[i] = (c-'A'+13)%26 + 'A'\n default:\n }\n }\n return\n}\n</code></pre>\n\n<p>I want to point out in particular that we never need to check \"err\" within this code, particularly not before processing all of the bytes that we did receive! <a href=\"http://golang.org/pkg/io/#Reader\">http://golang.org/pkg/io/#Reader</a> explicitly says \"Callers should always process the n > 0 bytes returned before considering the error err. Doing so correctly handles I/O errors that happen after reading some bytes and also both of the allowed EOF behaviors.\" In yasar's original code, checking the state of err early skips the proper processing of the n bytes that were produced before the error happened.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-09-07T08:23:17.727",
"Id": "190049",
"Score": "0",
"body": "Thanks, I was specifically wondering if `n` is relevant with an error."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-17T00:22:44.523",
"Id": "66947",
"ParentId": "15256",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-01T00:09:59.737",
"Id": "15256",
"Score": "13",
"Tags": [
"beginner",
"go",
"caesar-cipher"
],
"Title": "Rot13 Reader in Go"
}
|
15256
|
<p>I am animating 1400 objects trying to create a 'twinkling effect'. As the user moves the mouse faster more hexagon shapes pop into full opacity and have varying fade out rates. The version in the fiddle fills the space with enough color but feels jerky and clumpy. If I lessen the fade_time variable amounts it is smoother but does not have enough hexagons with full opacity. The end goal is to spell words with the hexagons.</p>
<p><a href="http://jsfiddle.net/st8ofmindz79/rz4yY/36/" rel="nofollow noreferrer">JSFiddle code</a></p>
<p>Here's the JS if you don't want to go over to jsfiddle:</p>
<pre><code>function getRandomInt (min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function shuffle(array) {
var tmp, current, top = array.length;
if(top){
while(--top) {
current = Math.floor(Math.random() * (top + 1));
tmp = array[current];
array[current] = array[top];
array[top] = tmp;
}
}
return array;
}
Raphael.el.animate_hex = function() {
var fade_time = [1000, 2000, 3000, 4000];
//var fade_time = [3000, 4000, 5000, 6000];
this.attr({"fill-opacity": 1});
this.animate({"fill-opacity": 0}, fade_time[getRandomInt(0, 4)], 'linear', function(){
});
};
//set paper to width and height of container
var container_width = document.getElementById('wrap').offsetWidth;
var container_height = document.getElementById('wrap').offsetHeight;
var paper = Raphael(document.getElementById('wrap'), container_width, container_height);
//create and position hexagon shapes.
var set = paper.set();
var abs_x = 0;
var abs_y = 0;
var total_hex = 1400;
for(h=0;h<total_hex;h++){
var HexM = [7.478, 8.66];
var HexL = [[7.478, 8.66], [2.542, 8.66], [0.05, 4.32], [2.542, 0.028], [7.478, 0.028], [9.97, 4.32], [7.478, 8.66]];
var hex = paper.path('M ' + HexM[0] + ' ' + HexM[1] + ' L ' + HexL[0][0] + ' ' + HexL[0][2] + ' L ' + HexL[1][0] + ' ' + HexL[1][3] + ' L ' + HexL[2][0] + ' ' + HexL[2][4] + ' L ' + HexL[3][0] + ' ' + HexL[3][5] + ' L ' + HexL[4][0] + ' ' + HexL[4][6] + ' L ' + HexL[5][0] + ' ' + HexL[5][7] + ' L ' + HexL[6][0] + ' ' + HexL[6][8]).attr({'fill':'#ec2b26','stroke-width':'0' ,'fill-opacity': 0 });
if(abs_x * 10 == container_width){ abs_y = abs_y + 10; abs_x = 0;}
hex.transform('...T' + 10 * abs_x + ',' + abs_y ).attr('id','hex' + h);
set.push(hex);
abs_x++;
}
//create an object to tie the mousemove event to (paper was only working with onmouseover)
var hover_span = paper.rect(0,0, container_width, container_height).attr({'opacity': '0', 'id': 'cover', 'fill': '#000000'});
newx = 0;
newy = 0;
beginx = 0;
beginy = 0;
//compare new and old cursor coordinates to get an idea of how far the cursor has moved.
hover_span.mousemove(function(e) {
newx = beginx;
newy = beginy;
beginx = e.pageX;
beginy = e.pageY;
var animate_count = 0;
animate_count = Math.sqrt((newx * beginx) + (newy * beginy)) / 1;
//animate an amount based on cursor movement. The division in the line above helps lessen or increase the amount of hexagons animated in a call of mousemove.
for(i=0; i<animate_count; i++){
var rdm_index = getRandomInt(0, 1400);
set[rdm_index].animate_hex();
}
});
</code></pre>
<p>The performance in Chrome is best, less so in FireFox and IE. I tested (using Raphael's element.touchmove) in mobile safari on an iPad and it was even worse.</p>
<p>I'm looking for any advice on what pieces of the code could be done differently for performance gains.</p>
<p><a href="https://stackoverflow.com/a/2868299">I saw this answer</a> somebody else gave that was supposed to help with performance, but I'm trying to base the amount of animating hexagons on cursor movement and I'm not sure I could do that with a timer.</p>
<p><a href="https://stackoverflow.com/a/7842355">This answer</a> mentioned using canvas:</p>
<blockquote>
<p>A good alternative would be using Canvas to draw the elements. From my
experiments it will be faster than SVG at drawing this many although
if you are using some animations, they will be harder to implement
than with the RaphaelJS library.</p>
</blockquote>
<p>Does that seem like a better route to people, even with the animations the code is using?</p>
<p>This is my first use of Raphael.js. I'm not very experienced in JS in general, so any help is wunderbar!</p>
<p><strong>Edit:</strong> Also, seeing <a href="https://codereview.stackexchange.com/a/10969/16237">this answer</a> about .resize being called more times than the questioner might have thought got me wondering if the .mousemove function may be called more times (more than I would need) than I would expect.</p>
|
[] |
[
{
"body": "<p>You are most certainly using a wrong tool for the job. <code><canvas></code> element and <code>requestAnimationFrame()</code> are your friends.</p>\n\n<p>Also, I'd expect opacity animation to tax the graphics stack heavily (unless GPU accelerated, perhaps.) If the background color is going to be white, animating the fill color should work better.</p>\n\n<p>Suggested reading:</p>\n\n<ol>\n<li><p><a href=\"http://paulirish.com/2011/requestanimationframe-for-smart-animating/\" rel=\"nofollow\">requestAnimationFrame for smart\nanimating</a></p></li>\n<li><p><a href=\"http://www.useragentman.com/blog/2012/09/23/cross-browser-gpu-acceleration-and-requestanimationframe-in-depth/\" rel=\"nofollow\">Cross Browser GPU Acceleration and requestAnimationFrame in\nDepth</a></p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-07T05:17:05.567",
"Id": "20219",
"ParentId": "15259",
"Score": "2"
}
},
{
"body": "<p>Just some ideas, not sure or they are usefull</p>\n\n<p>Personally I would go for a more 'EVENT' based solution. Instead of looping over all those elemnts everytime the mouse moves, iw ould simply trigger a 'mouse moved' event. then all elements listen to that event and randomly decide wether to change opacity or not.</p>\n\n<p>Events it the way to go :p</p>\n\n<p>Then for the animation, this could be done with css3. Instead of using the animate() function with different times, simply at random change the transition time (just an idea).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T08:54:02.367",
"Id": "32232",
"ParentId": "15259",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-01T02:41:11.487",
"Id": "15259",
"Score": "4",
"Tags": [
"javascript",
"performance",
"raphael.js",
"animation"
],
"Title": "Animating opacity of 1400 Raphael.js objects hurts animating performance"
}
|
15259
|
<p>I created this very simple stack concept's implementation.
Could you tell me if it is correct and clean? Do you see any bad coding habits?</p>
<pre><code>public class MyStack
{
private static final int MAXELEMENTS = 10;
private int[] elements;
private int numElements;
public MyStack()
{
numElements = 0;
elements = new int[MAXELEMENTS];
}
public boolean isEmpty()
{
return (numElements == 0);
}
public boolean isFull()
{
return (numElements == MAXELEMENTS);
}
public void push(int e)
{
if (!isFull())
elements[numElements++] = e;
}
public int top()
{
if (!isEmpty())
return elements[numElements - 1];
else
return -1;
}
public void pop()
{
if (!isEmpty())
numElements--;
}
}
</code></pre>
<p>You can use it with the following code:</p>
<pre><code>class MyStackTestDrive
{
public static void main(String[] args)
{
MyStack s1 = new MyStack();
MyStack s2 = new MyStack();
s1.push(2);
s2.push(4);
System.out.println(s1.top());
System.out.println(s2.top());
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-02T09:58:58.693",
"Id": "24769",
"Score": "2",
"body": "Will you ever want to put anything other than an `int` into the `Stack`? In that case, you should take a look at generics. In [one of my previous reviews](http://codereview.stackexchange.com/a/14404/9390), you can see how a solid `Stack` implementation might look like."
}
] |
[
{
"body": "<p>Some small notes:</p>\n\n<ol>\n<li><p>According to the <a href=\"http://www.oracle.com/technetwork/java/codeconventions-142311.html#430\" rel=\"nofollow\">Code Conventions for the Java Programming Language</a>,</p>\n\n<blockquote>\n <p>if statements always use braces {}.</p>\n</blockquote>\n\n<p>Omitting them is error-prone.</p></li>\n<li><p><code>top</code>, <code>push</code> and <code>pop</code> methods handle invalid client calls too generously. You shouldn't do that. Crash early. Does it make sense to pop from an empty stack? It is rather a bug in the client code. Instead of returning <code>-1</code> or swallowing the client error throw an <code>IllegalStateException</code> or an <code>EmptyStackException</code>. See: <em>The Pragmatic Programmer: From Journeyman to Master</em> by <em>Andrew Hunt</em> and <em>David Thomas</em>: <em>Dead Programs Tell No Lies</em>. You could use <a href=\"http://www.codinghorror.com/blog/2006/01/flattening-arrow-code.html\" rel=\"nofollow\">guard clauses</a> too: </p>\n\n<pre><code>public void push(final int e) {\n if (isFull()) {\n throw new IllegalStateException();\n }\n elements[numElements++] = e;\n}\n\npublic int top() {\n if (isEmpty()) {\n throw new EmptyStackException();\n }\n return elements[numElements - 1];\n}\n\npublic void pop() {\n if (isEmpty()) {\n throw new EmptyStackException();\n }\n numElements--;\n}\n</code></pre></li>\n<li><p>I'd make the maximal number of elements configurable via the constructor:</p>\n\n<pre><code>private static final int DEFAULT_MAX_ELEMENTS = 10;\n\nprivate final int maxElements;\nprivate final int[] elements;\nprivate int numElements;\n\npublic MyStack() {\n this(DEFAULT_MAX_ELEMENTS);\n}\n\npublic MyStack(final int maxElements) {\n if (maxElements < 1) {\n throw new IllegalArgumentException(\"maxElements cannot be less than 1, was: \" + maxElements);\n }\n this.maxElements = maxElements;\n elements = new int[maxElements];\n}\n</code></pre></li>\n<li><p>The default value of <code>int</code> fields are <code>0</code>, therefore <code>numElements = 0;</code> is unnecessary in the constructor.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-02T09:42:36.513",
"Id": "24768",
"Score": "1",
"body": "good points; although the error message for passing too few `maxElements` into the constructor is wrong, should be *`\"maxElements cannot be less than 0, was: \"`* in accordance with the condition in the if-clause."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-02T10:21:56.143",
"Id": "24771",
"Score": "0",
"body": "@codesparkle: Thank you, you're right. I've fixed it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-02T12:01:19.697",
"Id": "24772",
"Score": "0",
"body": "“Omitting them is error-prone.” – no, it’s simply not."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-02T12:32:36.730",
"Id": "24774",
"Score": "1",
"body": "Point 1 can be contentious. It largely depends on the code standards you want to enforce (or is enforced at your workplace). If you look through the Java standard libraries you will find many instances of brackets not being used for if blocks. My personal preference is brackets for multiline conditionals, no brackets for single line conditionals. I break lines at 80."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-16T20:06:52.200",
"Id": "33021",
"Score": "1",
"body": "Don't use IllegalStateException. Java provides the more specific EmptyStackException and StackOverflowError."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-16T21:12:29.197",
"Id": "33026",
"Score": "1",
"body": "@Eva: `EmptyStackException` is a great insight, thank you! I've updated the answer. `StackOverflowError` is a subclass of `VirtualMachineError` which does not seem appropriate here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-16T21:26:16.217",
"Id": "33028",
"Score": "1",
"body": "Good point. I think creating a StackOverflowException subclass of IllegalStateException is [justified](http://docs.oracle.com/javase/tutorial/essential/exceptions/creating.html)."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-01T16:14:15.053",
"Id": "15263",
"ParentId": "15262",
"Score": "6"
}
},
{
"body": "<p>Why split <code>top</code> and <code>pop</code>?</p>\n\n<p><code>pop</code> could easily return an int and adjust the number of elements.</p>\n\n<p>In cases were the consumer wanted to <code>pop</code> without the int, they would just not assign the return of <code>pop</code> to a variable. And I can't think of a valid case for using <code>top</code> without using <code>pop</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-02T12:48:16.970",
"Id": "24775",
"Score": "0",
"body": "another good reason for `pop` to return the popped element is consistency: [`java.util.Stack`](http://docs.oracle.com/javase/7/docs/api/java/util/Stack.html) and every other implementation I can think of works this way. However, a `peek` method should remain to check the top element without removing it (there are lots of valid use cases for examining the next item without removing it). **Edit: No. It does *not* print 4 twice because two separate stacks are involved. Run the code, please.**"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-02T12:57:00.497",
"Id": "24776",
"Score": "0",
"body": "That's true, but it's a bit of a rabbit hole to go down. Because once you start asking if your custom stack class should use the Java stack API, I think your next question should be, do I even need a custom stack in the first place? And maybe you do for a primitive type, but then again someone has probably already done it for you. See http://trove4j.sourceforge.net/javadocs/gnu/trove/stack/TIntStack.html."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-02T12:58:00.403",
"Id": "24777",
"Score": "0",
"body": "@codesparkle, You are correct, I misread the test code."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-02T12:38:25.677",
"Id": "15279",
"ParentId": "15262",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "15263",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-01T15:41:08.720",
"Id": "15262",
"Score": "6",
"Tags": [
"java",
"stack"
],
"Title": "Java and stacks: correct implementation?"
}
|
15262
|
<p>Can anyone help me prettify this code? The idea is to combine adjacent time spans so</p>
<p>[0:00-1:00, 1:00-2:00, 3:00-4:00] becomes [0:00-2:00, 3:00-4:00]</p>
<pre><code>private static IEnumerable<Span> CombineAdjacentSpans(IEnumerable<Span> spans)
{
var combined = new List<Span>();
var list = spans.OrderBy(s => s.Start).ToList();
var candidate = list.FirstOrDefault();
foreach (var span in list.Skip(1))
{
if (span.Start == candidate.End)
{
candidate.End = span.End;
continue;
}
combined.Add(candidate);
candidate = span;
}
if (candidate != null)
combined.Add(candidate);
return combined;
}
</code></pre>
|
[] |
[
{
"body": "<p>I would make three changes</p>\n\n<ol>\n<li><p>Drop the <code>ToList()</code> as you are working on <code>IEnumerable<Span></code> anyway and are not making use of list indexes.</p></li>\n<li><p>Take in account overlapping spans by testing for <code>span.Start <= candidate.End</code> instead of just <code>span.Start == candidate.End</code>.</p></li>\n<li><p>Use an <code>else</code>-clause instead of a <code>continue</code>. People are more used to <code>else</code>. It's a matter of personal preference, but I think that an <code>else</code> makes the control flow more obvious. <code>continue</code> remainds me a bit of <code>goto</code>.</p></li>\n</ol>\n\n\n\n<pre><code>private static IEnumerable<Span> CombineAdjacentSpans(IEnumerable<Span> spans)\n{\n var combined = new List<Span>();\n var list = spans.OrderBy(s => s.Start); // Drop the ToList(), its not necessary.\n\n var candidate = list.FirstOrDefault();\n foreach (var span in list.Skip(1))\n {\n if (span.Start <= candidate.End) { // Consider overlapping spans\n candidate.End = span.End;\n } else { // Use an else-clause instead of continue.\n combined.Add(candidate);\n candidate = span;\n }\n }\n\n if (candidate != null)\n combined.Add(candidate);\n\n return combined;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-01T20:19:24.097",
"Id": "24760",
"Score": "0",
"body": "Thanks for the feedback.\nRegarding the ToList() I used it to avoid potential multiple enumeration, not to use the indexes.\n\nRegarding point 2 -> good call. Although I will not encounter overlapping spans, this is far more 'correct' - thanks.\n\nRegarding 3) also a valid point, though I can's say that I agree on the 'goto' thing ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-01T20:48:19.057",
"Id": "24761",
"Score": "0",
"body": "Except if you don't use `ToList()`, sorting the sequence will be done twice (once for `FirstOrDefault()` and once for the `foreach`). With a large list, that could make a big difference."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-01T17:26:51.787",
"Id": "15266",
"ParentId": "15264",
"Score": "0"
}
},
{
"body": "<p>You can shorten this and get lazy evalution using yield:</p>\n\n<pre><code>private static IEnumerable<Span> CombineAdjacentSpans(this IEnumerable<Span> spans)\n{\n Span current = null;\n foreach (var span in spans.OrderBy(s => s.Start)) {\n if (current == null) { current == span; }\n // I made this handle overlaps, but if you don't care about those\n // you can change the comparison to just ==\n else if (span.Start <= current.End && span.End > current.End) {\n // current.End = span.End\n // it's probably better to make a new span rather than modifying the\n // current one here since that way this method doesn't modify elements\n // in the original list. If span is a struct, then modification would be\n // fine but we'd have to rely on a bool rather than checking against null\n current = new Span { Start = current.Start, End = span.End };\n } else {\n yield return current;\n current = span;\n } \n }\n\n if (current != null) { yield return current; }\n}\n</code></pre>\n\n<p>This way, something like mySpans.CombineAdjacentSpans().Take(3) will only do the work of combining the first 3 spans (although OrderBy will still have to look at all elements in the input sequence).</p>\n\n<p>In response to Chris's comment, if you really want the last if statement inside the loop here's one way I can think of to do it:</p>\n\n<pre><code>private static IEnumerable<Span> CombineAdjacentSpans(this IEnumerable<Span> spans)\n{\n Span current = null;\n // could also use Enumerable.Repeat() instead of new[] { ... }\n foreach (var span in spans.OrderBy(s => s.Start).Concat(new[] { default(Span) })) {\n if (current == null) { current == span; }\n // I made this handle overlaps, but if you don't care about those\n // you can change the comparison to just ==\n else if (span.Start <= current.End && span.End > current.End) {\n // current.End = span.End\n // it's probably better to make a new span rather than modifying the\n // current one here since that way this method doesn't modify elements\n // in the original list. If span is a struct, then modification would be\n // fine but we'd have to rely on a bool rather than checking against null\n current = new Span { Start = current.Start, End = span.End };\n } else {\n yield return current;\n current = span;\n } \n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-01T20:17:06.017",
"Id": "24759",
"Score": "0",
"body": "Excellent idea, thanks. There is one more thing that is bothering me though, and to be honest I don't know if it's doable or not and if so if it will improve or degrade the readability - it's the final call after the loop ends - the \n\n if (current != null) { ... }\n\nI wanted to drag that somehow into the loop. Any ideas on that?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-01T21:13:01.480",
"Id": "24762",
"Score": "0",
"body": "@Chris: I've added a second version that does just that. Not sure it's really more readable though."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-03T08:13:12.043",
"Id": "24796",
"Score": "0",
"body": "I was going in a similar direction with that ;) and am also not sure if that's more readable or not - but it is shorter, so I'll go for it. Thanks for your help. I like the refactorings."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-01T19:45:26.710",
"Id": "15267",
"ParentId": "15264",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "15267",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-01T16:17:12.460",
"Id": "15264",
"Score": "3",
"Tags": [
"c#",
"algorithm"
],
"Title": "Prettify this code - combine items in a list"
}
|
15264
|
<p>I needed a <code>boost.any</code> look-a-like, that could handle a <code>std::unique_ptr</code>. I came up with this. Please provide some C++11 criticism.</p>
<pre><code>#ifndef ANY_HPP
# define ANY_HPP
#include <cassert>
#include <stdexcept>
#include <typeinfo>
#include <type_traits>
#include <utility>
namespace generic
{
class any
{
public:
any() noexcept : content(nullptr) { }
any(any const& other)
: content(other.content ? other.content->clone() : nullptr)
{
}
any(any&& other) noexcept { *this = std::move(other); }
template<typename ValueType,
typename = typename std::enable_if<
!std::is_same<any, typename std::decay<ValueType>::type>::value
>::type
>
any(ValueType&& value)
: content(new holder<typename std::remove_reference<ValueType>::type>(
std::forward<ValueType>(value)))
{
}
~any() { delete content; }
public: // modifiers
void swap(any& other) noexcept { std::swap(content, other.content); }
any& operator=(any const& rhs) { return *this = any(rhs); }
any& operator=(any&& rhs) noexcept
{
content = rhs.content;
rhs.content = nullptr;
return *this;
}
template<typename ValueType,
typename = typename std::enable_if<
!std::is_same<any, typename std::remove_const<
typename std::remove_reference<ValueType>::type>::type>::value
>::type
>
any& operator=(ValueType&& rhs)
{
return *this = any(std::forward<ValueType>(rhs));
}
public: // queries
explicit operator bool() const noexcept { return content; }
std::type_info const& type() const noexcept
{
return content ? content->type() : typeid(void);
}
private: // types
struct placeholder
{
placeholder() = default;
virtual ~placeholder() noexcept { }
virtual placeholder* clone() const = 0;
virtual std::type_info const& type() const = 0;
};
template<typename ValueType, typename = void>
struct holder : public placeholder
{
public: // constructor
template <class T>
holder(T&& value) : held(std::forward<T>(value)) { }
holder& operator=(holder const&) = delete;
placeholder* clone() const final { throw std::invalid_argument(""); }
public: // queries
std::type_info const& type() const noexcept { return typeid(ValueType); }
public:
ValueType held;
};
template<typename ValueType>
struct holder<
ValueType,
typename std::enable_if<
std::is_copy_constructible<ValueType>::value
>::type
> : public placeholder
{
public: // constructor
template <class T>
holder(T&& value) : held(std::forward<T>(value)) { }
placeholder* clone() const final { return new holder<ValueType>(held); }
public: // queries
std::type_info const& type() const noexcept { return typeid(ValueType); }
public:
ValueType held;
};
private: // representation
template<typename ValueType>
friend ValueType* any_cast(any*) noexcept;
template<typename ValueType>
friend ValueType* unsafe_any_cast(any*) noexcept;
placeholder* content;
};
template<typename ValueType>
inline ValueType* unsafe_any_cast(any* const operand) noexcept
{
return &static_cast<any::holder<ValueType>*>(operand->content)->held;
}
template<typename ValueType>
inline ValueType const* unsafe_any_cast(any const* const operand) noexcept
{
return unsafe_any_cast<ValueType>(const_cast<any*>(operand));
}
template<typename ValueType>
inline ValueType* any_cast(any* const operand) noexcept
{
return operand && (operand->type() == typeid(ValueType))
? &static_cast<any::holder<ValueType>*>(operand->content)->held
: nullptr;
}
template<typename ValueType>
inline ValueType const* any_cast(any const* const operand) noexcept
{
return any_cast<ValueType>(const_cast<any*>(operand));
}
template<typename ValueType>
inline ValueType any_cast(any& operand)
{
typedef typename std::remove_reference<ValueType>::type nonref;
#ifndef NDEBUG
nonref* const result(any_cast<nonref>(&operand));
if (!result)
{
throw std::bad_cast();
}
// else do nothing
return *result;
#else
return *unsafe_any_cast<nonref>(&operand);
#endif // NDEBUG
}
template<typename ValueType>
inline ValueType any_cast(any const& operand)
{
typedef typename std::remove_reference<ValueType>::type nonref;
return any_cast<nonref const&>(const_cast<any&>(operand));
}
}
#endif // ANY_HPP
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-02T12:05:28.117",
"Id": "24773",
"Score": "0",
"body": "You mention `unique_ptr`. Why is `content` not a `unique_ptr`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-02T22:37:34.700",
"Id": "24786",
"Score": "0",
"body": "because unique_ptr is a class template. The different instantiations of it differ in type. But `any`, just like `boost::any`, can store any type."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-31T12:05:32.277",
"Id": "32053",
"Score": "0",
"body": "@user1095108: No he means that instead of `placeholder* content` you can use `unique_ptr<placeholder> content`. It will make your life much easier."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-01T17:10:53.537",
"Id": "32085",
"Score": "0",
"body": "It would make for prettier, but also heavier, code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T03:56:48.167",
"Id": "75152",
"Score": "0",
"body": "How concerned are you with the accuracy of your clone? It seems to be missing the `empty` and `clear` member functions, but I'm not sure how much you care (if at all)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-05T08:25:02.097",
"Id": "75170",
"Score": "0",
"body": "@JerryCoffin Not at all, but I did need the additional functionality this class provided (stored `std::unique_ptr`s to `any` instances in a map). Seemed a shame to waste space on a `std::shared_ptr` with the original `any`. I'll update the class one of these days... You can make your comment an answer, I'll accept, since this post did not receive an answer for a long time."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T18:52:41.840",
"Id": "76092",
"Score": "0",
"body": "I don't have a C++11 compiler here, but have you tried Poco's Any, or DynamicAny? http://pocoproject.org/slides/010-Types.pdf"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T19:26:02.713",
"Id": "76104",
"Score": "0",
"body": "@ArthurChamz it is easy to write your own `any`, that suits your needs, no need to look around"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T19:31:04.633",
"Id": "76110",
"Score": "0",
"body": "Gonna have to try it out someday, then =)"
}
] |
[
{
"body": "<p>Instead of </p>\n\n<pre><code> std::type_info const& type() const noexcept\n {\n return content ? content->type() : typeid(void);\n }\n</code></pre>\n\n<p>I would recommend:</p>\n\n<pre><code> std::type_info const& type() const noexcept\n {\n return content ? content->type() : typeid(nullptr);\n }\n</code></pre>\n\n<p>After all, the default content is a <code>nullptr</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-05T08:53:14.793",
"Id": "118609",
"Score": "1",
"body": "I disagree, after all, the principal requirement is, that `any` can hold an object of any type. Even a `nullptr`, which is of type `nullptr_t`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-05T08:57:32.343",
"Id": "118610",
"Score": "0",
"body": "@user1095108, I understand. Shouldn't type returned be `typeid(nullptr)` if the object is holding a `nullptr`?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-05T07:01:13.620",
"Id": "64770",
"ParentId": "15269",
"Score": "0"
}
},
{
"body": "<p>Watch the move assignment operator:</p>\n\n<pre><code>any& operator=(any&& rhs) noexcept\n{\n content = rhs.content;\n rhs.content = nullptr;\n\n return *this;\n}\n</code></pre>\n\n<p><code>content</code> was leaked here, and it'd be better to use <code>unique_ptr<placeholder></code>, as other commenters have said.</p>\n\n<pre><code>~any() { delete content; }\nvirtual ~placeholder() noexcept { }\n</code></pre>\n\n<p>Destructors are <code>noexcept</code> by default. If you want to be explicit about it, be consistent in that.</p>\n\n<p>I do not think you need all these applications of SFINAE. Non templated overloads are anyway preferred over templated ones.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-01-21T14:31:27.640",
"Id": "78220",
"ParentId": "15269",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-01T20:38:09.127",
"Id": "15269",
"Score": "17",
"Tags": [
"c++",
"c++11",
"pointers",
"variant-type"
],
"Title": "boost::any replacement with std::unique_ptr support"
}
|
15269
|
<p>How can this be minimized?</p>
<pre><code>// remove accent
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(input);
input = System.Text.Encoding.UTF8.GetString(bytes);
// make it all lower case
input = input.ToLower();
// remove stop words
input = System.Text.RegularExpressions.Regex.Replace(input, "\\b" + string.Join("\\b|\\b", ENGLISH_STOP_WORDS) + "\\b", "");
// remove entities
input = System.Text.RegularExpressions.Regex.Replace(input, @"&\w+;", "");
// remove anything that is not letters, numbers, dash, or space
input = System.Text.RegularExpressions.Regex.Replace(input, @"[^a-z0-9\-\s]", "");
// replace spaces
input = input.Replace(' ', '-');
// collapse dashes
input = System.Text.RegularExpressions.Regex.Replace(input, @"-{2,}", "-");
// collapse spaces
input = System.Text.RegularExpressions.Regex.Replace(input, @"\s+", " ").Trim();
// Trim dashes and spaces
input = input.Trim(' ').Trim('-').Trim(' '); // double trim the spaces incase dashes were covering them
return input;
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-02T09:19:26.907",
"Id": "24766",
"Score": "0",
"body": "What is the final intent of this snippet?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-02T10:14:08.923",
"Id": "24770",
"Score": "0",
"body": "i think its quite obvious, including the comments...\nit should generate a UrlFriendly Slug."
}
] |
[
{
"body": "<blockquote>\n<pre><code>// remove accent\n</code></pre>\n</blockquote>\n\n<p>Actually, no. The following code is just a lossless conversion to and from UTF-8 which doesn’t change the text.</p>\n\n<p>In the following, I’d coalesce the regular expressions – if nothing else, this is way more efficient. I’d also import the namespace to get rid of this overlong explicit namespace qualification. The “collapse spaces” phase makes no sense since you’ve already <em>removed</em> spaces.</p>\n\n<p>Finally, you can also coalesce the <code>Trim</code> statements.</p>\n\n<p>Ignoring for now that the accent removal doesn’t work, this leaves us with:</p>\n\n<pre><code>input = input.ToLower();\n\n// remove stop words, entities and anything that is not letters, numbers, dash, or space\nstring stopWords = string.Format(\"\\\\b{0}\\\\b\", string.Join(\"\\\\b|\\\\b\", ENGLISH_STOP_WORDS));\ninput = Regex.Replace(input, stopWords + @\"|&\\w+;|[^a-z0-9\\-\\s]\", \"\");\n\n// replace spaces\ninput = input.Replace(' ', '-');\n\n// collapse dashes\ninput = Regex.Replace(input, @\"-{2,}\", \"-\");\n\n// Trim dashes and spaces\ninput = input.Trim(' ', '-');\n</code></pre>\n\n<p>Finally, to remove accents, you need to <a href=\"http://www.siao2.com/2005/02/19/376617.aspx\" rel=\"nofollow\"><em>normalize</em> the Unicode string so that accented characters are decomposed into diacritics and remove combining diacritic marks</a>:</p>\n\n<pre><code>static string RemoveDiacritics(string stIn) {\n string stFormD = stIn.Normalize(NormalizationForm.FormD);\n StringBuilder sb = new StringBuilder();\n\n for(int ich = 0; ich < stFormD.Length; ich++) {\n UnicodeCategory uc = CharUnicodeInfo.GetUnicodeCategory(stFormD[ich]);\n if(uc != UnicodeCategory.NonSpacingMark) {\n sb.Append(stFormD[ich]);\n }\n }\n\n return sb.ToString();\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-02T19:39:00.510",
"Id": "24783",
"Score": "0",
"body": "nice, tested and works like a charm, interesting to see what others come up with."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-04T05:23:24.553",
"Id": "24832",
"Score": "0",
"body": "Why not make the regex a compiled regex: Regex theRegex = new Regex(stopWords + @\"|&\\w+;|[^a-z0-9\\-\\s]\", RegexOptions.Compiled); then theRegex.Replace(...) This should make the calls a little quicker, and use less resources."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-04T07:01:50.577",
"Id": "24834",
"Score": "1",
"body": "@Jeff True, it’s potentially very useful. But this should never be the default option because it creates a memory leak: there is no way of unloading the compiled regex from memory until the end of the application domain. As such, only unchanging, frequently used regexes should be compiled. But this is probably the case here anyway."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-02T12:20:16.117",
"Id": "15278",
"ParentId": "15274",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-02T08:03:57.620",
"Id": "15274",
"Score": "5",
"Tags": [
"c#",
"regex"
],
"Title": "Combining regex"
}
|
15274
|
<p>I would like to know what is null test in java? How to rewrite the below code by avoiding null test. I was asked this question in an online test. I'll be grateful for any help offered.</p>
<pre><code>String mystere() throws IOException {
InputStream input = null;
try {
input = new InputStream(new File("foo.txt"));
return new Scanner(input).nextLine();
} finally {
if (input != null)
input.close();
}
}
</code></pre>
|
[] |
[
{
"body": "<p>The <code>null</code> test is the <code>input != null</code> condition here.</p>\n\n<p>In your code if the constructor of the stream throws an exception the reference remains <code>null</code> so there is no way to call <code>close</code> on it, therefore the constructor call could be before the <code>try-catch</code> block. The generic pattern is the following:</p>\n\n<pre><code> final InputStream input = new FileInputStream(new File(\"foo.txt\"));\n try {\n // do something with the stream\n } finally {\n input.close();\n }\n</code></pre>\n\n<p>Please note that I've changed <code>new InputStream(...)</code> to <code>new FileInputStream(...)</code>. <code>InputStream</code> an interface, you cannot instantiate it.</p>\n\n<p>In Java 7 it's a little bit simpler:</p>\n\n<pre><code>try (final InputStream input = new FileInputStream(new File(\"foo.txt\"))) {\n // do something with the stream\n}\n</code></pre>\n\n<p>References: <em>Guideline 1-2: Release resources in all cases</em> in the <a href=\"http://www.oracle.com/technetwork/java/seccodeguide-139067.html\">Secure Coding Guidelines for the Java Programming Language, Version 4.0</a> documentation.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-02T09:37:12.853",
"Id": "24767",
"Score": "1",
"body": "It's so cool in java 7. Thank you so much."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-02T09:28:59.053",
"Id": "15276",
"ParentId": "15275",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "15276",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-02T09:13:20.723",
"Id": "15275",
"Score": "5",
"Tags": [
"java"
],
"Title": "what is Null Test in java? and how to rewrite the code to do the same by avoiding null test"
}
|
15275
|
<p>I am working on a small serialization function which serializes form input to json.</p>
<p>Here is the fiddle:
<a href="http://jsfiddle.net/jdQfj/2/" rel="nofollow">http://jsfiddle.net/jdQfj/2/</a></p>
<p>I have currently no idea how to split up the array declarations let alone a combination of array and object declaration. However the function works good with infinite object nestings and normal values. But I could believe that there is optimization room.</p>
<pre><code>jQuery.fn.serializeObject = function() {
var o = {};
var a = this.serializeArray();
$.each(a, function() {
// check if object
if (this.name.indexOf('.') !== -1) {
var path = this.name.split('.');
var current = o;
for (var i = 0; i < path.length; i++) {
if (i === (path.length - 1)) {
current[path[i]] = this.value;
} else {
if (current[path[i]] === undefined) {
current[path[i]] = {};
}
}
current = current[path[i]];
}
// check if array
} else if (this.name.indexOf('[') !== -1 && this.name.indexOf(']')) {
console.log(this.name + ' is an array');
// has to get implmented
// normal value
} else {
o[this.name] = this.value;
}
});
return o;
};
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-03T04:56:41.617",
"Id": "24795",
"Score": "1",
"body": "I thought it would hard to know how the code works without an example. However when it helps you I can do ;)"
}
] |
[
{
"body": "<p>Here's what I came up with:</p>\n\n<pre><code>var addNestedPropToObj = function (obj, name, value) {\n var path = name.split('.'),\n current = obj,\n len = path.length - 1,\n i = 0;\n for (; i < len; i++) {\n current[path[i]] = current[path[i]] || {};\n current = current[path[i]];\n }\n if ( 0 < path[i].indexOf( \"[]\" ) ) {\n name = path[i].replace('[]', '');\n current[name] = current[name] || [];\n current[name].push(value);\n } else {\n current[path[i]] = value;\n }\n return obj;\n};\njQuery.fn.serializeObject = function () {\n var o = {},\n a = this.serializeArray(),\n i = 0,\n len = a.length;\n for (; i < len; i++) {\n o = addNestedPropToObj(o, a[i].name, a[i].value);\n }\n return o;\n};\n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/jdQfj/3/\" rel=\"nofollow noreferrer\">Demo and test cases</a></p>\n\n<p>Tips:</p>\n\n<ul>\n<li>Always try to separate most of the logic from the plugin into small testable functions.</li>\n<li>Use a regular loop instead of the <code>$.each()</code>.</li>\n<li><p><code>String.prototype.split()</code> returns an array of the entire string if a match isn't found. So the else condition isn't required.</p>\n\n<pre><code>// not needed\nelse {\n o[this.name] = this.value;\n}\n</code></pre></li>\n<li><p>Instead of checking to see if you're at the end of the loop, iterate to <code>path.length - 1</code> then afterwards perform the statement, <code>current[path[i]] = this.value;</code>.</p></li>\n</ul>\n\n<p>As for the array format contained within the name property, for simplicity I suggest that the array notation should be an endpoint where the value is the push to the current property. So for a value to a added to an array, then <code>[]</code> must be at the end of the name.</p>\n\n<p>Here's an example:</p>\n\n<pre><code>var func = function( str ){\n return JSON.stringify( addNestedPropToObj( {}, str, 1));\n};\nfunc(\"a[].b\") === '{\"a[]\":{\"b\":1}}';\nfunc(\"a.b[]\") === '{\"a\":{\"b\":[1]}}';\n</code></pre>\n\n<p>Seen as an array: <code>a[]</code> or <code>a.b[]</code></p>\n\n<p>Seen as a string: <code>a[b]</code>, <code>a[b.c]</code></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-03T08:40:42.653",
"Id": "15293",
"ParentId": "15277",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "15293",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-02T11:08:29.617",
"Id": "15277",
"Score": "2",
"Tags": [
"javascript",
"jquery"
],
"Title": "jQuery serializeObject function"
}
|
15277
|
<p>I am looking for a general review of my project <a href="https://github.com/JamesMcMahon/mockjson.py" rel="noreferrer">here</a>. I have written some Python, but not enough to feel confident in my ability to produce idiomatic code.</p>
<pre><code>#!/usr/bin/env python
"""mockjson.py: Library for mocking JSON objects from a template."""
__author__ = "James McMahon"
__copyright__ = "Copyright 2012, James McMahon"
__license__ = "MIT"
try:
import simplejson as json
except ImportError:
import json
import random
import re
import string
import sys
from datetime import datetime, timedelta
_male_first_name = ("James", "John", "Robert", "Michael", "William", "David",
"Richard", "Charles", "Joseph", "Thomas", "Christopher", "Daniel",
"Paul", "Mark", "Donald", "George", "Kenneth", "Steven", "Edward",
"Brian", "Ronald", "Anthony", "Kevin", "Jason", "Matthew", "Gary",
"Timothy", "Jose", "Larry", "Jeffrey", "Frank", "Scott", "Eric")
_female_first_name = ("Mary", "Patricia", "Linda", "Barbara", "Elizabeth",
"Jennifer", "Maria", "Susan", "Margaret", "Dorothy", "Lisa", "Nancy",
"Karen", "Betty", "Helen", "Sandra", "Donna", "Carol", "Ruth", "Sharon",
"Michelle", "Laura", "Sarah", "Kimberly", "Deborah", "Jessica",
"Shirley", "Cynthia", "Angela", "Melissa", "Brenda", "Amy", "Anna")
_last_name = ("Smith", "Johnson", "Williams", "Brown", "Jones", "Miller",
"Davis", "Garcia", "Rodriguez", "Wilson", "Martinez", "Anderson",
"Taylor", "Thomas", "Hernandez", "Moore", "Martin", "Jackson",
"Thompson", "White", "Lopez", "Lee", "Gonzalez", "Harris", "Clark",
"Lewis", "Robinson", "Walker", "Perez", "Hall", "Young", "Allen")
_lorem = tuple("""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""".split())
def _random_item(items):
return items[random.randrange(len(items))]
def _random_data(key):
key = key.lstrip('@')
if not key in data:
return key
return data[key]()
def _lorem_ipsum():
length = random.randrange(2, len(_lorem) / 2)
result = ''
for i in xrange(length):
result += ' ' + _lorem[random.randrange(len(_lorem))]
return result.strip()
def _random_date():
return datetime.today() - timedelta(days=random.randrange(6571, 27375))
data = {
'NUMBER': lambda: _random_item("0123456789"),
'LETTER_UPPER': lambda: _random_item(string.uppercase),
'LETTER_LOWER': lambda: _random_item(string.lowercase),
'MALE_FIRST_NAME': lambda: _random_item(_male_first_name),
'FEMALE_FIRST_NAME': lambda: _random_item(_female_first_name),
'LAST_NAME': lambda: _random_item(_last_name),
'EMAIL': lambda: (_random_data('@LETTER_LOWER')
+ '.'
+ _random_data('@LAST_NAME').lower()
+ '@'
+ _random_data('@LAST_NAME').lower()
+ '.com'),
'LOREM': lambda: _random_item(_lorem),
'LOREM_IPSUM': _lorem_ipsum,
'DATE_YYYY': lambda: str(_random_date().year),
'DATE_MM': lambda: str(_random_date().month).zfill(2),
'DATE_DD': lambda: str(_random_date().day).zfill(2),
'TIME_HH': lambda: str(_random_date().hour).zfill(2),
'TIME_MM': lambda: str(_random_date().minute).zfill(2),
'TIME_SS': lambda: str(_random_date().second).zfill(2)
}
def generate_json_object(template, name=None):
length = 0
if name:
matches = re.search(r"\w+\|(\d+)-(\d+)", name)
if matches:
groups = matches.groups()
length_min = int(groups[0])
length_max = int(groups[1])
length = random.randint(length_min, length_max)
t_type = type(template)
if t_type is dict:
generated = {}
for key, value in template.iteritems():
stripped_key = re.sub(r"\|(\d+-\d+|\+\d+)", '', key)
generated[stripped_key] = generate_json_object(value, key)
# handle increments
inc_matches = re.search(r"\w+\|\+(\d+)", key)
if inc_matches and type(template[key]) is int:
increment = int(inc_matches.groups()[0])
template[key] += increment
elif t_type is list:
generated = []
for i in xrange(length):
generated.append(generate_json_object(template[0]))
elif t_type is int:
generated = length if matches else template
elif t_type is bool:
# apparently getrandbits(1) is faster...
generated = random.choice([True, False]) if matches else template
# is this always just going to be unicode here?
elif t_type is str or t_type is unicode:
if template:
generated = ''
length = length if length else 1
for i in range(length):
generated += template
matches = re.findall(r"(@[A-Z_0-9\(\),]+)", generated)
if matches:
for key in matches:
rd = _random_data(key)
generated = generated.replace(key, rd, 1)
else:
generated = (''.join(random.choice(string.letters)
for i in xrange(length)))
else:
generated = template
return generated
def generate_json(template, name=None):
return json.dumps(generate_json_object(json_data), sort_keys=False)
if __name__ == '__main__':
arg = sys.argv[1:][0]
with open(arg) as f:
json_data = json.load(f)
print(generate_json(json_data))
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-03T08:09:24.103",
"Id": "24797",
"Score": "0",
"body": "It would be better if you comment(heavily) on your code so that it could be easily understood."
}
] |
[
{
"body": "<h3>1. Introduction</h3>\n\n<p>This review grew to be very long, so I'll say up front that you shouldn't take the length of this to heart: your code is not bad, especially if you are new to Python. There's always a lot of things to say about a piece of code of this length, and idiomatic Python has a bunch of features (sets, generators, comprehensions, iterators) that will be unfamiliar to users of some other languages. So take everything I have to say with a pinch of salt (except for item #1 under \"General comments\", which is really the only big problem here).</p>\n\n<h3>2. General comments</h3>\n\n<ol>\n<li><p>By far the most important problem is your documentation. What is your library supposed to do? How do it use it? It is impossible to review code without understanding its purpose.</p>\n\n<p>As a user I expect to be able to write <code>help(mockjson)</code> to get a description of a module and <code>help(mockjson.generate_json)</code> to get a description of a function, but there's nothing here. Your <a href=\"https://github.com/JamesMcMahon/mockjson.py/blob/master/README.md\" rel=\"noreferrer\">online documentation</a> is also unhelpful.</p>\n\n<p>After some hunting around I eventually found Mennon van Slooten's <a href=\"http://experiments.mennovanslooten.nl/2010/mockjson/\" rel=\"noreferrer\">mockJSON documentation</a>. I'm going to proceed on the basis that your purpose is to reimplement this in Python.</p></li>\n<li><p>There's no test suite. I know it's hard for you to write test cases because of the randomness. You probably want to take a hint from Mennon van Slooten and provide a way for to change the random choices to a deterministic sequence of choices.</p></li>\n<li><p>Your collections of example data (<code>_male_first_name</code> etc.) are stored as tuples, but it would be better to store these as lists. Tuples are <em>fixed-size</em> collections typically used as lightweight representations of records. Lists sets are <em>variable-size</em> collections typically containing similar items.</p></li>\n<li><p>Your example data is very America-centric. Given that the purpose of your module is to produce example data for testing, it will be useful to have a wider variety of names, including names with accented letters, or in different scripts.</p></li>\n<li><p>It is generally results in source code that is easier to read (with fewer quotation characters and commas) if you produce this kind of data using <code>split</code>. For example,</p>\n\n<pre><code>_female_first_names = u\"\"\"\n Mary Patricia Linda Barbara Elizabeth\n Zoé Yến София فاطمة 明子 美玲 ยิ่งลักษณ์\n \"\"\".split()\n</code></pre></li>\n<li><p>The function <code>_random_item</code> is already in the Python library as <a href=\"http://docs.python.org/library/random.html#random.choice\" rel=\"noreferrer\"><code>random.choice</code></a>.</p></li>\n<li><p>The string <code>\"0123456789\"</code> is already in the Python library as <code>string.digits</code>.</p></li>\n<li><p>It's not clear why <code>_random_data</code> needs to strip all initial <code>@</code> signs from its argument before trying to look it up. You only call this function in a context where you could easily strip the <code>@</code>. It also fails to raise an error if the key is missing (so that mistakes like <code>@NUBMER</code> are not caught).</p></li>\n<li><p>Your definitions of <code>data</code> will look nicer (fewer quotation marks) if you use the <code>dict</code> constructor:</p>\n\n<pre><code>data = dict(\n NUMBER = lambda: _random_item(\"0123456789\"),\n LETTER_UPPER = lambda: _random_item(string.uppercase),\n LETTER_LOWER = lambda: _random_item(string.lowercase),\n ...\n</code></pre></li>\n<li><p>Since most of the values in <code>data</code> are of the form <code>lambda: _random_item(...)</code>, why not special-case them to save on boilerplate? You could write something like:</p>\n\n<pre><code>def _random_data(key):\n \"\"\"\n Construct a random data item for `key` and return it.\n Raise KeyError if `key` is unknown.\n \"\"\"\n constructor = data[key]\n if isinstance(constructor, types.FunctionType):\n return constructor()\n else:\n return random.choice(constructor)\n</code></pre>\n\n<p>and then:</p>\n\n<pre><code>data = dict(\n NUMBER = string.digits,\n LETTER_UPPER = string.uppercase,\n LETTER_LOWER = string.lowercase,\n ...\n</code></pre></li>\n<li><p>Building a string by repeatedly extending it with <code>+=</code> is a well-known anti-pattern in Python. This is because extending a string is inefficient in Python: a new string gets allocated and the old string copied across each time. This means that any algorithm that builds a string by repeated extension runs like O(<em>n</em><sup>2</sup>). It is nearly always better to <em>generate</em> the items to be assembled into the string and then <code>join</code> them to produce the result. This technique also avoids fencepost errors like spurious extra spaces at the start or end. So your could write:</p>\n\n<pre><code>def _lorem_ipsum():\n \"\"\"\n Return a random paragraph of placeholder text.\n \"\"\"\n length = random.randrange(2, len(_lorem) / 2)\n return ' '.join(random.choice(_lorem) for _ in xrange(length))\n</code></pre></li>\n<li><p><code>generate_json</code> takes an optional argument <code>name</code> which is always ignored. You can omit this.</p></li>\n</ol>\n\n<h3>3. Comments on <code>generate_json_object</code></h3>\n\n<ol>\n<li><p>The name could be improved: <em>generate</em> has a special meaning in Python (referring to the output of a <em>generator</em>), and the <em>json</em> part is misleading since there's nothing JSON-specific about this function (it operates on Python objects, not on JSON representations). Since <em>instantiate</em> is often used for filling in a template, I think I would use a name like <code>instantiate_object</code>. (And <code>instantiate_json</code> for <code>generate_json</code>.)</p></li>\n<li><p>The variable <code>length</code> is misleadingly named because it's not always a length (it might just be a number). Perhaps <code>n</code> would be better. You also have to go through contortions because you are overloading its meaning: it's <code>None</code> if no number was specified (in which case sometimes it needs to be treated as if it has the value <code>1</code>), or else it's a number. It would be much clearer to have a separate variable (<code>have_n</code> in my code below) that indicates whether a number was supplied.</p></li>\n<li><p>Your regular expression for finding repeat counts in JSON keys is <code>\\w+\\|(\\d+)-(\\d+)</code>. This matches strings like <code>\"a|0-2trailing garbage\"</code>. It's probably a good idea to anchor it to the end of the string (<code>\\w\\|(\\d+)-(\\d+)$</code>). Or maybe, depending on exactly what you want to match, to the beginning of the string as well: <code>re.match(r'\\w+\\|(\\d+)-(\\d+)$', name)</code>. But then you need to decide what to do for non-matching keys. Maybe raise an exception?</p></li>\n<li><p>The structure</p>\n\n<pre><code>matches = re.search(...)\nif matches:\n ...\n</code></pre>\n\n<p>is so common that readers will know what you mean if you abbreviate <code>matches</code> to <code>m</code>.</p></li>\n<li><p><code>matches.group(0)</code> is simpler than <code>matches.groups()[0]</code>.</p></li>\n<li><p>You perform <em>three</em> regular expression matches on the key: first, to find the repeat counts, second, to strip all suffixes, and third, to find the increment. If you refactor the function to take the repeat count as an argument (instead of the name), you can do these three matches all at the same time, like this:</p>\n\n<pre><code>m = re.match(r\"^(\\w+)(?:\\|(?:(\\d+)-(\\d+)|\\+(\\d+)))?$\", '', key)\nif not m:\n raise ValueError(\"Bad key: {0}\".format(key))\nhave_n = False\nn = 1\nif m.group(2):\n have_n = True\n n = random.randint(int(m.group(2)), int(m.group(3)))\nincrement = 0\nif m.group(4):\n increment = int(m.group(4))\n</code></pre>\n\n<p>Now this doesn't quite work as I've written it above because of the way you've structured the function. Having used your regular expression to parsed the number and increment out of the key, you then pass the <em>name</em> when you make your recursive call, which means that the number has to be parsed <em>again</em>. To do this, you need to restructure the function so that instead of passing <code>name</code> to the recursive call, you pass <code>have_n</code>, <code>n</code> and <code>increment</code>. See later on where I give the whole text of the function as revised.</p></li>\n<li><p>It is usually better in Python to test if an object belongs to a type <code>t</code> by writing <code>isinstance(object, t)</code> rather than <code>type(object) is t</code>. The reason is that <code>object</code> may belong to a <em>subtype</em> of <code>t</code> (for example, a <code>defaultdict</code> or <code>OrderedDict</code> instead of a plain <code>dict</code>).</p>\n\n<p>There is a gotcha here, which is that <code>bool</code> is a subtype of <code>int</code>, so you need to order your tests so that Booleans get tested before integers.</p></li>\n<li><p>The structure of <code>generate_json_object</code> involves various branches which assign an object to the variable <code>generated</code>. This is then returned at the end. Why not just return the object directly and avoid the local variable?</p></li>\n<li><p>When you're building a list, you do this by repeatedly calling <code>append</code>. This is not quite as bad as repeatedly calling <code>+=</code> on a string (lists are a bit more flexible), but you can simplify this code by using a <em>list comprehension</em>:</p>\n\n<pre><code>elif isinstance(template, list):\n return [generate_json_object(template[0]) for _ in xrange(length)]\n</code></pre>\n\n<p>Note that when the loop variable is ignored (as here) it's conventional in Python to name it <code>_</code>.</p></li>\n<li><p>When you handle an incremented value, you write <code>template[key] += increment</code> which updates the <em>template</em> permanently. That's all very well if you are going to use the template just once, but what if you want to use the same template many times?</p>\n\n<p>In order to allow re-use of templates, you are going to have to store the current increment for each template key in a separate data structure from the template, so that you can throw away this data structure when your instantiation is complete. The way to do this is to use a dictionary whose keys are locations in the template and whose values are the current increment for that location.</p>\n\n<p>Now, how can we represent a <em>location in a template</em> in such a way that we can use it as a key in a dictionary? Well, a location is a template is always a <em>key</em> in a <em>dictionary</em>, so we'd like to represent it as the pair (<em>dictionary</em>, <em>key</em>). However, this won't work, because <a href=\"http://docs.python.org/reference/datamodel.html#index-33\" rel=\"noreferrer\">only <em>immutable</em> (constant) objects can be used as keys in dictionaries</a> in Python, and the template (being a dictionary) is <em>mutable</em>. But Python provides the function <code>id</code> which returns a unique identifier for each object in memory, and we can use that instead:</p>\n\n<pre><code>increment = 0\ntemplate_key = (id(template), key)\nif template_key in _increments:\n increment = _increments[template_key]\nelif m.group(4):\n increment = int(m.group(4))\n _increments[template_key] = increment\n</code></pre>\n\n<p>Where should this <code>_increments</code> dictionary be stored? We need a new one for each instantiation we do, but it needs to persist throughout the recursive series of calls. We could pass it around as another function parameter, but if you find yourself doing this, that's a sign that you need to use a class. Again, see the final version at the end for how this can be done.</p>\n\n<p>The code I gave above isn't quite right, because although it remembers the increment, it doesn't actually update it each time it is used. Python has a very neat way to make this happen: <em>iterators</em>. Instead of storing <code>increment</code>, we'll construct an iterator that yields the values <code>0</code>, <code>increment</code>, <code>2*increment</code>, <code>3*increment</code>, and so on. The function <a href=\"http://docs.python.org/library/itertools.html#itertools.count\" rel=\"noreferrer\"><code>itertools.count</code></a> does this job. And when there's no increment, we'll construct an iterator that always yields the value <code>0</code> no matter how many times we call it (using <a href=\"http://docs.python.org/library/itertools.html#itertools.repeat\" rel=\"noreferrer\"><code>itertools.repeat</code></a>):</p>\n\n<pre><code>increment = itertools.repeat(0)\nif template_key in self._increments:\n increment = self._increments[template_key]\nelif m.group(4):\n increment = itertools.count(start = 0, step = int(m.group(4)))\n self._increments[template_key] = increment\n</code></pre></li>\n</ol>\n\n<h3>4. Revised instantiation code</h3>\n\n<p>OK, let's put all that together. (There are a couple of bonus improvements in here for you to spot for yourself!)</p>\n\n<pre><code>_constantly_zero = itertools.repeat(0)\n\nclass _Instantiator(object):\n def __init__(self):\n self._increments = dict()\n\n def instantiate(self, template, have_n = False, n = 1,\n increment = _constantly_zero):\n if isinstance(template, dict):\n generated = {}\n for key, value in template.iteritems():\n m = re.match(r\"^(\\w+)(?:\\|(?:(\\d+)-(\\d+)|\\+(\\d+)))?$\", key)\n if not m:\n raise ValueError(\"Bad key: {0}\".format(key))\n have_n = False\n n = 1\n if m.group(2):\n have_n = True\n n = random.randint(int(m.group(2)), int(m.group(3)))\n template_key = (id(template), key)\n increment = _constantly_zero\n if template_key in self._increments:\n increment = self._increments[template_key]\n elif m.group(4):\n increment = itertools.count(start = 0, step = int(m.group(4)))\n self._increments[template_key] = increment\n generated[m.group(1)] = self.instantiate(value, have_n, n, increment)\n return generated\n elif isinstance(template, list):\n return [self.instantiate(template[0]) for _ in xrange(n)]\n elif isinstance(template, bool):\n if have_n:\n return bool(n)\n else:\n return template\n elif isinstance(template, int):\n if have_n:\n return n\n else:\n return template + next(increment)\n elif isinstance(template, str) or isinstance(template, unicode):\n if template:\n pattern = re.compile(r'@([A-Z_0-9]+)')\n repl = lambda m: _random_data(m.group(1))\n return ''.join(pattern.sub(repl, template) for _ in xrange(n))\n else:\n return ''.join(random.choice(string.letters) for _ in xrange(n))\n else:\n return template\n\ndef instantiate_object(template):\n \"\"\"\n Instantiate an object based on `template` and return it.\n \"\"\"\n return _Instantiator().instantiate(template)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-04T02:13:04.763",
"Id": "24827",
"Score": "1",
"body": "I really appreciate you taking the time to review my code and write this up. As time permits I will go through my code and make many of the improvements you suggested. I do have a question about the list vs tuple point (number 3). I has assumed because my data is immutable I should make it a tuple, is this not the case?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-04T09:42:15.130",
"Id": "24836",
"Score": "1",
"body": "You're right that tuples are immutable and lists are mutable. But mutability only matters when you are storing objects in sets or as dictionary keys. When you're not worried about whether your collection can be hashed, the rule of thumb is that fixed-size records of different objects are best represented as tuples, while variable-size collections of similar objects are best represented as lists. But nothing particularly bad will happen if you don't follow this rule of thumb."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-03T08:59:47.880",
"Id": "15294",
"ParentId": "15280",
"Score": "14"
}
}
] |
{
"AcceptedAnswerId": "15294",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-02T13:06:09.280",
"Id": "15280",
"Score": "8",
"Tags": [
"python",
"json"
],
"Title": "JSON templates in Python"
}
|
15280
|
<p>I'm developing a small website which is responsive, and I'm planning on displaying a number of items ( <a href="http://www.chaoscod3r.com" rel="nofollow">Demo</a> ) on the page. As you can see in the link the items are displayed just fine, but what I'm trying to do is calculate the exact number of items that would fit inside the window ( more specific the actual space between the footer and the header ) so none of them will be shown only by half or overflown by the footer.</p>
<p>I got this small function working : </p>
<pre><code>Cluster.prototype.initiate_items_per_page_calculation = function() {
return Math.floor(Math.floor(($(window).width() - ($(window).width() * 4 / 100)) / $('body').find(this.cluster_public_classes.item_wrapper).outerWidth()) * Math.floor(Math.floor($(window).height() - ($('body').find('header').outerHeight() + $('body').find('footer').outerHeight()) - ($(window).height() * 4 / 100)) / $('body').find(this.cluster_public_classes.item_wrapper).outerHeight()));
};
</code></pre>
<p>Just that the calculations are not that exact. For instance I have the item's width of 260px and it's height 160px ( adding a few pixels because there two more layers of background behind the visible layer that are rotated 3deg, so there are about 5 pixels more on each side ) plus the white space between them which is 15px on each side, and there are the footer and the header heights which cut from the space, so taking all of this into consideration my calculations are not that accurate anymore. So I was wondering if I could get a little bit of help with making this work perfectly no matter what the screen size is (:</p>
|
[] |
[
{
"body": "<p>The best and easiest way to do this would be to place the items in a box container with a pre-computed height and width. Then in order to find the max amount of items that can be placed in the container, you just divide the area of the box container by the area of an item.</p>\n\n<p>I used this method with your previous function and got something like this.</p>\n\n<pre><code>Cluster.prototype.initiate_items_per_page_calculation = function () {\n var o = this.get_init_calculation_object(),\n areaOfHeaderAndFooter = ( o.header.w * o.header.h ) + ( o.footer.w * o.footer.h ),\n areaOfExtraPaddingToContainer = 150 * 250 * 2,\n areaOfBoxContainer = (o.screen.w * o.screen.h ) - areaOfHeaderAndFooter - areaOfExtraPaddingToContainer,\n areaOfBox = (o.item.w * o.item.h),\n containerBoxLimit = Math.floor( areaOfBoxContainer / areaOfBox );\n\n return containerBoxLimit;\n};\nCluster.prototype.get_init_calculation_object = function () {\n var $body = $('body'), \n $header = $body.find('header'),\n $footer = $body.find('footer'),\n $item = $body.find(this.cluster_public_classes.item_wrapper);\n\n return {\n footer:{\n h: $footer.outerHeight(true),\n w: $footer.outerWidth(true)\n },\n header:{\n h: $header.outerHeight(true),\n w: $header.outerWidth(true)\n },\n item:{\n h: $item.outerHeight(true),\n w: $item.outerWidth(true)\n },\n screen:{\n h: $body.outerHeight(true),\n w: $body.outerWidth(true)\n }\n };\n};\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-03T12:22:28.123",
"Id": "24798",
"Score": "0",
"body": "One question though, why use `.outerHeight(true)` ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-03T17:52:14.790",
"Id": "24809",
"Score": "0",
"body": "Shouldn't that be `var o = this.get_init_calculation_object()`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-03T19:48:10.027",
"Id": "24813",
"Score": "0",
"body": "@JosephSilber You're right. Fixed."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-03T20:03:57.007",
"Id": "24814",
"Score": "1",
"body": "@Roland http://api.jquery.com/outerHeight/ Passing true to outerHeight() will include the margin in the returned height. This might be important since the margin contributes to the total area that an item takes up."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-03T10:17:10.297",
"Id": "15297",
"ParentId": "15281",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "15297",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-02T16:59:49.927",
"Id": "15281",
"Score": "1",
"Tags": [
"javascript",
"jquery"
],
"Title": "Refine a math calculation function"
}
|
15281
|
<p>I know this is extremely trivial, but would you call the extension method below <code>Remove</code> or <code>RemoveMany</code>? Please provide justification.</p>
<pre><code>public static void Remove<TEntity>(this DbSet<TEntity> set, IEnumerable<TEntity> entities)
where TEntity : class
{
foreach (var entity in entities)
set.Remove(entity);
}
</code></pre>
<p>-- or --</p>
<pre><code>public static void RemoveMany<TEntity>(...) { ... }
</code></pre>
|
[] |
[
{
"body": "<p>I'd consider calling it <code>RemoveAll</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-02T19:07:54.043",
"Id": "24779",
"Score": "1",
"body": "Interesting idea, but one possible problem with `RemoveAll()` is that it might imply that you are clearing out all the entities in the set. What this extension method is supposed to do is clear out only the entities that are passed into the `entities` parameter."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-02T23:32:39.843",
"Id": "24789",
"Score": "0",
"body": "@DanM I think this can be remedied by introducing an overload without the `entities` parameter, which would fit in well with the LINQ `Any()` and `Any(x => x.Age > 18)` overload scheme."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-02T18:47:25.207",
"Id": "15283",
"ParentId": "15282",
"Score": "4"
}
},
{
"body": "<p>Your method is removing a collection of entities that exist in some set.</p>\n\n<p>When I see <code>Remove</code>, I'd say it removes a single item from something. Now if that collection actually existed in the set, then it would be perfect, but alas it's a collection of items to remove.</p>\n\n<p>One thing to consider, assuming you're making an extension method for the EF5 <a href=\"http://msdn.microsoft.com/en-us/library/gg696460%28v=vs.103%29\"><code>DbSet</code></a>, it already has a <a href=\"http://msdn.microsoft.com/en-us/library/gg679171%28v=vs.103%29\"><code>Remove</code></a> method that removes a single item, I think an overload to remove more items doesn't sound like a bad idea to me.</p>\n\n<p>On the other hand, LINQ to XML defines a <a href=\"http://msdn.microsoft.com/en-us/library/bb357554\"><code>Remove()</code></a> method on enumerables of <code>XNode</code>. But that's an extension on the collection of entities, not the parent set. I'm a little on the fence on this one.</p>\n\n<p><code>RemoveMany</code>, while better as it indicates we're removing many items, doesn't fit well with me. It mimics <code>SelectMany</code> by name but I'd associate the \"Many\" part with a projection, certainly not with a remove operation. I'd avoid that one.</p>\n\n<hr>\n\n<p>I might consider <code>ExceptEntities</code> to be similar to the LINQ method <a href=\"http://msdn.microsoft.com/en-us/library/bb300779.aspx\"><code>Except</code></a>. <code>Except</code> returns the set difference of two collections where the result contains unique values. Since this operation isn't quite the same, we'll still need to make this distinguishable hence the added \"Entities\". Since you are dealing with a set (?), this sounds perfect to me. But after thinking about this more, I'm not quite sure this is the better option since this modifies the collection.</p>\n\n<p>I think <code>RemoveEntities</code> might be a better fit. \"Remove\" makes it sound as though we're modifying something. <code>RemoveAll</code> doesn't cut it for me as it is named the same as <code>List.RemoveAll</code> which removes all that matches a predicate. There's also a <code>List.RemoveRange</code> which removes a range of consecutive values in the collection, not quite the same.</p>\n\n<p>So I'd go with <code>RemoveEntities</code> but an overload of the <code>Remove</code> name might be fine, just beware of the similarities of the names in other objects.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-02T19:53:06.780",
"Id": "24784",
"Score": "0",
"body": "+1. I think you managed to get down most of what I was debating in my head, plus a lot more :) Anyway, yes, I'm using the EF DbSet, and the extension method actually *uses* the built-in `Remove()` method inside the loop. As for `RemoveEntities()`, I see why you suggest this, but to me, it would only make sense if the native method were called `RemoveEntity()`. So, at the moment, I'm leaning toward just `Remove()` for the extension method."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-02T19:23:06.420",
"Id": "15284",
"ParentId": "15282",
"Score": "6"
}
},
{
"body": "<p>How about <code>RemoveExisting</code> considering you are removing existing entities from the object.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-02T22:57:12.337",
"Id": "24787",
"Score": "0",
"body": "I'm removing only a *subset* of the existing entities, so I think this would be misleading."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-02T23:32:06.780",
"Id": "24788",
"Score": "0",
"body": "Fair enough. I thought you were removing all entities that were supplied in the parameter where they existed in the DbSet."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-02T23:36:03.100",
"Id": "24790",
"Score": "0",
"body": "Wait, I actually *am* removing all entities supplied in the parameter, but I'm not removing all \"existing\" entities in the set. Wouldn't the method name would normally refer to the object being acted on (the DbSet) and not the parameter (the collection of entities)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-03T00:25:47.987",
"Id": "24791",
"Score": "0",
"body": "yep, good point."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-03T18:42:20.567",
"Id": "24811",
"Score": "2",
"body": "If you're removing a subset, why not `RemoveSubset`?"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-02T21:06:10.013",
"Id": "15288",
"ParentId": "15282",
"Score": "0"
}
},
{
"body": "<p>Just one correction. You cant modify the enumeration inside the for each. Try</p>\n\n<pre><code> public static void RemoveMany<TEntity>(this DbSet<TEntity> thisDbSet, IEnumerable<TEntity> entities) where TEntity : class\n {\n for (int i = entities.Count() - 1; i >= 0; i--)\n {\n if (entities.ElementAt(i) != null)\n thisDbSet.Remove(entities.ElementAt(i));\n }\n\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T05:47:55.010",
"Id": "26457",
"ParentId": "15282",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "15284",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-02T18:16:47.833",
"Id": "15282",
"Score": "5",
"Tags": [
"c#"
],
"Title": "Should I call this extension method Remove or RemoveMany?"
}
|
15282
|
<p>I'd like a review of this implementation of Async in ASP.NET 2.0 web form page below. Let me know if I am missing something.</p>
<p><strong>AsyncPagesASPNET20.aspx</strong></p>
<pre><code><%@ Page Language="C#" Async="true" AutoEventWireup="true" CodeFile="AsyncPagesASPNET20.aspx.cs" Inherits="AsyncPagesASPNET20" %>
</code></pre>
<p><strong>AsyncPagesASPNET20.aspx.cs</strong></p>
<pre><code>public partial class AsyncPagesASPNET20 : System.Web.UI.Page
{
private string queryCustomerSelect = "SELECT FirstName, LastName FROM SalesLT.Customer";
private DataAccess dataAccess = new DataAccess(WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.PreRenderComplete += AsyncPage_PreRenderComplete;
AddOnPreRenderCompleteAsync(new BeginEventHandler(BeginAsyncOperation), new EndEventHandler(EndAsyncOperation));
}
}
private void EndAsyncOperation(IAsyncResult ar)
{
Trace.Write("EndAsyncOperation...");
this.dataAccess.EndAsyncSelect(ar);
}
private IAsyncResult BeginAsyncOperation(object sender, EventArgs e, AsyncCallback cb, object extraData)
{
Trace.Write("BeginAsyncOperation...");
return dataAccess.BeginAsyncSelect(sender, e, cb, extraData, this.queryCustomerSelect);
}
void AsyncPage_PreRenderComplete(object sender, EventArgs e)
{
this.GridView1.DataSource = this.dataAccess.reader;
this.GridView1.DataBind();
}
public override void Dispose()
{
this.dataAccess.Dispose();
}
}
</code></pre>
<p><strong>DataAccess.cs</strong></p>
<pre><code>public class DataAccess : IDisposable
{
string connectionString = string.Empty;
private SqlConnection connection;
private SqlCommand command;
public SqlDataReader reader;
public DataAccess(string connectionString)
{
this.connectionString = connectionString;
this.connection = new SqlConnection(this.connectionString);
this.command = new SqlCommand();
}
public IAsyncResult BeginAsyncSelect(object sender, EventArgs e, AsyncCallback cb, object extraData, string query)
{
this.command.CommandText = query;
this.command.CommandType = CommandType.Text;
this.command.Connection = this.connection;
this.connection.Open();
return this.command.BeginExecuteReader(cb, extraData);
}
public void EndAsyncSelect(IAsyncResult ar)
{
this.reader = this.command.EndExecuteReader(ar);
}
public SqlDataReader SelectSync(string query)
{
this.command.CommandText = query;
this.command.Connection = connection;
this.connection.Open();
this.command.Connection = connection;
return this.command.ExecuteReader();
}
#region IDisposable Members
public void Dispose()
{
if (this.connection != null)
{
this.connection.Close();
}
}
#endregion
}
</code></pre>
|
[] |
[
{
"body": "<p>Overall a very cleanly written class. It is easy to follow and understand.</p>\n\n<p>A couple of suggestions though.</p>\n\n<p>Make the reader class variable a Property with a private setter. This will eliminate the ability to reassign it from outside of the class. I would also rename it Reader to fit with C# coding standards.</p>\n\n<p>Most C# coding standards I have read suggest prefixing private class variables with a _. This will allow you to remove the this. statement whenever you need to access one of the class variables. I think doing that will make you code much easier to read.</p>\n\n<p>I'm not sure what the SelectSync method is used for. I see it as a way to do a non-async query into the database. If that is the case, I would move it to a different class as it interferes with the async nature of the one you have written. Maybe rename this class to DataAccessAsync, and have a second one DataAccess? Its hard to say without an example of a call to that method.</p>\n\n<p>I can't see much more at this point.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-03T02:31:28.453",
"Id": "15290",
"ParentId": "15287",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "15290",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-02T21:05:18.810",
"Id": "15287",
"Score": "3",
"Tags": [
"c#",
"asp.net",
"asynchronous"
],
"Title": "AsyncPages in ASP.NET 2.0"
}
|
15287
|
<p>I'm writing an API and want to be able to pass in the attributes of a model without prefixing them with the name of the model.</p>
<p>I wrote this little extension to <code>ActiveRecord</code> in order to make it happen:</p>
<pre><code>module ActiveRecord
class Base
def self.filter_attributes(hash)
hash.stringify_keys.slice(*self.accessible_attributes.to_a)
end
end
end
</code></pre>
<p>And I use it like this:</p>
<pre><code>class IdeaController < ActiveRecord::Base
def create
@idea = Idea.create(Idea.filter_parameters(params))
respond_with @idea
end
end
</code></pre>
<p>I have two questions:</p>
<ol>
<li><p>What do you think about the name of the method? <code>filter_parameters()</code> seemed to make sense, but it's a little generic.</p></li>
<li><p>Are there uses of this that I'm not thinking of and that would cause problems, such as passing in nested attributes?</p></li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-08T21:27:06.753",
"Id": "26542",
"Score": "1",
"body": "As Fivell says, it's pretty pointless. You're doing the same thing that the mass assignment protection is doing for you already. But if you want parameter filtering, instead of mass assignment filtering, you should look into using the [`strong_parameters`](https://github.com/rails/strong_parameters) gem, since it exists to do specifically that (and it may become a part of Rails 4). Oh, and by the way, your system doesn't allow role-based filtering - something the built-in mass assignment system does out of the box."
}
] |
[
{
"body": "<p>Honsetly, I don't see any sense in your extension.\nCan you tell me what is the difference between </p>\n\n<pre><code>@idea = Idea.create(Idea.filter_parameters(params))\n</code></pre>\n\n<p>and </p>\n\n<pre><code>@idea = Idea.create(params)\n</code></pre>\n\n<p>mass assignment sanitizing make this code safety.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-07T11:24:49.217",
"Id": "16297",
"ParentId": "15289",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-02T23:00:02.837",
"Id": "15289",
"Score": "3",
"Tags": [
"ruby",
"ruby-on-rails",
"active-record"
],
"Title": "Cleaning parameters before passing them to a model"
}
|
15289
|
<p>I want an experienced Haskeller to critique my code and offer changes/suggestions (so I can learn the idioms of the language and culture around Haskell).</p>
<p>I've been using a <a href="http://en.wikipedia.org/wiki/Tabula_recta" rel="nofollow">Tabula Recta</a> for my passwords and used a Python script someone wrote to generate the table and do table traversal.</p>
<p>I've been wanting to learn Haskell and decided to take on building the same program but in Haskell.</p>
<p>I'm new to Haskell but not functional programming (I have Scheme and Erlang under my belt - Erlang I use in production on a daily basis). I feel like I kept compositional style but I doubt I adhered to idiomatic Haskell.</p>
<pre><code>{-# LANGUAGE BangPatterns #-}
{- |
Module : tabula.hs
Description : Generates a tabula recta
Copyright : (c) Parnell Springmeyer
License : BSD3
Maintainer : ixmatus@gmail.com
Stability : experimental
Generates and manipulates a tabula recta.
-}
module Main where
import Control.Monad.CryptoRandom
import Crypto.Random
import Data.String.Utils
import Data.List.Split
main :: IO()
main = do
values <- tabulay ['A'..'Z']
putStrLn $ " " ++ join " " (chunksOf 1 ['A'..'Z'])
putStrLn $ " + " ++ (take 52 $ cycle "- ")
putStrLn $ join "\n" (reverse values)
tabulay :: [Char] -> IO [[Char]]
tabulay cmap = tabulay' cmap []
where tabulay' [] acc = do return acc
tabulay' (x:xs) acc = do
chars <- tabulax 26
let formatted = [x, '|'] ++ chars
spaced = join " " (chunksOf 1 formatted)
tabulay' xs $! (spaced:acc)
tabulax :: Int -> IO [Char]
tabulax cint = tabulax' cint []
where tabulax' 0 acc = do return acc
tabulax' iint acc = do
val <- randomChoice characterMap
tabulax' (iint-1) $! (val:acc)
characterMap :: [Char]
characterMap =
let
cmap = ['a'..'z'] ++ ['A'..'Z'] ++ ['0'..'9']
symb = [',', '.', '/', '?', '~', '`', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '-', '_', '+', '=', '{', '[', ']', '}', '\\', '|', ':', ';', '"', '\'']
in cmap ++ symb
randVal :: Int -> IO Int
randVal len = do
g <- newGenIO :: IO SystemRandom
let Right (int, _) = crandomR (0, len-1) g :: Either GenError (Int, SystemRandom)
-- This MUST be strict - otherwise this function will keep too many file handles open
return $! int
randomChoice :: [Char] -> IO Char
randomChoice ls = do
randomIndex <- randVal (length ls)
let val = ls !! randomIndex
return val
</code></pre>
|
[] |
[
{
"body": "<p>Too much IO — most of this code could be pure. Seed the pure random generator with crypto source, you don't need to read from it every time, if you really want crypto source for this. <code>tabulay'</code> and <code>tabulax'</code> look suspiciously like <code>map</code>. <code>symb</code> in <code>characterMap</code> could be written with string notation.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-03T16:44:33.567",
"Id": "24806",
"Score": "0",
"body": "That was my suspicion (re: IO) but I noticed every time I tried to pass the integer from randVal I would get type errors with regards to \"expected type Int, got IO Int instead\"...\n\nMost of the information on the internet I read said I could pass IO Int to functions expecting Int as long as I was inside of a do block.\n\nCould you provide some examples of how I might do it the way you are talking about?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-03T17:33:50.040",
"Id": "24807",
"Score": "0",
"body": "@lxmatus: The type error is because you can't escape from IO (well, without using unsafe functions). What I'm proposing is removing the need of keeping the RNG in IO: RNG by nature is pure, the only thing you're using IO for is reading from urandom or whatnot. Take a look at System.Random instead of using Crypto.Random. You can initialise the generator from `main`, using external seed (like urandom or just time, really) and then pass it along to pure functions. I'll write you an example in a bit."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-03T17:47:34.773",
"Id": "24808",
"Score": "0",
"body": "The only problem with System.Random is that it isn't Cryptographically secure random number generation... That's what I want to achieve with the tabula program."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-03T17:52:45.390",
"Id": "24810",
"Score": "1",
"body": "@lxmatus: What do you need SPRNG for? Oh, passwords. Anyway, you can seed from secure source and then use pure generator and it'll have pretty much the same effect."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-03T19:27:32.990",
"Id": "24812",
"Score": "0",
"body": "Hmmm, everything I've played around with so far has produced nothing but type errors :-/ if you have any free time I would love (even just small) an example to help me a long."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-03T10:43:18.337",
"Id": "15298",
"ParentId": "15291",
"Score": "3"
}
},
{
"body": "<p>Yet another problem is the usage of lists. <code>!!</code> is O(N) operation. Use <code>Data.Array</code> instead.</p>\n\n<p>As for randoms, you should call <code>newGenIO</code> only once and use the cryptographically secure generator it returned after that instead of creation of new generators each time you need a random character.</p>\n\n<p>Your randVal function should look something like this:</p>\n\n<pre><code>randVal :: Int -> SystemRandom -> (Int, SystemRandom)\nrandVal len g = fromRight $ crandomR (0, len-1) g\n</code></pre>\n\n<p>It accepts old generator state and returns the new state to use in subsequent generations. To simplify passing the generator state around you can use a state monad. But there is already such monad - the <code>CRand</code> monad and corresponding <code>CRandT</code> monad transformer to combine random number generation with other monadic computations.</p>\n\n<p>The example from the documentation for <code>CRand</code> fails to typecheck because of monomorphism restriction - <code>getRandPair</code> looks like a value but it isn't, so the compiler detects a potential problem. You can disable it for now by adding <code>{-# LANGUAGE NoMonomorphismRestriction #-}</code> before <code>module Main where</code> line.</p>\n\n<p>Also, it is not clear how the <code>SystemRandom</code> generator works. It is secure, but I think it's not adviced to drain system entropy source. I'd rather use it just to seed <code>HashDRBG</code> from <code>Crypto.Random.DRBG</code>, which is SHA512-based RNG.</p>\n\n<p>Here is a hint:</p>\n\n<pre><code>type Gen a = CRand HashDRBG GenError a\n\nrandValM :: Int -> Gen Int\nrandValM len = getCRandomR (0, len-1)\n\nrandomChoice :: [a] -> Gen a\nrandomChoice ls = do\n randomIndex <- randValM (length ls)\n return $ ls !! randomIndex\n</code></pre>\n\n<p>Your <code>tabulax</code> function will remain the same, but will operate in a different monad, so it's type will change to <code>randomChoice :: [a] -> Gen a</code>. Note also that I used <code>getCRandomR</code> from <code>Control.Monad.Crypto.Random</code> to make use of the monadic helper to implicitly pass the cryptogenerator around and perform error checking.</p>\n\n<p>Your main will change too:</p>\n\n<pre><code>printGenerated values = do\n putStrLn $ \" \" ++ join \" \" (chunksOf 1 ['A'..'Z'])\n putStrLn $ \" + \" ++ (take 52 $ cycle \"- \")\n putStrLn $ join \"\\n\" (reverse values)\n\nfromRight (Right a) = a\n\ngenerate = evalCRand $ do\n a <- tabulay ['A'..'Z']\n return a\n\nmain = do\n g <- newGenIO :: IO HashDRBG\n printGenerated $ fromRight $ generate g\n</code></pre>\n\n<p>The idea is that we extracted <code>generate</code> - a pure function which accepts a generator and returns generated data. <code>evalCRand</code> is used to extract the inner <code>a</code> value from monadic <code>Gen a</code> value. It accepts two arguments: a monadic computation in <code>Gen</code> monad and initial state of random generator. There is also <code>runCRand</code> function which returns the final state of the generator in addition to the value, but we don't need the final state here.</p>\n\n<p>I abused the do-notation here to help you understand code better. I would write <code>generate</code> and <code>main</code> shorter:</p>\n\n<pre><code>generate = evalCRand $ tabulay ['A'..'Z']\n\nmain = newGenIO >>= printGenerated . fromRight . generate\n</code></pre>\n\n<p>Your <code>tabulatex'</code> function is already there in the standard library. It is <code>Control.Monad.replicateM</code>:</p>\n\n<pre><code>import Control.Monad hiding (join)\n\ntabulax :: Int -> Gen [Char]\ntabulax cint = replicateM cint $ randomChoice characterMap\n</code></pre>\n\n<p><code>tabulatey'</code> is also there in <code>Control.Monad</code>, it's <code>mapM</code>:</p>\n\n<pre><code>tabulay :: [Char] -> Gen [[Char]]\ntabulay = mapM $ \\x -> do \n chars <- tabulax 26\n let formatted = [x, '|'] ++ chars\n spaced = join \" \" (chunksOf 1 formatted)\n return spaced\n</code></pre>\n\n<p>Next step is to use immutable arrays:</p>\n\n<pre><code>import Data.Array.IArray\n\ntabulax :: Int -> Gen [Char]\ntabulax cint = replicateM cint $ randomChoiceA arrMap\n\narrMap :: Array Int Char\narrMap = listArray (0, (length characterMap) - 1) characterMap\n\nrandomChoiceA ls = do\n randomIndex <- randValM $ 1 + snd (bounds ls)\n return $ ls ! randomIndex\n</code></pre>\n\n<p>Now <code>randValM</code> seems to be perverted: we convert bounds from tuple to size and back. Eliminating the extra conversion we get rid of <code>randValM</code> completely, as getCRandomR and <code>bounds</code> perfectly fit each other:</p>\n\n<pre><code>randomChoiceA ls = do\n randomIndex <- getCRandomR $ bounds ls\n return $ ls ! randomIndex\n</code></pre>\n\n<p>Now we can shorten it by desugaring do-notation and using function composition and infix operator sections:</p>\n\n<pre><code>randomChoiceA ls = getCRandomR (bounds ls) >>= return . (ls !)\n</code></pre>\n\n<p>And even more using <code><$></code> from <code>Control.Applicative</code> (which is the same as <code>fmap</code>):</p>\n\n<pre><code>randomChoiceA ls = (ls !) <$> getCRandomR (bounds ls)\n</code></pre>\n\n<p>Finally, we can extract <code>separate = join \" \" . chunksOf 1</code> as it is used 2 times and shorten <code>tabulay</code> just for fun:</p>\n\n<pre><code>tabulay :: [Char] -> Gen [[Char]]\ntabulay = mapM $ \\x -> separate <$> ([x, '|'] ++) <$> tabulax 26\n</code></pre>\n\n<p>and get rid of ugly <code>-1</code> in array bounds:</p>\n\n<pre><code>arrMap :: Array Int Char\narrMap = listArray (1, length characterMap) characterMap\n</code></pre>\n\n<p>So the final source is:</p>\n\n<pre><code>{-# LANGUAGE NoMonomorphismRestriction #-}\nmodule Main where\n\nimport Control.Monad.CryptoRandom\nimport Crypto.Random.DRBG\nimport Data.String.Utils\nimport Data.List.Split\nimport Control.Monad hiding (join)\nimport Control.Applicative\nimport Data.Array.IArray\n\nprintGenerated values = do\n putStrLn $ \" \" ++ separate ['A'..'Z']\n putStrLn $ \" + \" ++ take 52 (cycle \"- \")\n putStrLn $ join \"\\n\" (reverse values)\n\nfromRight (Right a) = a\n\ngenerate = evalCRand $ tabulay ['A'..'Z']\n\nmain = newGenIO >>= printGenerated . fromRight . generate\n\nseparate = join \" \" . chunksOf 1\n\ntabulay :: [Char] -> Gen [[Char]]\ntabulay = mapM $ \\x -> separate <$> ([x, '|'] ++) <$> tabulax 26\n\ntabulax :: Int -> Gen [Char]\ntabulax cint = replicateM cint $ randomChoiceA arrMap\n\narrMap :: Array Int Char\narrMap = listArray (1, length characterMap) characterMap\n\nrandomChoiceA ls = (ls !) <$> getCRandomR (bounds ls)\n\ncharacterMap :: [Char]\ncharacterMap =\n let \n cmap = ['a'..'z'] ++ ['A'..'Z'] ++ ['0'..'9']\n symb = \",./?~`!@#$%^&*()-_+={[]}\\\\|:;\\\"'\"\n in cmap ++ symb\n\ntype Gen a = CRand HashDRBG GenError a\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-04T01:08:19.640",
"Id": "24823",
"Score": "0",
"body": "Reading this some more - thank you for putting so much time into it, very helpful. A lot for me to learn obviously as your use of >>= is new to me. I'll have to learn more about monads I guess (yes, I'm that new to the language).\n\nThis will be a good reference for me, thank you again."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-04T03:34:13.117",
"Id": "24828",
"Score": "0",
"body": "I rewrote this and it is MUCH faster than what I had wrote - I assume that's because with your code the newGenIO generator is being called only *once* rather than 676 times!! See I thought the generator had to be called multiple times in order to get a new random value each time - which when I originally wrote the program had \"too man files open\" errors - so this makes more sense now."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-04T03:35:19.573",
"Id": "24829",
"Score": "0",
"body": "Also I attempted to use replicateM before but I had issues with the IO Char type being expected - same thing with mapM (hence why I custom wrote the accumulators)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-04T04:46:08.250",
"Id": "24830",
"Score": "0",
"body": "Question, is there a benefit to using function composition other than succinctness? When is it considered appropriate to use and not? This: join \"\\n\" (reverse values) could just as easily be written as: (join \"\\n\" . reverse) values EDIT I've answered my own question with this URL: http://www.haskell.org/haskellwiki/Pointfree"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-04T11:59:54.283",
"Id": "24837",
"Score": "1",
"body": "See also http://stackoverflow.com/a/12229728/805266 . There is a separate discipline of functional-level programming, which is different from pointfree programming in Haskell. And regarding composition - one subtle advantage is that `(.)` is associative (that is, `(f . g) . h == f . (g . h)`) while `$` is not. For the same reason `>=>` is a 'better' way to compose monadic computations than `>>=`. This makes refactoring easier, as you can always extract a part of long composition chain into a separate function."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-03T19:37:17.453",
"Id": "15305",
"ParentId": "15291",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "15305",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-03T05:29:45.143",
"Id": "15291",
"Score": "8",
"Tags": [
"beginner",
"haskell",
"cryptography"
],
"Title": "Generating a tabula recta"
}
|
15291
|
<p>I have a Scala (Play!) application that must get and parse some data in JSON from an external service. I want to be able to gently handle failure in the response format, but it is becoming messy. What I am doing right now is, for instance,</p>
<pre><code>def columnsFor(json: JsValue): Option[Map[String, String]] =
try {
val cols = (json \ "responseBody" \ "columns") match {
case JsArray(xs) => xs map { col =>
((col \ "leafid").as[String], (col \ "name").as[String])
}
case _ => throw new Exception("Response unparsable")
}
Some(cols.toMap)
}
catch {
case e: Exception => None
}
</code></pre>
<p>That is, I go parsing optimistically and throw an exception whenever I find something that does not match my expected format (the methods <code>as[String]</code> also raise exceptions when they do not find strings). Then I recover from the exception and give back a <code>None</code>.</p>
<p>This approach is working and allows me to go from a potentially broken textual response to some type-safe data.</p>
<p>The problem is that having all these <code>try..catch</code> blocks looks ugly and messy. In theory it would be nicer to use optional types during all parsing steps. But then all my data structures become messy, as at each level you must have <code>Option</code>s. When the data is deeply nested, I do not know how to handle failure at all levels. Moreover, I do not want to return something like an <code>Option[Map[Option[String], Option[String]]</code>, but just an <code>Option[Map[String, String]]</code>.</p>
<p>Is there some better/more idiomatic way to handle failures during parsing?</p>
<p><strong>EDIT</strong></p>
<p>I try to make the question more clear. Say I am expecting a response like</p>
<pre><code>{
"foo": [1, 2, 3],
"bar": [2, 5]
}
</code></pre>
<p>I want to be able to parse it; taking failure into account I want to get something of type <code>Option[Map[String, List[Int]]]</code>. Now the problem is that parsing errors can appear at any level. Maybe I get a map with string keys, but its values are not lists. Or maybe the values are lists, but the content of the lists are strings instead of ints. And so on.</p>
<p>Whenever I want to parse a value, say as a string, I can choose between <code>x.as[String]</code> and <code>x.asOpt[String]</code>. The former will throw an exception when dealing with wrong input, while the latter returns a <code>Option[String]</code>. Similarly, when dealing with an array, I can do pattern matching like</p>
<pre><code>x match {
case JsArray(xs) => // continue parsing
case _ => // deal with failure
}
</code></pre>
<p>I can deal with failure returning <code>None</code> or with an exception.</p>
<p>If I choose to use exceptions all along, then I can just wrap everything inside a <code>try..catch</code> and be sure to have handled all failures. Otherwise, my problem is that at any level, I have to put an option. So I have to</p>
<ol>
<li>get something with an awful type like <code>Option[Map[Option[String], Option[List[Option[Int]]]]]</code></li>
<li>find some way to flatten this all the way down to turn into the more manageable <code>Option[Map[String, List[Int]]]</code></li>
</ol>
<p>Of course, thing become even worse as soon as the JSON gets more nested.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T08:26:54.313",
"Id": "84624",
"Score": "0",
"body": "and become more worse if you need async call to the database with `Future()` =)"
}
] |
[
{
"body": "<p>Having monads in your data structures is not messy, they allow you always to flatten their content during nested calculation steps. A simple definition of them can be:</p>\n\n<pre><code>trait Monad[A] {\n def map[B](f: A => B): Monad[B]\n def flatMap[B](f: A => Monad[B]): Monad[B]\n}\n</code></pre>\n\n<p>Because <code>Option</code> is a monad you do not have to work with nested types:</p>\n\n<pre><code>scala> def inc(i: Int) = Option(i+1)\ninc: (i: Int)Option[Int]\n\nscala> val opt = inc(0)\nopt: Option[Int] = Some(1)\n\nscala> val nested = opt map inc\nnested: Option[Option[Int]] = Some(Some(2))\n\nscala> val flattened = opt flatMap inc\nflattened: Option[Int] = Some(2)\n</code></pre>\n\n<p>Thus, there should never be a reason to nest monads deeply. Scala also has the for-comprehension which automatically decomposes monads:</p>\n\n<pre><code>scala> :paste\n// Entering paste mode (ctrl-D to finish)\n\nval none = for {\n o1 <- inc(0)\n o2 <- inc(o1)\n o3 <- inc(o2)\n} yield o3\n\nval some = for {\n o1 <- inc(0)\n o2 <- inc(o1)\n o3 <- inc(o2-1)\n} yield o3\n\n// Exiting paste mode, now interpreting.\n\nnone: Option[Int] = None\nsome: Option[Int] = Some(2)\n</code></pre>\n\n<p>In order to work with exceptions <code>scala.util.Try</code> is introduced in 2.10:</p>\n\n<pre><code>scala> import scala.util.{Try, Success, Failure}\nimport scala.util.{Try, Success, Failure}\n\nscala> def err: Int = throw new RuntimeException\nerr: Int\n\nscala> val fail = Try{err} map (_+1)\nfail: scala.util.Try[Int] = Failure(java.lang.RuntimeException)\n\nscala> val succ = Try{0} map (_+1)\nsucc: scala.util.Try[Int] = Success(1)\n</code></pre>\n\n<p>Nevertheless, <code>Try</code> should only used when you have to work with exceptions. When there is no special reason, exceptions should be avoided - they are not here to control the control flow but to tell us that an error occurred which normally can not be handled. They are some runtime thing - and why to use runtime things in a statically typed language? When you use monads the compiler always enforces you to write correct code:</p>\n\n<pre><code>scala> def countLen(xs: List[String]) = Option(xs) collect { case List(str) => str } map (_.length)\ncountLen: (xs: List[String])Option[Int]\n\nscala> countLen(List(\"hello\"))\nres8: Option[Int] = Some(5)\n\nscala> countLen(Nil)\nres9: Option[Int] = None\n\nscala> countLen(null) // please, never use null in Scala\nres13: Option[Int] = None\n</code></pre>\n\n<p>With <code>collect</code> you ensure that you don't throw an exception during matching the contents. After that with <code>map</code> one can operate on the String and doesn't care anymore if an empty or a full list is passed to <code>countLen</code>.</p>\n\n<p>Now, look at the documentation of <a href=\"http://www.scala-lang.org/api/current/index.html#scala.Option\">Option</a>, there are more useful methods which allow safe error handling. The only thing to keep in mind is not to use method <code>get</code> or a pattern match on the monad during calculation:</p>\n\n<pre><code>scala> Some(3).get\nres10: Int = 3\n\nscala> None.get // this throws an exception\njava.util.NoSuchElementException: None.get\n\n// this looks ugly and does not safe you from anything because it is equal\n// to a null check\nanyOption match {\n case Some(e) => // no error\n case None => // error\n}\n</code></pre>\n\n<p>Now you may ask how to get the contents of a monad? That is a good question and the answer is: you won't. When you use a monad you say something like: Hey, I'm not interested if my code threw an error or if all worked fine. I want that my code works up to end and then I will look what's happened. Pattern matching on the content of a monad (means: accessing their content explicitly) is the last thing which should be done and only if there is no other way any more to go further with control flow.</p>\n\n<p>There a lot of monads available in Scala and you have the possibility to easily create your own. <code>Option</code> allows only to get a notification if something happened wrong. If you wanna have the exact error message you can use <code>Try</code> (for exceptions) or <code>Either</code> (for all other things). Because <code>Either</code> is not really a monad (it has a Left- and a RightProjection which are the monads) it is unhandy to use. Thus, if you want to effectively work with error messages or even stack them you should take a look at <a href=\"https://github.com/scalaz/scalaz/blob/master/core/src/main/scala/scalaz/Validation.scala\">scalaz.Validation</a>.</p>\n\n<p><strong>EDIT</strong></p>\n\n<p>To address your edit, it seems that you never know the type you can get. This will complicate things a lot since you have to check the type of each element explicitly. I don't think it is possible to do this in a clean way without the use of a library which can do the typechecks for you. I suggest to take a look at some <a href=\"http://debasishg.blogspot.de/2011/02/applicatives-for-composable-json.html\">Scalaz</a> or <a href=\"https://github.com/milessabin/shapeless\">Shapeless</a> code.</p>\n\n<p>Nevertheless is is far easier to do such type checks in the parser and not in the AST traverser. Thus, I suggest using a JSON parser which can handle a type format given by the user and returns an error if it finds some unexpected content. I don't know if Play! can parse things like the following (which can be done in <a href=\"https://github.com/lift/lift/tree/master/framework/lift-base/lift-json/\">lift-json</a>):</p>\n\n<pre><code>val json = \"\"\"{ \"foo\": [1, 2, 3], \"bar\": [2, 5] }\"\"\"\nclass Content(foo: List[Double], bar: List[Double])\nparse(json).extract[Content]\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-03T12:49:40.747",
"Id": "24799",
"Score": "0",
"body": "I think I may have phrased the question poorly. The problem with nesting is not that I have `Option[Option[String]]`; I know I can flatten it. The problem is if I expect my Json return data to be already nested, say of type `Map[String, List[Int]]`. What I want to avoid is having to deal with a `Option[Map[Option[String], Option[List[Option[Int]]]]`. You see, it becomes messy very easily. And I have a `None` anywhere, this means the parsing has failed and I jsut want a `None` at the outer level. I do not know how to deal with this kind of nested flattening."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-03T13:10:09.940",
"Id": "24801",
"Score": "0",
"body": "@Andrea: Can you please edit your question and show an example how you get such an awful type like the one mentioned above? I do not understand how you get such a thing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-03T13:34:00.957",
"Id": "24803",
"Score": "0",
"body": "I have made the edit, I hope now it is more clear"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-03T15:46:30.917",
"Id": "24804",
"Score": "0",
"body": "@Andrea: I did a small edit."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-03T16:24:07.280",
"Id": "24805",
"Score": "0",
"body": "Thank you for the edit. Probably a more capable library like lift-json is the way to go. Just to be sure, though, I actually know the types I want to get. What I do not know is whether the JSON conforms to the format - in theory it should, but I am adding error handling for a reason! :-)"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-03T11:26:06.840",
"Id": "15301",
"ParentId": "15295",
"Score": "7"
}
},
{
"body": "<ol>\n<li><p>You can use <code>Try</code>:</p>\n<pre><code>val cols = Try {(json \\ "responseBody" \\ "columns")}\n</code></pre>\n<p>you can match it:</p>\n<pre><code>cols match {\n case Success(value) => ???\n case Failure(exception) => \n println(exception.getMessage)\n}\n</code></pre>\n</li>\n<li><p>You can convert it to Option to avoid exception</p>\n<pre><code>val cols = Try {(json \\ "responseBody" \\ "columns")}.toOption\n</code></pre>\n<p>It gives <code>None</code> or <code>Some(value)</code>.</p>\n<pre><code>cols match {\ncase Some(value) => ???\ncase None => ??\n}\n</code></pre>\n</li>\n<li><p>You can use <code>asOpt</code></p>\n<pre><code>val cols = (json \\ "responseBody" \\ "columns").asOpt[String].getOrElse("") \n</code></pre>\n<p>OR</p>\n<pre><code>val cols = (json \\ "responseBody" \\ "columns").asOpt[String].orNull\n</code></pre>\n</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-11T16:38:35.947",
"Id": "253349",
"ParentId": "15295",
"Score": "-1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-03T09:05:32.753",
"Id": "15295",
"Score": "7",
"Tags": [
"parsing",
"scala",
"json",
"exception-handling"
],
"Title": "Handling parsing failure in Scala without exceptions"
}
|
15295
|
<p>I have to create a website in Classic ASP, and I really want to do a clean design so I will try to put everything in Classes and Models to emulate the ViewModel Pattern.</p>
<p>So can you tell me if this approach of creating objects is good because I will use it everywhere</p>
<pre><code>Class User
Public Name
Public Adress
Public Title
Public Text
Public Rights 'ArrayList of Right objects
Private Sub Class_Initialize()
Initialize
End Sub
Private Sub Class_Terminate()
Dispose
End Sub
Private Sub Initialize()
Name = ""
Adress = ""
Title = ""
Text = ""
Set Rights = Server.CreateObject("System.Collections.ArrayList") ' Arraylist .net
End Sub
Private Sub Dispose()
End Sub
End Class
</code></pre>
<hr>
<pre><code>Class Right
Public Name
Private Sub Class_Initialize()
Initialize
End Sub
Private Sub Class_Terminate()
Dispose
End Sub
Private Sub Initialize()
Name = ""
End Sub
Private Sub Dispose()
End Sub
End Class
</code></pre>
<hr>
<p>And then I do this for instantiating objects : </p>
<pre><code>Dim myUser
Set myUser = New User
'Do some work
Set myUser = nothing 'Dispose the object
</code></pre>
<p>Any idea, suggestion or correction is welcome.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-04T05:10:19.500",
"Id": "24831",
"Score": "3",
"body": "I don't see any problems with the supplied code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-19T15:17:51.633",
"Id": "57941",
"Score": "0",
"body": "it's missing something.....Semicolons....jk"
}
] |
[
{
"body": "<p>I am not a big VB person, but I would think that if you give your class a Dispose method you should use it rather than setting it to nothing, I know this is kind of the same thing, but if you aren't going to use the Method don't create the method, it's extra stuff. if you are going to use it in the future, comment to that effect.</p>\n\n<pre><code>'This Method is for future development\nPrivate Sub Dispose()\nEnd Sub\n</code></pre>\n\n<p>OR</p>\n\n<pre><code>'TODO: Implement!\nPrivate Sub Dispose()\nEnd Sub\n</code></pre>\n\n<p>my comment syntax is probably off a little bit.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-19T15:28:07.950",
"Id": "57945",
"Score": "0",
"body": "Yeah, like `'''TODO: Crea Dispose Method.` should read `'TODO: Implement!!`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-19T15:31:26.623",
"Id": "57946",
"Score": "0",
"body": "I was trying to do the xml comment or whatever it is. so it alerts you that there is something left to do"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-19T15:37:24.903",
"Id": "57948",
"Score": "0",
"body": "I don't think there's such a fancypants thing in VBScript :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-19T15:45:52.147",
"Id": "57951",
"Score": "0",
"body": "well I was thinking ASP.NET....lol"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-19T15:27:04.320",
"Id": "35690",
"ParentId": "15300",
"Score": "2"
}
},
{
"body": "<p>That's very nice & tidy, if you write all your code as cleanly, I want to debug your code!!</p>\n\n<p>That said I might be wrong, but I don't think there's a <em>Dispose pattern</em> in VBScript (that's not .net!), but I see what you're trying to accomplish and it's excellent - use that method to set all your resources to <code>Nothing</code>.</p>\n\n<p>The only thing I'd warmly recommend, is to use the <code>vbNullString</code> constant instead of <code>\"\"</code> - <code>vbNullString</code> takes 0 bytes of memory, which isn't the case for <code>\"\"</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-19T15:36:08.567",
"Id": "57947",
"Score": "0",
"body": "I changed the Tag from vbscript to vb.net because of the wording of the question I thought that he was probably writing in vb.net and not vbscript"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-19T15:34:23.417",
"Id": "35691",
"ParentId": "15300",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-03T10:55:34.380",
"Id": "15300",
"Score": "5",
"Tags": [
"object-oriented",
"vbscript",
"asp-classic"
],
"Title": "VbScript/ASP Classic good OOP Pattern"
}
|
15300
|
<p>I wrote this login method: </p>
<pre><code> [HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginModel logModel, string returnUrl)
{
if (!ModelState.IsValid)
{
TempData[Keys.ACCOUNT_TEMPDATA_LOGINSTATUS] = LoginStatus.InvalidCredentials;
return RedirectToAction("LoginFailed");
}
User user;
try
{
user = _usersRepository.SingleOrDefault(u => String.Equals(u.Username, logModel.LoginUsername));
}
catch(Exception ex)
{
//log it
TempData[Keys.ACCOUNT_TEMPDATA_LOGINSTATUS] = LoginStatus.DatabaseException;
return RedirectToAction("LoginFailed");
}
if (user == null)
{
TempData[Keys.ACCOUNT_TEMPDATA_LOGINSTATUS] = LoginStatus.InvalidCredentials;
return RedirectToAction("LoginFailed");
}
//if we got so far it means that username does exist
//is user blocked?
if (user.IsLockedOut)
{
TempData[Keys.ACCOUNT_TEMPDATA_LOGINSTATUS] = LoginStatus.AccountBlocked;
return RedirectToAction("LoginFailed");
}
//is the password correct?
string passHash = ComputePasswordHash(logModel.LoginPassword, user.Salt);
if (!String.Equals(passHash, user.Password))
{
user.FailedPasswordAttemptCount++;
try
{
_usersRepository.Update(user);
}
catch(Exception ex)
{
//just log it, not a big deal the FailedPasswordAttemptCount could not be updated
user.FailedPasswordAttemptCount--;
}
TempData[Keys.ACCOUNT_TEMPDATA_LOGINSTATUS] = LoginStatus.InvalidCredentials;
TempData[Keys.ACCOUNT_TEMPDATA_INVALIDATTEMPTS] = user.FailedPasswordAttemptCount;
return RedirectToAction("LoginFailed");
}
//is the account activated?
if (!user.IsApproved)
{
TempData[Keys.ACCOUNT_TEMPDATA_LOGINSTATUS] = LoginStatus.AccountNotAcctivated;
return RedirectToAction("LoginFailed");
}
//if we got so far then everything is ok
FormsAuthentication.SetAuthCookie(logModel.LoginUsername, false);
if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/") && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "Home");
}
}
</code></pre>
<ul>
<li>Is it ok to retrieve all the user related information, specifically sensitive info like password? Should I first check if that username exists, then select the salt, compute the password hash and check if there is a user with that username and that password hash?</li>
<li>What would you improve?</li>
</ul>
|
[] |
[
{
"body": "<p>If you can, I would encrypt the password entered before it is passed back to the service. This will eliminate any chance it could be intercepted. As for the rest of your first question, I think the how you process is up to you. I don't think there is a right or wrong answer.</p>\n\n<p>Now onto improvements:</p>\n\n<p>First off, I think you code is doing too much. This is very evident by then number of if/else and return statements.</p>\n\n<p>I think a better approach would be to pull out all of the logic into a number of separate methods, or even better classes that all work together to process the login, and decide what the appropriate course of action is. I'm going to tackle the multiple method approach. If you want to see how multiple classes can be implemented let me know, and I'll update the post then.</p>\n\n<p>There are two important pieces of data that you require, the <em>LoginStatus</em> and the <em>ActionResult</em> Keeping this in mind, I would first create a class call LoginResult, which contains the two pieces of information in it</p>\n\n<pre><code>internal class LoginResult\n{\n public ActionResult ActionResult { get; private set; }\n public LoginStatus LoginStatus { get; private set; }\n\n public LoginResult(ActionResult actionResult, LoginStatus loginStatus)\n {\n ActionResult = actionResult;\n LoginStatus = loginStatus;\n }\n}\n</code></pre>\n\n<p>This will allow for each method to return the important data.</p>\n\n<p>Now that you have the first building block, I would start by pulling out every if/else statement in your original code into its own method, returning a LoginResult. There is another important piece of data returned from one of the checks, and that is user, so add a UserLoginResult class:</p>\n\n<pre><code>internal class LoginResult\n{\n public ActionResult ActionResult { get; private set; }\n public LoginStatus LoginStatus { get; private set; }\n\n public LoginResult(ActionResult actionResult, LoginStatus loginStatus)\n {\n ActionResult = actionResult;\n LoginStatus = loginStatus;\n }\n}\n\ninternal class RetrieveUserResult\n{\n public LoginResult Result { get; private set; }\n public User User { get; private set; }\n\n public RetrieveUserResult(LoginResult loginResult, User user)\n {\n Result = loginResult;\n User = user;\n }\n}\n\n[HttpPost]\n[ValidateAntiForgeryToken]\npublic ActionResult Login(LoginModel logModel, string returnUrl)\n{\n _returnUrl = returnUrl;\n _logModel = logModel;\n\n var result = EnsureModalStateIsValid();\n if (result.LoginStatus == LoginStatus.InvalidCredentials)\n {\n TempData[Keys.ACCOUNT_TEMPDATA_LOGINSTATUS] = result.LoginStatus;\n\n return result.ActionResult;\n }\n\n var retrieveResult = TryToRetrieveUserFromRepository();\n\n if (retrieveResult.User == null)\n {\n TempData[Keys.ACCOUNT_TEMPDATA_LOGINSTATUS] = result.LoginStatus;\n return result.ActionResult;\n }\n\n var lockedResult = CheckIfUserIsLockedOut(retrieveResult.User);\n\n if (lockedResult.LoginStatus == LoginStatus.AccountBlocked)\n {\n TempData[Keys.ACCOUNT_TEMPDATA_LOGINSTATUS] = lockedResult.LoginStatus;\n return lockedResult.ActionResult;\n }\n\n var passwordResult = ConfirmUserPasswordMatches(retrieveResult.User);\n if (passwordResult.LoginStatus == LoginStatus.InvalidCredentials)\n {\n TempData[Keys.ACCOUNT_TEMPDATA_LOGINSTATUS] = passwordResult.LoginStatus;\n return passwordResult.ActionResult;\n }\n\n //is the account activated?\n var activatedResult = ConfirmUserIsActivated(retrieveResult.User);\n if (activatedResult.LoginStatus == LoginStatus.AccountNotActivated)\n {\n TempData[Keys.ACCOUNT_TEMPDATA_LOGINSTATUS] = activatedResult.LoginStatus;\n return activatedResult.ActionResult;\n }\n\n return activatedResult.ActionResult;\n\n}\n\nprivate LoginResult EnsureModalStateIsValid()\n{\n if (!ModelState.IsValid)\n {\n return new LoginResult(RedirectToAction(\"LoginFailed\"), LoginStatus.InvalidCredentials);\n }\n\n // Should come up with a dummy Action for this case\n return DetermineSuccessResult();\n}\n\nprivate RetrieveUserResult TryToRetrieveUserFromRepository()\n{\n try\n {\n var user = _usersRepository.SingleOrDefault(u => String.Equals(u.Username, logModel.LoginUsername));\n return new RetrieveUserResult(new LoginResult(RedirectToAction(\"Index\", \"Home\"), LoginStatus.LoginOK), user);\n }\n catch (Exception ex)\n {\n\n return new RetrieveUserResult(DetermineSuccessResult(), null);\n }\n}\n\nprivate LoginResult CheckIfUserIsLockedOut(User user)\n{\n if (user.IsLockedOut)\n {\n return new LoginResult(RedirectToAction(\"LoginFailed\"), LoginStatus.AccountBlocked);\n }\n\n return DetermineSuccessResult();\n}\n\nprivate LoginResult ConfirmUserPasswordMatches(User user)\n{\n string passHash = ComputePasswordHash(logModel.LoginPassword, user.Salt);\n if (!String.Equals(passHash, user.Password))\n {\n user.FailedPasswordAttemptCount++;\n try\n {\n _usersRepository.Update(user);\n }\n catch (Exception ex)\n {\n //just log it, not a big deal the FailedPasswordAttemptCount could not be updated\n user.FailedPasswordAttemptCount--;\n }\n\n TempData[Keys.ACCOUNT_TEMPDATA_INVALIDATTEMPTS] = user.FailedPasswordAttemptCount;\n\n return new LoginResult(RedirectToAction(\"LoginFailed\"), LoginStatus.InvalidCredentials);\n }\n\n return DetermineSuccessResult();\n}\n\nprivate LoginResult ConfirmUserIsActivated(User user)\n{\n if (!user.IsApproved)\n {\n return new LoginResult(RedirectToAction(\"LoginFailed\"), LoginStatus.AccountNotActivated);\n }\n\n return DetermineSuccessResult();\n}\n\nprivate LoginResult DetermineSuccessResult()\n{\n FormsAuthentication.SetAuthCookie(_logModel.LoginUsername, false);\n return new LoginResult(ReturnUrlIsValid() ? Redirect(_returnUrl) : RedirectToAction(\"Index\", \"Home\"), LoginStatus.LoginOK);\n}\n\nprivate bool ReturnUrlIsValid()\n{\n return (Url.IsLocalUrl(_returnUrl) && _returnUrl.Length > 1 && _returnUrl.StartsWith(\"/\") &&\n !_returnUrl.StartsWith(\"//\") && !_returnUrl.StartsWith(\"/\\\\\"));\n}\n</code></pre>\n\n<p>The Login method still is doing too much, but at least it has moved the checking logic out into sub routines. You should now start to see a pattern emerging in the Login method: DoCheck -> CheckResult -> return if failed -> repeat. This can be moved into a chain event where if the first one fails, it returns, if it passes, it calls the next event:</p>\n\n<pre><code>[HttpPost]\n[ValidateAntiForgeryToken]\npublic ActionResult Login(LoginModel logModel, string returnUrl)\n{\n _returnUrl = returnUrl;\n _logModel = logModel;\n\n var result = Process();\n\n TempData[Keys.ACCOUNT_TEMPDATA_LOGINSTATUS] = result.LoginStatus;\n\n return result.ActionResult;\n}\n\nprivate LoginResult Process()\n{\n LoginResult result = EnsureModalStateIsValid();\n return result.LoginStatus == LoginStatus.InvalidCredentials ? result : TryToRetrieveUserFromRepository();\n}\n\nprivate LoginResult EnsureModalStateIsValid()\n{\n return !ModelState.IsValid\n ? new LoginResult(RedirectToAction(\"LoginFailed\"), LoginStatus.InvalidCredentials)\n : DetermineSuccessResult();\n\n // Should come up with a dummy Action for this case\n}\n\nprivate LoginResult TryToRetrieveUserFromRepository()\n{\n try\n {\n var user = _usersRepository.SingleOrDefault(u => String.Equals(u.Username, logModel.LoginUsername));\n\n return retrieveUserResult.User == null ? result : CheckIfUserIsLockedOut(retrieveUserResult.User);\n }\n catch (Exception ex)\n {\n return new LoginResult(RedirectToAction(\"LoginFailed\"), LoginStatus.DatabaseException);\n }\n}\n\nprivate LoginResult CheckIfUserIsLockedOut(User user)\n{\n return user.IsLockedOut\n ? new LoginResult(RedirectToAction(\"LoginFailed\"), LoginStatus.AccountBlocked)\n : ConfirmUserPasswordMatches(user);\n}\n\nprivate LoginResult ConfirmUserPasswordMatches(User user)\n{\n //is the password correct?\n string passHash = ComputePasswordHash(logModel.LoginPassword, user.Salt);\n if (!String.Equals(passHash, user.Password))\n {\n user.FailedPasswordAttemptCount++;\n try\n {\n _usersRepository.Update(user);\n }\n catch (Exception ex)\n {\n //just log it, not a big deal the FailedPasswordAttemptCount could not be updated\n user.FailedPasswordAttemptCount--;\n }\n\n TempData[Keys.ACCOUNT_TEMPDATA_INVALIDATTEMPTS] = user.FailedPasswordAttemptCount;\n\n return new LoginResult(RedirectToAction(\"LoginFailed\"), LoginStatus.InvalidCredentials);\n }\n\n return ConfirmUserIsActivated(user);\n}\n\nprivate LoginResult ConfirmUserIsActivated(User user)\n{\n return !user.IsApproved\n ? new LoginResult(RedirectToAction(\"LoginFailed\"), LoginStatus.AccountNotActivated)\n : DetermineSuccessResult();\n}\n\nprivate LoginResult DetermineSuccessResult()\n{\n FormsAuthentication.SetAuthCookie(_logModel.LoginUsername, false);\n return new LoginResult(ReturnUrlIsValid() ? Redirect(_returnUrl) : RedirectToAction(\"Index\", \"Home\"),\n LoginStatus.LoginOK);\n}\n\nprivate bool ReturnUrlIsValid()\n{\n return (Url.IsLocalUrl(_returnUrl) && _returnUrl.Length > 1 && _returnUrl.StartsWith(\"/\") &&\n !_returnUrl.StartsWith(\"//\") && !_returnUrl.StartsWith(\"/\\\\\"));\n}\n</code></pre>\n\n<p>With this interation, you get rid of the <em>RetrieveUserResult</em> class.</p>\n\n<p>There are a few more things I'd suggest, but I don't like giving too much information in these all at once.</p>\n\n<p>Hope this helps.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-04T04:48:07.453",
"Id": "15314",
"ParentId": "15303",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-03T17:17:33.513",
"Id": "15303",
"Score": "3",
"Tags": [
"c#",
"asp.net",
"asp.net-mvc-3"
],
"Title": "Asp.net MVC login method"
}
|
15303
|
<p>I wrote a program that generates a set of <a href="http://en.wikipedia.org/wiki/Elementary_cellular_automaton" rel="nofollow noreferrer">1D</a> <a href="http://mathworld.wolfram.com/ElementaryCellularAutomaton.html" rel="nofollow noreferrer">cellular automaton</a>. Basically, it generates this (rule 150):</p>
<p><img src="https://i.stack.imgur.com/WJie4.png" alt="simple triangle"></p>
<p>...and rotates it to form this:</p>
<p><img src="https://i.stack.imgur.com/UX71V.png" alt="simple square"></p>
<p>I then introduced an element of randomness to it, so it could form images like this:</p>
<p><img src="https://i.stack.imgur.com/fN9rA.png" alt="complex square"></p>
<p>I was hoping I could get reviews for the code I have, focusing around how to optimize it and improve its performance. This program feels like it takes a second or two to generate a 511x511 square on my machine, which makes it feel a bit laggy.</p>
<p>Here's the complete code:</p>
<pre><code>#!/usr/bin/env python
'''
Code that will generate a fractal or a pseudo-random fractal
based on an initial seed and any acceptable 1-d cellular automata
algorithm.
'''
import sys
import random
import time
import pygame
class Rules(object):
'''Contains a variety of rules that determines if a cell should turn black
based on the cells in the row above. Each function is namespaced inside
the 'Rules' class for convenience.
'''
@staticmethod
def rule150(above):
'''Colors a cell black if there is an odd number of black cells
above it.'''
return sum(above) in (1, 3)
@staticmethod
def rule150randomized(above):
'''Colors a cell black if there's an odd number of black cells above it
(although this rule will be ignored 0.05% of the time.'''
if sum(above) in (1, 3):
return random.randint(0, 2000) != 0
else:
return False
class Generator(object):
'''An object which generates a single wedge based on an initial seed
and a rule. If the seed is `None`, a random one will be generated.'''
def __init__(self, seed=None, rule=Rules.rule150):
self.seed = seed
self.rule = rule
def _generate_seed(self, seed=None):
'''Takes a seed and converts it into an integer.
If the seed is `None`, a random seed based on system time
will be generated.'''
to_int = lambda item : int(''.join([str(ord(x)) for x in str(item)]))
if seed is None:
return to_int(time.time())
elif type(seed) in (int, long):
return seed
else:
return to_int(seed)
def _calculate_row(self, previous_row):
'''Generates the next row based on the previous row.'''
def _above(row):
previous_row = [False, False]
previous_row.extend(row)
previous_row.extend([False, False])
for i in range(len(previous_row) - 2):
yield previous_row[i: i+3]
return [self.rule(i) for i in _above(previous_row)]
def generate(self, n=None):
'''Yields n rows.'''
row = [True]
yield row
if n == None:
while True:
row = self._calculate_row(row)
yield row
else:
for i in xrange(n - 1):
row = self._calculate_row(row)
yield row
def create_grid(self, n):
'''Returns a `Grid` object containing a wedge that
has been rotated four times to form a square.
The generated wedge will be `n` rows long, yielding
a square of size `n * 2 - 1`'''
size = n * 2 - 1
grid = Grid(size, size)
# Takes raw coordinates and returns new ones
# based on the center of the grid.
x = lambda raw_x: grid.center[0] + raw_x
y = lambda raw_y: grid.center[1] + raw_y
grid.seed = self._generate_seed(self.seed)
random.seed(grid.seed)
for index, row in enumerate(self.generate(n)):
for i, cell in enumerate(row):
if cell:
raw_x = index
raw_y = i - index
# Rotates a wedge four times to form a square.
grid.set(x(raw_x), y(raw_y))
grid.set(x(-raw_x), y(-raw_y))
grid.set(x(-raw_y), y(raw_x))
grid.set(x(raw_y), y(-raw_x))
return grid
def __call__(self, *args, **kwargs):
'''A convenience function to create a grid.'''
return self.create_grid(*args, **kwargs)
class Grid(object):
'''An object which holds an arbitrary grid of pixels.'''
def __init__(self, x, y, seed=None):
self.width = x
self.height = y
self.array = []
# The seed used to generate the grid.
self.seed = seed
for i in xrange(self.height):
self.array.append([False for i in xrange(self.width)])
@property
def center(self):
'''Gets the center of the grid. Assumes the height and
width are odd.'''
return (int(self.width / 2), int(self.height / 2))
def get(self, x, y):
return self.array[y][x]
def set(self, x, y, value=True):
self.array[y][x] = value
class PygameRenderer(object):
'''Renders a grid object using Pygame, and also contains code to
save the current grid.'''
def __init__(self, n, pixel_size,
background=(255, 255, 255), foreground=(0, 0, 0)):
self.pixel_size = pixel_size
side_length = n * 2 - 1
self.size = (side_length * self.pixel_size,
side_length * self.pixel_size)
self.background = background
self.foreground = foreground
self._configure_pygame()
self._configure_graphics()
self.grid = None
def _configure_pygame(self):
pygame.init()
pygame.display.set_mode(self.size)
self.surface = pygame.display.get_surface()
def _configure_graphics(self):
self.tile = pygame.Surface((self.pixel_size, self.pixel_size))
self.tile.fill(self.foreground)
def render(self, grid):
'''Renders the grid, and prints the current seed to stdout.'''
self.grid = grid
self.surface.fill(self.background)
for x in xrange(self.grid.width):
for y in xrange(self.grid.height):
if self.grid.get(x, y):
self.surface.blit(
self.tile,
(x * self.pixel_size, y * self.pixel_size)
)
pygame.display.flip()
print self.grid.seed
def wait(self):
while True:
event = pygame.event.poll()
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
def refresh(self):
'''Waits until Pygame is closed. Clicking any keyboard
button will save the current image to the current directory,
and clicking the mouse will break from the mainloop so that
the containing function can create a new grid.'''
while True:
event = pygame.event.poll()
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
return # Returns so that a new grid can be generated.
elif event.type == pygame.KEYDOWN:
filename = str(self.grid.seed) + '.png'
pygame.image.save(self.surface, filename)
class AsciiRenderer(object):
'''Creates an ASCII version of the grid.'''
def to_string(self, grid):
out = []
for x in xrange(grid.width):
row = ['[']
for y in xrange(grid.height):
if grid.get(x, y):
row.append('#')
else:
row.append(' ')
row.append(']')
out.append(''.join(row))
return '\n'.join(out)
def render(self):
print self.to_string()
def test_rows(n=5):
'''Tests generating a series of rows.'''
g = Generator()
for index, row in enumerate(g.generate(n)):
padding = " " * (n - index - 1)
out = "[{0}{1}{0}]"
print out.format(padding, "".join("#" if n else " " for n in row))
def test_grid(n = 5, pixel_size = 16, rule=Rules.rule150):
'''Creates a normal grid.'''
grid = Generator(rule=rule)(n)
r = PygameRenderer(n, pixel_size)
r.render(grid)
while True:
r.refresh()
def test_grid_randomized(n=256, pixel_size=1, rule=Rules.rule150randomized):
'''Creates a randomized grid, and will repeatedly create a new one.'''
g = Generator(rule=rule)
r = PygameRenderer(n, pixel_size)
while True:
grid = g(n)
r.render(grid)
r.refresh()
def generate_single_random_grid(n=256, pixel_size=1,
rule=Rules.rule150randomized, seed=None):
'''Creates a randomized grid.'''
grid = Generator(rule=rule, seed=seed)(n)
r = PygameRenderer(n, pixel_size)
r.render(grid)
r.refresh()
def profiling_test(n):
Generator(rule=rule)(n)
if __name__ == '__main__':
#test_rows()
#test_grid(16, 4, Rules.rule150)
test_grid_randomized(256, 1, Rules.rule150randomized)
#profiling_test(256, 1, Rules.rule150)
</code></pre>
<hr>
<p><strong>Some specific questions I have:</strong></p>
<p>This specific code I'm using to render each square:</p>
<pre><code>def render(self, grid):
'''Renders the grid, and prints the current seed to stdout.'''
self.grid = grid
self.surface.fill(self.background)
for x in xrange(self.grid.width):
for y in xrange(self.grid.height):
if self.grid.get(x, y):
self.surface.blit(
self.tile,
(x * self.pixel_size, y * self.pixel_size)
)
pygame.display.flip()
print self.grid.seed
</code></pre>
<p>It basically iterates through a 2D array (the <code>grid</code> object), and blits a tile to the surface if the given cell should be black. Is there any way to optimize this method? I feel I shouldn't be blitting so much, but I'm not sure how else to do it.</p>
<p>This is the code I'm using to generate the actual rows (see the 1st picture):</p>
<pre><code>def _calculate_row(self, previous_row):
'''Generates the next row based on the previous row.'''
def _above(row):
previous_row = [False, False]
previous_row.extend(row)
previous_row.extend([False, False])
for i in range(len(previous_row) - 2):
yield previous_row[i: i+3]
return [self.rule(i) for i in _above(previous_row)]
def generate(self, n=None):
'''Yields n rows. If n is None, this will yield an infinite amount of rows.'''
row = [True]
yield row
if n == None:
while True:
row = self._calculate_row(row)
yield row
else:
for i in xrange(n - 1):
row = self._calculate_row(row)
yield row
</code></pre>
<p>Similarly, is there any way to optimize this and make it faster?</p>
|
[] |
[
{
"body": "<p>Warning: this hasn't been rigorously tested (<em>i.e.</em>, with a known seed)!</p>\n\n<p>There are a couple of things that can be tried without majorly changing things:</p>\n\n<ol>\n<li><p>Grid.center - you already know what it is on initialisation, so create a normal variable for it and remove the @property version. This avoids calculating it several hundred thousand times.</p>\n\n<pre><code>self.center = (int(x / 2), int(y / 2))\n</code></pre></li>\n<li><p>Enumerate over the array/columns when displaying as you do in other places. This will stop you doing an list index that's repeated:</p>\n\n<pre><code>def render(self, grid):\n '''Renders the grid, and prints the current seed to stdout.'''\n self.grid = grid\n self.surface.fill(self.background)\n for x,col in enumerate( grid.array ):\n xc = x * self.pixel_size\n for y,cell in enumerate( col ):\n if cell:\n self.surface.blit(\n self.ftile,\n (xc, y * self.pixel_size)\n )\n pygame.display.flip()\n</code></pre></li>\n<li><p>The lambdas in Generator.create_grid can be removed (function calls)</p>\n\n<pre><code>xc,yc = grid.center\nfor index, row in enumerate(self.generate(n)):\n raw_x = index\n for i, cell in enumerate(row):\n if cell: \n raw_y = i - index\n # Rotates a wedge four times to form a square.\n grid.set( xc + raw_x, yc + raw_y )\n grid.set( xc - raw_x, yc - raw_y )\n grid.set( xc - raw_y, yc + raw_x )\n grid.set( xc + raw_y, yc - raw_x )\n</code></pre></li>\n<li><p>Changing the rules. rather than doing <code>sum(above) in (1,3)</code>, why not explicitly state the combinations?</p>\n\n<pre><code>black_set = ( [False, False, True], [False, True, False], [True, False, False], [True, True, True] )\n...\nif above in Rules.black_set:\n #etc\n</code></pre></li>\n</ol>\n\n<p>All these might give you ~60-65% of the original.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-04T01:08:34.367",
"Id": "24824",
"Score": "0",
"body": "Wow, thanks! Applying these brought the time of a single trial run from about 2.25 seconds (discounting pygame's initialization) down to about 1.25 seconds."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-03T23:58:04.120",
"Id": "15311",
"ParentId": "15304",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "15311",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-03T17:25:49.123",
"Id": "15304",
"Score": "6",
"Tags": [
"python",
"performance",
"cellular-automata"
],
"Title": "Generating a 1D cellular automata in Python"
}
|
15304
|
<p>I just created this during a live screencast. The people who were on there were <em>very</em> critical of almost every line of code. They say I am a horrible coder and know nothing. Looking at this tax calculator, would you say I'm an OK coder?</p>
<p><a href="http://www.phpu.cc/repo/phpu-training/5.tax-calc/" rel="nofollow">Demo</a></p>
<p>I don't think they're right, but I require one or more objective subject-matter experts to confirm whether or not the code is horrible.</p>
<pre><code><?php
// Set up autoloading
set_include_path(get_include_path() . PATH_SEPARATOR .
realpath('../'));
// This uses my Thrive framework, which extends
// the Flourish framework.
// NOTE: Using require, or require_once has performance penalties that aren't
// necessary. If the file isn't loaded successfully, the app will crash
// anyway.
include_once 'thrive/Autoloader.php';
new Thrive_Autoloader;
// Iteration 2: Create the Data Models.
// TIP: By always building out class datatypes instead of relying on hashmaps (array keys0, you
// make it much easier to create what's called an API that people can easily use later.
class TaxBracket
{
public $min;
public $max;
public $rate;
}
// Let's create an interface for our new taxing system.
interface API_Tax
{
public function getTaxLiability(fMoney $revenue, fMoney $deductions);
}
// It makes more sense to use a Factory for this.
// Uses the Factory Design Pattern.
class USFederalTaxesFactory
{
public static function create(fMoney $revenue, fMoney $deductions, $numOfEmployees)
{
// TODO: Rearchitect out the magic Constants.
// TODO: Add a proper Service Locator Pattern here...
$taxes = array(
'ssi' => 'SocialSecurityTax',
'medicare' => 'MedicareTax',
//'unemployment' => 'UnemploymentTax',
);
foreach ($taxes as $taxName => $taxClass)
{
$tax = new $taxClass();
/** @var $tax API_Tax */
$liabilities[$taxName] = $tax->getTaxLiability($revenue, $deductions);
}
$tax = new UnemploymentTax($numOfEmployees);
$liabilities['unemployment'] = $tax->getTaxLiability($revenue, $deductions);
$incomeTax = new USFederalIncomeTax($revenue, $deductions, $liabilities);
return $incomeTax;
}
}
// FIXME: Figure out a way to save the API_Tax interface ;-/
class USFederalIncomeTax /* implements API_Tax*/
{
// AVOID MAGIC CONSTANTS.
// FIXME: These need to be moved to their own classes. It's a serious weakness right now!!!!
const INCOME_TAX_KEY = 'income';
const SSI_TAX_KEY = 'ssi';
const MEDCARE_TAX_KEY = 'medicare';
const UNEMPLOYMENT_TAX_KEY = 'unemployment';
/** @var TaxBracketManager */
protected $bracketManager;
/** @var TaxBracket[] */
protected $brackets;
/** @var fMoney */
protected $revenue;
/** @var fMoney */
protected $deductions;
/** @var fMoney[] */
protected $taxLiabilities;
public function __construct(fMoney $revenue, fMoney $deductions, array $otherTaxLiabilities, $bracketManager = null)
{
$this->amountOwed = new fMoney('0', 'USD');
$this->revenue = $revenue;
$this->deductions = $deductions;
$this->taxLiabilities = $otherTaxLiabilities;
if ($bracketManager === null)
{
$bracketManager = new TaxBracketManager();
}
$this->bracketManager = $bracketManager;
}
/**
* @param $tax
* @return fMoney
* @throws LogicException*/
public function getLiabilityByTax($tax)
{
if (!isset($this->taxLiabilities[$tax]))
{
throw new LogicException("No tax liabilities named '$tax'");
}
return $this->taxLiabilities[$tax];
}
public function getTaxLiability()
{
$brackets = $this->fetchTaxBracketRates();
// Federal income tax algorithm works like this:
// Total Revenue - Qualified Deductions - Other Fed Taxes -> Tax Brackets -> Rate.
// Minimum possible taxes owed: $0.
$otherTaxes = new fMoney(0, 'USD');
// TODO: It'd be a nice-to-have to be able to dynamically figure out which
// taxes are non-income and just do a foreach() here...
$otherTaxes = $otherTaxes->add($this->getLiabilityByTax(self::SSI_TAX_KEY));
$otherTaxes = $otherTaxes->add($this->getLiabilityByTax(self::MEDCARE_TAX_KEY));
$otherTaxes = $otherTaxes->add($this->getLiabilityByTax(self::UNEMPLOYMENT_TAX_KEY));
$amountOwed = $this->calculateTaxLiability($this->revenue, $this->deductions, $otherTaxes);
$this->taxLiabilities[self::INCOME_TAX_KEY] = $amountOwed;
return $amountOwed;
}
protected function calculateTaxLiability(fMoney $taxableRevenue, fMoney $deductions, fMoney $otherTaxes)
{
$taxableRevenue = $taxableRevenue->sub($deductions);
$taxableRevenue = $taxableRevenue->sub($otherTaxes);
$totalTaxLiability = new fMoney(0, 'USD');
foreach ($this->brackets as /** @var TaxBracket */ $bracket)
{
// Assume 500 0000
// Algorithm: Get subvalue -> get liability -> add liability -> subtract subvalue -> continue
if ($bracket->max !== null)
{
$amountTaxedInBracket = $bracket->max - $bracket->min;
}
else
{
$amountTaxedInBracket = $taxableRevenue;
}
if ($taxableRevenue->lte($amountTaxedInBracket))
{
$amountTaxedInBracket = $taxableRevenue;
}
$taxLiability = new fMoney($amountTaxedInBracket, 'USD');
$taxLiability = $taxLiability->mul($bracket->rate);
$totalTaxLiability = $totalTaxLiability->add($taxLiability);
$taxableRevenue = $taxableRevenue->sub($amountTaxedInBracket);
if ($taxableRevenue->lte(0))
{
break;
}
}
if (isset($_GET['debug']))
{
echo "</pre>";
}
return $totalTaxLiability;
}
protected function fetchTaxBracketRates()
{
if ($this->brackets !== null)
{
return $this->brackets;
}
// TODO: Load this from a database table.
// FIXME: Add more brackets.
// TIP: By doing a little extra work now, all i have to do later is do $pdo->fetchArray() later ;-)
// I **LOVE** our complicated corporate income tax system!! WOOO!!!!!
$brackets = $this->bracketManager->fetchAll();
$this->brackets = $brackets;
return $brackets;
}
}
class TaxBracketManager
{
public function fetchTaxBrackets()
{
$bracketsInfo = array(
array('min' => 0, 'max' => 50000, 'rate' => 0.15),
array('min' => 50001, 'max' => 75000, 'rate' => 0.25),
array('min' => 75001, 'max' => 100000, 'rate' => 0.34),
array('min' => 100001, 'max' => 335000, 'rate' => 0.39),
array('min' => 335001, 'max' => 10000000, 'rate' => 0.34),
array('min' => 10000001, 'max' => 15000000, 'rate' => 0.35),
array('min' => 15000001, 'max' => 18333333, 'rate' => 0.38),
array('min' => 18333334, 'max' => null, 'rate' => 0.35),
);
$brackets = array();
foreach ($bracketsInfo as $i)
{
$bracket = new TaxBracket;
$bracket->min = $i['min'];
$bracket->max = $i['max'];
$bracket->rate = $i['rate'];
$brackets[] = $bracket;
}
return $brackets;
}
}
// Social security tax does not allow for deductions. It is off of the entire gross wage.
class SocialSecurityTax implements API_Tax
{
public function getTaxLiability(fMoney $revenue, fMoney $deductions)
{
$taxLiability = $this->calculateTaxLiability($revenue);
return $taxLiability;
}
protected function calculateTaxLiability(fMoney $taxableRevenue)
{
$maxTaxable = $this->fetchMaxTaxableAmount();
$taxableRevenue = min($maxTaxable, $taxableRevenue);
$taxRate = $this->fetchTaxRate();
$taxLiability = $taxableRevenue->mul($taxRate);
if (isset($_GET['debug']))
{
echo "<pre>";
echo "[ssi] Taxable Revenue: $taxableRevenue\n";
echo "[ssi] Tax Rate: $taxRate\n";
echo "[ssi] Total Tax Liability: $taxLiability\n";
echo "</pre>";
}
return $taxLiability;
}
protected function fetchMaxTaxableAmount()
{
return new fMoney(110100, 'USD');
}
protected function fetchTaxRate()
{
return 0.062;
}
}
// Medicare tax does not allow for deductions. It is off of the entire gross wage.
class MedicareTax implements API_Tax
{
public function getTaxLiability(fMoney $revenue, fMoney $deductions)
{
$taxLiability = $this->calculateTaxLiability($revenue);
return $taxLiability;
}
protected function calculateTaxLiability(fMoney $taxableRevenue)
{
$taxRate = $this->fetchTaxRate();
$taxLiability = $taxableRevenue->mul($taxRate);
if (isset($_GET['debug']))
{
echo "<pre>";
echo "[medicare] Taxable Revenue: $taxableRevenue\n";
echo "[medicare] Tax Rate: $taxRate\n";
echo "[medicare] Total Tax Liability: $taxLiability\n";
echo "</pre>";
}
return $taxLiability;
}
protected function fetchTaxRate()
{
return 0.0145;
}
}
// Unemployment Insurance tax does not allow for deductions. It is off of the entire gross wage.
// Source: http://workforcesecurity.doleta.gov/unemploy/uitaxtopic.asp
class UnemploymentTax implements API_Tax
{
protected $numOfEmployees;
public function __construct($numOfEmployees = null)
{
if ($numOfEmployees !== null)
{
echo "Num of Employees 2.5: $numOfEmployees";
$this->setNumberOfEmployees($numOfEmployees);
}
}
public function setNumberOfEmployees($numOfEmployees)
{
echo "Num of Employees 3: " . $numOfEmployees;
$this->numOfEmployees = $numOfEmployees;
}
public function getTaxLiability(fMoney $revenue, fMoney $deductions)
{
if (empty($this->numOfEmployees))
{
throw new LogicException("Cannot calculate Unemployment tax without specifying the number of employees.");
}
$taxLiability = new fMoney(0, 'USD');
for ($a = 0; $a < $this->numOfEmployees; ++$a)
{
$taxLiability = $taxLiability->add($this->calculateTaxLiability($revenue));
}
return $taxLiability;
}
protected function calculateTaxLiability(fMoney $taxableRevenue)
{
if ($taxableRevenue->lte($this->fetchMinimumAmountToTax()))
{
return new fMoney(0, 'USD');
}
$maxTaxLiability = $this->fetchMaxTaxLiability();
$taxRate = $this->fetchTaxRate();
$taxLiability = $taxableRevenue->mul($taxRate);
if ($taxLiability->gte($maxTaxLiability))
{
$taxLiability = $maxTaxLiability;
}
if (isset($_GET['debug']))
{
echo "<pre>";
echo "[unemployment] Taxable Revenue: $taxableRevenue\n";
echo "[unemployment] Tax Rate: $taxRate\n";
echo "[unemployment] Total Tax Liability: $taxLiability\n";
echo "</pre>";
}
return $taxLiability;
}
protected function fetchMinimumAmountToTax()
{
return new fMoney(1500, 'USD');
}
protected function fetchMaxTaxLiability()
{
return new fMoney(56.00, 'USD');
}
protected function fetchTaxRate()
{
return 0.062;
}
}
class FedTaxes
{
/** @var fMoney */
public $income;
/** @var fMoney */
public $ssi;
/** @var fMoney */
public $medicare;
/** @var fMoney */
public $unemployment;
/** @var fMoney */
public $total;
public function __construct()
{
$this->income = new fMoney(0, 'USD');
$this->ssi = new fMoney(0, 'USD');
$this->medicare = new fMoney(0, 'USD');
$this->unemployment = new fMoney(0, 'USD');
$this->total = new fMoney(0, 'USD');
}
}
// Main execution path.
function getTaxLiability()
{
if (!empty($_POST['gross_income']))
{
// I prefer filter_var($_POST) over filter_input(INPUT_POST) because it
// is **impossible** to simulate form data in unit tests with filter_input().
if (($grossIncome = filter_var($_POST['gross_income'], FILTER_SANITIZE_NUMBER_FLOAT)) === false)
{
throw new InvalidArgumentException("Invalid input for gross income, only numbers are accepted.");
}
if (($expenses = filter_var($_POST['expenses'], FILTER_SANITIZE_NUMBER_FLOAT)) === false)
{
throw new InvalidArgumentException("Invalid input for expenses, only numbers are accepted.");
}
if (($numOfEmployees = filter_var($_POST['num_of_employees'], FILTER_SANITIZE_NUMBER_INT)) === false)
{
throw new InvalidArgumentException("Invalid input for number of employees, only integers are accepted.");
}
echo "Num of Employees: $numOfEmployees";
fMoney::setDefaultCurrency('USD');
$taxManager = USFederalTaxesFactory::create(new fMoney($grossIncome), new fMoney($expenses), $numOfEmployees);
$amountOwed = $taxManager->getTaxLiability();
$fedTaxes = new FedTaxes;
$fedTaxes->income = $amountOwed;
$fedTaxes->ssi = $taxManager->getLiabilityByTax('ssi');
$fedTaxes->medicare = $taxManager->getLiabilityByTax('medicare');
$fedTaxes->unemployment = $taxManager->getLiabilityByTax('unemployment');
// TODO: fMoney **really** should be able to add multiple values at once. I mean, come on!
foreach (array('income', 'ssi', 'medicare', 'unemployment') as $tax)
{
$fedTaxes->total = $fedTaxes->total->add($fedTaxes->$tax);
}
return $fedTaxes;
}
return null;
}
$fedTaxes = null;
try
{
$fedTaxes = getTaxLiability();
}
catch(InvalidArgumentException $e)
{
$errorMessage = "Oops! An error has occurred:<br/>\n";
$errorMessage .= $e->getMessage();
}
catch(Exception $e)
{
$errorMessage = "Oops: An error has occured.";
$errorMessage .= $e->getMessage();
error_log($e->getMessage());
}
?>
<?php
// Start of the view.
$e_grossIncome = isset($_POST['gross_income']) ? htmlspecialchars($_POST['gross_income']) : '';
$e_expenses = isset($_POST['expenses']) ? htmlspecialchars($_POST['expenses']) : '';
$e_numOfEmployees = isset($_POST['num_of_employees']) ? htmlspecialchars($_POST['num_of_employees']) : '';
if (isset($errorMessage))
{
$e_errorMessage = htmlspecialchars($errorMessage);
}
// Iteration 1: Create the HTML.
?>
<!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>
<title>Federal Corporate Income Tax Calculator</title>
<style type="text/css">
table#tax_data_table th { text-align: left; }
table#tax_data_table td { text-align: right; }
</style>
</head>
<body>
<h1>Federal Corporate Income Tax Calculator</h1>
<p>This app is designed to calculate the estimated income tax of a corporation.</p>
<h4>Disclaimer</h4>
<p>This app is for educational purposes only. It is by no means a substitute for proper tax accounting services!</p>
<p><em>Note: Because of <a href="http://workforcesecurity.doleta.gov/unemploy/uitaxtopic.asp">Congressional bungling</a>, the Unemployment Taxrate
for 2011 is overstated (usually by just 0.2%).</em></p>
<?php
if (isset($e_errorMessage)):
?>
<div id="error_messag">
<?php echo $e_errorMessage; ?>
</div>
<?php endif; ?>
<div id="income_form">
<form method="post">
<table id="income_data_table">
<tr>
<th><label for="gross_income">Gross income:</label></th>
<td><input type="text" name="gross_income" value="<?php echo $e_grossIncome; ?>"/></td>
</tr>
<tr>
<th><label for="expenses">Expenses:</label></th>
<td><input type="text" name="expenses" value="<?php echo $e_expenses; ?>"/></td>
</tr>
<tr>
<th><label for="expenses">No. of Employees:</label></th>
<td><input type="text" name="num_of_employees" value="<?php echo $e_numOfEmployees; ?>"/></td>
</tr>
<tr>
<td span="2"><input type="submit" value="Calculate"></td>
</tr>
</table>
</form>
</div>
<?php
if ($fedTaxes instanceof FedTaxes):
?>
<div id="taxes_data">
<h3>Tax Information</h3>
<table id="tax_data_table">
<tr>
<th>Income Tax: </th>
<td><?php echo $fedTaxes->income; ?></td>
</tr>
<tr>
<th>Social Security Tax:</th>
<td><?php echo $fedTaxes->ssi; ?></td>
</tr>
<tr>
<th>Medicare Tax:</th>
<td><?php echo $fedTaxes->medicare; ?></td>
</tr>
<tr>
<th><a href="http://workforcesecurity.doleta.gov/unemploy/uitaxtopic.asp">Unemployment Tax:</a></th>
<td><?php echo $fedTaxes->unemployment; ?></td>
</tr>
<tr>
<th>Total Liability:</th>
<td><?php echo $fedTaxes->total; ?></td>
</tr>
</table>
</div>
<?php endif; ?>
</body>
</html>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-03T23:53:41.387",
"Id": "24822",
"Score": "2",
"body": "horrible coder tag sounds pretty harsh. I'm not a php guru but from a read-ability point of view the code looks clean and easy to follow."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-04T18:38:06.200",
"Id": "24851",
"Score": "3",
"body": "Did these other people give you actual constructive criticism (i.e., these things are all wrong, _here's why and how you fix them_), or were they just telling you that you sucked? I personally find that the latter indicates lack of experience on the criticizing person's part."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-12T02:13:05.917",
"Id": "25202",
"Score": "3",
"body": "Your ego is stopping you from being able to learn how to write good code. Why does your ego limit you to only produce code \"good enough for teaching beginners\"? You have received a myriad of suggestions on how to improve, why not heed them (rather than argue against them)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-12T23:30:30.290",
"Id": "25247",
"Score": "0",
"body": "@Paul it's a very good point. I think you may have missed this comment of mine down below: \" \n+1 Thank you for all of your suggestions. I've implemented almost all of your suggestions. You can see them at bazaar.launchpad.net/~theodore-phpexperts/phpu-training/trunk/…\""
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-12T23:34:33.313",
"Id": "25248",
"Score": "0",
"body": "@Paul One suggestion is that USFederalTaxes::calculatTaxLiability() is too long, but it's jsut 18 active lines of code long. Now, I honestly can't see a clear cut way to break it up or any real reason to, but if someone wanted to help out, i'd be thankful."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-12T23:48:44.933",
"Id": "25268",
"Score": "2",
"body": "\"The people who were on there were very very very critical of almost every line of code. They say I am a horrible coder and know nothing.\" Welcome to the internet."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-13T00:22:02.013",
"Id": "25273",
"Score": "12",
"body": "\"presenting himself as tutor (for what he asks money at phpu.cc)\" - This could have been mentioned in your initial post. I would have been a bit more harsh in my review. There is a difference in asking for a personal project review, and asking for a review to prove you are capable of being a tutor. If you had asked the later, I would have informed you that this code is not acceptable. Not bad, but not nearly good enough to be passing off as instructive, nor to be charging for, no matter your Zend scores. Certification is no replacement for experience or good practice."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-02T03:06:38.163",
"Id": "30753",
"Score": "0",
"body": "@mseancole Whatever. It is good enough to pass on to others. Far good enough and better than virtually all the bad and/or outdated PHP cruft out there."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-21T21:59:01.450",
"Id": "31740",
"Score": "3",
"body": "@TheodoreR.Smith: Comments like that are the reason there is so much \"bad and/or outdated PHP cruft out there\"."
}
] |
[
{
"body": "<p>Are you a horrible programmer...no probably not. </p>\n\n<p>Is there room for improvement? There usually is.</p>\n\n<p>here's my two cents: I see one factory class, but then you have a whole-lotta creation work going on throughout the rest of your code <code>new fMoney</code>, <code>new TaxBracketManager</code>, <code>new TaxBracket</code>, etc... </p>\n\n<p>When you hard code these dependencies into your methods how can you test them? What if you needed to inject a Stub/Mock/Spy into your code to verify some conditional logic is actually executed; or executed in a specific manner? What if you needed to inject a Saboteur into you code to validate your failure points and ensure your code dies gracefully? Continue down your path w/ Dependency Injection and you can work to make this better. If you're having a hard time trying to figure out how to remove these, then maybe look into an <a href=\"http://www.giorgiosironi.com/2010/01/practical-php-patterns-abstract-factory.html\">abstract factory pattern</a>.</p>\n\n<p>Speaking of DI and Factories, your <code>USFederalTaxesFactory</code> instantiates a copy of your <code>USFederalIncomeTax</code> object but never passes in the fourth parameter, <code>$bracketManager</code>. Two things wrong I see here: You're doing \"<a href=\"http://misko.hevery.com/code-reviewers-guide/flaw-constructor-does-real-work/\">work</a>\" in the constructor every single time you call this factory b/c it does a conditional check (big no-no) to see if the object is NULL, then does more \"work\" by creating a new object (another big no-no) since it evaluates to true every single time - just pass in what you want to pass in.</p>\n\n<p>For example, <code>FedTaxes</code>, should have each of those five <code>fMoney</code> objects created outside of it and passed in as parameters and set on those object properties.</p>\n\n<pre><code>new FedTaxes(new fMoney(0, 'USD'), new fMoney(0, 'USD'), new fMoney(0, 'USD'), new fMoney(0, 'USD'), new fMoney(0, 'USD'));\n\nclass FedTaxes\n{\n /** @var fMoney */\n public $income;\n /** @var fMoney */\n public $ssi;\n /** @var fMoney */\n public $medicare;\n /** @var fMoney */\n public $unemployment;\n /** @var fMoney */\n public $total;\n\n public function __construct(fMoney $income, fMoney $ssi, fMoney $medicare,\n fMoney $unemployment, fMoney $total)\n {\n $this->income = $income;\n $this->ssi = $ssi;\n $this->medicare = $medicare;\n $this->unemployment = $unemployment;\n $this->total = $total;\n }\n}\n</code></pre>\n\n<p>Strive to write <a href=\"http://misko.hevery.com/code-reviewers-guide/\">testable code</a> and you will find the by-product is cleaner more loosely coupled objects that you can reuse more easily and maintain exponentially easier.</p>\n\n<p>Also, it looks like your tax classes <code>UnemploymentTax</code>, <code>MedicareTax</code>, etc.. are a good use for the Strategy Design Pattern. What was your reason to make the tax rates of these classes methods instead of class constants? ie: <code>CONST TAX_RATE = 0.0145</code>. These seem like prime candidates for a constant to me.</p>\n\n<p>...thats just a few quick things that popped out at me, hopefully you can take something away from it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-10T08:42:17.133",
"Id": "25083",
"Score": "0",
"body": "+1 Thank you for all of your suggestions. I've implemented almost all of your suggestions. You can see them at http://bazaar.launchpad.net/~theodore-phpexperts/phpu-training/trunk/view/head:/5.tax-calc/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-11T00:49:21.497",
"Id": "25140",
"Score": "7",
"body": "@veilig , you might reconsider your answer, since this individual is actually presenting himself as tutor (for what he asks money at phpu.cc), and the post in CodeReview was [to prove](http://www.reddit.com/r/PHP/comments/zn8pc/codeathon_4_hour_livecast_coding_sprint_time/) how good he is to reddit's `/r/PHP` community."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-11T01:49:06.047",
"Id": "25141",
"Score": "0",
"body": "Yes, please consider your answer. Is it good enough for teaching beginners, as opposed to the best and brightest of /r/php?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-13T03:45:16.593",
"Id": "25275",
"Score": "3",
"body": "@TheodoreR.Smith That one is easy...teaching beginners the right way to do things is _especially_ important because you otherwise create an incorrect first impression. Unfortunately, you did a great job of making a bad first impression of PHP on anyone who took this at face value. As for \"the best and brightest of /r/php\"...why would they be using an introductory tutorial?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-11T07:15:27.627",
"Id": "29428",
"Score": "0",
"body": "@Lusitanian I would **love** to see ANY training code that is substantially better than the code I've written. Why? So I can feel better about the state of things. Frankly, I don't think I've ever seen any training code that is anywhere near as good as what I posted."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-28T01:09:27.333",
"Id": "476969",
"Score": "0",
"body": "In 8 years, no one has ever shown me better training material."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-04T04:32:54.930",
"Id": "15313",
"ParentId": "15307",
"Score": "18"
}
},
{
"body": "<p>Veilig is right and made some very good points +1. There's nothing \"horrible\" about this code. Everyone can stand to use some improvement somewhere, even professionals. So saying this is \"horrible\" is just naive and immature. Don't listen to anyone with such negative criticism, especially if they aren't willing to explain themselves. Even constructive criticism should be taken with a grain of salt. Criticism is good to learn from, but you shouldn't let it dictate how you do something. Take note of it, do your own research, and come to your own conclusions. Especially mine :) That being said, here's some more research for you.</p>\n\n<p>Comments are good, but should not be excessive, should not be useless, and their placement is important too. Upon first scanning this code I did not realize you had code between your first comment blocks, I thought that was just a long introductory comment. This would have been easier to spot if you were using the proper comment syntax for multiline comments (see below). Similarly, you should not have comments inside you methods, use PHPDoc comments to explain what needs to be explained and let your code explain the rest. Especially don't have comments INSIDE your parameter lists as this makes them hard to read and could cause confusion. As for useless comments, don't have a comment just to be witty. There were a couple of these and they just distract from the code. Example <code>// I **LOVE** our complicated corporate income tax system!! WOOO!!!!!</code>. This right here would make other programmers think you are immature and might be why someone might throw this kind of insult at you. Not saying they are right to do so, just that I've seen people get bashed for less.</p>\n\n<pre><code>/* This uses my Thrive framework, which extends\n the Flourish framework.\n NOTE: Using require, or require_once has performance penalties that aren't\n necessary. If the file isn't loaded successfully, the app will crash\n anyway.\n*/\n</code></pre>\n\n<p>Speaking of PHPDoc comments, the one's you have here could use some work. You shouldn't define a doccomment in the middle of a foreach loop. At this point it isn't even a doccomment anymore. Doccomments, besides being used to documment your code, are used to interface your code with your IDE. Good doccomments allow you to easily see what is going on without needing to go to the file/method/property/class in question. Additionally, doccomments should come before the element being documented rather than after, there was at least one instance where this happened, though that was inside a method and so the doccomment was useless anyways. And, as mentioned above, they shouldn't be inside your parameter lists, I found one inside the parameter list for a foreach loop. Correct doccomments look like this:</p>\n\n<pre><code>/** Sometimes this should have a description as well\n * @var fMoney[]\n */\nprotected $taxLiabilities;\n\n/** Short Desc\n *\n * Long Description\n * @param $tax\n * @return fMoney\n * @throws LogicException\n */\npublic function getLiabilityByTax( $tax ) {\n</code></pre>\n\n<p>Incorrect:</p>\n\n<pre><code>$tax = new $taxClass();\n/** @var $tax API_Tax */\n\nforeach ($this->brackets as /** @var TaxBracket */ $bracket)\n</code></pre>\n\n<p>I don't think there is such a thing as a \"Magic Constant\" at least not in the same way that you mean. PHP has magic constants such as <code>__FILE__</code>, but a \"magic\" anything usually refers to an undefined number or string that was not set up as a variable or constant, is hardcoded into the script, and usually is untraceable or unintelligible. So, a constant, by definition, can not be \"magical\" as it has been defined and it is known where it has come from. As pointed out, that is usually how \"magic\" things are fixed. Now, your comment about moving this into its own class to fix this is concerning. A class should not <em>just</em> contain constants. If you have a number of constants you want to integrate into a system, you can set up a config file, but a class is overkill. So the <code>TaxBracket</code> class also seems a bit unjustified. The following are examples of \"magical\" things I found in your code.</p>\n\n<pre><code>/*Would be better as a constant (because it shouldn't change)\nand placed into that config file I mentioned above. As it stands\nthese are just numbers. Numbers with structure, but numbers.*/\n$bracketsInfo = array(\n array('min' => 0, 'max' => 50000, 'rate' => 0.15),\n array('min' => 50001, 'max' => 75000, 'rate' => 0.25),\n array('min' => 75001, 'max' => 100000, 'rate' => 0.34),\n array('min' => 100001, 'max' => 335000, 'rate' => 0.39),\n array('min' => 335001, 'max' => 10000000, 'rate' => 0.34),\n array('min' => 10000001, 'max' => 15000000, 'rate' => 0.35),\n array('min' => 15000001, 'max' => 18333333, 'rate' => 0.38),\n array('min' => 18333334, 'max' => null, 'rate' => 0.35),\n);\n\n/*Where did \"110100\" come from? What is it? What about \"USD\"?\nThese are both magical. They came from no where and have no\nexplanation. USD should be assumed as we are talking about US\nFederal Taxes, so this should be set up as a constant or default\nparameter value.*/\nprotected function fetchMaxTaxableAmount()\n{\n return new fMoney(110100, 'USD');\n}\n\n/*Again, this would be better served as a constant. It isn't going to change\nexcept from year to year, and if your config file is set up properly it will be\neasy enough to exchange these tax brackets and rates for each year*/\nprotected function fetchTaxRate()\n{\n return 0.062;\n}\n</code></pre>\n\n<p>Make sure to clean up your debugging code from live code. There are a few instances where you still have <code>$_GET[ 'debug' ]</code> in your code, and all it is doing now is making your code harder to read because of the bulk these statements add. I understand this was done in a livecast and maybe you got cut off short, but this still stands.</p>\n\n<p>Finally, make sure you separate your code logically into different files. I can't tell from this post, but from the looks of it, some of this code appears to be grouped into the same file. Each class should be in its own file. Each interface in its own. Configuration settings, such as setting the include path, should be done in the config file, or in the HTML file in which this code is called.</p>\n\n<p>I hope this helps!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-04T20:07:12.537",
"Id": "24858",
"Score": "0",
"body": "+1 constructive criticism should be taken with a grain of salt."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-12T23:36:42.250",
"Id": "25267",
"Score": "0",
"body": "magic constants are real: http://en.wikipedia.org/wiki/Magic_number_(programming)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-12T23:50:53.367",
"Id": "25269",
"Score": "0",
"body": "@TheodoreR.Smith: I don't know if you were trying to say magic constants weren't real, but just in case: http://php.net/manual/en/language.constants.predefined.php"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-12T23:58:50.437",
"Id": "25270",
"Score": "0",
"body": "Oh, I see... Its been a while since I wrote this and that link didn't prove anything, so I found it confusing. Still my link is more pertinent to magic constants as how they apply to PHP."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-04T15:27:15.207",
"Id": "15323",
"ParentId": "15307",
"Score": "13"
}
},
{
"body": "<p>People who want to teach other should not write code like this.</p>\n\n<ol>\n<li><p>Not even slightest indication that you understand what <strong>Separation of Concerns</strong> is. The pattern that you are using is called <a href=\"http://c2.com/cgi/wiki?BigBallOfMud\">Big Ball of Mud</a>. You have everything in the same file.</p></li>\n<li><p>No understanding of HTML. The code you wrote is not valid, it uses tables for layout and completely ignores semantics.</p></li>\n<li><p>Code is tightly coupled. Instead of using dependency injection, you have sprinkled <code>new</code> operator all over the codebase.</p></li>\n<li><p>Why have you written an interface if you never use it ?</p></li>\n<li><p>Pointless use of static factory antipattern.</p></li>\n<li><p>Computation in the constructors making them virtually untestable.</p></li>\n<li><p>Long methods with high cyclomatic complexity.</p></li>\n<li><p>Hardcoded values in almost every class violating OCP.</p></li>\n<li><p>Two classess with not behavior: <code>TaxBracket</code> and <code>FedTaxes</code>. And some magical <code>fMoney</code> class which has never been defined.</p></li>\n</ol>\n\n<p>Basically , if someone handed this to me as a homework, I would give C. Code demonstrates knowledge of language structures, but no understanding of underlying principles and practices.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-10T14:33:27.950",
"Id": "25099",
"Score": "15",
"body": "\"People who want to teach other should not write code like this.\" <-- this! If you want to teach at least teach it correctly. Especially if you call yourself an expert."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-11T01:50:50.553",
"Id": "25142",
"Score": "0",
"body": "So you can do better coding on the spot in front of a live audience? I'd like to watch with my own eyes. Not being arrogant, I just want to witness such awesomeness."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-11T01:59:12.570",
"Id": "25145",
"Score": "0",
"body": "Average Method Length (NCLOC): 15\n Cyclomatic Complexity / Number of Methods: 1.91\nWhere are those \"long lines and high cyclomatic complexity\", buddy?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-11T02:09:52.137",
"Id": "25146",
"Score": "0",
"body": "Forget about perfection and ask yourself, \"Is this code better than what I can find in most books and tutorials?\" If so, you should not be hating against someone who's honestly just trying to help his fellow human out by helping take years off their learning curves."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-11T02:22:21.907",
"Id": "25147",
"Score": "21",
"body": "I am talking about `USFederalIncomeTax::calculateTaxLiability()` - complexity 9, lines ~50 and `getTaxLiability()` - complexity 7, lines ~50 , **buddy**. And you seem a bit confused about the goal of *CodeReview* site. Most of people, when posting code here, understand, that the code will be criticized. Otherwise it would be named *PraiseMyAwesomeness*. And .. I'm not sure how to tell you this .. but teaching is not a form of freestyle improvisation. You are *supposed to* prepare and plan beforehand. Then again, one is also supposed to have extensive understanding of the subject .."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-11T03:01:10.293",
"Id": "25149",
"Score": "0",
"body": "When one removes the debug information, it's less than 33 lines, total. When you count only active lines, it's merely 21 lines. http://pastie.org/4699422 How is that so bad? Federal taxes are pretty complex..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-11T17:34:25.227",
"Id": "25186",
"Score": "3",
"body": "Which is why you shouldn't jam large parts of the calculation into one method."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-11T21:21:42.043",
"Id": "25195",
"Score": "0",
"body": "@Lusitanian what is why?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-11T21:25:09.107",
"Id": "25196",
"Score": "0",
"body": "\"Federal taxes are pretty complex...\""
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-13T17:25:19.120",
"Id": "25323",
"Score": "0",
"body": "@Lusitanian I'm sorry, but your circular reasoning hasn't helped me any."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-13T18:00:45.147",
"Id": "25326",
"Score": "0",
"body": "@TheodoreR.Smith Federal taxes are complex. Large chunks of complex processes shouldn't be jammed into one method."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-02T03:08:17.307",
"Id": "30754",
"Score": "0",
"body": "@Lusitanian it's not. it's 20 active lines of code. If you think **that** is complex, I honestly feel sorry for you."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-10-20T17:16:01.303",
"Id": "198676",
"Score": "2",
"body": "(Late to the thread.) Just a line count has nothing to do with complexity, although for my money, 20 lines *is* too long for a single method. The ultimate issue I have is that you asked for constructive criticism and when you get it you sound defensive and \"let's see you do any better!\" which seems like the exact opposite of what I'd expect when someone asks for constructive criticism. You can disagree, of course. But why ask for information if you're just going to lash out against it?"
}
],
"meta_data": {
"CommentCount": "13",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-10T14:18:52.293",
"Id": "15481",
"ParentId": "15307",
"Score": "25"
}
},
{
"body": "<blockquote>\n <p>Looking at this code, would you say I'm an OK coder?</p>\n</blockquote>\n\n<p>Yes, I would say that you are an <em>OK</em> coder even though there are some fairly egregious issues with the code you've presented.</p>\n\n<p>Everyone has to start somewhere and I personally love teaching others how to get better and to become better multi-discipline programmers. This generally has the nice side-effect of making one a better coder.</p>\n\n<p>At the end of the day, the world doesn't need <strong>YASPT</strong> (yet another s***y PHP tutorial).</p>\n\n<blockquote>\n <p>I just created this during a live screencast. The people who were on\n there were very very very critical of almost every line of code. They\n say I am a horrible coder and know nothing.</p>\n</blockquote>\n\n<p>A couple things:</p>\n\n<ul>\n<li>I would recommend that if you are charging people for this, you do some preparation. To teach beginners bad practices and wave it off under the guise of \"doing it on the fly\" is disrespectful, unprofessional, and unethical.</li>\n<li>If you really want to continue, you should study the methods of true professionals such as <a href=\"https://www.destroyallsoftware.com/screencasts\" rel=\"nofollow\">Gary Bernhardt</a> and <a href=\"https://peepcode.com/\" rel=\"nofollow\">Geoffrey Grosenbach</a>.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-10T20:25:33.920",
"Id": "20397",
"ParentId": "15307",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "15313",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-03T20:06:41.493",
"Id": "15307",
"Score": "13",
"Tags": [
"php",
"php5",
"finance"
],
"Title": "Heavily-criticized tax calculator"
}
|
15307
|
<p>So I'm writing an abstraction layer that wraps a telephony RESTful service for sending text messages and making phone calls. I should build this in such a way that the low-level provider, in this case Twilio, can be easily swapped without having to re-code the higher level interactions.</p>
<p>I'm using a package that is pre-built for Twilio and so I'm thinking that I need to create a wrapper interface to standardize the interaction between the Twilio service package and my application. Let us pretend that I cannot modify this pre-built package.</p>
<pre><code><?php
namespace Telephony;
class Provider_Twilio implements Provider_Interface {
public function send_sms(Provider_Request_SMS $request) {
if (!$request->is_valid())
throw new Provider_Exception_InvalidRequest();
$sms = \Twilio\Twilio::request('SmsMessage');
$response = $sms->create(array(
'To' => $request->to,
'From' => $request->from,
'Body' => $request->body
));
if ($this->_did_request_fail($response)) {
throw new Provider_Exception_RequestFailed($response->message);
}
$response = new Provider_Response_SMS(TRUE);
return $response;
}
private function _did_request_fail($api_response) {
return isset($api_response->status);
}
}
</code></pre>
<p>The idea is that I can write another file like this for any other telephony service provided that it implements <code>Provider_Interface</code> making them swappable. Here are my questions:</p>
<ol>
<li>Do you think this is a good design? How could it be improved?</li>
<li>I'm having a hard time testing this because I need to mock out the Twilio package so that I'm not actually depending on Twilio's API for my tests to pass or fail. Do you see any strategy for mocking this out?</li>
</ol>
|
[] |
[
{
"body": "<p>In circumstances like you have here; the almost lowest level layer wrapping a dependency, it can be hard to see another layer lower to allow abstraction, but remember this: The lowest level wrapper of a dependency is a literal straight pass-through.</p>\n\n<p>This means, if you take the twilio api and create a direct correlary that simply passes-through everything to the twilio api, then that wrapper is the lowest level wrapper and therefore bears no need of testing at the unit level (testing at the integration and build-verification levels however is worth while) as it has no actual functionality.</p>\n\n<p>If you create such a wrapper, you may then pass in a mock of it to your next-level-up which is your provider here.</p>\n\n<p>So i guess there are two rules I'm stating here, and glad to hear people give points for or against:</p>\n\n<ul>\n<li>The lowest level wrapper possible of external dependencies is a direct pass-through (which feels stupid and tedious when writing it, but actually serves a purpose)</li>\n<li>The lowest level wrapper of an external dependency has no need of testing at the unit level as it maintains no testable functionality, but should be tested at the integration and build-verification levels as well as all external dependencies should.</li>\n</ul>\n\n<p>Also, for your particular case and similar ones, you have an obvious default implementation of the dependency that you will be wrapping so feel free to have a default constructor so its consumer's do not need to construct the twilio wrapper, while maintaining the ability for the twilio wrapper to be settable for the unit tests. Sometimes making the accessibility of these setters protected enough that consumers will not think it's ok to change it, while accessible enough for proper unit testing can be tricky; I tend to treat those situations with a use your best-judgement approach.</p>\n\n<p>Edit:\nI would unit test the Provider_Interface. Though that's one man's opinion, many people would say unit testing at this level is stupid, I maintain that where there is functionality, which your Provider_Interface has, there may be bugs. You could have a typo in 'SmsMessage' for instance, and therefore should unit test for these things. However I acknowledge there is much disagreement in industry about the ROI on unit testing at this level, or maintaining pass-through wrappers for such purpose as I am advocating.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-03T19:25:59.407",
"Id": "24815",
"Score": "0",
"body": "So what you're saying is that unit testing the low-level wrapper around the Twilio package is not necessary, but I should unit test the layer that uses `Provider_Interface` instead?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-03T19:28:36.530",
"Id": "24816",
"Score": "0",
"body": "@JesseBunch You're almost there; you missed the part about the lowest level wrapper is a *pass-through* which the code listed here is not. a pass-through has zero functionality, merely mimicing the external dependencie's API so that said API can be faked. Said pass-through would not check inputs or do any form of functionality whatsoever. This is where I was saying, it's hard to see there is another layer lower to allow abstraction, one below what you have."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-03T19:41:59.520",
"Id": "24817",
"Score": "0",
"body": "Gotcha. So, since I cannot modify the Twilio Package, I should create the pass-thru wrapper which can then be mocked and thus responses can be faked. Did I get it this time?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-03T20:04:05.470",
"Id": "24818",
"Score": "0",
"body": "@JesseBunch Yep :)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-03T19:23:13.120",
"Id": "15309",
"ParentId": "15308",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "15309",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-03T19:09:33.397",
"Id": "15308",
"Score": "5",
"Tags": [
"php",
"design-patterns",
"unit-testing",
"mobile"
],
"Title": "Wrapping a telephony RESTful service for sending text messages and making phone calls"
}
|
15308
|
<p>I needed a class where I could store an instance of any type. The goal was an interface as follows:</p>
<pre><code>class TypeMap {
template<typename T>
T& get();
};
</code></pre>
<p>Such that:</p>
<ul>
<li>Iff <code>&m1 == &m2</code> then <code>&m1.get<T>() == &m2.get<T>()</code>. </li>
<li>The first call to <code>m.get<T></code> for all <code>m</code>, <code>T</code> combinations returns a reference to a default-constructed <code>T</code>.</li>
<li>A <code>TypeMap</code> going out of scope deallocates all memory that was accessible through it.</li>
</ul>
<p>Here is my solution:</p>
<pre><code>#pragma once
// Note to CR.SO: Provides the ASSERT macro.
#include "assert.hpp"
#include <boost/utility.hpp>
#include <set>
//! A map of types to values.
//!
//! Associative container which allows mapping of types to values of that
//! type.
class TypeMap : boost::noncopyable {
template<typename T>
class TypeMapDetail {
struct Node : boost::noncopyable {
Node(void* key, Node* parent) : key(key), lhs(), rhs(), parent(parent), data() {}
void* key;
Node* lhs;
Node* rhs;
Node* parent;
T data;
};
Node* root;
typedef void (*destruct_func)(void*);
static void destroy_impl(void* p) {
delete static_cast<Node*>(p);
}
destruct_func destroy;
// No member data past this point.
Node*& get_parent_to_this(Node* current) {
if (!current->parent)
return root;
if (current->parent->lhs == current)
return current->parent->lhs;
else
return current->parent->rhs;
}
void remove_specific(Node* current) {
Node*& parent_to_this = get_parent_to_this(current);
if (!current->lhs && !current->rhs) {
parent_to_this = nullptr;
return;
}
if (!current->lhs) {
parent_to_this = current->rhs;
current->rhs->parent = current->parent;
return;
}
if (!current->rhs) {
parent_to_this = current->lhs;
current->lhs->parent = current->parent;
return;
}
Node* replacement = current->lhs;
while (replacement->rhs)
replacement = replacement->rhs;
replacement->parent->rhs = replacement->lhs;
replacement->lhs->parent = replacement->parent;
parent_to_this = replacement;
current->lhs->parent = replacement;
current->rhs->parent = replacement;
replacement->lhs = current->lhs;
replacement->rhs = current->rhs;
replacement->parent = current->parent;
}
public:
static TypeMapDetail map_;
TypeMapDetail() : destroy(destroy_impl), root() {}
// Will construct if not found.
Node* retrieve(void* key) {
if (!root)
return root = new Node(key, nullptr);
Node* current = root;
while (true) {
if (key < current->key) {
if (current->lhs)
current = current->lhs;
else
return current->lhs = new Node(key, current);
} else if (key > current->key) {
if (current->rhs)
current = current->rhs;
else
return current->rhs = new Node(key, current);
} else {
return current;
}
}
ASSERT(!"Unreachable code.");
}
static T& get(TypeMap* p) {
return map_.retrieve(p)->data;
}
void remove(void* key) {
Node* current = root;
while (current) {
if (key < current->key) {
current = current->lhs;
} else if (key > current->key) {
current = current->rhs;
} else {
remove_specific(current);
destroy(current);
return;
}
}
ASSERT(!"Tried to remove a non-existent node.");
}
// Kept for debugging.
void print(Node* p) const {
if (!p)
return;
std::cerr << "(";
print(p->lhs);
std::cerr << " " << p->data << " ";
print(p->rhs);
std::cerr << ")";
}
void print() const {
print(root);
std::cerr << '\n';
}
};
std::set<void*> members_;
public:
//! Retrieve the data associated with the given type.
template<typename T>
T& get() {
members_.insert(&TypeMapDetail<T>::map_);
return TypeMapDetail<T>::get(this);
}
~TypeMap() {
struct DummyForCleaningPurposes {};
for (auto m : members_) {
auto map = static_cast<TypeMapDetail<DummyForCleaningPurposes>*>(m);
map->remove(this);
}
}
template<typename T>
static void print() {
TypeMapDetail<T>::map_.print();
}
};
template<typename T>
TypeMap::TypeMapDetail<T> TypeMap::TypeMapDetail<T>::map_;
</code></pre>
<p>I know I am currently using a simple algorithm for the binary search tree which will not auto-balance the tree. I'll take a look at fixing it once I'm sure this way will work. I'll also be splitting out the functions so that they class definition is easier to read.</p>
<p>I'm also aware that I should add a <code>const</code> getter of some sort, but I have no need for it and don't want to complicate the code any further.</p>
<p>Questions:</p>
<ul>
<li>Does what I wrote satisfy the requirements? It seems to work so far, but I'd really like to know about any issues.</li>
<li>What are some non-obvious cases of undefined behaviour here, and are they likely to cause issues in practice? I can see that treating <code>Node<T>*</code>s as <code>Node<DummyForCleaningPurposes>*</code> may break aliasing (could optimisations do anything nasty?), but perhaps there's more issues. (Layout of <code>Node<T></code> that would make the four pointers in it fail?)</li>
<li>Any stylistic issues that could be improved? Stuff that should be commented on?</li>
</ul>
|
[] |
[
{
"body": "<p>I don't see why you use <code>void*</code> as a key, when that pointer is always a <code>TypeMap*</code>.</p>\n\n<p>You could use a <code>std::map<TypeMap*, T*></code> as <code>TypeMapDetail<T></code>'s member. (Yes, <code>std::less<X*></code> is a safe total ordering, even though <code>operator<(X*, X*)</code> is undefined behavior unless within a common complete object.)</p>\n\n<p>Or if C++11 features and libraries are available, <code>std::map<NodeMap*, std::unique_ptr<T>></code> is even easier.</p>\n\n<p>I think I would approach the cleanup more like:</p>\n\n<pre><code>class TypeMap : boost::noncopyable {\n typedef void cleanup_func(TypeMap*);\n template<typename T>\n class TypeMapDetail : boost::noncopyable {\n static std::map<TypeMap*, std::unique_ptr<T> > objects;\n public:\n static T& get(TypeMap*);\n static void cleanup(TypeMap* tm) { objects.erase(tm); }\n };\n\n typedef std::map<std::type_index, cleanup_func> cleanup_map_type;\n cleanup_map_type cleanup_actions;\n\npublic:\n TypeMap() : cleanup_actions() {}\n ~TypeMap() {\n for (cleanup_map_type::iterator iter = cleanup_actions.begin();\n iter != cleanup_actions.end();\n ++iter) {\n iter->second(this);\n }\n }\n template <typename T>\n T& get() {\n cleanup_actions.insert(std::make_pair(\n std::cref(typeid(T)), &TypeMapDetail<T>::cleanup));\n return TypeMapDetail<T>::get(this);\n }\n};\n</code></pre>\n\n<p>... which doesn't involve any of that <code>static_cast</code> undefined behavior at all. If C++11 is out, <code>struct type_index</code> is fairly easy to implement.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T00:26:03.990",
"Id": "42482",
"ParentId": "15316",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "42482",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-04T11:52:41.080",
"Id": "15316",
"Score": "7",
"Tags": [
"c++",
"template-meta-programming"
],
"Title": "Type to instance map"
}
|
15316
|
<p><strong>This is the existing code. Clearly way too much is going on in this index method and furthermore it's untested (and hard to test in its current form).</strong></p>
<pre><code> def index
# @s = ""
# @now=DateTime.now
@from = params[:from]? ('01/01/'+params[:from]).to_date : '01/01/1991'.to_date
@to = params[:to]? params[:to]+'/12/31' : '2099/12/31' # + DateTime.now.year + 100.years# .year)+100.to_s).to_date
if params[:search_text_1]
@srch = params[:search_text_1]
if params[:search_text_2] # An advanced search
#
# groups...
@groups_comparison = ' and group_id in (-1'
if params[:groups]
params[:groups].each do |group_id|
@groups_comparison+= ','+group_id
end
@groups_comparison+= ')'
end
#
@srch_2 = params[:search_text_2] # May be null
@version = (params[:version].to_f) #.is_a?(Integer))? params[:version].to_i : 0 # May be 0
@version_comparison = '(version_number ' + params[:version_comparison] + ' ' + @version.to_s
if params[:include_blank_version] # If not checked doesn't pass.'
@version_comparison+= " or version_number is NULL or version_number = '' )"
else
@version_comparison+= " and version_number is not NULL and version_number <> '' )"
end
@date_comparison = ' and ((content_date is NULL) or (content_date > ' + @from.to_s + '))' #+ ' and content_date <= ' + @to.to_s + '))'
case params[:join_operator].downcase
when /and/
@conditions =
[@version_comparison + @groups_comparison + @date_comparison +
' and ((url_address LIKE ? or alt_text LIKE ?) and (url_address LIKE ? or alt_text LIKE ?))',
"%"+@srch+"%", "%"+@srch+"%", "%"+@srch_2+"%", "%"+@srch_2+"%"]
when /or/
@conditions =
[@version_comparison + @groups_comparison + @date_comparison +
' and ((url_address LIKE ? or alt_text LIKE ?) or (url_address LIKE ? or alt_text LIKE ?))',
"%"+@srch+"%", "%"+@srch+"%", "%"+@srch_2+"%", "%"+@srch_2+"%"]
end
else # Just a simple search
@conditions = ['(url_address LIKE ? or alt_text LIKE ? or version_number LIKE ?)', "%"+@srch+"%", "%"+@srch+"%", "%"+@srch+"%"]
end
else
@conditions = ''
end
@links = Link.all(:joins => :group, :order => 'groups.group_name, links.position', :conditions => @conditions)
session[:row_shading] = (params[:row_shading] == 'true') ? 'true' : 'false' rescue 'false'
session[:full_details] = (params[:full_details] == 'true') ? 'true' : 'false' rescue 'false'
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @links }
end
end
</code></pre>
|
[] |
[
{
"body": "<p>Create a model to hold all the logic and call that with parameters and have tests for the model methods:</p>\n\n<blockquote>\n <p>Unit Tests</p>\n</blockquote>\n\n<pre><code>require 'spec_helper'\n\ndescribe \"Prepare Search methods\" do\n\n describe \"PrepareSearch#start_date\" do\n\n subject { PrepareSearch.start_date('2000') }\n it { should == DateTime.new(2000,1,1) }\n\n end \n\n describe \"PrepareSearch#end_date\" do\n\n subject { PrepareSearch.end_date('2009') }\n it { should == DateTime.new(2009,12,31) }\n\n end \n\n describe \"PrepareSearch#groups\" do\n\n subject { PrepareSearch.groups(['1','2','3']) }\n it { should == \" and group_id in (-1,1,2,3)\" }\n\n end \n\n describe \"PrepareSearch#versions\" do\n\n before(:each) do \n @versions= {:version => 0, :version_comparison => '>=', :include_blank_version => true}\n end \n subject { PrepareSearch.versions(@versions) } \n it { should == \" and (version_number >= 0.0 or version_number is NULL or version_number = '' )\" }\n\n end \n\n describe \"PrepareSearch#dates\" do\n\n subject { PrepareSearch.dates(Date.new(2009), Date.new(2012) ) } \n it { should == \" and ((content_date is NULL) or( (content_date >= \\\"2009-01-01\\\") and (content_date <= \\\"2012-01-01\\\") ) )\" }\n\n end \n\n describe \"PrepareSearch#basic_search\" do\n\n subject { PrepareSearch.basic_search(\"test\") }\n it { should == [\"(url_address LIKE ? or alt_text LIKE ? or version_number LIKE ?)\",\"%test%\",\"%test%\",\"%test%\"] }\n\n end \n\n describe \"PrepareSearch#text_search\" do\n\n subject { PrepareSearch.text_search(\"tests\",\"or\",\"rs\") }\n it { should == \" and ( (url_address LIKE \\\"%tests%\\\" or alt_text LIKE \\\"%tests%\\\" or version_number LIKE \\\"%tests%\\\") or (url_address LIKE \\\"%rs%\\\" or alt_text LIKE \\\"%rs%\\\" or version_number LIKE \\\"%rs%\\\") )\" }\n\n end \n\nend\n</code></pre>\n\n<blockquote>\n <p>New Model \"PrepareSearch\"</p>\n</blockquote>\n\n<pre><code>class PrepareSearch\n\n def self.start_date(start_year)\n (start_year + '/01/01').to_date\n end \n\n def self.end_date(end_year)\n (end_year + '/12/31').to_date\n end \n\n def self.groups(groups=[])\n @groups_comparison= ' and group_id in (-1'\n groups.each do |group_id|\n @groups_comparison << ','+group_id\n end \n @groups_comparison+= ')' \n end \n\n def self.versions(version_information={} )\n @version = version_information[:version].to_f\n @version_comparison = ' and (version_number ' + version_information[:version_comparison] + ' ' + @version.to_s\n if version_information[:include_blank_version]\n @version_comparison+= \" or version_number is NULL or version_number = '' )\"\n else\n @version_comparison+= \" and version_number is not NULL and version_number <> '' )\"\n end \n end \n\n def self.dates(from, to) \n @from= from\n @to= to\n ' and ((content_date is NULL) or( (content_date >= \"' + @from.to_s + '\") and (content_date <= \"' + @to.to_s + '\") ) )'\n end \n\n def self.text_search(words_1,comparison_operator='',words_2='')\n @words_1 = words_1\n @words_2 = words_2\n @comparison_operator= comparison_operator\n if @words_2.length > 0 \n @text_search = ' and ( (url_address LIKE \"%'+@words_1+'%\" or alt_text LIKE \"%'+@words_1+'%\" or version_number LIKE \"%'+@words_1+'%\") '\n @text_search+= @comparison_operator\n @text_search+= ' (url_address LIKE \"%'+@words_2+'%\" or alt_text LIKE \"%'+@words_2+'%\" or version_number LIKE \"%'+@words_2+'%\") )'\n else\n ' and (url_address LIKE \"%'+@words_1+'%\" or alt_text LIKE \"%'+@words_1+'%\" or version_number LIKE \"%'+@words_1+'%\")'\n end \n end \n\n def self.basic_search(words)\n @words = words\n @conditions = ['(url_address LIKE ? or alt_text LIKE ? or version_number LIKE ?)', \"%\"+@words+\"%\", \"%\"+@words+\"%\", \"%\"+@words+\"%\"]\n end \n\nend\n</code></pre>\n\n<blockquote>\n <p>Refactored index action</p>\n</blockquote>\n\n<pre><code> def index\n @from = PrepareSearch.start_date(params[:from] ||= '1991')\n @to = PrepareSearch.end_date(params[:to] ||= '2299')\n\n if params[:search_text_1st_phrase] # both simple and advanced search use this field.\n @words_1 = params[:search_text_1st_phrase]\n if params[:commit].downcase == 'advanced search'\n @join_operator = params[:join_operator].downcase\n @words_2 = params[:search_text_2nd_phrase]\n @text_search = PrepareSearch.text_search(@words_1, @join_operator, @words_2)\n @groups_comparison = PrepareSearch.groups(params[:groups])\n @version_information = { :version => params[:version], :version_comparison => params[:version_comparison], :include_blank_version => params[:include_blank_version] }\n @version_comparison = PrepareSearch.versions(@version_information) \n @date_comparison = PrepareSearch.dates(@from, @to)\n @conditions = '1=1' + @groups_comparison+ @version_comparison+ @date_comparison + @text_search\n else\n @conditions = PrepareSearch.basic_search(@words_1)\n end \n else\n @conditions = ''\n end \n @links = Link.all(:joins => :group, :include => :group, :order => 'groups.group_name, links.position', :conditions => @conditions)\n session[:full_details] = (params[:full_details] == 'true') ? 'true' : 'false' rescue 'false'\n respond_to do |format|\n format.html\n end \n end \n</code></pre>\n\n<p>Also (next steps): </p>\n\n<ol>\n<li><p>Write controller/integration tests to check actual search results for various combinations of parameters. Needs a bunch of test data. Probably at least 20 links and 4 groups for useful testing data. </p></li>\n<li><p>consider making an object for all the params and passing them to one method call.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-04T13:43:27.967",
"Id": "15319",
"ParentId": "15318",
"Score": "3"
}
},
{
"body": "<p>There is an easy way to use <em>join</em> and a function to take away the complexity of an <em>in</em> clause concatenation so that the following:</p>\n\n<pre><code>@groups_comparison = ' and group_id in (-1'\nif params[:groups]\n params[:groups].each do |group_id|\n @groups_comparison+= ','+group_id\n end \n @groups_comparison+= ')' \nend \n</code></pre>\n\n<p>can be rewritten as:</p>\n\n<pre><code>def comparison_section group_ids\n return if group_ids.nil?\n\n groups_comparison + \"and group_id in (-1, #{group_ids.join(',')} )\"\nend\n</code></pre>\n\n<p>Also, in general, a good way to test things is to put them into functions with parameters\nso:</p>\n\n<pre><code>def format_from\n params[:from]? \"01/01/#{params[:from]}\".to_date : '01/01/1991'.to_date\nend\n</code></pre>\n\n<p>would be harder to test than</p>\n\n<pre><code>def format_from(from)\n from ? \"01/01/#{from}\".to_date : '01/01/1991'.to_date\nend\n</code></pre>\n\n<p>because you would need to set <em>params</em> to test the first function. Also, since the first one doesn't rely on explicitly passing arguments, the value could potentially be changed before the function *format_from* is used causing a difficult to catch bug.</p>\n\n<p>One of the reasons that you are seeing such complexity here is that SQL queries in rails just simply aren't supposed to be generated this way. Putting a query like this into a separate library or potentially as a series of scopes on your model may help in reducing some of the complexity. Also, running tests on models/libraries is less expensive time-wise than running tests on controllers.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-05T21:42:38.543",
"Id": "15366",
"ParentId": "15318",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "15319",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-04T13:43:27.967",
"Id": "15318",
"Score": "0",
"Tags": [
"ruby",
"controller"
],
"Title": "How can I refactor this oversized Ruby method into smaller bits and have unit tests for them?"
}
|
15318
|
<p>This is used to change a Cyrillic word with a stress marker into the same Cyrillic word but with the stress marker separately represented as a number. As I want to return two values I pass two parameters by reference. I assume there is at most only one stress marker per word.</p>
<p>What could I improve here?</p>
<pre><code>function seperateStress($word,&$cleanWord,&$stressLetter){
$stressLetter=-1;
$cleanWord="";
for($i=0;$i<strlen($word);$i++){
if($word[$i]=="&" ){
//echo $i."</br>";
$stressLetter=$i;
$i=$i+5;
}else{
$cleanWord .=$word[$i];
//echo $word[$i].":".$i."</br>";
}
}
//return array($cleansedWord,$stressedLetter);
}
//Sample Test run
$stressWord= "велосипе́ды";
$noStressWord="";
$stressLetter=-1;
seperateStress($stressWord,$noStressWord,$stressLetter);
echo $noStressWord."::".$stressLetter."</br>";
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-06T08:34:16.707",
"Id": "24919",
"Score": "0",
"body": "It appears that I have found another solution to the problem. I stumbled across php's multibyte string functions and I am thus able to avoid using this implementation myself. Great :)"
}
] |
[
{
"body": "<p>Normally I would look at the PHP manual and make sure you aren't recreating a function that already exists, but I have no experience with non ASCII characters so i don't feel comfortable with the terminology to look this up. I would suggest that you make sure of this though. This sounds like something that might already exist somewhere. As to your function, there are a few things that jumped out at me.</p>\n\n<p>First are those references. They are a powerful tool, but I would be careful using them. They are relatively difficult to spot and not everyone knows what they do. Sometimes its better just to use plain return statements, but that is something you will have to decide based on the scope of this project. If its something that isn't likely to be used by others, then this is fine, otherwise you might think about changing it.</p>\n\n<p>When incrementing a variable by more than one, a more elegant way of doing so is by using the following syntax. By the way, where did the five come from? Unless cyrillic always has three digit entities, then you run the risk of missing some of the escape sequence. For example <code>nbsp</code> is a four digit entity. I would use <code>strpos()</code> or something similar to find the position of the semicolon instead.</p>\n\n<pre><code>$i += 5;\n</code></pre>\n\n<p><code>$stressLetter</code> and <code>$cleanWord</code> definitions are redundant. You set them to the same values before the function was called. The only reason this would be necessary is if you revert back to using a return value instead of references, and then you should remove those parameters from the parameter list and from the procedural code before the function call.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-04T17:04:05.917",
"Id": "24850",
"Score": "0",
"body": "Thank you for the response. The reason I increment by five is because the string is something like врфвра†вфыврю. On locating the ampersand I have found the stress marker and know I can skip the next few characters to get to the в. The reason the variables appear again is because I wanted to make sure they are null to start with as they are passed in as referecnes. I am using references because I wanted to return two values. Nobody else will look at this code I do not think. It's just for a pet project that I am doing in my own time."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-05T11:28:51.320",
"Id": "24867",
"Score": "0",
"body": "If you wan't to return two values then return an array as you have commented out."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-04T16:35:02.150",
"Id": "15328",
"ParentId": "15321",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "15328",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-04T15:25:56.890",
"Id": "15321",
"Score": "3",
"Tags": [
"php"
],
"Title": "Modifying stress markers in Cyrillic words"
}
|
15321
|
<pre><code>(!empty($student->former_name) ? print $student->former_name : '');
</code></pre>
<p>I only want to print out the former name if it is not empty, nothing else.</p>
<p>I imagine I do not need the else part of it, but I do not know how to do it like that without the else.</p>
<p>I want to shorthand this:</p>
<pre><code>if(!empty($student->former_name))
print $student->former_name;
</code></pre>
|
[] |
[
{
"body": "<p>Why not just</p>\n\n<pre><code>echo $student->former_name\n</code></pre>\n\n<p>If its empty, it will be an empty string and thus the same thing. There is no way to remove the else from a ternary statement. The only other way to write that would be like so:</p>\n\n<pre><code>echo empty( $student->former_name ) ? '' : $student_former_name;\n</code></pre>\n\n<p>Edit: Actually, I sort of lied above, you could remove the empty check altogether.</p>\n\n<pre><code>echo $student->former_name ? $student->former_name : '';\n</code></pre>\n\n<p>And of course, if your PHP version is >= 5.3, then you could use short ternary, assuming that your statement returns the same value that your if section should return.</p>\n\n<pre><code>echo $student->former_name ?: '';\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-04T15:53:07.663",
"Id": "24842",
"Score": "0",
"body": "I needed to append the former name within parentheses, I did not include them originally for simplicity. Your second option looks better, thanks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-04T16:41:58.020",
"Id": "24848",
"Score": "0",
"body": "@Brad: Edited comment, for 5.3 used to having to do things for 5.2."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-04T15:51:27.433",
"Id": "15325",
"ParentId": "15324",
"Score": "7"
}
},
{
"body": "<p>The simplest way to do this would be:-</p>\n\n<pre><code>if(!empty($student->former_name)) print $student->former_name;\n</code></pre>\n\n<p>The way you are using the ternary statement there is inappropriate, which is illustrated by your difficulty in using it.</p>\n\n<p>Your ternary statement is harder to read, is no shorter, so my advice would be to go with the single line if statement.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-05T13:06:48.997",
"Id": "15345",
"ParentId": "15324",
"Score": "1"
}
},
{
"body": "<p>Please find few alternatives below:</p>\n\n<pre><code>print @$a->b; // @ will ignore the PHP notices\n$a->b && print $a->b; // This version could generate some PHP notices.\n!empty($a->b) && print $a->b;\necho !empty($a->b) ? $a->b : NULL;\nprint !empty($a->b) ? $a->b : NULL;\n!empty($a->b) ? print $a->b : NULL;\nif (!empty($a->b)): print $a->b; endif;\nif (!empty($a->b)) print $a->b;\n</code></pre>\n\n<p>Note: Instead of <code>NULL</code> you still can use <code>''</code>. <code>$a->b</code> in your case it's the same as <code>$student->former_name</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-25T09:51:01.060",
"Id": "58027",
"ParentId": "15324",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "15325",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-04T15:37:03.790",
"Id": "15324",
"Score": "3",
"Tags": [
"php"
],
"Title": "Print out a student's former name if it is not empty"
}
|
15324
|
<p>I have just finished another page of my project and everything is working just great with the following code example. </p>
<p>My first concern is whether you could recommend something to make my code look more beautiful or probably more secure? As I have no user input, I suppose this code can not be <a href="https://stackoverflow.com/questions/11939226/sql-injections-and-adodb-library-general-php-website-security-with-examples">SQL injected</a>? For connecting to MySQL I use latest ADOdb. I also use pagination class as you will see below (but I didn't attach it here but it's already OO based).</p>
<p>My second question is if I must switch, this style of codes to OO style. I don't really understand why should I use OO so far, because, I have separate file for functions, I never repeat my self (stay "<a href="http://en.wikipedia.org/wiki/Don%27t_repeat_yourself" rel="nofollow noreferrer">DRY</a>"), as a result, by editing on functions it will change behavior of hundreds of other files? If you have reasons for me to use OO could you please emphasize them and could you please provide the converted working version of my code in OO so I colud study on it and compare it with my code as it's something I wrote and know thoroughly?</p>
<p>Thank you very much in advance,<br>
Ilia</p>
<pre><code>require( 'config.php' );
require( 'function.php' );
$active = ( $config[ 'approve' ] == '1' ) ? " AND v.active = '1'" : NULL;
$page = ( isset( $_REQUEST[ 'page' ] ) && is_numeric( $_REQUEST[ 'page' ] ) ) ? $_REQUEST[ 'page' ] : 1;
$sort = ( isset( $_REQUEST[ 'sort' ] ) && $_REQUEST[ 'sort' ] ) ? $_REQUEST[ 'sort' ] : NULL;
$paginate = ( isset( $_REQUEST[ 'paginate' ] ) && is_numeric( $_REQUEST[ 'paginate' ] ) ) ? $_REQUEST[ 'paginate' ] : NULL;
switch ( $sort )
{
case 'popular':
$orderBy = " ORDER BY v.viewed DESC";
break;
case 'highest':
$orderBy = " ORDER BY (like_count) DESC";
break;
case 'lowest':
$orderBy = " ORDER BY (dislike_count) DESC";
break;
case 'discussed':
$orderBy = " ORDER BY (comment_count) DESC";
break;
case 'featured':
$orderBy = " AND v.featured = 'yes' ORDER BY v.add_time DESC";
$sqlPaginationAppend = " AND featured = 'yes'";
break;
default:
$orderBy = " ORDER BY v.add_time DESC";
break;
}
switch ( $paginate )
{
case '12':
$paginationValue = '12';
break;
case '18':
$paginationValue = '18';
break;
case '24':
$paginationValue = '24';
break;
case '36':
$paginationValue = '36';
break;
case '48':
$paginationValue = '48';
break;
case '60':
$paginationValue = '60';
break;
case '96':
$paginationValue = '96';
break;
default:
$paginationValue = '12';
break;
}
$sqlPaginationAppend = ( isset( $sqlPaginationAppend ) ) ? $sqlPaginationAppend : NULL;
$sqlPaginationAppend .= " AND active = '1'";
$sql = "SELECT count(VID) AS total_videos FROM video WHERE type = 'public'" . $sqlPaginationAppend;
$ars = $conn->execute( $sql );
$total = $ars->fields[ 'total_videos' ];
$pagination = new Pagination( $paginationValue );
$limit = $pagination->getLimit( $total );
$sql =
"SELECT
v.*,
u.username,
count(DISTINCT c.comment_id) AS comment_count,
count(DISTINCT l.UID) AS like_count,
count(DISTINCT d.UID) AS dislike_count
FROM
video AS v
LEFT JOIN
users AS u ON v.UID = u.UID
LEFT JOIN
comments AS c ON v.VID = c.VID
LEFT JOIN
video_rate_likes AS l ON v.VID = l.VID
LEFT JOIN
video_rate_dislikes AS d ON v.VID = d.VID
WHERE
v.type = 'public' " . $active . "
GROUP BY
v.VID
" . $orderBy . "
LIMIT "
. $limit;
$rs = $conn->execute( $sql );
$videos = $rs->getrows();
$paginate ? $paginate .= '/' : NULL;
$pagination_url = $config['BASE_URL']. '/videos/' .$paginate. $sort. '-{#PAGE#}';
$page_link = $pagination->getPagination( $pagination_url );
$start_num = $pagination->getStartItem();
$end_num = $pagination->getEndItem();
$pagination_number = $pagination->getTotalPages();
</code></pre>
|
[] |
[
{
"body": "<p><strong>Beautifying Your Code</strong></p>\n\n<p>You could start by dropping some of these parenthesis. This is purely a stylistic choice, but I view it like this: The more parenthesis there are, the harder the code is to read, especially if nesting parenthesis. If the parenthesis are necessary and numerous (more than one pair per line honestly), then it is better to separate that line into multiple lines. I'd rather see three or four lines of clean code than one extra long line that is hard to decipher because of run-on parenthesis. A couple of examples of how you can remove some of these parenthesis from your code:</p>\n\n<pre><code>require 'config.php';\n$active = $config[ 'aprove' ] == 1 ? \" AND v.active = '1'\" : NULL;\n</code></pre>\n\n<p>By the way, in the above example, note that I removed the quotes from around the <code>1</code>. These are unnecessary. When doing a loose comparison a string value of \"1\" is the same as an integer value of <code>1</code>. Its only when we do an absolute comparisons that this kind of thing becomes important. Also, if the type isn't important from the start, then it is easier just to drop the quotes altogether, which is usually the case with numbers. PHP is very forgiving about its type conversion, so you can easily go back and forth between an integer and a string without any consequences.</p>\n\n<p>You should refrain from using the <code>$_REQUEST</code> super global. This array holds all of the other super globals and overwrites certain keys based on precedence. For example, if you had both a GET and a POST \"page\" variable then using REQUEST would return the POST version. The precedence is logical, but its better to explicitly declare from where you are expecting this value to come from in case there are issues. Additionally, no matter which super global you end up using it is always a good idea to validate and sanitize the results. You can check out PHP's <code>filter_input()</code> if your PHP version is >= 5.2.</p>\n\n<pre><code>$page = filter_input( INPUT_GET, 'page', FILTER_SANITIZE_NUMBER_INT );\n</code></pre>\n\n<p>DRY isn't just about not repeating functional code, but not repeating anything. This makes it easier to make updates should you decide to change how a certain feature is implemented. For example, that first switch is full of DRY violations. If you create a template for the <code>$orderBy</code> results, then modify the template variables in the switch, then you will more easily be able to update this code should you ever decide that ordering by descending value isn't what you want to do.</p>\n\n<pre><code>$and = '';\n$by = 'v.add_time';\n\nswitch( $sort ) {\n case 'popular' :\n $by = 'v.viewed';\n break;\n //etc...\n case 'featured' :\n $and = \" AND v.featured = 'yes'\";\n $sqlPaginationAppend = \" AND featured = 'yes'\";\n break;\n}\n\n$orderBy = \"$and ORDER BY $by DESC\";\n</code></pre>\n\n<p>What is the point of this second switch? It is extremely redundant and has too much overhead. Just set the two variables equal to each other. If you need to ensure that <code>$paginate</code> defaults to 12 if its value is too large, use a greater than comparison. If you need to do so for a list of variables, do an <code>in_array()</code> check.</p>\n\n<pre><code>$paginationValue = $paginate;\n//OR\n$paginationValue = $paginate > $max ? 12 : $paginate;\n//OR\n$whitelist = array( 12, 18, 24, 36, 48, 60, 96 );\n$paginationValue = in_array( $paginate, $whitelist ) ? $paginate : 12;\n</code></pre>\n\n<p>Of course, with the last of the above examples you start violating the rule about magic numbers, so these should actually be part of a config file as constants you have set, then you can use the <code>defined()</code> function instead of in array, but that's altogether different and is usually done when upgrading to an OOP style. Though this is still some good information and couldn't hurt to read up on.</p>\n\n<p>Instead of checking to see if a variable is set to determine if it needs a default value, just set it with the default value and override that value whenever you need to. This saves a function call and makes your code a little more natural to read.</p>\n\n<pre><code>$sqlPaginationAppend = NULL;\n//etc...\n case 'featured':\n $orderBy = \" AND v.featured = 'yes' ORDER BY v.add_time DESC\";\n $sqlPaginationAppend = \" AND featured = 'yes'\";\n break;\n//etc...\n</code></pre>\n\n<p><strong>Security</strong></p>\n\n<p>As for security, well MySQL is usually frowned upon now. A better way to go would be MySQLi or PDO. I think PDO is the more popular of the two, but I am unfamiliar with both, so I can't help you here.</p>\n\n<p><strong>OOP</strong></p>\n\n<p>It's always a good idea to adopt an OOP style for larger projects, but you have to weigh the benefits versus your project's scope. When starting a large project you have the advantage of not having developed anything yet, so you can decide what design pattern you want to implement and work towards that goal. However, you mentioned something about having hundreds of files already. Converting these all to OOP will be a huge task and may not be worth the time or effort. You have to decide if this is something that is feasible for you. I did it on one of my projects, and while it was boring and tedious as hell, the overall benefits for me were worth it. It is now much more easier to update and maintain my code, and I am still actively working on adding new features, so the OOP framework allows me to more easily add things without breaking the rest. This will also ensure that people who come after me will be able to more easily integrate into it. So you see, there are a great many things to take into account.</p>\n\n<p>By the way, it appears that you have the misconception that just because something is in a class that it is OOP. OOP is more than just classes, it is how those classes interact. It doesn't even really have to be classes. From my understanding, you can do OOP with functions as well, but conventionally, it is more commonly accepted that a class should contain OOP code. In fact, your code, at least in its separation and purpose, already resembles OOP. The only thing this is really missing is for everything to be contained within logical functions that can be reused and communicate with eachother.</p>\n\n<p>As for reworking your code into OOP for you? I'm sorry, but no. Not that I don't want to help, but that's the wrong way to go about it. My implementation may not be the right one. I would make this a Model for an MVC framework. Because that's the one I'm most familiar with and what it most resembles to me. But who's to say that this is the right one? There isn't enough code here to make a good determination. Take a look at wikipedia's article on design patterns and determine which one would best fit your needs, then read up on that pattern. If you have more questions about which one to adopt, make a couple of attempts and post them as another question about which one seems most appropriate and if you are going about it properly. Chances are there wont be a single consensus, so you'll have to make the final decision yourself.</p>\n\n<p>Sorry I couldn't answer your overall question. I hope the rest helps though.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-05T06:42:19.827",
"Id": "24863",
"Score": "0",
"body": "Thank you for the fantastic answer! I will take everything in consideration! Your writing skills are superb!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-04T22:01:30.577",
"Id": "15338",
"ParentId": "15334",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "15338",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-04T19:16:43.157",
"Id": "15334",
"Score": "2",
"Tags": [
"php",
"mysql"
],
"Title": "Procedural PHP code for showing videos on the page, sorting them in different ways. Is this good? Should it be switched to OOP?"
}
|
15334
|
<p>Here's my solution to Project Euler <a href="http://projecteuler.net/problem=40">problem 40</a>.</p>
<pre><code>import operator
import math
def levels(n):
return 9 * n * 10 ** (n - 1)
def face_value(i):
def level_filler(i):
n = 1
yield 1
while i > levels(n):
yield int(levels(n)/n * 1.0)
i -= levels(n)
n += 1
yield int(math.ceil(i / n * 1.0))
if i == 1: return 1
else:
return sum(level_filler(i))
def d(i):
j = str(face_value(i))
k = len(j)
l = sum(levels(x) for x in xrange(1, k)) + 1
m = (i-l)%k
return int(j[m])
# d(1) * d(10) * d(100) * d(1000) * d(10000) * d(100000) * d(1000000)
print(reduce(operator.mul, (d(10**i) for i in xrange(7))))
</code></pre>
<p>It answers without building the actual string, and gets the value of d(i) in (quasi-)linear time. </p>
<p>The problem is that it's messy and I feel it's not easy to read. I cannot even find proper names for my variables. </p>
<p>I was wondering if anyone could give me a code review tell me how my ideas are unclear and how can I express them better.</p>
<p><em>(I tested the code on Python 2.6)</em></p>
|
[] |
[
{
"body": "<h3>1. Bug</h3>\n\n<p>Your program contains a bug. The second digit of 123456... is 2, but:</p>\n\n<pre><code>>>> d(2)\n3\n</code></pre>\n\n<p>However, solving Project Euler problem 40 only relies on you having the correct result for <code>d(10**i)</code>, and this you got right.</p>\n\n<h3>2. Improving your solution</h3>\n\n<ol>\n<li><p>There are no docstrings, so even though I have solved Project Euler problem 40 myself, it took me a while to figure out what your functions are doing. Even if you struggle to pick good names for functions (and this can be very hard), you can always make things clearer with a brief description and some examples.</p>\n\n<p>There are also no <a href=\"http://docs.python.org/library/doctest.html\" rel=\"nofollow\">doctests</a>. Even a handful of doctests might well have found the bug.</p>\n\n<p>The discipline of writing down what each function actually does will make it easier for you to choose good names. For example, once you have written the docstring for your function <code>levels</code>, it should be clear that a better name would be something like <code>total_digits</code>:</p>\n\n<pre><code>def total_digits(n):\n \"\"\"\n Return the total number of digits among all the `n`-digit decimal\n numbers.\n\n >>> total_digits(1) # 1 to 9 (note that 0 is not included)\n 9\n >>> total_digits(2) # 10 to 99\n 180\n \"\"\"\n return n * 9 * 10 ** (n - 1)\n</code></pre></li>\n<li><p>Choosing good names for variables is particularly hard when writing mathematical code (as when solving problems from Project Euler). It's typical of mathematical code that variables contain a number whose meaning is hard to capture in a short name. Long names would end up making your code hard to read, so it's often the case that the best approach is to give your variables arbitrary names like <code>i</code>, <code>j</code>, <code>m</code>, and <code>n</code>, and to explain their meaning in longer comments.</p></li>\n<li><p>There's no need for <code>level_filler</code> to be a local function inside <code>face_value</code> (it doesn't make use of any context from <code>face_value</code>). If you moved it out to the top level then it would be easier to test it. (But in fact, it will be better just to remove it, as I will explain below.)</p></li>\n<li><p>The expression <code>int(levels(n)/n * 1.0)</code> is the same as <code>int((levels(n) / n) * 1.0)</code> since multiplication and division have the same precedence and associate from left to right. So this expression converts <code>levels(n) / n</code> to a float and then back to an int, which is pointless. Also, since <code>levels(n)</code> is <code>n * 9 * 10 ** (n - 1)</code>, when divided by <code>n</code> the result is always <code>9 * 10 ** (n - 1)</code>. It would be better to write this directly and avoid the useless multiplication by <code>n</code> followed immediately by division by <code>n</code>.</p></li>\n<li><p>Similarly the expression <code>int(math.ceil(i / n * 1.0))</code> doesn't do what you think it does: the division happens before the multiplication, so in Python 2 (where <code>/</code> truncates the result) this expression is actually the same as <code>i // n</code> and evaluates to the <em>floor</em> of the division, not the ceiling.</p></li>\n<li><p>You make three calls to <code>levels(n)</code> in succession. It would be better to make just one call and remember the result.</p></li>\n<li><p>The purpose of <code>face_value(i)</code> function is to return the number which contains the <code>i</code>th digit. This is where the bug lives:</p>\n\n<pre><code>>>> face_value(2)\n3\n</code></pre>\n\n<p>In some sense you knew that this was incorrect, because you compensate for the error with your test <code>if i == 1: return 1</code>!</p></li>\n</ol>\n\n<h3>3. A better solution?</h3>\n\n<p>My own approach to this problem would be to simplify the structure as much as possible. The function <code>levels</code> is so simple (just a single expression) that we can easily inline it into <code>face_value</code>. And then various other simplifications become possible. Here's my version of your <code>face_value</code>:</p>\n\n<pre><code>def number_containing(i):\n \"\"\"\n Return the number containing the `i`th digit in the sequence\n 123456789101112...\n\n >>> number_containing(5)\n 5\n >>> number_containing(13)\n 11\n >>> number_containing(99)\n 54\n >>> number_containing(100)\n 55\n \"\"\"\n n = 1 # Number of digits.\n first = 1 # The first n-digit number.\n count = 9 # Count of n-digit numbers.\n while True:\n # The i-th digit is in the j-th n-digit number (but not if\n # there are more than j n-digit numbers).\n j = (i + n - 1) // n\n if j <= count:\n return first + j - 1\n first += count\n i -= n * count\n n += 1\n count *= 10\n</code></pre>\n\n<p>Having computed which number contains the <code>i</code>th digit, we then have to work out which digit it is, which you do using another sum over <code>levels</code>. In fact, it is much simpler to work out which digit you want at the same time as you work out which number this digit comes from. If you look at my function above, you'll see that all the information is already present at the point where we return the result. So it's easy just to return the digit at this point:</p>\n\n<pre><code>def d(i):\n \"\"\"\n Return the `i`th digit of the sequence 123456789101112...\n\n >>> d(5)\n 5\n >>> d(15)\n 2\n >>> d(100)\n 5\n >>> sequence = ''.join(str(i) for i in xrange(1, 10001))\n >>> all(d(i + 1) == int(digit) for i, digit in enumerate(sequence))\n True\n \"\"\"\n n = 1 # Number of digits.\n first = 1 # The first n-digit number.\n count = 9 # Count of n-digit numbers.\n while True:\n # Check the loop invariants.\n assert first == 10 ** (n - 1)\n assert count == 9 * first\n\n # The i-th digit is in the j-th n-digit number (but not if\n # there are more than j n-digit numbers).\n j = (i + n - 1) // n\n if j <= count:\n return int(str(first + j - 1)[(i - 1) % n])\n first += count\n i -= n * count\n n += 1\n count *= 10\n</code></pre>\n\n<p>Note that the last doctest is quite thorough!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-05T14:45:18.623",
"Id": "15347",
"ParentId": "15336",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "15347",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-04T21:37:48.357",
"Id": "15336",
"Score": "11",
"Tags": [
"python",
"project-euler"
],
"Title": "Help me make my Python code clearer"
}
|
15336
|
<p>Very simple requirements here:</p>
<ol>
<li>connect to web service</li>
<li>check if account number exists</li>
<li>if it exists update it</li>
<li>if it does not exist create the account</li>
</ol>
<p>I have accomplished this with the code below I am wondering if this is efficient and secondly if there is a better way of doing this. </p>
<pre><code> protected void Button1_Click(object sender, EventArgs e)
{
//authentication header
com.x.w_1.www.WebService ws = new com.x.w_1.www.WebService();
com.dat_e_baseonline.w_1.www.AuthenticationHeader header = new com.x.w_1.www.AuthenticationHeader();
header.UserName = "";
header.Password = "";
ws.AuthenticationHeaderValue = header;
string email = TextBox1.Text.ToString();
//Are they a subscriber?
XmlNode result = ws.getAccountIDbyEmail(email, "247");
Label1.Text = result.OuterXml;
foreach (XmlNode x in result.FirstChild)
{
string m = x.InnerText;
string account = result.LastChild.InnerText;
switch (m)
{
case "100":
//update the account
ws.Subscribe("x", "3", account);
Label1.Text = "account exists";
break;
case "200":
//create an account
ws.createAccount("x", "5", email, "x", "x", "x", "01-01-1998", "1", "yes");
Response.Redirect("/thankyou.aspx");
break;
}
}
</code></pre>
<p>For reference here is the XML I get back when I send an email to be updated:</p>
<pre class="lang-xml prettyprint-override"><code><getAccountID:name xmlns:getAccountID="http://x">
<getAccountIDResultCode xmlns="">100</getAccountIDbyEmailResultCode>
<getAccountIDResultDescr xmlns="">Account found.</getAccountIDResultDescr>
<accountID xmlns="">12345</accountID>
</getAccountIDbyEmail:name>
</code></pre>
|
[] |
[
{
"body": "<p>I would move the operations on the web service out to their own class:</p>\n\n<pre><code>public class AccountRepository\n{\n private readonly void _webService;\n\n public AccountRepository()\n {\n //authentication header\n\n var header = new AuthenticationHeader\n {\n header.UserName = \"\";\n header.Password = \"\";\n }\n\n _webService = new WebService\n {\n ws.AuthenticationHeaderValue = header;\n }\n }\n\n public IEnumerable<AccountResult> SearchByEmail(string email)\n {\n return ConvertXmlToResultsList(_webService.getAccountIDbyEmail(email, \"247\"));\n }\n\n private IEnumerable<AccountResult> ConvertXmlToResultsList(XmlDocument xmlDocument)\n {\n // logic to convert xml to account results\n }\n\n public void UpdateAccount(/* parameters */)\n {\n _webService.Subscribe(/* parameters */);\n }\n\n public void CreateAccount(/* parameters */)\n {\n _webService.createAccount(/* parameters */\n }\n}\n</code></pre>\n\n<p>Doing this gets rid of most of the housekeeping code out of the event handler.</p>\n\n<p>I would also consider creating two classes: Account, and SearchResult.</p>\n\n<p>Account should be obvious, it contains all the functionality and data that an account requires. This would be instantiated in the Repository on the search, and also in the event handler when you need to create a new Account.</p>\n\n<p>The SearchResult class I would use to return the results of the search. It would contain the Account from the search, and the status of the search. You could also put stuff like error checking, or anything else you see as being relevant. You will also see a ResultCode variable type. ResultCode is an enum that contains all of the possible codes returned from the search.</p>\n\n<pre><code>public enum ResultCode\n{\n Error,\n UpdateAccount,\n CreateAccount,\n}\n\npublic class SearchResult\n{\n private readonly Account _account;\n private readonly ResultCode _code;\n\n public SearchResult(Account account, int resultCode)\n {\n _account = account;\n _code = DetermineCode(resultCode);\n }\n\n private static ResultCode DetermineCode(int resultCode)\n {\n switch(resultCode)\n {\n case 100:\n return ResultCode.UpdateAccount;\n case 200:\n return ResultCode.CreateAccount;\n }\n\n return ResultCode.Error;\n }\n}\n</code></pre>\n\n<p>The final result of all this is an event handler that looks like:</p>\n\n<pre><code>protected void Button1_Click(object sender, EventArgs e)\n{\n\n var results = _accountRepository.SearchByEmail(TextBox1.Text); \n\n foreach (var result in results)\n {\n switch (result.ResultCode)\n {\n case ResultCode.UpdateAccount:\n result.Account.Update(/* parameters */);\n _accountRepository.Update(result.Account);\n\n Label1.Text = \"account exists\";\n break;\n case ResultCode.CreateAccount:\n var account = new Account(\"x\", \"5\", email, \"x\", \"x\", \"x\", \"01-01-1998\", \"1\", \"yes\");\n\n _accountRepository.Create(account);\n\n Response.Redirect(\"/thankyou.aspx\");\n break;\n\n }\n }\n }\n</code></pre>\n\n<p>There are a few more points I'd like to make.</p>\n\n<p>Calling .ToString() on a .Text property of a TextBox is counterproductive. TextBox.Text returns a string, no need to make it a string.</p>\n\n<p>In your code, I would move ResultStatus magic numbers into constants. This will better describe what they represent. Of course, if you take my code suggestions, no need to worry about this.</p>\n\n<p>I don't know who wrote the web service, but the method names follow java naming conventions, not C#. This is just a btw, ignore if the web service is written in Java.</p>\n\n<p>Finally, there is quite a bit more clean-up to do on the code, even what I have posted, but this is a good start. Hopefully you can pick up some tips from it.</p>\n\n<p>Cheers.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-05T02:08:24.650",
"Id": "15341",
"ParentId": "15340",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "15341",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-04T23:51:34.737",
"Id": "15340",
"Score": "2",
"Tags": [
"c#",
"xml",
"web-services"
],
"Title": "Using XML from web service with switch"
}
|
15340
|
<p>first here is the code:</p>
<pre><code>Part 1
$('#monhpf').keyup(function()
{
/* General variable(s) */
var monhpf = $('#monhpf').val();
if(monhpf=="")
{
$('#monhpf').css('border-color',red);
$('.mondayErrors').text(emptyField).show();
}else
if(monhpf.length > 0)
{
/* Verifies the charset of the zip code */
$.post('functions/hoursCharset.php',{hoursPHP:monhpf},function(hoursCharset)
{
if(hoursCharset==true)
{
/* Charset valid*/
$('#monhpf').css('border-color',green);
$('.mondayErrors').hide();
mondayErrors = false;
}else
{
/* Charset not valid */
$('#monhpf').css('border-color',orange);
$('.mondayErrors').text(invalid).show();
mondayErrors = true;
}
});
}
});
Part 2
$('#monmpf').keyup(function()
{
/* General variable(s) */
var monmpf = $('#monmpf').val();
if(monmpf=="")
{
$('#monmpf').css('border-color',red);
$('.mondayErrors').text(emptyField).show();
}else
if(monmpf.length > 0)
{
/* Verifies the charset of the zip code */
$.post('functions/minutesCharset.php',{minutesPHP:monmpf},function(minutesCharset)
{
if(minutesCharset==true)
{
/* Charset valid*/
$('#monmpf').css('border-color',green);
$('.mondayErrors').hide();
mondayErrors = false;
}else
{
/* Charset not valid */
$('#monmpf').css('border-color',orange);
$('.mondayErrors').text(invalid).show();
mondayErrors = true;
}
});
}
});
</code></pre>
<p>As you can see part 1 and part 2 are pretty much the same except for the #monhpf and #monmpf variables. My question is, how can I improve this code to be smaller? Like in a single function for example.</p>
|
[] |
[
{
"body": "<pre><code>$('#monhpf,#monmpf').keyup(function()\n{\n var mon = $(this);\n var monValue = mon.val();\n // continue using mon\n});\n</code></pre>\n\n<p>Warning: Not Tested!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-05T18:19:36.880",
"Id": "24889",
"Score": "0",
"body": "Can you elaborate on your code snippet a bit. A description of what you are doing and why you decided to do it would be very helpful."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-05T13:06:11.377",
"Id": "15344",
"ParentId": "15342",
"Score": "0"
}
},
{
"body": "<h1>1)</h1>\n\n<p>Take advantage of javascript's truthy and falsey values.</p>\n\n<pre><code>Boolean(undefined); // => false\nBoolean(null); // => false\nBoolean(false); // => false\nBoolean(0); // => false\nBoolean(\"\"); // => false\nBoolean(NaN); // => false\n\nBoolean(1); // => true\nBoolean([1,2,3]); // => true\nBoolean(function(){}); // => true\n</code></pre>\n\n<p>More here: <a href=\"http://james.padolsey.com/javascript/truthy-falsey/\" rel=\"nofollow\">http://james.padolsey.com/javascript/truthy-falsey/</a></p>\n\n<p><code>if(monmpf == \"\")</code> => <code>if(!monmpf)</code>. </p>\n\n<p><code>if(minutesCharset == true)</code> => <code>if(minutesCharset)</code></p>\n\n<p><code>if(monhpf.length > 0)</code> => <code>if( monhpf.length )</code></p>\n\n<h1>2)</h1>\n\n<p>You can refer to the current element by using <code>$(this)</code>.</p>\n\n<pre><code>$('#monmpf').keyup(function () {\n// el refers to $(\"monmpf\")\nvar el = $(this);\n</code></pre>\n\n<h1>3)</h1>\n\n<p><code>if (monhpf.length > 0)</code> is redundant since you already checked the string value with this, <code>if(monmpf == \"\")</code>.</p>\n\n<h1>4)</h1>\n\n<p>You're using too many global variables, such as <code>emptyField</code>, <code>invalid</code>, <code>green</code>, <code>red</code>, <code>orange</code>, etc.\nTry wrapping the variables inside a meaningful namespace, like </p>\n\n<pre><code>var COLORS = { red: \"red\", green: \"green\" };\nvar MESSAGE = { invalid: \"Wrong\", emptyField: \"\" };\n</code></pre>\n\n<h1>5)</h1>\n\n<p><code>mondayErrors</code>? I think you should rename this variable.</p>\n\n<h1>6)</h1>\n\n<p>Break up functions that are longer than 8-12 lines of code into smaller ones.</p>\n\n<p>With all that said, here's what I came up with.</p>\n\n<pre><code>var getRequestObject = function (name, value) {\n var obj = {};\n switch (name) {\n case \"monhpf\":\n obj.url = 'functions/hoursCharset.php';\n obj.paramObj = {\n hoursPHP : value\n };\n break;\n case \"monmpf\":\n obj.url = 'functions/minutesCharset.php';\n obj.paramObj = {\n minutesPHP : value\n };\n break;\n }\n return obj;\n};\nvar getPostFunc = function ($el) {\n return function (isCharset) {\n mondayErrors = !isCharset;\n if (isCharset) {\n $el.css('border-color', green);\n $('.mondayErrors').hide();\n } else {\n $el.css('border-color', orange);\n $('.mondayErrors').text(invalid).show();\n }\n };\n};\n$('#monhpf, #monmpf').keyup(function () {\n var $el = $(this),\n request,\n value = $el.val(),\n id = $el.attr('id');\n\n if (value) {\n request = getRequestObject(id, value);\n $.post(request.url, request.paramObj, getPostFunc($el));\n } else {\n $el.css('border-color', red);\n $('.mondayErrors').text(emptyField).show();\n }\n});\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-05T16:48:44.643",
"Id": "15354",
"ParentId": "15342",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "15354",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-05T08:01:31.640",
"Id": "15342",
"Score": "0",
"Tags": [
"javascript",
"jquery",
"ajax"
],
"Title": "Possible redundant code improvement"
}
|
15342
|
<p>The application needs to keep a secret which is known to logged in windows user. User enters secret in windows form's text box which is read by application. This is in form of <code>System.String</code>. Now I have to persist this secret into a XML file. And later able to decipher it back and use it.</p>
<p><strong>Questions:</strong></p>
<ol>
<li>Do you see any concern with encoding done below?</li>
<li>Is there any concern with using <code>System.String</code> to begin with? I was
considering to use <code>System.Security.SecureString</code> but at some point
down the line the application needs to have base underlying string
in clear text.</li>
</ol>
<p>I'm using <code>System.Security.Cryptography.ProtectedData</code> to do the encryption.</p>
<p>The code</p>
<pre><code>using System.Security.Cryptography;
static public string Encrypt(string password, string salt)
{
byte[] passwordBytes = Encoding.Unicode.GetBytes(password);
byte[] saltBytes = Encoding.Unicode.GetBytes(salt);
byte[] cipherBytes = ProtectedData.Protect(passwordBytes, saltBytes, DataProtectionScope.CurrentUser);
return Convert.ToBase64String(cipherBytes);
}
static public string Decrypt(string cipher, string salt)
{
byte[] cipherBytes = Convert.FromBase64String(cipher);
byte[] saltBytes = Encoding.Unicode.GetBytes(salt);
byte[] passwordBytes = ProtectedData.Unprotect(cipherBytes, saltBytes, DataProtectionScope.CurrentUser);
return Encoding.Unicode.GetString(passwordBytes);
}
</code></pre>
<p>Typical usage</p>
<pre><code>[TestMethod()]
public void EncryptDecryptTest()
{
string password = "Gussme!";
string salt = new Random().Next().ToString();
string cipher = Authenticator.Encrypt(password, salt);
Assert.IsFalse(cipher.Contains(password), "Unable to encrypt");
Assert.IsFalse(cipher.Contains(salt), "Unable to encrypt");
string decipher = Authenticator.Decrypt(cipher, salt);
Assert.AreEqual(password, decipher);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-12T17:21:18.720",
"Id": "26796",
"Score": "0",
"body": "Just a small point, in cryptography unencrypted data is referred to as `clear text` and encrypted data is referred to as `cipher text`."
}
] |
[
{
"body": "<ol>\n<li>Your code is correct. I usually use Encoding.UTF8 because it is more compact for typical character sets.</li>\n<li>SecureString is kind of a useless class. It is meant to never keep a secret unencrypted even in memory. This would only help if an attacker could read your processes memory. If he can do that you have lost already because he can read every character of your password the moment you use it or add it to the SecureString. Anyway, what attack scenario on earth allows an attacker to read your webserver process memory and not do other more dangerous things at the same time? In that case your box is probably compromised entirely. So you are right not using this class.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-09-10T18:08:24.247",
"Id": "114042",
"Score": "3",
"body": "[Heartbleed](http://heartbleed.com/) for one"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-11T11:33:54.263",
"Id": "15519",
"ParentId": "15346",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-05T13:19:18.843",
"Id": "15346",
"Score": "11",
"Tags": [
"c#",
".net",
"security",
"cryptography"
],
"Title": "Using System.Security.Cryptography.ProtectedData, do you see any issue with encryption and encoding?"
}
|
15346
|
<p>I'm working on a config class for PHP, where I can easily bring in config options. Any improvements/suggestions are appreciated.</p>
<p><strong>Example usage:</strong></p>
<pre><code>echo Config::get('database.host');
// Returns: localhost
</code></pre>
<p><strong>Example config file:</strong></p>
<pre><code><?php
return array(
'host' => 'localhost',
'username' => 'root',
'password' => '',
'database' => 'example_database'
);
</code></pre>
<p><strong>The class:</strong></p>
<pre><code><?php
class Config {
/**
* All of the items from the config file that is loaded
*
* @var array
*/
public static $items = array();
/**
* Loads the config file specified and sets $items to the array
*
* @param string $filepath
* @return void
*/
public static function load($filepath)
{
static::$items = include('config/' . $filepath . '.php');
}
/**
* Searches the $items array and returns the item
*
* @param string $item
* @return string
*/
public static function get($key = null)
{
$input = explode('.', $key);
$filepath = $input[0];
unset($input[0]);
$key = implode('.', $input);
static::load($filepath);
if ( ! empty($key))
{
return static::$items[$key];
}
return static::$items;
}
}
</code></pre>
<p>I should also add that this doesn't seem to work with multidimensional arrays - I'm working on this. If anyone has a solution, I'd appreciate it.</p>
|
[] |
[
{
"body": "<p>You can continue to use a class if you want, but I think making a config class is overkill. Just a plain config file with constants should be good enough. It has less overhead and less abstraction. As for loading a specific config file, you can use a helper function to simulate what you have here, or just manually include it. Not everything has to be in a class.</p>\n\n<pre><code>echo Config::get( 'database.host' );\n//VS\necho DB_HOST;\n\n$config->load( 'config' );\n//VS\nconfig( 'config' );//helper function\n//OR\ninclude 'config/config.php';\n</code></pre>\n\n<p>I think there's something wrong with your <code>load()</code> method by the way. You are resetting the array each time you load a new config file. I believe it should look something like so.</p>\n\n<pre><code>static::$items[] = include \"config/$filepath.php\";\n</code></pre>\n\n<p>I'm not sure I really agree with setting <code>$items</code> to static. I understand you aren't instantiating the class, but I think you should, and then just make this a normal property. Typically when I think of static properties, I think of properties that aren't supposed to change, but you are adding to it, which seems contradictory. Maybe I'm wrong here, but this just seems odd to me. Of course I really just dislike the static keyword altogether.</p>\n\n<p>You can set an array element to a variable and unset it all at the same time by using <code>array_shift()</code>. For example.</p>\n\n<pre><code>$filepath = array_shift( $input );\n</code></pre>\n\n<p>It might be worth profiling that explode/implode task and comparing it to a substr version. Assuming the array version is faster, then I would suggest changing the first delimiter to something other than a period since that's the only one you care about. Maybe a forward slash or underscore instead? It would make needing to implode the array unnecessary.</p>\n\n<pre><code>$input = explode( '/', $key);\n$filepath = array_shift( $input );\n$key = strval( $input );\n</code></pre>\n\n<p>PHP <code>empty()</code> should really only be used when checking arrays. A string can be determined just by querying it. For example:</p>\n\n<pre><code>if ( $key ) {//not empty\nif( ! $key ) {//empty\n</code></pre>\n\n<p>Finally, I would think that the \"default\" return value for your getter would be NULL or FALSE. Why return the entire configuration array? This could be confusing, especially since you mentioned using multidimensional arrays. Speaking of which, what about this doesn't work for them? The config file? The getter? What exactly is happening, and what are you expecting? Besides the things I already mentioned, I don't see anything that would cause an issue.</p>\n\n<p><strong>Edit to clarify last comment:</strong></p>\n\n<p>Early check and return ensures less overhead and better legibility.</p>\n\n<pre><code>public static function get( $key = null ) {\n if( ! $key ) {\n return static::$items;\n }\n //etc...\n</code></pre>\n\n<p>I don't condone the use of variable-variables, but its the only way I can foresee doing this. Unless you can put all of those arrays into another array, then you can access them as associative arrays.</p>\n\n<pre><code>$input = explode( '.', $key );\n$filepath = array_shift( $input );\nif( count( $input ) > 1 ) {\n $array = array_shift( $input );\n $key = $$array[ strval( $input ) ];\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-05T17:58:12.693",
"Id": "24887",
"Score": "0",
"body": "Resetting the array limits the extensibility, but ok. If you want to return entire array, then you should do an early check and return if your parameter is empty. Don't implode the array if you want to use multidimensional. Check the length and if > 1 then use variable variables. However, this will make your code more difficult to read."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-05T18:21:06.470",
"Id": "24890",
"Score": "0",
"body": "@Bethesda: edited answer to clarify that last comment"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-05T20:33:58.217",
"Id": "24903",
"Score": "0",
"body": "May I ask why I was downvoted? if there is something wrong with my post let me know and I will fix it. Please don't just downvote with no explanation."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-05T20:43:32.187",
"Id": "24904",
"Score": "0",
"body": "+1 to offset the seemingly arbitrary downvote - I think this is a good response to the question."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-05T15:26:58.743",
"Id": "15351",
"ParentId": "15348",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "15351",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-05T14:46:36.560",
"Id": "15348",
"Score": "4",
"Tags": [
"php",
"object-oriented",
"classes",
"php5"
],
"Title": "PHP Config Class"
}
|
15348
|
<p>After a week of searching and testing each approach via <code>Stopwatch</code>,
I came to this method using the fastest way possible to capture screen into a bitmap and then to a <code>byte[]</code>.</p>
<ol>
<li><p>Is it possible to make it any faster using parallel features or any idea I have not taken into account? (As I am a newbie, 4 months of self learning.)</p></li>
<li><p>I mixed two or three versions of the copying function (portion of screen to memory
then convert captured/crop into <code>byte[]</code>). I might have left unnecessary lines of code, I would like to refine it (if and where needed).</p></li>
</ol>
<p></p>
<pre><code>unsafe public static Bitmap NatUnsfBtmp(IntPtr hWnd, Size Ms)
{
Stopwatch swCap2Byte = new Stopwatch();
swCap2Byte.Start();
WINDOWINFO winInfo = new WINDOWINFO();
bool ret = GetWindowInfo(hWnd, ref winInfo);
if (!ret)
{
return null;
}
int height = Ms.Height;
int width = Ms.Width;
if (height == 0 || width == 0) return null;
Graphics frmGraphics = Graphics.FromHwnd(hWnd);
IntPtr hDC = GetWindowDC(hWnd); //gets the entire window
//IntPtr hDC = frmGraphics.GetHdc(); -- gets the client area, no menu bars, etc..
System.Drawing.Bitmap tmpBitmap = new System.Drawing.Bitmap(width, height, frmGraphics);
Bitmap bitmap = (Bitmap)Clipboard.GetDataObject().GetData(DataFormats.Bitmap);
Graphics bmGraphics = Graphics.FromImage(tmpBitmap);
IntPtr bmHdc = bmGraphics.GetHdc();
BitBlt(bmHdc, 0, 0, width, height, hDC, 0, 0, TernaryRasterOperations.SRCCOPY);
swCap2Byte.Stop();
string swCopiedFF = swCap2Byte.Elapsed.ToString().Remove(0, 5);
swCap2Byte.Restart();
#region <<=========== CopytoMem->ByteArr ============>>
BitmapData bData = tmpBitmap.LockBits(new Rectangle(new Point(), Ms),
ImageLockMode.ReadOnly,
PixelFormat.Format24bppRgb);
MyForm1.MyT.Cap.TestBigCapturedBtmp = tmpBitmap;
// number of bytes in the bitmap
int byteCount = bData.Stride * tmpBitmap.Height;
byte[] bmpBytes = new byte[byteCount];
// Copy the locked bytes from memory
Marshal.Copy(bData.Scan0, bmpBytes, 0, byteCount);
byte[] OrgArr = bmpBytes;//File.ReadAllBytes("testFcompScr.bmp");
// don't forget to unlock the bitmap!!
swCap2Byte.Stop();
string SwFCFscr = swCap2Byte.Elapsed.ToString().Remove(0, 5);
System.IO.File.WriteAllBytes(MyForm1.AHItemsInitialDir + "testBig4BenchViaChaos.bar", OrgArr);
System.Windows.Forms.MessageBox.Show(" Copied @ " +swCopiedFF + Environment.NewLine+"Converted @ " + SwFCFscr);
btmp.UnlockBits(bData);
if(System.IO.File.ReadAllBytes(MyForm1.AHItemsInitialDir + "testBig4BenchViaChaos.bar")== OrgArr)
System.Windows.Forms.MessageBox.Show("OK");
else System.Windows.Forms.MessageBox.Show("Not same");
if (BigOrsmall == "Big")
{
MyT.Cap.TestBigCapturedBtmp = btmp;
MyT.CapSave.TestBigCaptSavedAsBar = OrgArr;
File.WriteAllBytes(AHItemsInitialDir + "testBig4BenchViaChaos.bar", OrgArr);
}
else if (BigOrsmall == "Small")
{
MyT.Cap.TestSmallCapturedBtmp = btmp;
File.WriteAllBytes(AHItemsInitialDir + "testSmall4BenchViaChaos.bar", OrgArr);
MyT.CapSave.TestSmallCaptSavedAsBar = OrgArr;
}
TestedCap_DoPutInPicBox(PicBox_CopiedFromScreen);
#endregion
bmGraphics.ReleaseHdc(bmHdc);
ReleaseDC(hWnd, hDC);
return tmpBitmap;
}
</code></pre>
|
[] |
[
{
"body": "<p>There are a few things I see at a glance:</p>\n\n<ul>\n<li>If you have to enclose a section of code within a method in region\ntags, you should be pulling that code out into a helper method. You\ncould probably split this method into several. Don't worry about\noverhead of extra method calls -- the compiler will likely re-inline\nthem anyways.</li>\n<li>Split the body of your if/else on \"Big\" and \"Small\" into a helper method that takes in a file name. That's the only difference I see in each block.</li>\n<li>There are a lot of lines where you are declaring and assigning variables. When you do that, it is likely more readable to declare as var, because you indicate what type it is immediately to the right of the assignment operator.</li>\n<li>Rather than converting your elapsed times with <code>ToString ().Remove ()</code> calls, I would instead suggest storing them as TimeSpan types and using a string format in your message boxes.</li>\n<li>Move \"Big\", \"Small\", \"testBig4BenchViaChaos.bar\", and \"testSmall4BenchViaChaos.bar\" into constants.</li>\n<li>If this is just a utility that is not client-facing, move your other strings to constants. Otherwise, move them into a resx so they can be localized.</li>\n<li>Naming - you should use longer, more descriptive names. You are not saving much by using a name like OrgArr instead of the longer OriginalArray. You should also be consistent in capitalization. Some of your local variables are camel case, and some are pascal case. The standard for the framework is camel case for local variables.</li>\n<li>You are overwriting testBig4BenchViaChaos.bar with OrgArr, but then comparing the bytes in testBig4BenchViaChaos.bar with OrgArr. Am I missing something, or should this always return a match because the data is the same? Though, on that note, you are doing == with byte arrays, so you should really always mis-match due to object reference comparison.</li>\n<li>Your quickest way to compare the two byte arrays is probably going to be using a for loop (single-threaded) or possibly PLINQ using <a href=\"http://msdn.microsoft.com/en-us/library/dd268439\">SequenceEqual</a>. As always, benchmark to be sure because test results are worth a thousand expert opinions.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-05T22:32:44.783",
"Id": "24909",
"Score": "0",
"body": "yeah i was thinking of namings, name it clearer . it's a thought about using to much long names so maybe the compiler will get tired reading long names . but as i mtured a little i could have a clue here and there to the theory that eventually it's translated into from myLongNameFunctionName() into somthing like ^$5"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-05T23:01:33.160",
"Id": "24911",
"Score": "0",
"body": "data suppose to be same ...it all started like an analogy to human finding meat to eat, there was a fire then they discoverd rosted meat, i did try save as bmp. then when loaded from file was not the same as the one that is just captured to memory. no matter what i chose as a file format. so then came bitmap-byteArray brotherhood, when i saved as byte[] it did match a second crop of same area in byte[] against byte[] data comparison then i thought i could split them to four slices an load it via paralel class to compute on all I5 4Cores"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-05T17:53:52.467",
"Id": "15359",
"ParentId": "15349",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-05T14:48:09.430",
"Id": "15349",
"Score": "4",
"Tags": [
"c#",
"performance",
"image"
],
"Title": "Comparing screen captures using unsafe / API calls"
}
|
15349
|
<p>I am setting a few vars in JavaScript. I typically like to make my code really readable so that it's easy to go back and edit. I have a few questions about the code below:</p>
<p>1) Is this is a good way to break up the setting of the vars? The comment seems redundant, but it seems to really help break up the code into relevant chunks.</p>
<p>2) When I set a var like this ~~ $IPPWrapper = $("div.iqPaginItemsPerPageWrapper") ~~ I always include the HTML element, in this case the "div". Is this overkill? Is there a performance hit or benefit? I know in the CSS best practices, it's frowned upon.</p>
<p>3) I need to create an array, but I don't know the best type to use. Basically, I am just storing messages that I will use later in popups. Is there a more common or better way to create this array?</p>
<p>Thanks in advance for any advice or helpful comments.</p>
<pre><code>// GENERAL VARS
var UpRate = 250,
DownRate = UpRate,
OpenHeight = "25px";
// SET IPP VARS
var $IPPWrapper = $("div.iqPaginItemsPerPageWrapper"),
$IPPDefault = $IPPWrapper.children("div.iqPaginDefault"),
$IPPNonDefault = $IPPWrapper.children("div.iqPaginNonDefault"),
$IPPOptions = $IPPWrapper.children("div.ItemsPerPage"),
$IPPValue = $("span#ItemsPerPageValue");
// SET SB VARS
var $SBWrapper = $("div.iqPaginSortByWrapper"),
$SBDefault = $SBWrapper.children("div.iqPaginDefault"),
$SBNonDefault = $SBWrapper.children("div.iqPaginNonDefault"),
$SBOptions = $SBWrapper.children("div.SortBy"),
$SBValue = $("span#SortByValue");
// CREATE SB TEXT ARRAY
var SBTextArray = new Array();
SBTextArray[1] = "Company Name A - Z";
SBTextArray[2] = "Company Name Z - A";
SBTextArray[3] = "Product Name A - Z";
SBTextArray[4] = "Product Name Z - A";
SBTextArray[5] = "Model Number A - Z";
SBTextArray[6] = "Model Number Z - A";
</code></pre>
<p>EDIT ~~ Is this a better way of coding the above array?</p>
<pre><code>// CREATE SB TEXT ARRAY
var SBTextArray = [
"Company Name A - Z", "Company Name Z - A",
"Product Name A - Z", "Product Name Z - A",
"Model Number A - Z", "Model Number Z - A",
];
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-05T16:33:43.207",
"Id": "24877",
"Score": "1",
"body": "don't use `new Array()` go for the array literal `var SBTextArray = [\"Company Name A - Z\",\"Company Name Z - A\", ....];` [read more here](http://stackoverflow.com/questions/1094723/what-is-array-literal-notation-in-javascript-and-when-should-you-use-it)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-05T17:04:06.903",
"Id": "24881",
"Score": "0",
"body": "@rlemon, thanks for the link. I have this correct now, right?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-05T17:33:52.337",
"Id": "24885",
"Score": "2",
"body": "yes, the array is now zero index'd - if you want to set the keys you will use an object. Arrays should be zero index'd in js."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-05T23:55:02.930",
"Id": "24913",
"Score": "0",
"body": "You can test for performance yourself - check out [jsperf.com](http://jsperf.com/)."
}
] |
[
{
"body": "<p>Your code is great so far.\nThe only tip I can think of is to wrap grouped variables inside a namespace / singleton.\nThis would make it easier to debug and perform operations of group of related elements.</p>\n\n<pre><code> // GENERAL VARS\nvar UpRate = 250,\n DownRate = UpRate,\n OpenHeight = \"25px\";\n\n// SET IPP VARS\nvar $IPP = {};\n$IPP.Wrapper = $(\"div.iqPaginItemsPerPageWrapper\");\n$IPP.Default = $IPP.Wrapper.children(\"div.iqPaginDefault\");\n$IPP.NonDefault = $IPP.Wrapper.children(\"div.iqPaginNonDefault\");\n$IPP.Options = $IPP.Wrapper.children(\"div.ItemsPerPage\");\n$IPP.Value = $(\"span#ItemsPerPageValue\");\n\n// SET SB VARS\nvar $SB = {};\n$SB.Wrapper = $(\"div.iqPaginSortByWrapper\");\n$SB.Default = $SB.Wrapper.children(\"div.iqPaginDefault\");\n$SB.NonDefault = $SB.Wrapper.children(\"div.iqPaginNonDefault\");\n$SB.Options = $SB.Wrapper.children(\"div.SortBy\");\n$SB.Value = $(\"span#SortByValue\");\n\n// CREATE SB TEXT ARRAY\nvar SBTextArray = [];\nSBTextArray[1] = \"Company Name A - Z\";\nSBTextArray[2] = \"Company Name Z - A\";\nSBTextArray[3] = \"Product Name A - Z\";\nSBTextArray[4] = \"Product Name Z - A\";\nSBTextArray[5] = \"Model Number A - Z\";\nSBTextArray[6] = \"Model Number Z - A\";\n</code></pre>\n\n<p>1) Use a namespace for related elements and functionality.</p>\n\n<p>2) It depends. In most cases it doesn't matter unless if you different tags with the same classes. Like <code>p.class1</code> and <code>dd.class1</code>. More info <a href=\"http://tutorialzine.com/2011/06/15-powerful-jquery-tips-and-tricks-for-developers/\" rel=\"nofollow\">here</a></p>\n\n<p>3) You could just use an object literal to store the message by a reference name.\nSomething like this.</p>\n\n<pre><code>var listing = { az: {}, za: {} };\nlisting.az.company = \"Company Name A - Z\";\nlisting.az.product = \"Product Name A - Z\";\nlisting.az.model = \"Model Number A - Z\";\nlisting.za.company = \"Company Name Z - A\";\nlisting.za.product = \"Product Name Z - A\";\nlisting.za.model = \"Model Number Z - A\";\n</code></pre>\n\n<p>I think your current code is good enough though.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-05T16:59:53.070",
"Id": "24879",
"Score": "0",
"body": "Larry, that looks interesting. Do you have a link to a good article on the concept of using the namespace like you are using?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-05T17:01:30.837",
"Id": "24880",
"Score": "1",
"body": "\"Namespacing in javascript\" http://elegantcode.com/2011/01/26/basic-javascript-part-8-namespaces/"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-05T16:55:16.307",
"Id": "15355",
"ParentId": "15352",
"Score": "4"
}
},
{
"body": "<p>In javascript notmally Classes are <code>CamelCase</code> constants are <code>ALLCAPS</code></p>\n\n<p>These look like constants to me:</p>\n\n<pre><code>// GENERAL VARS\nvar UpRate = 250,\n DownRate = UpRate,\n OpenHeight = \"25px\";\n</code></pre>\n\n<p>and as such I would change them to all caps</p>\n\n<pre><code>// GENERAL VARS\nvar UPRATE = 250,\n DOWNRATE = UPRATE,\n OPENHEIGHT = \"25px\";\n</code></pre>\n\n<p>Some people like <code>CONSTANTS_WITH_UNDERSCORES</code> and some don't. That's really up to you but this way allows you to easily distinguish between classes and constants.</p>\n\n<p>Regular variables</p>\n\n<pre><code>var $IPPWrapper = $(....\n\nvar SBTextArray = [ ... ] ;\n</code></pre>\n\n<p>should either be <code>$lowerCase</code> or just <code>lowerCase</code>. Something like:</p>\n\n<pre><code>var $ippWrapper = $(....\n\nvar sbTextArray = [ ... ] ;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-05T23:29:13.263",
"Id": "15370",
"ParentId": "15352",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-05T16:26:51.270",
"Id": "15352",
"Score": "0",
"Tags": [
"javascript",
"jquery"
],
"Title": "Setting vars in jQuery / JavaScript"
}
|
15352
|
<p>I'm new to iOS development and I'm having trouble figuring out how to efficiently load my app's data at launch time. My app consists of a UITableView that is populated with a list of songs. Each cell displays data about the song: current user rating(if rated) and avg. user rating (avg. rating of all users). I'm using <a href="https://parse.com/" rel="nofollow">Parse</a> for my backend data storage. </p>
<p>At launch time, my app runs two queries. The first query fetches songs to populate the table. It then calculates the avg. user rating (my backend schema includes count objects: rating1_count, rating2_count, etc. which are incremented when the user rates a song). It also orders the songs into separate data model arrays: topTracksOfTheWeek, topTracksOfTheMonth, topTracksAllTime. </p>
<p>The second query fetches all of the rated songs by the current user. It then compares this query to the first query to embed the user rating data into the first query to form the app's data model.</p>
<p>I'd like to limit the first query to 50 songs to optimize load time. However, with my current data model, I need to query all of the songs in my database to calculate all of the avg. user ratings and then order the songs into the topTracks arrays.</p>
<p>The only solution I can come up with is running a server-side script periodically to calculate the avg. user ratings. I would have to create a new class in my database for the topTracks arrays that are ordered by the script. In my app, I would do a lazily do a third query for the topTracks arrays. </p>
<p>Here is my data model code:</p>
<pre><code>- (void)getDataSource
{
PFUser *user = [PFUser currentUser];
NSMutableArray *ratings;
if (user) {
PFQuery *queryRatings = [PFQuery queryWithClassName:@"Ratings"];
[queryRatings whereKey: @"user" equalTo: user.username];
[queryRatings orderByDescending:@"createdAt"];
queryRatings.limit = 1000;
ratings = [NSMutableArray arrayWithArray:[queryRatings findObjects]];
}
else
[self displayLoginViewController];
PFQuery *query = [PFQuery queryWithClassName:@"HotSongs"];
[query orderByDescending:@"createdAt"];
query.limit = 50;
_parseTracksArray = [NSMutableArray arrayWithArray:[query findObjects]];
if (!_favoriteTracks)
_favoriteTracks = [[NSMutableArray alloc] init];
else
[_favoriteTracks removeAllObjects];
if (!_topTracksOfTheWeek)
_topTracksOfTheWeek = [[NSMutableArray alloc] init];
else
[_topTracksOfTheWeek removeAllObjects];
if (!_topTracksOfTheMonth)
_topTracksOfTheMonth = [[NSMutableArray alloc] init];
else
[_topTracksOfTheMonth removeAllObjects];
if (!_topTracksOfTheYear)
_topTracksOfTheYear = [[NSMutableArray alloc] init];
else
[_topTracksOfTheYear removeAllObjects];
//Create NSDate objects for Top Charts comparison
NSDate *dateOfWeekFromNow = [NSDate dateWithTimeIntervalSinceNow:-604800]; // (60*60*24*7) in seconds
NSDate *dateOfMonthFromNow = [NSDate dateWithTimeIntervalSinceNow:-2592000]; // (60*60*24*30)
NSDate *dateOfYearFromNow = [NSDate dateWithTimeIntervalSinceNow:-31536000]; // (60*60*24*365)
NSInteger i, a;
for (a = 0; a < _parseTracksArray.count; a++) {
NSMutableDictionary *dictionary = [_parseTracksArray objectAtIndex:a];
NSString *trackId = [dictionary objectForKey:@"track_id"];
NSNumber *rating_1 = @([[dictionary objectForKey:@"rating_1"] floatValue]);
NSNumber *rating_2 = @([[dictionary objectForKey:@"rating_2"] floatValue]);
NSNumber *rating_3 = @([[dictionary objectForKey:@"rating_3"] floatValue]);
NSNumber *rating_4 = @([[dictionary objectForKey:@"rating_4"] floatValue]);
NSNumber *rating_5 = @([[dictionary objectForKey:@"rating_5"] floatValue]);
float totalRatingCount = rating_1.floatValue + rating_2.floatValue + rating_3.floatValue + rating_4.floatValue + rating_5.floatValue;
if (totalRatingCount > 0) {
float avgRating = (rating_1.floatValue + rating_2.floatValue*2 + rating_3.floatValue*3 + rating_4.floatValue*4 + rating_5.floatValue*5) / totalRatingCount;
[dictionary setObject:@(avgRating) forKey:@"avgRating"];
double confidenceRating = [self calculateConfidenceRating:avgRating basedOn:totalRatingCount];
[dictionary setObject:@(confidenceRating) forKey:@"confidenceRating"];
}
BOOL isRatedHigh = NO;
NSNumber *userRating = @0;
if (user) {
for (i = 0; i < ratings.count; i++) {
NSDictionary *dictionaryRatings = [ratings objectAtIndex:i];
NSString *ratedTrackId = [dictionaryRatings objectForKey:@"track_id"];
if ([trackId isEqualToString:ratedTrackId]) {
userRating = [dictionaryRatings objectForKey:@"userRating"];
if (userRating.intValue > 3) {
isRatedHigh = YES;
}
}
}
}
[dictionary setObject:userRating forKey:@"userRating"];
if (isRatedHigh == YES) {
[_favoriteTracks addObject:dictionary];
}
//Set createdAt object
PFObject *object = [_parseTracksArray objectAtIndex:a];
NSDate *dateTrackWasAddedToDatabase = [object createdAt];
if ([dateTrackWasAddedToDatabase compare:dateOfYearFromNow] == NSOrderedDescending) {
[_topTracksOfTheYear addObject:dictionary];
if ([dateTrackWasAddedToDatabase compare:dateOfMonthFromNow] == NSOrderedDescending) {
[_topTracksOfTheMonth addObject:dictionary];
if ([dateTrackWasAddedToDatabase compare:dateOfWeekFromNow] == NSOrderedDescending) {
[_topTracksOfTheWeek addObject:dictionary];
}
}
}
}
[self assignDataSource];
}
- (double)calculateConfidenceRating: (float)avgRating basedOn: (float)voteCount
{
const double baseConfidenceRating = 3;
const double baseConfidence = log10(CONFIDENT_NUMBER_OF_VOTES);
double confidence = log10( 1 + voteCount ) / baseConfidence;
double confidenceWeight = fmin( confidence, 1.0 );
double confidenceRating = (1.0 - confidenceWeight) * baseConfidenceRating + confidenceWeight * avgRating;
return confidenceRating;
}
- (void)assignDataSource
{
switch (_dataSourceAssignment.intValue) {
case 0: _dataSource = [NSMutableArray arrayWithArray:_parseTracksArray]; break;
case 1: _dataSource = [NSMutableArray arrayWithArray:_favoriteTracks]; break;
case 2: _dataSource = [NSMutableArray arrayWithArray:_topTracksOfTheWeek]; break;
case 3: _dataSource = [NSMutableArray arrayWithArray:_topTracksOfTheMonth]; break;
case 4: _dataSource = [NSMutableArray arrayWithArray:_topTracksOfTheYear]; break;
default: break;
}
if (_dataSourceAssignment.intValue >= 2) {
NSSortDescriptor *avgRatingSortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"confidenceRating" ascending:NO];
NSArray *sortDescriptors = @[avgRatingSortDescriptor];
NSArray *sortedArray = [_dataSource sortedArrayUsingDescriptors:sortDescriptors];
_dataSource = [NSMutableArray arrayWithArray:sortedArray];
}
// Filter genres
NSMutableArray *selectedGenresByUser = [[NSUserDefaults standardUserDefaults] objectForKey:@"selectedGenres"];
NSPredicate *predicate = [NSPredicate predicateWithFormat: @"trackGenre in $SELECTED_GENRES"];
predicate = [predicate predicateWithSubstitutionVariables:@{@"SELECTED_GENRES": [NSArray arrayWithArray:selectedGenresByUser]}];
NSArray *filtered = [NSArray arrayWithArray:[_dataSource filteredArrayUsingPredicate: predicate]];
_dataSource = [NSMutableArray arrayWithArray:filtered];
[self.tableView reloadData];
}
</code></pre>
|
[] |
[
{
"body": "<p>Consider following scheme -</p>\n\n<p>Each song has a key <code>numberOfRatings</code> and a key <code>averageRating</code>.\nTheir initial value is 0.</p>\n\n<p>When user rates a song with <code>newRating</code>, you change the value of <code>averageRating</code> according to this formula</p>\n\n<pre><code>averageRating = ((averageRating * numberOfRatings) + newRating) / (numberOfRatings + 1)\n</code></pre>\n\n<p>And of course you increase numberOfRatings</p>\n\n<pre><code>numberOfRatings = (numberOfRatings + 1)\n</code></pre>\n\n<p>With this approach you can utilize <a href=\"https://parse.com/docs/ios_guide#queries/iOS\" rel=\"nofollow\">queries</a> (query only the first 50 songs according to their averageRating etc.) for your topTracks chart views, and you do not have to query all songs just to count their average rating - at any given moment you have an up-to-date <code>averageRating</code> stored for every song.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-10T02:38:27.087",
"Id": "19444",
"ParentId": "15353",
"Score": "3"
}
},
{
"body": "<p>Just looking at the code, I recommend to address several things.</p>\n\n<hr>\n\n<pre><code> NSDate *dateOfYearFromNow = [NSDate dateWithTimeIntervalSinceNow:-31536000];\n ...\n</code></pre>\n\n<p>This is incorrect (leap years, 31-day months). Use <code>[NSCalendar dateByAddingComponents: toDate:]</code> to subtract a year or a month from today's date.</p>\n\n<hr>\n\n<pre><code>_topTracksOfTheWeek = [[NSMutableArray alloc] init];\n_favoriteTracks = [[NSMutableArray alloc] init];\n</code></pre>\n\n<p>You should encapsulate those into some class:</p>\n\n<pre><code>_topTrackOfTheWeek = [[TopTracksProvider alloc] initWithTopTracksFrom: database inTimePeriod:oneWeek withName:@\"Top Songs of the Week\"];\n...\n</code></pre>\n\n<p>Your classes shouldn't be based on <code>NSArray</code>, but rather they should be different data providers that return corresponding views of the existing common database.</p>\n\n<p>There are several advantages of this approach:</p>\n\n<ol>\n<li><p>Your classes will clearly separate the Model parts of your applications in the MVC framework.</p></li>\n<li><p>It's more reasonable to consider those to be different representations of the same data, rather then completely separate entities. </p></li>\n<li><p>This way you automatically get fresh data as the underlying database is updated.</p></li>\n<li><p>For example, the 'top songs' class can implement accessor to get the first 10 songs without holding the entire array of songs.</p></li>\n<li><p>As seen above, your 'top songs of the week', 'top songs of the year', etc. can be based on the same class, while favorites can be based on another class.</p></li>\n<li><p>You'll be able to easily add new classes for new data providers. For example, if a user adds 'Smart folder' that says 'all songs by Elton John', you create a new instance of some similar class, and use it in the same place as the ones you already had.</p></li>\n<li><p>As you see in the example, you encapsulate keep all of data source properties, such as a name, close to its other data.</p></li>\n</ol>\n\n<p>You data source assignment, getting the title of data source, etc. then won't need any weird <code>switch</code> operators. Also, the recurring user might want to customize this list:</p>\n\n<pre><code>_dataSources = try to read the list from settings\nif (!_dataSources)\n _dataSources = @[[_topTracksOfTheWeek, _favoriteTracks...] // default\n</code></pre>\n\n<hr>\n\n<pre><code> NSNumber *rating_5 = @([[dictionary objectForKey:@\"rating_5\"] floatValue])\n</code></pre>\n\n<p>The <code>floatValue</code> and <code>NSNumber</code> wrapper seem strange here; from your usage those seems to be integers.</p>\n\n<p>You can simplify things with </p>\n\n<pre><code> NSInteger rating_5 = dictionary[@\"rating_5\"].integerValue;\n ... rating_4 + rating_5 + ...\n</code></pre>\n\n<p>Or even better, create Core Data model class for a <code>Song</code> record with <code>NSInteger</code> property <code>rating_5</code> then use one of the existing open-source libraries:</p>\n\n<pre><code>[incomingData parseAssumingEntity: Song.entity] // something like that\n</code></pre>\n\n<p>then you can encapsulate number of ratings and average rating in the model class -</p>\n\n<pre><code>@implementation Song \n- (NSUInteger)totalNumberOfRatings {\n return self.rating_1 + self.rating_2 + ... ;\n}\n- (CGFloat)averageRating {\n ... \n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-09T11:16:41.537",
"Id": "32462",
"ParentId": "15353",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-05T16:34:10.717",
"Id": "15353",
"Score": "3",
"Tags": [
"optimization",
"objective-c",
"ios"
],
"Title": "Data model code review for iOS app"
}
|
15353
|
<p>My logger posted below makes use of condition variables in order to notify the "flusher" thread that new items are available. The notification occurs every time a message is logged.</p>
<p>My questions are:</p>
<ul>
<li>If the notification immediately follows the log action then does that mean that the queue will only contain one element at most?</li>
<li><p>What would be the difference between:</p>
<pre><code>{
std::unique_lock<std::mutex> lock(mMutex);
mLogItems.push_back(std::make_pair(inLevel, std::move(inMessage)));
mCondition.notify_one();
}
</code></pre>
<p>and</p>
<pre><code>{
std::unique_lock<std::mutex> lock(mMutex);
mLogItems.push_back(std::make_pair(inLevel, std::move(inMessage)));
}
mCondition.notify_one();
</code></pre>
<p>And which is correct?</p></li>
<li><p>Should I prefer an approach where flushing occurs at periodic intervals?</p></li>
<li><p>If yes, then should I use a loop where I flush and sleep until a stop condition? Or should <code>sleep()</code> be avoided?</p></li>
<li><p>Is it feasible to use a lockless approach?</p></li>
</ul>
<p>Working code sample:</p>
<pre><code>#include <atomic>
#include <condition_variable>
#include <deque>
#include <iostream>
#include <mutex>
#include <sstream>
#include <thread>
enum class LogLevel
{
Debug,
Info,
Warning,
Error
};
const char * ToString(LogLevel inLogLevel)
{
switch (inLogLevel)
{
case LogLevel::Debug: return "DEBUG";
case LogLevel::Info: return "INFO";
case LogLevel::Warning: return "WARNING";
case LogLevel::Error: return "ERROR";
default: return "UNKNOWN";
}
}
class Logger
{
public:
static Logger & Instance()
{
static Logger fInstance;
return fInstance;
}
~Logger()
{
setQuit();
}
void setQuit()
{
std::unique_lock<std::mutex> lock(mMutex);
mQuit = true;
mCondition.notify_one();
}
void setTreshold(LogLevel inLogLevel)
{
mTreshold = inLogLevel;
}
LogLevel getTreshold() const
{
return mTreshold;
}
bool isAllowed(LogLevel inLogLevel) const
{
bool result = inLogLevel >= mTreshold;
return result;
}
typedef std::pair<LogLevel, std::string> LogItem;
typedef std::deque<LogItem> LogItems;
void log(LogLevel inLevel, std::string inMessage)
{
if (mQuit)
{
return;
}
{
std::unique_lock<std::mutex> lock(mMutex);
mLogItems.push_back(std::make_pair(inLevel, std::move(inMessage)));
mCondition.notify_one();
}
}
template<typename PrintFunction>
void flush(const PrintFunction & inPrintFunction)
{
while (!mQuit)
{
LogItems items;
{
std::unique_lock<std::mutex> lock(mMutex);
if (mLogItems.empty())
{
mCondition.wait(lock); // unlocks the mutex
}
items.swap(mLogItems); // internal pointer swap
}
for (LogItems::const_iterator it = items.begin(), end = items.end(); it != end; ++it)
{
inPrintFunction(*it);
}
}
}
private:
std::atomic<bool> mQuit;
LogLevel mTreshold;
std::mutex mMutex;
std::condition_variable mCondition;
LogItems mLogItems;
};
struct LogHelper
{
LogHelper(LogLevel inLevel) :
mLevel(inLevel)
{
}
~LogHelper()
{
Logger::Instance().log(mLevel, mStream.str());
}
std::stringstream & ss()
{
return mStream;
}
private:
LogLevel mLevel;
std::stringstream mStream;
};
#define LOG(LEVEL) \
if (!Logger::Instance().isAllowed(LogLevel::LEVEL)) {} else LogHelper(LogLevel::LEVEL).ss()
#define LogInfo() LOG(Info)
#define LogWarning() LOG(Warning)
#define LogError() LOG(Error)
#define LogDebug() \
if (!Logger::Instance().isAllowed(LogLevel::Debug)) {} else LogHelper(LogLevel::Debug).ss() << __FILE__ << ":" << __LINE__ << ": "
void Thread(const std::string & inName)
{
for (unsigned i = 0; i < 5; ++i)
{
LOG(Info) << inName << " " << i;
}
}
struct print_to_ostream
{
print_to_ostream(std::ostream & os) : os(os) {}
void operator()(const Logger::LogItem & inLogItem) const
{
os << ToString(inLogItem.first) << "\t" << inLogItem.second << std::endl;
}
std::ostream & os;
};
int main()
{
LogDebug() << "Start of program!";
LogInfo() << "Test info";
LogWarning() << "Test warning";
LogError() << "Test error";
// Start a flush thread
std::thread flusher([]{ Logger::Instance().flush(print_to_ostream(std::cout)); });
LogDebug() << "Starting threads...";
std::thread t1(std::bind(&Thread, "t1"));
std::thread t2(std::bind(&Thread, "t2"));
std::thread t3(std::bind(&Thread, "t3"));
std::thread t4(std::bind(&Thread, "t4"));
std::thread t5(std::bind(&Thread, "t5"));
LogDebug() << "Join threads...";
t1.join();
t2.join();
t3.join();
t4.join();
t5.join();
// Cleanup
LogDebug() << "Cleanup ...";
Logger::Instance().setQuit();
flusher.join();
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-05T17:16:46.003",
"Id": "24883",
"Score": "0",
"body": "Does `mCondition.notify_one();` flush, or merely send a message to another thread?"
}
] |
[
{
"body": "<p>The main thing I'm noticing is that you have a \"Throw a lock at the problem\" approach (and eww <code>mMember</code>).</p>\n\n<p>You really need a true concurrent queue- these can operate atomically (for any <code>T</code>). If you download, say, TBB, it ships with a <code>concurrent_queue</code> you can use. Here you can simply <code>push</code> on members without regard to your concurrency situation, as it is guaranteed to be safe to <code>push</code>- even whilst other threads are pushing, popping, or a bunch of other things. In addition, this protects you from, say, simply forgetting to lock the mutex one day. It also simplifies your flush code considerably.</p>\n\n<pre><code>LogItem l;\nwhile(queue.try_pop(l))\n inPrintFunction(l);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-05T17:26:30.173",
"Id": "15357",
"ParentId": "15356",
"Score": "2"
}
},
{
"body": "<p>You're already half-way to double-buffering here (you're swapping the whole deque), but you've missed a couple of tricks:</p>\n\n<ol>\n<li>the log thread <em>only</em> waits if <code>mLogItems.empty()</code>, so the log function <em>only</em> needs to signal if <code>mLogItems.empty()</code> is true before pushing</li>\n<li>you're discarding the working deque every time: your allocator could cache deallocated blocks and recycle them back to <code>mLogItems</code>' allocator instance for re-use</li>\n</ol>\n\n<p>I suspect that reducing heap operations by re-cycling memory like this could dominate both the signalling and lock-free changes, but I'd rather benchmark and find out for sure.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-05T19:09:59.143",
"Id": "24898",
"Score": "0",
"body": "Good point about the redundant allocation. It occurred to me while walking home from work today :p"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-05T19:02:21.480",
"Id": "15362",
"ParentId": "15356",
"Score": "1"
}
},
{
"body": "<p>Which is more correct?</p>\n<pre><code>{\n std::unique_lock<std::mutex> lock(mMutex);\n mLogItems.push_back(std::make_pair(inLevel, std::move(inMessage)));\n mCondition.notify_one();\n}\n</code></pre>\n<p>I would say this one (though if the condition variable is written correctly it should not matter). But I tend to want to stay on the conservative side when coding with threads. Thus any resource that is used by multiple threads should only be accessed when you have a lock to make sure access is exclusive. In my opinion <code>mCondition</code> is a shared resource and thus needs to be only accessed when you hold a lock.</p>\n<blockquote>\n<p>Should I prefer an approach where flushing occurs at periodic intervals?</p>\n</blockquote>\n<p>That really depends a lot on the features and characteristics of your system.<br />\nDo you care if you batch up requests? If the answer is no then I would definately look into and try the period logging approach.</p>\n<blockquote>\n<p>If yes, then should I use a loop where I flush and sleep until a stop condition? Or should sleep() be avoided?</p>\n</blockquote>\n<p>Nothing wrong with sleep. It actually releases the processor for other threads to use (ie its <strong>not</strong> a busy wait). But most conditional variables have a timed wait that allows you to break out after a timed period.</p>\n<pre><code> clock_t start = clock();\n while (mLogItems.empty() || (clock() - start) < WAIT_PERIOD)\n {\n clock_t waitTime = WAIT_PERIOD - (clock() - start);\n if (waitTime < 0)\n { waitTime = /* appropriate value for you conditional for\n wait until next event. This will only\n happen if you have eaited past WAIT_PERIOD\n and nothing has been added to mLogItems\n */\n }\n mCondition.timedwait(lock, waitTime);\n }\n</code></pre>\n<blockquote>\n<p>Is it feasible to use a lockless approach?</p>\n</blockquote>\n<p>Yes. Use a lock-less queue implementation.</p>\n<h3>Comments on Code</h3>\n<p>Inline:</p>\n<pre><code>void log(LogLevel inLevel, std::string inMessage)\n{\n if (mQuit)\n {\n return;\n }\n\n { // I would not add this block\n // It looks slightly ugly\n\n std::unique_lock<std::mutex> lock(mMutex);\n mLogItems.push_back(std::make_pair(inLevel, std::move(inMessage)));\n mCondition.notify_one();\n\n } // Then you can delete this as well.\n}\n</code></pre>\n<p>Standard Singleton pattern here:</p>\n<pre><code>static Logger & Instance()\n{\n static Logger fInstance;\n return fInstance;\n}\n</code></pre>\n<p>Of course this tightly couples your code with the logging system. To make singeltons work effectively they should always be used in conjunction with other patterns so that you don't tightly couple the code.</p>\n<p>There are a couple of different ways to avoid the tight coupling. One of the simplest is to use a factory pattern. Then get the appropriate logger object from the factory. This allows you to use a different type of logger during testing etc.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-06T11:53:38.913",
"Id": "24937",
"Score": "0",
"body": "wait needs to re-acquire the lock when it wakes, so releasing the lock before notifying avoids unnecessary contention. It's legal in pthreads at least, although I'm not sure what std::condition_variable says about it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-06T15:34:43.557",
"Id": "24952",
"Score": "0",
"body": "@Useless: True. But I think that is a false assumption that it will cause unnecessary contention. Once the conditional thread is signaled it is free to run that does not mean it can (it still needs a processor to run on and this one is busy running a thread). It also is free to contend in acquire the lock with all the other threads (ie there is no special privileged given to the thread held in conditional variable). But the only way to validate this is to test and time."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-07T13:15:36.967",
"Id": "25002",
"Score": "0",
"body": "Yeah, I should have said that `signal->unlock` creates an _avoidable opportunity for contention_, or something; it's naturally neither guaranteed to happen nor the only point of contention."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-05T20:24:33.053",
"Id": "15363",
"ParentId": "15356",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-05T17:09:30.280",
"Id": "15356",
"Score": "1",
"Tags": [
"c++",
"multithreading"
],
"Title": "Performance and correctness of my threaded logger?"
}
|
15356
|
<p>I am using jQuery 1.7.2</p>
<p>I have two ways of writing the same code. One way seems more verbose and the other seems more flexible. Is this the only difference? Is there any performance difference? Is there a better way of writing these?</p>
<p>Code sample #1 uses two named functions so they are reusable. It's a bit more code.</p>
<p>Code sample #2 uses two unnamed functions that work only on the hover method. It's less code but not reusable.</p>
<p>Any thoughts or comments?</p>
<pre><code>// CODE SAMPLE #1
// IPP FUNCTIONS
var openIPP = function openIPP() {
$IPPNonDefault.stop().animate({"height": OpenHeight}, DownRate);
}
var closeIPP = function closeIPP() {
$IPPNonDefault.stop().animate({"height": "0px"}, UpRate);
}
// IPP ACTIONS
$IPPWrapper.mouseover(openIPP).mouseout(closeIPP);
// CODE SAMPLE #2
$IPPWrapper.hover(
function() {
$IPPNonDefault.stop().animate({"height": OpenHeight}, DownRate);
},
function() {
$IPPNonDefault.stop().animate({"height": "0px"}, UpRate);
}
);
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-05T17:54:41.497",
"Id": "24886",
"Score": "2",
"body": "If you have to re-use them, use named functions. If you won't be re-using them, there's no point in using named functions (other than for debugging purposes)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-05T23:57:55.750",
"Id": "24914",
"Score": "1",
"body": "Where you're creating a function, use either `function foo() {}` or `var foo = function () {};`, not `var foo = function foo() {};`. The last method can have some very odd side-effects in IE<9, and is more prone to typos."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-06T16:36:26.427",
"Id": "24957",
"Score": "0",
"body": "@st-boost, this is an answer (advice), not a comment. If you copy your comment into an answer box, I will happily vote it up. Thanks!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-06T19:08:38.847",
"Id": "24962",
"Score": "0",
"body": "@EvikJames thanks, but I think an answer should be a thorough analysis of the problem, and I just wanted to drop a tip. I'm happy with \"useful comment\", thanks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-06T19:10:15.397",
"Id": "24963",
"Score": "0",
"body": "@JosephSilber also, re-using doesn't necessarily mean writing in multiple places. For example, a function should (almost) never be created in a loop."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-06T19:18:14.603",
"Id": "24964",
"Score": "0",
"body": "@st-boost - Well of course. Writing it in a loop *is* re-using it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-06T19:28:30.220",
"Id": "24966",
"Score": "0",
"body": "@JosephSilber yes, just thought it was worth being explicit about."
}
] |
[
{
"body": "<p>Generally speaking, anonymous (unnamed) functions are completely acceptable within the land of Javascript. They are used frequently and without prejudice, so don't be afraid of them.</p>\n\n<p>That said, I'm not a fan of the second code sample. Without an understanding of the jQuery API, I don't really know what the two functions do to the hover call. Are both called, one after another? Perhaps something else happens? The name <code>hover</code> doesn't really give any clues here.</p>\n\n<p>I think a great option here would be to combine the two samples. Use the anonymous functions of the second with the explicit naming of the first. Furthermore, it should be noted that according to the <a href=\"http://api.jquery.com/hover/\" rel=\"nofollow\">docs</a>, <code>hover</code> is shorthand for <code>mouseenter</code> and <code>mouseleave</code>, not <code>mousein</code> and <code>mouseout</code>. I'll let you read over the docs and decide which of the two you decide to go with, but ultimately I recommend going with something like this:</p>\n\n<pre><code>$IPPWrapper.mouseenter(function() {\n $IPPNonDefault.stop().animate({\"height\": OpenHeight}, DownRate);\n}).mouseleave(function() {\n $IPPNonDefault.stop().animate({\"height\": \"0px\"}, UpRate);\n});\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-05T18:44:39.847",
"Id": "24895",
"Score": "0",
"body": "Danny, the hover method does exactly what the mouseenter and mouseleave methods do. It just makes it simpler. Again, my functions above both do the exact same thing, just through a different means. Your code actually confuses the code a bit. It's actually less flexible and more code. Yikes!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-05T18:46:52.073",
"Id": "24896",
"Score": "0",
"body": "Perhaps you missed the point of my question, but I was asking if there was any benefit other than reusability. You did, however, address that. I try to make my code reusable so try to use named functions."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-05T18:03:01.223",
"Id": "15360",
"ParentId": "15358",
"Score": "2"
}
},
{
"body": "<p>So this is redundant.</p>\n\n<pre><code>var openIPP = function openIPP() {\n $IPPNonDefault.stop().animate({\"height\": OpenHeight}, DownRate);\n}\n</code></pre>\n\n<p>Because both of these functions are the same.</p>\n\n<pre><code>var openIPP = function() {\n $IPPNonDefault.stop().animate({\"height\": OpenHeight}, DownRate);\n}\nfunction openIPP() {\n $IPPNonDefault.stop().animate({\"height\": OpenHeight}, DownRate);\n}\n</code></pre>\n\n<p>This is the easiest for me to read.</p>\n\n<pre><code>$IPPWrapper.hover(\n function() {\n $IPPNonDefault.stop().animate({\"height\": OpenHeight}, DownRate);\n },\n function() {\n $IPPNonDefault.stop().animate({\"height\": \"0px\"}, UpRate);\n }\n);\n</code></pre>\n\n<p>But if you want more information in case a bug is thrown then use named functions like so.</p>\n\n<pre><code>$IPPWrapper.hover(\n function openIPP() {\n $IPPNonDefault.stop().animate({\"height\": OpenHeight}, DownRate);\n },\n function closeIPP() {\n $IPPNonDefault.stop().animate({\"height\": \"0px\"}, UpRate);\n }\n);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-05T21:53:25.107",
"Id": "15367",
"ParentId": "15358",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-05T17:26:37.863",
"Id": "15358",
"Score": "2",
"Tags": [
"javascript",
"jquery"
],
"Title": "Should I use unnamed or named functions?"
}
|
15358
|
<p><strong>The goal of this question:</strong><br/>
Your goal here is to find a security hole in my code which allows a user to create input that contains a script doing anything they want, without that script being stopped by my code.</p>
<p>Please bear in mind that that is the ONLY goal of this post. I am not so much here to talk about how good the algorithm is, only if it works. However, that being said, I am still open to ideas on how to improve the algorithm, make it faster, etc, but please as comments. I will upvote any good suggestions :)</p>
<p>With that out of the way,<br/>
<strong>My code:</strong><br/>
As you may have read above, you are trying to trick my code into letting a script through. What does that mean exactly? Well, I have created a php script which attempts to parse HTML and remove scripts and embeds which are not from trusted websites. Yes.... Using some regex... I know, but I do have a good reason -- You see, the only reasons I have found and can think of NOT to use regex are:</p>
<p>HTML is recursive, regex is not. (hence all this talk about context-free vs regular. I am sure there are more reasons for HTML being "above regex" but the recursion is the best one I can persoanly come up with.)</p>
<p>However, the interesting thing about my problem is this: <strong>Scripts are not recursive!</strong> This means that WHENEVER I come across a script tag, everything between that and the next end tag will NEVER be html! Thinking of HTML as a bunch of random letters, with every once in a while an open-script tag and a close-script tag actually brings HTML down to a level that regex can handle. And that's almost exactly what I did...</p>
<p>The other reason is memory constriction. I've used a lot of non-capturing groups with my regex, so, that should not be a problem. I also don't use 100% regex, I only use it as a generic way to detect tags. Actual handling of the tags is done with my own code (only with a bit more regex to select src attributes)</p>
<p>The reason I decided to push so hard for regex is this:</p>
<ul>
<li>DomDocument only handles CLEAN html. I will be receiving html form potentially malicious users. Clean html will very likely NOT be provided.</li>
<li>PHP HTML tidying libraries are not an option as they require installation to the backend, which I have no control over whatsoever.</li>
<li>Writing my own 100% substring-indexof interpreter would become a mess. Especially when having to deal with both embed and script tags. Regex expresses all of the same logic but much more concisely, which is why I chose to go with it instead.</li>
</ul>
<p>So, there you have my reasons. <strong>If you attack my code for the regex, I would rather you not attack it without at least reading that section of the question above.</strong></p>
<p><strong>The question:</strong>
With all of that said, I will clearly define what I need: I need to know if the following code has security holes. IE is there a way that a user could cause a script within the inputted text to be ignored and passed through? For testing, I consider a script that alerts the text "haxored" to be acceptable. You will find some example input at the bottom.</p>
<pre><code><?php
header('Content-type: text/plain');
function dbStr($string)
{
$ranges = dbStr_GetRanges($string);
return dbStr_FilterStringWithRanges($string, $ranges);
}
function dbStr_FilterStringWithRanges($string, $ranges)
{
$offset = 0;
$maxidx = 0;
foreach ($ranges as $range)
{
if ($range[0] + $range[1] <= $maxidx) continue;
if ($range[0] < $maxidx)
{
$orig = $range[0];
$range[0] = $maxidx;
$range[1] -= $range[0]-$orig;
}
$string = substr_replace($string, '', $range[0]-$offset, $range[1]);
if ($range[0]+$range[1] > $maxidx) $maxidx = $range[0] + $range[1];
$offset += $range[1];
}
return $string;
}
function dbStr_GetRanges($string)
{
preg_match_all
(
"#<(/){0,1}?\s*?(?:script|embed)"."[^'\"/]*?(?:[^'\"/]*?[\"'](?:(?:\\\\\"|\\\\'|[^\"'])*?)['\"][^'\"/]*?)*?[^'\"/]*?"."(/){0,1}?>#imsSX",
$string,
$matches,
PREG_SET_ORDER|PREG_OFFSET_CAPTURE
);
$ranges = array();
foreach ($matches as $key=>$value)
{
if (!in_array($value, $matches))continue;
$type = get_dbStrMatchType($value);
$possiblesave = null;
if ($type == 1)
{
$idx = strlen($string-1);
$len = 0;
$protectkey;
foreach ($matches as $key2=>$value2)
{
if ($key2 < $key) continue;
$type2 = get_dbStrMatchType($value2);
if ($type2 == 2)
{
$idx = $value2[0][1];
$len = strlen($value2[0][0]);
$protectkey = $key2;
break;
}
}
$substrstart = $value[0][2] + strlen($value[0][0]);
$content = substr($string, $substrstart, $idx - $substrstart);
if (preg_match("#[^\s]#imsSX", $content))
{
$ranges[] = array($value[0][3], ($idx+$len)-$value[0][4]);
}
else
{
if (isset($protectkey))
{
$possiblesave = $protectkey;
}
$type = 3;
}
}
if ($type == 2)
{
$ranges[] = array($value[0][5], strlen($value[0][0]));
}
else if ($type == 3)
{
preg_match_all
(
"#src=[\"']((\\\\\"|\\\\'|[^\"'])*?)['\"]#imsSX",
$value[0][0],
$submatches,
PREG_SET_ORDER|PREG_OFFSET_CAPTURE
);
if (count($submatches) !=1 || !approve_dbStrSrc($submatches[0][6][0]))
{
$ranges[] = array($value[0][7], strlen($value[0][0]));
}
else
{
if ($possiblesave != null)
{
unset($matches[$possiblesave]);
}
}
$possiblesave = null;
}
}
return $ranges;
}
function get_dbStrMatchType($val)
{
if (count($val) == 3 && strcmp($val[2][0], "/")==0)
{
return 3;
}
else if (count($val) == 2 && strcmp($val[1][0], "/")==0)
{
return 2;
}
else
{
return 1;
}
}
function approve_dbStrSrc($src)
{
$dbStrTrusted = array
(
"http://www.youtube.com",
"http://youtube.com",
"http://widgets.twimg.com/",
"http://www.twiigs.com/",
"http://twiigs.com/",
"http://twitter.com/",
"http://www.twitter.com/",
"http://picasaweb.google.com",
"http://www.flickr.com",
"http://flickr.com",
"http://static.pbsrc.com/",
);
foreach ($dbStrTrusted as $trusted)
{
if (strpos($src, $trusted) === 0)
{
return true;
}
}
return false;
}
echo "test" . dbStr
(
'
This will be passed:
<embed type="application/x-shockwave-flash" src="http://picasaweb.google.com/s/c/bin/slideshow.swf" width="288" height="192" flashvars="host=picasaweb.google.com&amp;hl=en_US&amp;feat=flashalbum&amp;RGB=0x000000&amp;feed=http%3A%2F%2Fpicasaweb.google.com%2Fdata%2Ffeed%2Fapi%2Fuser%2F109941697484668010012%2Falbumid%2F5561383933745906193%3Falt%3Drss%26kind%3Dphoto%26authkey%3DGv1sRgCN2H88H41qeT6AE%26hl%3Den_US" pluginspage="http://www.macromedia.com/go/getflashplayer"></embed>
This will not:
<script type="text/javascript">
alert("U R HAXORED");
</script>
');
?>
</code></pre>
<p>If the full version interests you (E.G. the version filled with notes about how the algorithm works) then check this out:</p>
<p><a href="http://pastebin.com/jYZH07cK" rel="nofollow">http://pastebin.com/jYZH07cK</a></p>
<p>EDIT:
Here is an online demo of the code:
<a href="http://www.geiodo.com/g-cont/mars3/MarsSecurity.php" rel="nofollow">http://www.geiodo.com/g-cont/mars3/MarsSecurity.php</a></p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-05T18:26:07.723",
"Id": "24891",
"Score": "2",
"body": "I'm pretty sure this is the wrong site for this. You might try your luck at Code Golf or SO or something. This site is only for reviews. If you want the code reviewed, that's fine, but saying that you ONLY want someone to break your code is against the FAQ"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-05T18:27:25.000",
"Id": "24892",
"Score": "1",
"body": "Hmm, I apologize. I asked first on Meta, and people there seemed to feel that this was the right place. I will check the FAQ. http://meta.stackexchange.com/questions/145949/testing-of-algorithms#comment417575_145949"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-05T18:38:45.307",
"Id": "24894",
"Score": "0",
"body": "I read the main part of the FAQ. Are you positive I am in violation? I would like to have peers review my code for a \"Security issue\". I would just prefer that over an algorithm change aimed at efficiency"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-05T19:03:50.263",
"Id": "24897",
"Score": "2",
"body": "Now that you have reworded it, it looks a lot more in line to the FAQ, but the original wording made it seem that you were just challenging people to hack your code, which seemed more like a post for code golf. And now that I'm thinking more deeply about it, maybe that wasn't against the FAQ either, it just seemed poorly worded for what you truly wanted. Carry on"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-05T19:11:17.240",
"Id": "24899",
"Score": "1",
"body": "@meanscole Thankyou for pointing out my wording! I wouldn't want to turn potential reviews away due to a simple mistake in writing on my part"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-05T21:55:53.247",
"Id": "24907",
"Score": "0",
"body": "@GeorgesOatesLarsen Do you have an online demo? That would be much easier to test/hack against."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-05T23:14:41.500",
"Id": "24912",
"Score": "0",
"body": "@LarryBattle You can try http://www.geiodo.com/g-cont/mars3/MarsSecurity.php"
}
] |
[
{
"body": "<p>The filter doesn't block inline javascript.</p>\n\n<p>Example 1:</p>\n\n<p><code><body onscroll=alert(1)><br><br><br><br><br><br>...<br><br><br><br><input autofocus></code></p>\n\n<p>Example 2:</p>\n\n<p><code><form id=\"test\"></form><button form=\"test\" formaction=\"javascript:alert(1)\">X</button></code></p>\n\n<p>Also, it doesn't encode the html, thus this will break your filter. <code></textarea></code></p>\n\n<p>Example:</p>\n\n<p>Inserts HTML:</p>\n\n<p><code></textarea><marquee><h1>I'm a bug</h1></marquee><textarea></code></p>\n\n<p>Inserts Script:</p>\n\n<p><code></textarea><script>alert(\\'I'm a bug\\')</script><textarea></code></p>\n\n<p>If you're trying to prevent XSS attacks then your goal should be not to allow ANY html to render. One way to do this would be to replace the <code><</code> and <code>></code> symbols with the respective special html entries, being <code>&lt;</code> and <code>&gl;</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-06T03:50:17.160",
"Id": "24915",
"Score": "0",
"body": "That was just a demo -- The idea is not to get code outside of the textarea, the idea is to get a script to appear INSIDE the text area. For instance, if you write <script>alert(\"hax05\");</script> in the top text box, you will find that this does not appear in the bottom text box. This answer only breaks the demo I whipped up in 5 minutes -- NOT the underlying filter. Still, thankyou for the effort"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-06T08:23:13.017",
"Id": "24918",
"Score": "0",
"body": "Aha! Just saw your update... Of COURSE... I missed inline js.... Thankyou! I will accept this as answer. I am writing this for a system which originally did not block anything at all. We went for years allowing ANY html whatsoever on posts... REmoving html 100% is something the creator is not willing to do, but i would agree, removing all HTML is definitely the way to go imo."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-06T00:44:54.453",
"Id": "15371",
"ParentId": "15361",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "15371",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-05T18:16:36.923",
"Id": "15361",
"Score": "4",
"Tags": [
"javascript",
"php",
"html",
"parsing",
"regex"
],
"Title": "Is my PHP script/embed remover robust?"
}
|
15361
|
<p>Did I write this code to correctly be tail call optimized? Am I forcing computations more than I need with <code>!</code>? Did I generally write this asynchronously correctly to allow sends and receives to occur in their own time? Is this using multiple threads needlessly? Other general critiques?</p>
<pre><code>open System
open System.Net.Sockets
let asyncGetInput = async { return BitConverter.GetBytes(Console.Read()) }
let rec asyncSendInput (stream : NetworkStream) = async {
let! input = asyncGetInput
stream.WriteByte |> Array.map <| input |> ignore
do! asyncSendInput stream
}
let asyncGetResponse (stream : NetworkStream) = async { return Char.ConvertFromUtf32(stream.ReadByte()) }
let rec asyncPrintResponse (stream : NetworkStream) = async {
let! response = asyncGetResponse stream
Console.Write(response)
do! asyncPrintResponse stream
}
#light
[<EntryPoint>]
let main args =
let client = new System.Net.Sockets.TcpClient()
client.Connect(args.[0], Int32.Parse(args.[1]))
printfn "Connected to %A %A..." args.[0] args.[1]
let stream = client.GetStream()
printfn "Got stream, starting two way asynchronous communication."
Async.Parallel [asyncSendInput stream; asyncPrintResponse stream] |> Async.RunSynchronously |> ignore
0
</code></pre>
|
[] |
[
{
"body": "<p>It seems you are using asyncGetInput and asyncGetReponse to introduce concurrency, although this is a noble goal it is kind of useless because you are only using those from other workflows which are already running in the thread pool anyway. In that case it would be ok to make a synchronous call from inside those workflows.</p>\n\n<p>The second point is about the do! at the end of asyncPrintResponse, you should use return! in your recursive call otherwise you will get a memory leak. I'm not sure if we can call this a bug because it can probably be considered normal that the definition of Do in the workflow isn't built for that. I've personally been corrected for that same error here: <a href=\"https://stackoverflow.com/questions/6905251/f-async-difference-between-two-structure\">https://stackoverflow.com/questions/6905251/f-async-difference-between-two-structure</a></p>\n\n<p>[edit]\nThere's a difference between handling concurrency and introducing concurrency. If we ignore your code for a moment, you have two distinct inherently sequential workflows that you can parallelize and asyncSendInput and asyncPrintResponse is already doing that by itself, as such asyncGetInput and asyncGetResponse are unnecessary and will only create more lightweight thread that will end up being scheduled/deschedule from the thread pool.</p>\n\n<p>Here's a little cleanup:</p>\n\n<pre><code>open System\nopen System.Net.Sockets\n\nlet rec asyncSendInput (stream : NetworkStream) =\n async {\n let input = Console.Read() |> BitConverter.GetBytes\n input |> Array.iter stream.WriteByte\n return! asyncSendInput stream\n }\n\nlet rec asyncPrintResponse (stream : NetworkStream) =\n async {\n let response = stream.ReadByte() |> Char.ConvertFromUtf32\n Console.Write(response)\n return! asyncPrintResponse stream\n }\n\n[<EntryPoint>]\nlet main args =\n let client = new System.Net.Sockets.TcpClient()\n client.Connect(args.[0], Int32.Parse(args.[1]))\n printfn \"Connected to %A %A...\" args.[0] args.[1]\n let stream = client.GetStream()\n printfn \"Got stream, starting two way asynchronous communication.\"\n asyncSendInput stream |> Async.Start\n asyncPrintResponse stream |> Async.RunSynchronously\n 0\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-23T21:55:15.910",
"Id": "30229",
"Score": "0",
"body": "I had written this question off quite a while ago as one no one would ever bother to figure out! Thanks!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-23T21:57:13.557",
"Id": "30230",
"Score": "0",
"body": "That said, you understand my *goal* in handling concurrency, any tips on what I could change to get them to cooperatively work with eachother in the same thread as I was trying, or is that going to require a lot more plumbing to create proper continuations?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-23T22:10:50.883",
"Id": "30231",
"Score": "0",
"body": "Added some more info, understand that I didn't try to answer anything related to Sockets/Client/Server as I'm not familiar enough with them to give any useful feedback."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-23T23:47:52.153",
"Id": "30234",
"Score": "1",
"body": "@JimmyHoffa Jon Harrop sent us here via the intertweets. :)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-23T21:53:37.410",
"Id": "18954",
"ParentId": "15364",
"Score": "5"
}
},
{
"body": "<p>The biggest problem with your code is that you can't really parse a char from a single byte if it is UTF32. \nDo you know if it is UTF32? </p>\n\n<p>I find the backward pipe hard to read, and it really isn't needed here at all. Instead of ignoring the result, you can use iter instead of map. This conveys intent better. </p>\n\n<pre><code>let rec asyncSendInput (stream : NetworkStream) = async {\n let! input = asyncGetInput\n Array.iter stream.WriteByte input\n do! asyncSendInput stream\n }\n</code></pre>\n\n<p>This is subjective and minor, but I would probably get rid of the recursion here too. I think this reads better:</p>\n\n<pre><code>let rec asyncSendInput (stream : NetworkStream) = async {\n while true do\n let! input = asyncGetInput\n Array.iter stream.WriteByte input\n }\n\nlet rec asyncPrintResponse (stream : NetworkStream) = async {\n while true do\n let! response = asyncGetResponse stream\n Console.Write(response)\n}\n</code></pre>\n\n<p>You're blocking a thread in ReadByte(). This can easily be asynced. I'd also probably get rid of asyncGetResponse entirely. </p>\n\n<pre><code>let rec asyncPrintResponse (stream : NetworkStream) = async {\n while true do\n let! bytes = stream.AsyncRead(1)\n Char.ConvertFromUtf32 (int bytes.[0]) |> printf \"%A\"\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-24T00:04:58.647",
"Id": "30235",
"Score": "0",
"body": "It's utf8, that was the only nearby conversion method I could dig up off hand; I know that bit is totally wrong but this was a quick hack more for figuring out how to make the async stuff play nice. Also I didn't realize F# had loops.. I like your asyncPrintResponse, very readable! Thanks for the tips, I'll have to comb over this and give it a shot!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-24T04:54:16.077",
"Id": "30243",
"Score": "0",
"body": "+1 for the async Read and while true. You can also remove the rec in that case. A recursive call is useful if you want to carry an immutable state"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-26T15:57:08.483",
"Id": "30354",
"Score": "0",
"body": "@DavidGrenier I learned haskell before meddling in F# so statelessness just seems.. prettier to me. How does mutual recursion between a reader and a printer function sound stylistically for F#? Would that be non-idiomatic? On a side note.. f# || F# ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-26T20:41:17.383",
"Id": "30377",
"Score": "2",
"body": "No it's perfectly fine, yet the while true do is a little more pragmatic that's all. I too have to force myself to be a little more down to earth sometimes.\n\nF#"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-26T22:52:41.820",
"Id": "30393",
"Score": "0",
"body": "@DavidGrenier I have to do that too. :)"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-23T23:47:06.663",
"Id": "18956",
"ParentId": "15364",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "18954",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-05T21:10:22.343",
"Id": "15364",
"Score": "2",
"Tags": [
".net",
"functional-programming",
"asynchronous",
"f#",
"recursion"
],
"Title": "simple stupid F# async telnet client"
}
|
15364
|
<p>I am working on asp.net/MVC and I need to read a value from my web.config file. Splitting the list into multiple keys is not an option.</p>
<pre><code><add key="DepartAssign" value="Depart1:PersonAssignTo1; Depart2:PersonAssignTo2"/>
</code></pre>
<p>I handled the problem by doing the following (which I am sure that there is a better approach)</p>
<pre><code>public List<string> departmentList = new List<string>();
public List<string> assignedtoList = new List<string>();
public string[] pair = ConfigurationManager.AppSettings["DepartAssign"].Split(';');
foreach (string s in pair)
{
departmentList.Add(s.Split(':').First()); //add the department to the list
assignedtoList.Add(s.Split(':').Last()); //add the assignedto to the list
}
</code></pre>
<p>and of course, I would be able to match the department with the assigned person by using the same index. Not really the cleanest approach but it works for now.</p>
<p>any way to make this code better?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-05T21:57:47.537",
"Id": "24908",
"Score": "1",
"body": "Wouldn't it be better if you used `Dictionary<string, string>` instead of two `List`s?"
}
] |
[
{
"body": "<p>You could create your own custom section in your config file.</p>\n\n<p>First define what each record looks like:</p>\n\n<pre><code>public class Department : ConfigurationSection\n{\n [ConfigurationProperty(\"name\", IsRequired = true)]\n public string Name\n {\n get { return (string)this[\"name\"]; }\n set { this[\"name\"] = value; }\n }\n\n [ConfigurationProperty(\"assignee\", IsRequired = true)]\n public string Assignee\n {\n get { return (string)this[\"assignee\"]; }\n set { this[\"assignee\"] = value; }\n }\n}\n</code></pre>\n\n<p>Define the a collection so the framework can work with your section</p>\n\n<pre><code>public class DepartmentCollection : ConfigurationElementCollection\n{\n public override ConfigurationElementCollectionType CollectionType\n {\n get { return ConfigurationElementCollectionType.BasicMap; }\n }\n\n protected override string ElementName\n {\n get { return \"Department\"; }\n }\n\n protected override ConfigurationPropertyCollection Properties\n {\n get { return new ConfigurationPropertyCollection(); }\n }\n\n public Department this[int index]\n {\n get { return (Department) BaseGet(index); }\n set\n {\n if (BaseGet(index) != null)\n {\n BaseRemoveAt(index);\n }\n base.BaseAdd(index, value);\n }\n }\n\n public Department this[string name]\n {\n get { return (Department) BaseGet(name); }\n }\n\n public void Add(Department item)\n {\n base.BaseAdd(item);\n }\n\n public void Remove(Department item)\n {\n BaseRemove(item);\n }\n\n public void RemoveAt(int index)\n {\n BaseRemoveAt(index);\n }\n\n protected override ConfigurationElement CreateNewElement()\n {\n return new Department();\n }\n\n protected override object GetElementKey(ConfigurationElement element)\n {\n return (element as Department).Name;\n }\n}\n</code></pre>\n\n<p>Define what the list looks like</p>\n\n<pre><code>public class DepartmentList : ConfigurationSection\n{\n private static readonly ConfigurationPropertyCollection DepartmentListProperties;\n private static readonly ConfigurationProperty DepartmentProperty;\n\n static DepartmentList()\n {\n DepartmentProperty = new ConfigurationProperty(\n \"\",\n typeof (DepartmentCollection),\n null,\n ConfigurationPropertyOptions.IsRequired | ConfigurationPropertyOptions.IsDefaultCollection\n );\n\n DepartmentListProperties = new ConfigurationPropertyCollection\n {\n DepartmentProperty\n };\n }\n\n public DepartmentCollection Departments\n {\n get { return (DepartmentCollection) base[DepartmentProperty]; }\n set { base[DepartmentProperty] = value; }\n }\n\n protected override ConfigurationPropertyCollection Properties\n {\n get { return DepartmentListProperties; }\n }\n}\n</code></pre>\n\n<p>Now, in your .config file specify the new type:</p>\n\n<pre><code><configSections>\n <section name=\"DepartmentAssigneeMapping\" type=\"DatabaseCleanup.DepartmentList, DatabaseCleanup, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null\"/>\n</configSections>\n</code></pre>\n\n<p>and add your section</p>\n\n<pre><code><DepartmentAssigneeMapping>\n <Department name=\"Depart1\" assignee=\"PersonAssignTo1\" />\n <Department name=\"Depart2\" assignee=\"PersonAssignTo2\" />\n</DepartmentAssigneeMapping>\n</code></pre>\n\n<p>Now, in your class:</p>\n\n<pre><code>public List<string> departmentList;\npublic List<string> assignedtoList;\n\nvar mappings = (DepartmentList) ConfigurationManager.GetSection(\"DepartmentAssigneeMapping\");\n\ndepartmentList = (\n from Department department in mappings.Departments \n select department.Name).ToList();\nassignedtoList = (\n from Department department in mappings.Departments \n select department.Assignee).ToList();\n</code></pre>\n\n<p>Your class is much nicer, and the config is way cleaner.</p>\n\n<p>This is fully tested, and the results you are looking for are replicated.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-06T08:48:37.157",
"Id": "24920",
"Score": "0",
"body": "interesting. But why not make the result a dictionary with `Name` as key and `Assignee` as value? (using `ToDictionary` once instead of `ToList` twice)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-06T13:18:06.180",
"Id": "24947",
"Score": "0",
"body": "Didn't think of doing it that way because the OP said 2 lists were needed. There's no reason you can't make it into a dictionary and pull the keys and values into separate lists I guess."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-05T22:09:54.757",
"Id": "15368",
"ParentId": "15365",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "15368",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-05T21:13:16.030",
"Id": "15365",
"Score": "3",
"Tags": [
"c#",
"asp.net",
"asp.net-mvc-3"
],
"Title": "Creating a list of pairs after splitting the string containing all of the sets"
}
|
15365
|
<p>I would like a review on this code, and how I could make it better.</p>
<pre><code>#include <boost/bind/bind.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/function.hpp>
#include <boost/thread/thread.hpp>
#include <boost/signals2/mutex.hpp>
#include <stdint.h>
#include <iostream>
#include <vector>
class CallBack1000 {
public:
void Method() {
std::cout << "1000 Millis called" << std::endl;
}
};
class CallBack2000 {
public:
void Method() {
std::cout << "2000 Millis called" << std::endl;
}
};
template <uint32_t tMilliSeconds>
class Timer {
private:
static Timer *_instance;
uint32_t mMilliSeconds;
boost::mutex mListMutex;
std::vector<boost::function<void()> > mHandlerList;
Timer() {
mMilliSeconds = tMilliSeconds;
}
Timer(const Timer &other) {}
Timer &operator=(const Timer &other) {}
public:
static Timer *Instance() {
if (_instance == NULL) {
_instance = new Timer();
}
return _instance;
}
void Run() {
while(true) {
boost::this_thread::sleep(
boost::posix_time::milliseconds(mMilliSeconds));
mListMutex.lock();
for (std::vector<boost::function<void()> >::iterator vect_it =
mHandlerList.begin(); vect_it != mHandlerList.end();
++vect_it) {
(*vect_it)();
}
mListMutex.unlock();
}
}
void AddHandler(boost::function<void()> tmpBoostFunction) {
mListMutex.lock();
mHandlerList.push_back(tmpBoostFunction);
mListMutex.unlock();
}
};
template<> Timer<1000> *Timer<1000>::_instance = NULL;
template<> Timer<2000> *Timer<2000>::_instance = NULL;
int main(int /*argc*/, char ** /*argv*/) {
CallBack1000 tmpCB1000;
boost::shared_ptr<Timer<1000> > mPtrTimer1000(Timer<1000>::Instance());
mPtrTimer1000->AddHandler(boost::bind(&CallBack1000::Method, tmpCB1000));
CallBack2000 tmpCB2000;
boost::shared_ptr<Timer<2000> > mPtrTimer2000(Timer<2000>::Instance());
mPtrTimer2000->AddHandler(boost::bind(&CallBack2000::Method, tmpCB2000));
boost::thread tmpThread1000(
boost::bind(&Timer<1000>::Run, mPtrTimer1000));
boost::thread tmpThread2000(
boost::bind(&Timer<2000>::Run, mPtrTimer2000));
tmpThread1000.join();
tmpThread2000.join();
}
</code></pre>
<hr>
<p><strong>EDIT</strong></p>
<pre><code>#include <boost/shared_ptr.hpp>
#include "singletontimer.h"
#include <assert.h>
class CallBack100 {
public:
void Method() {
std::cout << "100 Millis called" << std::endl;
}
};
class CallBack20 {
public:
void Method() {
std::cout << "20 Millis called" << std::endl;
}
};
int main(int /*argc*/, char ** /*argv*/) {
boost::shared_ptr<Timer<20> > tmpPtrTimer_20 = Timer<20>::Instance();
boost::shared_ptr<Timer<100> > tmpPtrTimer_100 = Timer<100>::Instance();
boost::shared_ptr<Timer<20> > tmpPtrTimer2_20 = Timer<20>::Instance();
CallBack20 tmpCallBack1;
tmpPtrTimer_20->AddHandler(boost::bind(&CallBack20::Method, tmpCallBack1));
CallBack20 tmpCallBack2;
tmpPtrTimer2_20->AddHandler(boost::bind(&CallBack20::Method, tmpCallBack2));
CallBack100 tmpCallBack3;
tmpPtrTimer_100->AddHandler(boost::bind(&CallBack100::Method, tmpCallBack3));
assert(tmpPtrTimer_20 == tmpPtrTimer2_20 && "Smart Pointers do Not Equal");
while(true) {
boost::this_thread::sleep(
boost::posix_time::milliseconds(100000));
}
}
#ifndef TIMER_H
#define TIMER_H
#include <boost/bind/bind.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/function.hpp>
#include <boost/thread/thread.hpp>
#include <boost/thread/recursive_mutex.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>
#include <stdint.h>
#include <iostream>
#include <vector>
template <uint32_t tMilliSeconds>
class Timer {
private:
static Timer *_instance;
uint32_t mMilliSeconds;
boost::recursive_mutex mListMutex;
boost::thread mTimerThread;
std::vector<boost::function<void()> > mHandlerList;
Timer();
Timer(const Timer &other);
Timer &operator=(const Timer &other);
public:
static boost::shared_ptr<Timer<tMilliSeconds> > Instance();
void Run();
void AddHandler(boost::function<void()> tmpBoostFunction);
};
template <uint32_t tMilliSeconds>
Timer<tMilliSeconds>::Timer() {
mMilliSeconds = tMilliSeconds;
mTimerThread = boost::thread(
boost::bind(&Timer<tMilliSeconds>::Run, this));
}
template <uint32_t tMilliSeconds>
boost::shared_ptr<Timer<tMilliSeconds> >
Timer<tMilliSeconds>::Instance() {
if (!_instance) {
_instance = new Timer<tMilliSeconds>();
}
return boost::shared_ptr<Timer<tMilliSeconds> >(_instance);
}
template <uint32_t tMilliSeconds>
void Timer<tMilliSeconds>::Run() {
while(true) {
boost::this_thread::sleep(
boost::posix_time::milliseconds(mMilliSeconds));
boost::lock_guard<boost::recursive_mutex> tmpLockGuard(mListMutex);
for (std::vector<boost::function<void()> >::iterator vect_it =
mHandlerList.begin(); vect_it != mHandlerList.end();
++vect_it) {
(*vect_it)();
}
}
}
template <uint32_t tMilliSeconds>
void Timer<tMilliSeconds>::AddHandler(
boost::function<void()> tmpBoostFunction) {
boost::lock_guard<boost::recursive_mutex> tmpLockGuard(mListMutex);
mHandlerList.push_back(tmpBoostFunction);
}
#endif // TIMER_H
#include "singletontimer.h"
template<> Timer<20> *Timer<20>::_instance = NULL;
template<> Timer<100> *Timer<100>::_instance = NULL;
</code></pre>
|
[] |
[
{
"body": "<p>If you are going to disable the copy and assignment operators then don't define the body:</p>\n<pre><code>Timer(const Timer &other); // don't do this {} \nTimer &operator=(const Timer &other); // {}\n</code></pre>\n<p>This way if you accidentally use them (inside your class or from a friend) you will get a compiler error.</p>\n<p>Using a manual locking scheme when running code that is not yours is very dangerous.</p>\n<pre><code> mListMutex.lock();\n\n (*vect_it)(); // Call unknown function that may throw\n\n mListMutex.unlock();\n</code></pre>\n<p>You need to make this exception safe with RAII</p>\n<p>Again here:</p>\n<pre><code> mListMutex.lock();\n mHandlerList.push_back(tmpBoostFunction);\n mListMutex.unlock();\n</code></pre>\n<p>vector will not break but the copy constructor of <code>tmpBoostFunction</code> my throw an exception.</p>\n<p>I don't like singeltons where you use(return) pointers. The resource is not controlled. and you make it dangerous to use. Your code should be designed so that it is imposable to use incorrectly.</p>\n<p>This it is quite legal for me to do (and potentially quite likely given a team of programmers):</p>\n<pre><code>boost::shared_ptr<Timer<1000> > timeer1(Timer<1000>::Instance());\n\n// Lots of code\n\nboost::shared_ptr<Timer<1000> > timer2(Timer<1000>::Instance());\n</code></pre>\n<p>Now the code is broken with a double delete (shared pointers do not automatically know about each other. If you wanted your singleton to controlled by smart pointers you should have returned one from the call to <code>Instance()</code>.</p>\n<p>I prefer the singelton to control its own lifespan:</p>\n<pre><code>static Timer& Instance()\n{\n static Timer instance; // lazily allocated and correctly destroyed.\n return instance;\n}\n</code></pre>\n<p>Also I don't like your design of the run method.</p>\n<pre><code>boost::thread tmpThread1000(\n boost::bind(&Timer<1000>::Run, mPtrTimer1000));\n</code></pre>\n<p>So I have to create a thread to use your class. That breaks the rule of making it obvious to use. Your class is a timer class why am I making the thread. The call to run() should start a thread to do the dirty work then return immediately. The destructor should wait for the thread to exit (potentially sending a kill signal to the thread).</p>\n<p>I see you are using a singeltong to try and prevent too many actual Timer objects (and thus threads) being created. But I think your design of the singelton for each period will actually result in many more timers being created.</p>\n<p>I would have made the queue inside the Timer object a priority queue. With the job needing to go first at the head of the list. Then the timer sleeps until this jobs needs to be done executes it and moves it to the back of the list (or the appropriate place in the list). You then examine the next job and see if you need to sleep before executing again.</p>\n<h3>Comments on changed code:</h3>\n<p>You fixed the constructor/assignment operator.\nYou fixed the RAII locking.</p>\n<p>You have not got the singelton correct. You have just moved the problem.</p>\n<pre><code>template <uint32_t tMilliSeconds>\nboost::shared_ptr<Timer<tMilliSeconds> >\nTimer<tMilliSeconds>::Instance()\n{\n if (!_instance) {\n _instance = new Timer<tMilliSeconds>();\n }\n return boost::shared_ptr<Timer<tMilliSeconds> >(_instance);\n}\n</code></pre>\n<p>Every time you call <code>Instance()</code> you create a new shared pointer using a RAW pointer. None of these shared pointers know about each other. When creating shared pointers you <strong>need</strong> (must) create them using another shared pointer (otherwise they each individually own the pointer). i.e. Once you put a RAW pointer into a shared_pointer you should never use that pointer again (it is owned by the shared pointer) you should only use it via the owning shared pointer (or another shared pointer created from the original shared pointer (as they all share ownership)).</p>\n<p>If you want to use shared pointers you need to do it more like this:</p>\n<pre><code>class Timer\n{\n .....\n\n static boost::shared_ptr<Timer<tMilliSeconds>> _instance;\n\n static boost::shared_ptr<Timer<tMilliSeconds>> Instance()\n {\n if (!_instance.get()) {\n _instance.reset(new Timer<tMilliSeconds>());\n }\n return _instance;\n }\n ...\n }\n</code></pre>\n<p>But at this point you may as well use a unique pointer internally and return a reference.</p>\n<pre><code>class Timer\n{\n .....\n\n static boost::unique_ptr<Timer<tMilliSeconds>> _instance;\n\n static Timer<tMilliSeconds>& Instance()\n {\n if (!_instance.get()) {\n _instance.reset(new Timer<tMilliSeconds>());\n }\n return *_instance;\n }\n ...\n }\n</code></pre>\n<p>But I still prefer the simpler form of singelton:</p>\n<pre><code>static Timer& Instance()\n{\n static Timer instance; // lazily allocated and correctly destroyed.\n return instance;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-06T19:19:19.457",
"Id": "24965",
"Score": "0",
"body": "@Lokie Astari I have made the requested changes, but am not sure how full proof the code is. I am still learning here, and your help in understanding how to write better code helps. I have appended to my post above."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-07T19:38:47.740",
"Id": "26485",
"Score": "0",
"body": "About \"If you are going to disable the copy and assignment operators\". Since he's already using boost, perhaps he could use `boost::noncopyable`."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-06T15:53:23.057",
"Id": "15388",
"ParentId": "15369",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "15388",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-05T22:39:52.780",
"Id": "15369",
"Score": "2",
"Tags": [
"c++",
"singleton",
"timer",
"boost"
],
"Title": "Singleton Boost-based timer"
}
|
15369
|
<p>I have a simple cache service that i am using inside my WPF prism application, i am concerned about the thread safety of it - we will be accessing this via multiple threads and using the current code it has started deadlocking, it works fine without the locks but obviously this is not acceptable.</p>
<p>How can i go about imroving this, i have read about using <code>ReaderWriterLockSlim</code> or even a thread safe dictionary - but i am not sure if this is the best approach.</p>
<pre><code>public class CacheService : ICacheService
{
internal class CacheItem
{
internal string Key { get; set; }
internal DateTime Expires { get; set; }
internal object Data { get; set; }
internal CacheItem(string key, TimeSpan lifeTime)
{
this.Key = key;
this.Expires = lifeTime == TimeSpan.MaxValue ? DateTime.MaxValue : DateTime.Now.Add(lifeTime);
}
internal bool IsExpired
{
get
{
return this.Expires < DateTime.Now;
}
}
}
private Dictionary<string, CacheItem> internalCache = new Dictionary<string, CacheItem>();
private object syncRoot = new object();
public void ClearCache()
{
foreach (var item in this.internalCache.ToList())
{
ClearCache(item.Key);
}
}
public void ClearCache(string key)
{
lock (syncRoot)
{
CacheItem item;
if (this.internalCache.TryGetValue(key, out item))
{
this.internalCache.Remove(key);
var disp = item.Data as IDisposable;
if (disp != null)
{
disp.Dispose();
}
}
}
}
public T Cache<T>(string key, Func<T> loadFunc, TimeSpan cacheFor) where T : class
{
lock (syncRoot)
{
CacheItem item;
if (this.internalCache.TryGetValue(key, out item))
{
if (item.IsExpired)
{
ClearCache(key);
item = null;
}
}
if (item == null)
{
item = new CacheItem(key, cacheFor);
item.Data = loadFunc();
this.internalCache.Add(key, item);
}
return item.Data as T;
}
}
}
</code></pre>
<p>Example Usage</p>
<pre><code>var results = ServiceLocator.Current.GetInstance<ICacheService>().Cache<object>(key, () =>
{
return GetSomeData();
},TimeSpan.FromSeconds(60));
</code></pre>
<p>We actually use this from within a <code>PostSharp</code> aspect :</p>
<pre><code>[Serializable]
[MulticastAttributeUsage(MulticastTargets.Method, PersistMetaData = true)]
public class MethodCacheAttribute : MethodInterceptionAspect
{
public const int ShortCacheSeconds = 120; // two mins
public const int MediumCacheSeconds = 1200; // 20 minutes
public const int LongCacheSeconds = 18000; //5 hours
public const int DefaultCacheSeconds = MediumCacheSeconds;
private ICacheService CacheService { get; set; }
private string methodName;
[IntroduceMember(Visibility = PostSharp.Reflection.Visibility.Family, OverrideAction = MemberOverrideAction.Ignore, IsVirtual = true)]
public double CacheForSeconds { get; set; }
public MethodCacheAttribute() : this(900) { } // 15 mins default;
public MethodCacheAttribute(int seconds)
{
this.CacheForSeconds = seconds;
}
public override void CompileTimeInitialize(MethodBase method, AspectInfo aspectInfo)
{
var genericArgs = String.Join(".", method.GetGenericArguments().Select(t => t.Name));
this.methodName = String.Format("{0}_{1}", method.Name, genericArgs);
}
public override void OnInvoke(MethodInterceptionArgs args)
{
var key = this.BuildCacheKey(args.Arguments);
var item = ServiceLocator.Current.GetInstance<ICacheService>().Cache<object>(key, () =>
{
return args.Invoke(args.Arguments);
},CacheForSeconds ==0 ? TimeSpan.MaxValue : TimeSpan.FromSeconds(CacheForSeconds));
args.ReturnValue = item;
}
private string BuildCacheKey(Arguments arguments)
{
var sb = new StringBuilder();
sb.Append(this.methodName);
foreach (var argument in arguments.ToArray())
{
sb.Append(argument == null ? "_" : argument.GetHashCode().ToString());
}
return sb.ToString();
}
}
</code></pre>
<p>Then it is just a case of popping the attribute on a method - and its is cached automatically.</p>
<p>Example :</p>
<pre><code> [MethodCache(0)]
public IEnumerable<IUserPermission> GetUserPermissions(string userName)
{}
</code></pre>
|
[] |
[
{
"body": "<p>I don't see any reason why your code should deadlock. Deadlocks require at least two locks (or similar constructs) used at the same time, but there is only one lock in your code. The only potential for deadlocok I can see is if some <code>loadFunc</code> also used locking.</p>\n\n<p>And your code is not thread-safe: iterating <code>Dictionary</code> while its being modified may not work correctly, you should use locking there too (<code>ReaderWriterLockSlim</code> might make sense here):</p>\n\n<pre><code>public void ClearCache()\n{\n List<CacheItem> items;\n lock (syncRoot)\n {\n items = this.internalCache.ToList();\n }\n\n foreach (var item in items)\n {\n ClearCache(item.Key);\n }\n}\n</code></pre>\n\n<p>But I think a better solution here would be to use <code>ConcurrentDictionary</code>, because its methods fit closely with what you need (especially <a href=\"http://msdn.microsoft.com/en-us/library/ee378677.aspx\" rel=\"nofollow\"><code>GetOrAdd()</code></a>):</p>\n\n<pre><code>private readonly ConcurrentDictionary<string, CacheItem> internalCache =\n new ConcurrentDictionary<string, CacheItem>();\n\npublic void ClearCache()\n{\n foreach (var item in this.internalCache.ToList())\n {\n ClearCache(item.Key);\n }\n}\n\npublic void ClearCache(string key)\n{\n CacheItem item;\n if (this.internalCache.TryRemove(key, out item))\n {\n var disp = item.Data as IDisposable;\n if (disp != null)\n {\n disp.Dispose();\n }\n }\n}\n\npublic T Cache<T>(string key, Func<T> loadFunc, TimeSpan cacheFor) where T : class\n{\n CacheItem item;\n if (this.internalCache.TryGetValue(key, out item))\n {\n if (item.IsExpired)\n {\n ClearCache(key);\n item = null;\n }\n }\n if (item == null)\n item = this.internalCache.GetOrAdd(\n key, _ => new CacheItem(key, cacheFor) { Data = loadFunc() });\n return (T)item.Data;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-06T09:29:18.990",
"Id": "24927",
"Score": "0",
"body": "I think the deadlock occurs because the loadFunc may call into another cached method, which tries to aquire the lock."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-06T09:35:36.473",
"Id": "24928",
"Score": "0",
"body": "I think that shouldn't cause a deadlock if it's the same cache. `lock`s are reentrant, so if a thread already owns it and tries to take it again, it will succeed and not block."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-06T09:21:44.047",
"Id": "15376",
"ParentId": "15374",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "15376",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-06T08:27:01.100",
"Id": "15374",
"Score": "3",
"Tags": [
"c#",
".net",
"multithreading",
"thread-safety"
],
"Title": ".Net caching service - thread safety"
}
|
15374
|
<p>I have this piece of code I developed but it doesn't look efficient to me, can anyone improve it please.</p>
<pre><code> private void AddToDataBase(SPItemEventProperties properties)
{
DataAccess DA = new DataAccess(ConnectionString());
DetailsRow result = DA.GetDetails(properties.WebUrl);
if (result != null && string.IsNullOrEmpty(result.URL))
{
DA.DeleteDetails(properties.WebUrl);
}
if (bool.Parse(properties.ListItem.Properties["Regular Customer"].ToString()) == true)
{
DA.InsertDetails(properties.Name, properties.WebUrl, DateTime.Now);
}
else
{
if (NumberOfInvoices(properties) > 0)
{
DA.InsertDetails(properties.Name, properties.WebUrl, DateTime.Now);
}
else
{
DeleteInvoiceDocument(properties);
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-06T09:08:53.393",
"Id": "24924",
"Score": "0",
"body": "Hello TimeToThine. How do you suppose anyone can answer that **without knowing what your conditions are?** Your question is at risk of being closed as \"not a real question\" if you don't include this critical information. By the way, your assumption is probably wrong - even *if* the code is different, it can have a big influence on the possible refactorings, so you should show that too."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-06T09:13:30.983",
"Id": "24925",
"Score": "0",
"body": "basically my conditions are just checking few results returned by a DataTable and it checks if they are null or not + few other validations, I want this code to be reviewed based on structure of it as I got 1 empty \"else\" statement in there which doesn't look great to me to be honest :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-11T14:36:22.780",
"Id": "392374",
"Score": "2",
"body": "This question is incomplete. To help reviewers give you better answers, please add sufficient context to your question. The more you tell us about [what your code does](//codereview.meta.codereview.stackexchange.com/q/1226) and what the purpose of doing that is, the easier it will be for reviewers to help you. The current title states your concerns about the code; it needs an [edit] to simply *state the task*; see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles."
}
] |
[
{
"body": "\n\n<p>Since I don't have the SharePoint libraries I wasn't able to test my solution, but it should work.</p>\n\n<ol>\n<li>Use proper indentation and formatting.</li>\n<li><code>== true</code> is redundant and can be removed.</li>\n<li><p>Instead of the following:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>bool.Parse(properties.ListItem.Properties[\"Regular Customer\"].ToString())\n</code></pre>\n\n<p>just <em>convert to <code>bool</code></em> (casting won't work because of SharePoint):</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>Convert.ToBoolean(properties.ListItem.Properties[\"Regular Customer\"])\n</code></pre></li>\n<li><p>Reduce nesting by using <code>else if</code> instead of <code>else { if (...) }</code></p></li>\n<li>Use <code>||</code> instead of two seperate conditions with the same associated code to avoid redundancy.</li>\n</ol>\n\n<hr>\n\n<p><strong>Result of refactoring</strong></p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>private void AddToDataBase(SPItemEventProperties properties)\n{\n DataAccess dataAccess = new DataAccess(ConnectionString());\n DetailsRow result = dataAccess.GetDetails(properties.WebUrl);\n bool isRegular = Convert.ToBoolean(properties.ListItem.Properties[\"Regular Customer\"])\n\n if (result != null && string.IsNullOrEmpty(result.URL))\n {\n dataAccess.DeleteDetails(properties.WebUrl);\n }\n\n if (isRegular || NumberOfInvoices(properties) > 0)\n {\n dataAccess.InsertDetails(properties.Name, properties.WebUrl, DateTime.Now);\n }\n else\n {\n DeleteInvoiceDocument(properties);\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-06T11:13:06.217",
"Id": "24931",
"Score": "0",
"body": "my code is ignoring rest of code after this line \"bool isRegularCustomer = (bool)properties.ListItem.Properties[\"Regular Customer\"];\" tried debugging but when it comes to this line it simply refreshes SharePoint page and there's nothing left to process"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-06T11:14:47.697",
"Id": "24932",
"Score": "0",
"body": "the cast to bool seems to be throwing an exception. try using the old version `isRegularCustomer = bool.Parse(...ToString())` instead."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-06T11:19:32.527",
"Id": "24933",
"Score": "0",
"body": "its something related to sharepoint I guess, I tried it so many times before as you suggested but never worked, so used to prase it"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-06T11:23:12.363",
"Id": "24934",
"Score": "0",
"body": "hm... according to [this comment on a related StackOverflow post](http://stackoverflow.com/questions/4033988/getting-value-from-spfieldboolean#comment4328627_4034070), `Convert.ToBoolean` should also work."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-06T11:24:07.073",
"Id": "24935",
"Score": "0",
"body": "Is convert.ToBoolean is better then bool.prase"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-06T11:28:35.630",
"Id": "24936",
"Score": "1",
"body": "I prefer it because we can leave out the call to `ToString()`. There are some [subtle differences](http://stackoverflow.com/questions/7031964/what-is-the-difference-between-convert-tobooleanstring-and-boolean-parsestrin), but the main reason for me is that `Convert.ToBoolean` will work with any compatible type, not just with `string`."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-06T09:25:13.150",
"Id": "15377",
"ParentId": "15375",
"Score": "12"
}
}
] |
{
"AcceptedAnswerId": "15377",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-06T09:05:23.867",
"Id": "15375",
"Score": "0",
"Tags": [
"c#",
"sharepoint"
],
"Title": "too many conditions"
}
|
15375
|
<p>I'm rather new to Clojure and so I decided to program a Connect Four for fun and learning.</p>
<p>The code below is a Clojure implementation of this <a href="https://stackoverflow.com/questions/4261332/optimization-chance-for-following-bit-operations">bitboard algorithm</a>.</p>
<p>The whole code can be found here: <a href="https://gist.github.com/3639220" rel="nofollow noreferrer">https://gist.github.com/3639220</a></p>
<p>What I'm unsure about are the functions (insert) and (bit-check-board):</p>
<pre><code>(defn insert
"Inserts symbol for given player (either 1 or 2) at specified x and
calls bit-insert for corresponding bitboard."
[boards x player-num]
(let [y (get-y (boards 0) x)]
(if (= player-num 1) ; TODO: improve
(vector
(assoc-in (boards 0) [y x] (player player-num))
(bit-insert (boards 1) (- 5 y) x)
(boards 2))
(vector
(assoc-in (boards 0) [y x] (player player-num))
(boards 1)
(bit-insert (boards 2) (- 5 y) x)))))
(defn bit-check-board ; TODO: improve
"Checks whether given bitboard is a win."
[bitboard]
(let [diag1 (bit-and bitboard (bit-shift-right bitboard 6))
hori (bit-and bitboard (bit-shift-right bitboard 7))
diag2 (bit-and bitboard (bit-shift-right bitboard 8))
vert (bit-and bitboard (bit-shift-right bitboard 1))]
(bit-or (bit-and diag1 (bit-shift-right diag1 (* 2 6)))
(bit-and hori (bit-shift-right hori (* 2 7)))
(bit-and diag2 (bit-shift-right diag2 (* 2 8)))
(bit-and vert (bit-shift-right vert (* 2 1))))))
</code></pre>
<ol>
<li>insert: Is there a better way to somehow make function calls depend on some test?</li>
<li>bit-check-board: A lot of similar lines where just one number (and one variable name) is different.</li>
</ol>
|
[] |
[
{
"body": "<p>The <code>bit-check-board</code> can be indeed improved. This is what I got by just joining together common parts, even though I guess it could be further improved:</p>\n\n<pre><code>(defn check [c x]\n (bit-and c (bit-shift-right c x)))\n\n(defn bit-check-board\n \"Checks whether given bitboard is a win.\"\n [bitboard]\n (let [positions [6 7 8 1]\n coords (mapv (partial check bitboard) positions)]\n (apply bit-or (map check coords (map #(* 2 %) positions)))))\n</code></pre>\n\n<p>Also, you can reduce the repetition in the <code>insert</code> function by better modularize the code and use higher order functions with a pre-calculated transformation table:</p>\n\n<pre><code>(defn insert* [board x y]\n (bit-insert board (- 5 y) x))\n\n(defn get-transforms [num]\n (if (= 1 num)\n [identity insert* identity]\n [identity identity insert*]))\n\n(defn insert\n \"Inserts symbol for given player (either 1 or 2) at specified x and\n calls bit-insert for corresponding bitboard.\"\n [boards x player-num]\n (let [y (get-y (boards 0) x)\n board0 (assoc-in (boards 0) [y x] (player player-num))\n transfv (get-transforms player-num)]\n (mapv [board0 (boards 1) (boards 2)] transv)))\n</code></pre>\n\n<p>If you're on Clojure < 1.4 than you have to change <code>(mapv ...)</code> in <code>(vector (map ...))</code></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-06T12:32:06.637",
"Id": "24938",
"Score": "0",
"body": "I understand what map(v), apply and partial do, but I just couldn't come up with what you did. My mind is not that functional it seems...\n\nI can't remember seeing identity before and for sure not in such a usage. I don't understand `(mapv [board0 (boards 1) (boards 2)] transv)` - mapv returns a vector of applying a vector containing the boards on a vector containing functions? o.O\n\nalso: let binding is transfv and in mapv it's transv and insert* should take [board y x] instead of [board x y] and while writing that I realized that I have no clue where insert* actually get its parameters from?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-10T20:01:02.973",
"Id": "25115",
"Score": "0",
"body": "Your code seems not to work, I guess you meant something similar to this:\n`(defn insert\n [boards x player-num]\n (let [y (get-y (boards 0) x)\n board0 (assoc-in (boards 0) [y x] (player player-num))\n funcorder (if (= 1 player-num)\n [identity #(bit-insert % (- 5 y) x) identity]\n [identity identity #(bit-insert % (- 5 y) x)])]\n (mapv #(% %2) funcorder [board0 (boards 1) (boards 2)])))`"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-06T10:38:40.693",
"Id": "15379",
"ParentId": "15378",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-06T09:39:52.457",
"Id": "15378",
"Score": "4",
"Tags": [
"lisp",
"functional-programming",
"clojure",
"bit-twiddling"
],
"Title": "Connect Four: Bitboard checking algorithm"
}
|
15378
|
<p>I don't write too many bash scripts and I can usually struggle my way through getting the odd thing I need working, but my scripts always seem to feel a bit brittle. Below is a script I wrote for adding trusted timestamps to commits in a Git repository. I would appreciate any feedback on ways I could improve it.</p>
<pre><code>#!/bin/bash
# Exit immediately if any commands return non-zero
set -e
# Config variables.
url=<use a URL to an RFC3161 service>
cafile="${HOME}/time-stamping-cert-chain.crt"
request_delay=15 # COMODO asks for this in scripts.
blobref="tsa-blobs" # tsa = time stamp authority
# Make sure the script was called from within a Git repo. Ignore
# stdout.
git rev-parse --show-toplevel > /dev/null
# Start with flags set to false
delay_next=false
verbose=false
ltime=false
prep() {
# Assume we start with no note.
note=false
# The revision should be the first argument.
rev="$1"
# If no revision is specified, assume HEAD.
if [ -z "$rev" ]; then
rev="HEAD"
fi
# Run git rev-parse since it will expand HEAD and shortend hashes for
# us.
rev="$(git rev-parse "$rev")"
# Figure out if the timestamp note exists.
git notes --ref="$blobref" show "$rev" > /dev/null 2>&1 && note=true \
|| true # Make sure the command exits 0
}
print_rev() {
if $verbose; then
echo "$rev"
else
echo "$(git rev-parse --short "$rev")"
fi
}
print_signed_timestamp() {
tsatime="$(echo "$1" | grep -i "time stamp:" | cut -c13-)"
echo -e "\t$(date -d "$tsatime" +"SIGNED-%d-%b-%Y")"
#echo "$(date -d "$tsatime" --iso-8601=minutes)"
#echo "$(date -d "$tsatime" +"%Y-%m-%d-%T-%Z")"
}
print_local_timestamp() {
if $ltime; then
ctime="$(git log --pretty=format:"%ad" --date=iso "$rev" -1)"
echo -e "\t$(date -d "$ctime" +"COMMITTED-%d-%b-%Y")"
fi
}
# This outputs the text version of the TSA reply for the current
# revision.
examine() {
if $note; then
timestamp="$(git notes --ref="$blobref" show "$rev")"
text="$(echo "$timestamp" | openssl enc -d -base64 | openssl ts -reply -in /dev/stdin -text)"
echo "--------------------------------------------------------------------------------"
echo "Revision: ${rev}$(print_local_timestamp)"
echo "--------------------------------------------------------------------------------"
echo "$text"
echo "--------------------------------------------------------------------------------"
else
echo "$(print_rev)$(print_local_timestamp)\tNo trusted timestamp."
fi
}
# This loads the TSA reply for the current revision from git notes,
# re-verifies it, and outputs short info about the verified timestamp.
verify() {
if ! $note; then
echo -e "$(print_rev)$(print_local_timestamp)\tNo trusted timestamp."
return 0
fi
timestamp="$(git notes --ref="$blobref" show "$rev")"
text="$(echo "$timestamp" | openssl enc -d -base64 | openssl ts -reply -in /dev/stdin -text)"
echo "$timestamp" | openssl enc -d -base64 \
| openssl ts -verify -digest "$rev" -in /dev/stdin -CAfile "$cafile" > /dev/null 2>&1
echo -e "$(print_rev)$(print_local_timestamp)$(print_signed_timestamp "$text")"
}
# This creates a note for the current revision and verifies it. If the
# verification is successful, the reply is base64 encoded and stored
# in the $ref namespace of git notes for the current revision. After
# storing the note, it is re-loaded, un-coded, and re-verified before
# outputting short info about the verified timestamp.
create() {
if $note; then
verify
return 0
fi
# Wait for the delay requested by the timestamp service.
if $delay_next; then
sleep $request_delay
fi
# Content-type and Accept type need to be included in the request header
# when connecting to the timestamp service.
CONTENT_TYPE="Content-Type: application/timestamp-query"
ACCEPT_TYPE="Accept: application/timestamp-reply"
# Create the timestamp request using the specified revision as a digest. The
# sha1 hashes Git uses for revisions are already in the correct format. The
# default should be sha1, but we specify it anyway to show our intent is to
# pass an sha1 hash.
#
# The request is submitted to the timestamp server using curl.
#
# The data is base64 encoded and temporarily stored in the TSREPLY variable so
# the timestamp can be verified before storing it in Git notes.
timestamp=$(openssl ts -query -cert -digest "$rev" -sha1 \
| curl -s -H "$CONTENT_TYPE" -H "$ACCEPT_TYPE" --data-binary @- "$url" \
| openssl enc -base64)
# Verify the reply to make sure the timestamp is valid. We don't want to add
# invalid timestamps to Git notes since an invalid timestamp has no value.
echo "$timestamp" \
| openssl enc -d -base64 \
| openssl ts -verify -digest "$rev" -in /dev/stdin -CAfile "$cafile" > /dev/null 2>&1
# Put the base64 encoded blob into the $BLOBblobref namespace.
echo "$timestamp" | git notes --ref="$blobref" add "$rev" --file -
# Perform a sanity check to make sure we can re-verify the
# timestamp using the blob we just added to the $blobref
# namespace.
git notes --ref="$blobref" show "$rev" | openssl enc -d -base64 \
| openssl ts -verify -digest "$rev" -in /dev/stdin -CAfile "$cafile" > /dev/null 2>&1
# Get the text version of the reply
text="$(echo "$timestamp" | openssl enc -d -base64 | openssl ts -reply -in /dev/stdin -text)"
echo -e "$(print_rev)$(print_local_timestamp)$(print_signed_timestamp "$text") (CREATED)"
delay_next=true
}
# This removes the verified timestamp for the current revision.
remove() {
if ! $note; then
echo -e "$(print_rev)$(print_local_timestamp)\tNo trusted timestamp. Skipping."
return 0
fi
git notes --ref="$blobref" remove "$rev" > /dev/null 2>&1
echo -e "$(print_rev)$(print_local_timestamp)\tTrusted timestamp removed."
}
push() {
git push "origin" "refs/notes/${blobref}"
}
fetch() {
git fetch "origin" "refs/notes/${blobref}:refs/notes/${blobref}"
}
# Script logic starts below here.
# Check for very basic switches, mainly to output detailed information
# about the timestamp.
while getopts ":vlh" opt; do
case $opt in
v)
verbose=true
;;
l)
ltime=true
;;
h)
echo "Usage: git-timestamp [options] command [revision]" >&2
echo
echo " options"
echo " -h - Show this usage info. All other options are ignored."
echo " -v - Output long revision instead of short."
echo " -l - Also show the local commit time of the specified revision."
echo
echo " command"
echo " create - Create a timestamp. Revisions with existing timestamps will be"
echo " verified instead."
echo " verify - Verify an existing timestamp. Revisions without a timestamp will"
echo " be skipped."
echo " examine - Show the full text output of an existing timestamp. Revisions"
echo " without a timestamp will be skipped."
echo " remove - Remove an existing timestamp. Revisions without a timestamp"
echo " will be skipped."
echo " push - Push the timestamp namespace we're using for git notes to origin."
echo " fetch - Fetch the timestamp namespace we're using for git notes from origin."
echo
echo " revision"
echo " A git revision number. Long and short versions are accepted. The default"
echo " is HEAD if no revision is specified. Using '-' as the revision number will"
echo " read a rev-list from stdin and run the given command for every revision in"
echo " the rev-list."
echo
echo " warnings"
echo " Existing timestamps are NEVER overwritten. It is necessary to explicitly"
echo " remove a timestamp with the 'remove' command if you want to replace it with"
echo " a newer timestamp. There is likely nothing to be gained from removing a good"
echo " timestamp, so the 'remove' command should normally be used to delete corrupted"
echo " timestamps."
echo
echo " advanced examples"
echo " - Create timestamps for the HEAD of every branch in the 'origin' repo."
echo " $ git fetch && git ls-remote --heads origin | cut -f1 | git timestamp create -"
echo
echo " - Get a rev-list for the origin/develop branch and verify the timestamp for"
echo " each revision in the list. This is an easy way of showing every trusted"
echo " timestamp for a branch. Uses the -l option to list commit timestamps too."
echo " $ git fetch && git rev-list origin/develop | git timestamp -l verify -"
exit 0
;;
\?)
echo "Invalid option: -$OPTARG" >&2
;;
esac
done
# Shift past all options so the command is at $1.
shift $(( OPTIND - 1 ))
cmd="$1"
if [[ "$cmd" != "create" ]] \
&& [[ "$cmd" != "examine" ]] \
&& [[ "$cmd" != "verify" ]] \
&& [[ "$cmd" != "remove" ]] \
&& [[ "$cmd" != "push" ]] \
&& [[ "$cmd" != "fetch" ]]; then
echo "Invalid command ${cmd}. Try -h for usage."
exit 1
fi
run() {
case "$cmd" in
create)
create
;;
examine)
examine
;;
verify)
verify
;;
remove)
remove
;;
push)
push
;;
fetch)
fetch
;;
esac
}
# Shift past the given command so $1 is the revision.
shift
# If the revision argument is '-' and stdin is not empty, assume
# we're reading a rev-list from stdin and run the command for
# every revision in the list.
if [[ "$1" == "-" ]]; then
if [ ! -z /dev/stdin ]; then
cat /dev/stdin | while read nextrev; do
prep "$nextrev" && isprep=true || true
if $isprep; then
run || one_failed=true
fi
done
fi
else
prep "$1"
run
fi
if $one_failed; then
exit 1
fi
exit 0
</code></pre>
|
[] |
[
{
"body": "<p>You can use a <a href=\"http://en.wikipedia.org/wiki/Here_document\" rel=\"nofollow\"><em>here document</em></a> to avoid all those calls to <code>echo</code>:</p>\n\n<pre><code>cat <<END\nUsage: git-timestamp [options] command [revision]\n\n options\n -h - Show this usage info. All other options are ignored.\n -v - Output long revision instead of short.\n -l - Also show the local commit time of the specified revision.\n\n ...etc...\nEND\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-06T15:25:35.977",
"Id": "15386",
"ParentId": "15380",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "15386",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-06T12:17:17.763",
"Id": "15380",
"Score": "6",
"Tags": [
"beginner",
"bash",
"git",
"openssl"
],
"Title": "Adding trusted timestamps to Git commits"
}
|
15380
|
<p>I want to refactor my code but I can't find and much simplier one. Can you please suggest on how to refactor the code below without using a loop? maybe using only array functions? TIA</p>
<pre><code><?php
$week_no = array(2,3,4);
$days = array('TU', 'WE', 'TH');
foreach ($week_no as $n) {
foreach ($days as $d) {
$out[] = $n . $d;
}
}
var_dump($out); // array('2TU', '2WE', '2TH','3TU', '3WE', '3TH, '4TU', '4WE', '4TH)
?>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-06T10:30:09.507",
"Id": "24940",
"Score": "4",
"body": "that's the simple and the fastest way to do it !!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-06T10:31:50.597",
"Id": "24941",
"Score": "0",
"body": "yes. but is there anymore more elegant than this? :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-06T10:32:34.157",
"Id": "24942",
"Score": "0",
"body": "maybe you can change the structure of youre array depends on how you want to use it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-06T10:36:47.463",
"Id": "24943",
"Score": "0",
"body": "I was working out a version using `array_reduce` just for shits and giggles, but my hands got tired halfway through... Seriously, this is the simplest way to do it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-06T12:45:07.100",
"Id": "24944",
"Score": "0",
"body": "$week_no = array(2,3,4);\n$days = array('TU', 'WE', 'TH');\n\nfunction concatenateArrayValues(&$value, $key, $data)\n{\n $value = $data[1][floor($key/count($data[1]))] . $data[0][$key % count($data[0])];\n}\n\n$compositeArray = array_fill(0,count($week_no)*count($days),NULL);\narray_walk($compositeArray,'concatenateArrayValues',array($days,$week_no));\n\nvar_dump($compositeArray);"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-06T12:45:47.413",
"Id": "24945",
"Score": "0",
"body": "WOuldn't say it's simpler, and a lot less efficient; but just a proof of concept that it can be done with other than nested loops... it'd probably be a bit faster with a closure, but still not very efficient"
}
] |
[
{
"body": "<p>How about this for some madness:</p>\n\n<pre><code>function weekday($a, $b){global $days; return \"$a $b\".join(\" $b\", $days);};\n$out = explode(' ', trim(array_reduce($week_no, 'weekday')));\n</code></pre>\n\n<p><em>(Urm, yes well maybe not...)</em></p>\n\n<p>Sometimes to attain elegance you have to change the way your code is working, i.e. what are your reasons behind generating such an odd array? From my experience something like this would be more useful:</p>\n\n<pre><code>$out = array_fill(reset($week_no),count($week_no),$days);\n</code></pre>\n\n<p>Which generates the following:</p>\n\n<pre><code>Array\n(\n [2] => Array\n (\n [0] => TU\n [1] => WE\n [2] => TH\n )\n\n [3] => Array\n (\n [0] => TU\n [1] => WE\n [2] => TH\n )\n\n [4] => Array\n (\n [0] => TU\n [1] => WE\n [2] => TH\n )\n\n)\n</code></pre>\n\n<p>The above would be much easier to traverse and would be more extendable.</p>\n\n<p>In sticking with your question however the foreach method is by far the best as stated in the comments... but it was fun trying odd work arounds ;) Am surprised that there is no php function to directly prepend or append array items with another set of array items... probably because it's quite easy and fast to do so with a few foreachs.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-06T14:24:04.523",
"Id": "24949",
"Score": "0",
"body": "I would say using globals is not really an improvement."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-06T15:41:56.400",
"Id": "24954",
"Score": "0",
"body": "Yep, totally... that's was the reason for the *(erm, yes well maybe not part)* ;) Was just an example of the lengths you would have to go to in order to achieve the same... and the reason for me stating a possible implementation change."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-06T16:13:40.357",
"Id": "24955",
"Score": "0",
"body": "+1 For the restructure, not for the globals *shudder* I was originally debating `array_combine()`, but this comes out nicer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-06T21:22:19.090",
"Id": "24968",
"Score": "0",
"body": "Thanks, heh, yep Globals are rather evil - It's a shame `array_reduce` doesn't accept a `userdata` param like array_walk. However, on the plus side it's the first time I've actually found a use for `array_reduce`... albeit a rather non-use. The worse part imo though is the conversion to string and then back to array again... *(which I was expecting ppl to complain about more)*"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-06T13:55:02.417",
"Id": "15383",
"ParentId": "15382",
"Score": "4"
}
},
{
"body": "<p>What's wrong with a simple:</p>\n\n<pre><code>$out = array('2TU', '2WE', '2TH','3TU', '3WE', '3TH, '4TU', '4WE', '4TH);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-06T17:03:56.467",
"Id": "24959",
"Score": "1",
"body": "Its repetitive and doesn't allow for extension. Now if you were to add Monday or Friday to that list, you'd have to manually do so for each week."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-07T03:54:21.350",
"Id": "24976",
"Score": "0",
"body": "+1 from me, this is the simplest. If there aren't multiple places (at least 3 or more) where these week/days are used then this beats adding other complexity with a function etc."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-07T08:23:02.643",
"Id": "24988",
"Score": "2",
"body": "There's no mention in the question of extensions. I'm a pragmatic programmer. The time to add complexity is when the problem becomes more complex, not before ;-)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-06T16:04:27.230",
"Id": "15389",
"ParentId": "15382",
"Score": "4"
}
},
{
"body": "<p>The only thing I would do is wrap everything inside a function.</p>\n\n<pre><code>function getWeekArray( $week_no, $days ){\n $result = array();\n foreach ($week_no as $n) {\n foreach ($days as $d) {\n $result[] = $n . $d;\n }\n }\n return $result;\n}\n\n$a = array(2,3,4);\n$b = array('TU', 'WE', 'TH'); \n\nvar_dump(getWeekArray( $a, $b )); // array('2TU', '2WE', '2TH','3TU', '3WE', '3TH, '4TU', '4WE', '4TH)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-06T22:39:59.310",
"Id": "15394",
"ParentId": "15382",
"Score": "0"
}
},
{
"body": "<p>I found another solution with array_merge and array_map. However it's bigger and probably slower than your foreach-solution.</p>\n\n<pre><code>$out = call_user_func_array('array_merge',\n array_map(function($a) use ($days){\n return array_map(function($b) use ($a){\n return $a . $b;\n }, $days);\n }, $week_no, $days)\n );\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-07T08:12:11.927",
"Id": "24986",
"Score": "0",
"body": "Indentation works just fine if you use the provided formatting functions which are explained in the (not overlookable!) help just above the input field, highlighted by an ugly mustard yellow."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-07T08:15:42.047",
"Id": "24987",
"Score": "0",
"body": "You're right. I was hung up on backticks as they are meant to highlight code. It's probably just there that indentation doesn't work as expected.\n\nThanks anyway!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-07T07:56:24.823",
"Id": "15405",
"ParentId": "15382",
"Score": "1"
}
},
{
"body": "<p>Not necessarily shorter, but you could create an object that takes the two arrays and does the merge for you, possibly using something like array_walk or array_map.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-07T08:15:41.433",
"Id": "15407",
"ParentId": "15382",
"Score": "1"
}
},
{
"body": "<p>Stop. This is as simple as you're going to get it. Any further refactoring will be making your code more complex rather than simpler. Look at the other code suggestions... are they making it simpler or more complex? You may want to wrap this inside a function depending on how your application uses it, but without seeing more code it's impossible to judge.</p>\n\n<p>There are a lot of cases where there is a nice array function to call, but this is not one of those cases. Instead of worrying about how many characters or lines it takes to perform a task, worry about which implementation makes your intent the most clear. That's what matters.</p>\n\n<p>Don't be sad... what you have is perfect.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-20T04:29:35.230",
"Id": "15754",
"ParentId": "15382",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-06T10:28:53.563",
"Id": "15382",
"Score": "2",
"Tags": [
"php"
],
"Title": "Is there simplier than this one in PHP?"
}
|
15382
|
<p>How can I make this code snippet be improved to become more professional?</p>
<pre><code>(function($){
$.fn.showMenu = function(options){
return this.each(function(){
$this = $(this);
var high = $this.outerHeight(),
scrollHeight = $this.get(0).scrollHeight;
$this.bind('mouseenter',function(){
$this.css({overflow:'visible'})
.stop()
.animate({height:scrollHeight},'fast');
}).bind('mouseleave',function(){
$this.animate({height:high}, function(){
$this.css({overflow:'hidden'});
});
});
});
}//the end of $.fn.showMenu
$('#theme_content').showMenu();
});
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-17T16:10:50.380",
"Id": "25516",
"Score": "0",
"body": "Have you considered using CSS animations instead?"
}
] |
[
{
"body": "<p>You could also use .hover, if you are going for shorter code.\n<a href=\"http://api.jquery.com/hover/\" rel=\"nofollow\">Jquery Hover</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-06T18:11:40.740",
"Id": "15393",
"ParentId": "15385",
"Score": "1"
}
},
{
"body": "<ol>\n<li><p>Proper Indentation. You shouldn't need the <code>//end of fn</code> comment. Just indent that entire block.</p></li>\n<li><p><code>$this = $(this)</code> needs a <code>var</code> statement.</p></li>\n<li><p>You wrap your code in a function, which is good, but you need to call that function. The last line should be <code>})();</code></p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-14T14:12:50.913",
"Id": "15618",
"ParentId": "15385",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-06T15:16:44.517",
"Id": "15385",
"Score": "3",
"Tags": [
"javascript",
"jquery"
],
"Title": "Function to show/hide a menu on hover"
}
|
15385
|
<p>I'm working on a feature for the <a href="http://github.com/jessemiller/HamlPy" rel="nofollow">HamlPy (Haml for Django)</a> project:</p>
<h2>About Haml</h2>
<p>For those who don't know, Haml is an indentation-based markup language which compiles to HTML:</p>
<pre><code>%ul#atheletes
- for athelete in athelete_list
%li.athelete{'id': 'athelete_{{ athelete.pk }}'}= athelete.name
</code></pre>
<p>compiles to</p>
<pre><code><ul id='atheletes'>
{% for athelete in athelete_list %}
<li class='athelete' id='athelete_{{ athelete.pk }}'>{{ athelete.name }}</li>
{% endfor %}
</ul>
</code></pre>
<h2>The code</h2>
<p><code>{'id': 'athelete_{{ athelete.pk }}'}</code> is referred to as the 'attribute dictionary'. It is an (almost) valid Python dictionary and is currently parsed with some very ugly regular expressions and an <code>eval()</code>. However, I would like to add some features to it that would no longer make it a valid Python dictionary, e.g. using Haml within the attributes:</p>
<pre><code>%a.link{
'class':
- if forloop.first
link-first
- else
- if forloop.last
link-last
'href':
- url some_view
}
</code></pre>
<p>among other things.</p>
<p>I began by writing a class which I could swap out for the eval and would pass all of the current tests: </p>
<pre><code>import re
# Valid characters for dictionary key
re_key = re.compile(r'[a-zA-Z0-9-_]+')
re_nums = re.compile(r'[0-9\.]+')
class AttributeParser:
"""Parses comma-separated HamlPy attribute values"""
def __init__(self, data, terminator):
self.terminator=terminator
self.s = data.lstrip()
# Index of current character being read
self.ptr=1
def consume_whitespace(self, include_newlines=False):
"""Moves the pointer to the next non-whitespace character"""
whitespace = (' ', '\t', '\r', '\n') if include_newlines else (' ', '\t')
while self.ptr<len(self.s) and self.s[self.ptr] in whitespace:
self.ptr+=1
return self.ptr
def consume_end_of_value(self):
# End of value comma or end of string
self.ptr=self.consume_whitespace()
if self.s[self.ptr] != self.terminator:
if self.s[self.ptr] == ',':
self.ptr+=1
else:
raise Exception("Expected comma for end of value (after ...%s), but got '%s' instead" % (self.s[max(self.ptr-10,0):self.ptr], self.s[self.ptr]))
def read_until_unescaped_character(self, closing, pos=0):
"""
Moves the dictionary string starting from position *pos*
until a *closing* character not preceded by a backslash is found.
Returns a tuple containing the string which was read (without any preceding backslashes)
and the number of characters which were read.
"""
initial_pos=pos
while pos<len(self.s):
if self.s[pos]==closing and (pos==initial_pos or self.s[pos-1]!='\\'):
break
pos+=1
return (self.s[initial_pos:pos].replace('\\'+closing,closing), pos-initial_pos+1)
def parse_value(self):
self.ptr=self.consume_whitespace()
# Invalid initial value
val=False
if self.s[self.ptr]==self.terminator:
return val
# String
if self.s[self.ptr] in ("'",'"'):
quote=self.s[self.ptr]
self.ptr += 1
val,characters_read = self.read_until_unescaped_character(quote, pos=self.ptr)
self.ptr += characters_read
# Django variable
elif self.s[self.ptr:self.ptr+2] == '={':
self.ptr+=2
val,characters_read = self.read_until_unescaped_character('}', pos=self.ptr)
self.ptr += characters_read
val="{{ %s }}" % val
# Django tag
elif self.s[self.ptr:self.ptr+2] in ['-{', '#{']:
self.ptr+=2
val,characters_read = self.read_until_unescaped_character('}', pos=self.ptr)
self.ptr += characters_read
val=r"{%% %s %%}" % val
# Boolean Attributes
elif self.s[self.ptr:self.ptr+4] in ['none','None']:
val = None
self.ptr+=4
# Integers and floats
else:
match=re_nums.match(self.s[self.ptr:])
if match:
val = match.group(0)
self.ptr += len(val)
if val is False:
raise Exception("Failed to parse dictionary value beginning at: %s" % self.s[self.ptr:])
self.consume_end_of_value()
return val
class AttributeDictParser(AttributeParser):
"""
Parses a Haml element's attribute dictionary string and
provides a Python dictionary of the element attributes
"""
def __init__(self, s):
AttributeParser.__init__(self, s, '}')
self.dict={}
def parse(self):
while self.ptr<len(self.s)-1:
key = self.__parse_key()
# Tuple/List parsing
self.ptr=self.consume_whitespace()
if self.s[self.ptr] in ('(', '['):
tl_parser = AttributeTupleAndListParser(self.s[self.ptr:])
val = tl_parser.parse()
self.ptr += tl_parser.ptr
self.consume_end_of_value()
else:
val = self.parse_value()
self.dict[key]=val
return self.dict
def __parse_key(self):
'''Parse key variable and consume up to the colon'''
self.ptr=self.consume_whitespace(include_newlines=True)
# Consume opening quote
quote=None
if self.s[self.ptr] in ("'",'"'):
quote = self.s[self.ptr]
self.ptr += 1
# Extract key
if quote:
key,characters_read = self.read_until_unescaped_character(quote, pos=self.ptr)
self.ptr+=characters_read
else:
key_match = re_key.match(self.s[self.ptr:])
if key_match is None:
raise Exception("Invalid key beginning at: %s" % self.s[self.ptr:])
key = key_match.group(0)
self.ptr += len(key)
# Consume colon
ptr=self.consume_whitespace()
if self.s[self.ptr]==':':
self.ptr+=1
else:
raise Exception("Expected colon for end of key (after ...%s), but got '%s' instead" % (self.s[max(self.ptr-10,0):self.ptr], self.s[self.ptr]))
return key
def render_attributes(self):
attributes=[]
for k, v in self.dict.items():
if k != 'id' and k != 'class':
# Boolean attributes
if v==None:
attributes.append( "%s" % (k,))
else:
attributes.append( "%s='%s'" % (k,v))
return ' '.join(attributes)
class AttributeTupleAndListParser(AttributeParser):
def __init__(self, s):
if s[0]=='(':
terminator = ')'
elif s[0]=='[':
terminator = ']'
AttributeParser.__init__(self, s, terminator)
def parse(self):
lst=[]
# Todo: Must be easier way...
val=True
while val != False:
val = self.parse_value()
if val != False:
lst.append(val)
self.ptr +=1
if self.terminator==')':
return tuple(lst)
else:
return lst
</code></pre>
<p>The class can be used stand-alone as follows:</p>
<pre><code>>>> from attribute_dict_parser import AttributeDictParser
>>> a=AttributeDictParser("{'id': 'a', 'class': 'b'}")
>>> d=a.parse()
>>> d
{'id': 'a', 'class': 'b'}
>>> type(d)
<type 'dict'>
</code></pre>
<p><code>AttributeDictParser</code> iterates through characters in <code>s</code> (the attribute dictionary) and uses the variable <code>ptr</code> to track its location (to prevent unnecessary string splicing). The function <code>parse_key</code> parses the keys (<code>'id':</code> and <code>'class':</code>), and the function <code>parse_value</code> parses the values (<code>'a'</code> and <code>'b'</code>). parse_value works with data types other than strings. It returns <code>False</code> if it reaches the end of the attribute dictionary, because <code>Null</code> is a valid value to return.</p>
<p><code>AttributeTupleAndListParser</code> parses list and tuple values, as these are valid values (e.g. <code>{'id': ['a','b','c']}</code>. </p>
<p>Both of these classes inherit from <code>AttributeParser</code> because they share the same way of parsing values.</p>
<h2>Questions:</h2>
<ol>
<li><p>Is this a sensible approach? Am I insane to think that I can move from <code>eval()</code>ing the code as a Python dictionary to a custom parser without causing issues for users, just because it passes the tests?</p></li>
<li><p>I'm worried that the performance hit of writing a parser in an interpreted language will be too much compared to doing the <code>eval()</code>. I've written similar things before for parsing JSON expressions, and was dismayed that for all my optimisations, the two-line regular expression won on the benchmarks. I will do some profiling on it once I've tidied up a few things. Are there any notable ineffeciencies in my approach?</p></li>
<li><p>There are some things in the old parser that have not been ported to the new one (e.g. supporting the Ruby Haml <code>=></code> syntax). This feature has never been documented however and I doubt anybody knows it's there. What is a good rule of thumb for breaking an undocumented feature in open source projects?</p></li>
<li><p>I would welcome any feedback on my coding style, as I don't get to be around other developers much.</p></li>
</ol>
|
[] |
[
{
"body": "<h3>1. Answers to your questions</h3>\n<ol>\n<li><p>If the goal of the project is to be able to include Haml in attribute values, then you've got no choice but to switch to your own parser. I haven't looked at the set of test cases, but it does seem plausible that you are going to introduce incompatibilities because of the complexity of Python's own parser. You are going to find that you have users who used the oddities of Python's string syntax (<code>r</code>-strings, <code>\\u</code>-escapes and all).</p>\n<p>The way to manage the transition from the old parser to the new is to start out by shipping both, with the old parser selected by default, but the new parser selectable with an option. This gives your users time to discover the incompatibilities and fix them (or submit bug reports). Then in a later release make the new parser the default, but with the old parser available but deprecated. Finally, remove the old parser.</p>\n</li>\n<li><p>Correctness and simplicity first, speed later. You can always port the parser to C if nothing else will do.</p>\n</li>\n<li><p>My answer to question 1 applies here too.</p>\n</li>\n<li><p>See below.</p>\n</li>\n</ol>\n<h3>2. Designing a parser</h3>\n<p>Now, let's look at the code. I thought about making a series of comments on the various misfeatures, but that seems less than helpful, given that the whole design of the parser isn't quite right:</p>\n<ol>\n<li><p>There's no separation between the lexer and the parser.</p>\n</li>\n<li><p>You have different classes for different productions in your syntax, so that each time you need to parse a tuple/list, you construct a new <code>AttributeTupleAndListParser</code> object, construct a string for it to parse (by copying the tail of the original string), and then throw away the parser object when done.</p>\n</li>\n<li><p>Some of your parsing methods don't seem well-matched to the syntax of the language, making it difficult to understand what they do. <code>consume_end_of_value</code> is a good example: it doesn't seem to correspond to anything natural in the syntax.</p>\n</li>\n</ol>\n<p>Computer science is by no means a discipline with all the answers, but one thing that we know how to do is write a parser! You don't have to have read <a href=\"http://en.wikipedia.org/wiki/Compilers:_Principles,_Techniques,_and_Tools\" rel=\"noreferrer\">the dragon book</a> from cover to cover to know that it's conventional to develop a <a href=\"http://en.wikipedia.org/wiki/Formal_grammar\" rel=\"noreferrer\"><em>formal grammar</em></a> for your language (often written down in a variation on <a href=\"http://en.wikipedia.org/wiki/Backus%E2%80%93Naur_form\" rel=\"noreferrer\">Backus–Naur form</a>), and then split your code into a <a href=\"http://en.wikipedia.org/wiki/Lexical_analysis\" rel=\"noreferrer\"><em>lexical analyzer</em></a> (which transforms source code into <em>tokens</em> using a finite state machine or something similar) and a <a href=\"http://en.wikipedia.org/wiki/Parsing\" rel=\"noreferrer\"><em>parser</em></a> which takes a stream of tokens and constructs a <em>syntax tree</em> or some other form of output based on the syntax of the input.</p>\n<p>Sticking to this convention has a bunch of advantages: the existence of a formal grammar makes it easier to build compatible implementations; you can modify and test the lexical analyzer independently from the parser and vice versa; and other programmers will find it easier to understand and modify your code.</p>\n<h3>3. Rewriting your parser conventionally</h3>\n<p>Here's how I might start rewriting your parser to use the conventional approach. This implements a deliberately incomplete subset of the HamlPy attribute language, in order to keep the code short and to get it finished in a reasonable amount of time.</p>\n<p>First, a class whose instances represent source tokens. The original string and position of each token is recorded in that token so that we can easily produce an error message related to that token. I've used the built-in exception <code>SyntaxError</code> here so that the error messages match those from other Python libraries. (You might later want to extend this so that the class can represent tokens from files as well as tokens from strings.)</p>\n<pre><code>class Token(object):\n """\n An object representing a token in a HamlPy document. Construct it\n using `Token(type, value, source, start, end)` where:\n\n `type` is the token type (`Token.DELIMITER`, `Token.STRING`, etc);\n `value` is the token value;\n `source` is the string from which the token was taken;\n `start` is the character position in `source` where the token starts;\n `ends` is the character position in `source` where the token finishes.\n """\n\n # Enumeration of token types.\n DELIMITER = 1\n STRING = 2\n END = 3\n ERROR = 4\n\n def __init__(self, type, value, source, start, end):\n self.type = type\n self.value = value\n self.source = source\n self.start = start\n self.end = end\n\n def __repr__(self):\n type_name = 'UNKNOWN'\n for attr in dir(self):\n if getattr(self, attr) == self.type:\n type_name = attr\n break\n return ('Token(Token.{0}, {1}, {2}, {3}, {4})'\n .format(type_name, repr(self.value), repr(self.source),\n self.start, self.end))\n\n def matches(self, type, value):\n """\n Return True iff this token matches the given `type` and `value`.\n """\n return self.type == type and self.value == value\n\n def error(self, msg):\n """\n Return a `SyntaxError` object describing a problem with this\n token. The argument `msg` is the error message; the token's\n line number and position are also reported.\n """\n line_start = 1 + self.source.rfind('\\n', 0, self.start)\n line_end = self.source.find('\\n', self.end)\n if line_end == -1: line_end = len(self.source)\n e = SyntaxError(msg)\n e.lineno = 1 + self.source.count('\\n', 0, self.start)\n e.text = self.source[line_start: line_end]\n e.offset = self.start - line_start + 1\n return e\n</code></pre>\n<p>Second, the lexical analyzer, using Python's <a href=\"http://docs.python.org/library/stdtypes.html#iterator-types\" rel=\"noreferrer\">iterator protocol</a>.</p>\n<pre><code>class Tokenizer(object):\n """\n Tokenizer for a subset of HamlPy. Instances of this class support\n the iterator protocol, and yield tokens from the string `s` as\n Token object. When the string `s` runs out, yield an END token.\n\n >>> from pprint import pprint\n >>> pprint(list(Tokenizer('{"a":"b"}')))\n [Token(Token.DELIMITER, '{', '{"a":"b"}', 0, 1),\n Token(Token.STRING, 'a', '{"a":"b"}', 2, 3),\n Token(Token.DELIMITER, ':', '{"a":"b"}', 4, 5),\n Token(Token.STRING, 'b', '{"a":"b"}', 6, 7),\n Token(Token.DELIMITER, '}', '{"a":"b"}', 8, 9),\n Token(Token.END, '', '{"a":"b"}', 9, 9)]\n """\n def __init__(self, s):\n self.iter = self.tokenize(s)\n\n def __iter__(self):\n return self\n\n def next(self):\n return next(self.iter)\n\n # Regular expression matching a source token.\n token_re = re.compile(r'''\n \\s* # Ignore initial whitespace\n (?:([][{},:]) # 1. Delimiter\n |'([^\\\\']*(?:\\\\.[^\\\\']*)*)' # 2. Single-quoted string\n |"([^\\\\"]*(?:\\\\.[^\\\\"]*)*)" # 3. Double-quoted string\n |(\\S) # 4. Something else\n )''', re.X)\n\n # Regular expression matching a backslash and following character.\n backslash_re = re.compile(r'\\\\(.)')\n\n def tokenize(self, s):\n for m in self.token_re.finditer(s):\n if m.group(1):\n yield Token(Token.DELIMITER, m.group(1),\n s, m.start(1), m.end(1))\n elif m.group(2):\n yield Token(Token.STRING,\n self.backslash_re.sub(r'\\1', m.group(2)),\n s, m.start(2), m.end(2))\n elif m.group(3):\n yield Token(Token.STRING,\n self.backslash_re.sub(r'\\1', m.group(3)),\n s, m.start(3), m.end(3))\n else:\n t = Token(Token.ERROR, m.group(4), s, m.start(4), m.end(4))\n raise t.error('Unexpected character')\n yield Token(Token.END, '', s, len(s), len(s))\n</code></pre>\n<p>And third, the <a href=\"http://en.wikipedia.org/wiki/Compilers:_Principles,_Techniques,_and_Tools\" rel=\"noreferrer\">recursive descent</a> parser, with the formal grammar given in the docstring for the class. The parser needs one token of <a href=\"http://en.wikipedia.org/wiki/Parsing#Lookahead\" rel=\"noreferrer\">lookahead</a>.</p>\n<pre><code>class Parser(object):\n """\n Parser for the subset of HamlPy with the following grammar:\n\n attribute-dict ::= '{' [attribute-list] '}'\n attribute-list ::= attribute (',' attribute)*\n attribute ::= string ':' value\n value ::= string | '[' [value-list] ']'\n value-list ::= value (',' value)*\n """\n\n def __init__(self, s):\n self.tokenizer = Tokenizer(s)\n self.lookahead = None # The lookahead token.\n self.next_token() # Lookahead one token.\n\n def next_token(self):\n """\n Return the next token from the lexer and update the lookahead\n token.\n """\n t = self.lookahead\n self.lookahead = next(self.tokenizer)\n return t\n\n # Regular expression matching an allowable key.\n key_re = re.compile(r'[a-zA-Z_0-9-]+$')\n\n def parse_value(self):\n t = self.next_token()\n if t.type == Token.STRING:\n return t.value\n elif t.matches(Token.DELIMITER, '['):\n return list(self.parse_value_list())\n else:\n raise t.error('Expected a value')\n\n def parse_value_list(self):\n if self.lookahead.matches(Token.DELIMITER, ']'):\n self.next_token()\n return\n while True:\n yield self.parse_value()\n t = self.next_token()\n if t.matches(Token.DELIMITER, ']'):\n return\n elif not t.matches(Token.DELIMITER, ','):\n raise t.error('Expected "," or "]"')\n\n def parse_attribute(self):\n t = self.next_token()\n if t.type != Token.STRING:\n raise t.error('Expected a string')\n key = t.value\n if not self.key_re.match(key):\n raise t.error('Invalid key')\n t = self.next_token()\n if not t.matches(Token.DELIMITER, ':'):\n raise t.error('Expected ":"')\n value = self.parse_value()\n return key, value\n\n def parse_attribute_list(self):\n if self.lookahead.matches(Token.DELIMITER, '}'):\n self.next_token()\n return\n while True:\n yield self.parse_attribute()\n t = self.next_token()\n if t.matches(Token.DELIMITER, '}'):\n return\n elif not t.matches(Token.DELIMITER, ','):\n raise t.error('Expected "," or "}"')\n\n def parse_attribute_dict(self):\n t = self.next_token()\n if not t.matches(Token.DELIMITER, '{'):\n raise t.error('Expected "{"')\n return dict(self.parse_attribute_list())\n</code></pre>\n<p>You'll probably want to know how to handle Haml's significant whitespace. The way to do this is to modify the tokenizer to emit <code>NEWLINE</code>, <code>INDENT</code> and <code>DEDENT</code> tokens, and then modify <code>next_token</code> to take an <code>include_newlines</code> optional parameter, and discard or return these extra tokens as appropriate.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-09T17:16:51.363",
"Id": "15450",
"ParentId": "15395",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "15450",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-06T22:45:31.233",
"Id": "15395",
"Score": "5",
"Tags": [
"python",
"parsing",
"django",
"haml"
],
"Title": "Python parser for attributes in a HAML template"
}
|
15395
|
<p>I've been learning Python for about a year and now I'm trying to improve my JavaScript. I wrote this simple d3 visualization that shows your Facebook friends as a force-directed graph. Here's a <a href="http://ecmendenhall.github.com/d3friendgraph/" rel="nofollow">live version</a> and here's <a href="https://github.com/ecmendenhall/d3friendgraph" rel="nofollow">the source</a> on GitHub. It works well, but it can be slow.</p>
<p>I understand that the number of edges to calculate grows \$O(n^2)\$ with nodes, so complexity increases quickly for users with lots of friends, but I'm wondering if:</p>
<ol>
<li><p>there are any obvious optimizations I could make</p></li>
<li><p>what bad habits I might be importing from Python</p></li>
<li><p>how I might tweak the layout parameters to reach equilibrium faster</p></li>
</ol>
<p>I'm pretty new to programming and very new to JavaScript, so I'm sure I'm making some mistakes.</p>
<p>Content of file friendgraph.js:</p>
<pre><code>// Facebook SDK
// Initialize the Facebook SDK
window.fbAsyncInit = function () {
FB.init({
appId: '341827359241906', // App ID
channelUrl: 'channel.html', // Path to your Channel File
status: true, // check login status
cookie: true, // enable cookies to allow the server to access the session
xfbml: true // parse XFBML
});
// Listen for and handle auth.statusChange events
FB.Event.subscribe('auth.statusChange', function(response) {
if (response.authResponse) {
// On login...
FB.api('/me', function(me) {
if (me.name) {
// Display user name
document.getElementById('auth-displayname').innerHTML = me.name;
// Retrieve friends API object
FB.api('/me/friends', getFriends);
}
})
document.getElementById('auth-loggedout').style.display = 'none';
document.getElementById('auth-loggedin').style.display = 'block';
} else {
// User has not authorized your app or isn't logged in
document.getElementById('auth-loggedout').style.display = 'block';
document.getElementById('auth-loggedin').style.display = 'none';
}
});
// Respond to clicks on login and logout links
document.getElementById('auth-loginlink').addEventListener('click', function() {
FB.login();
});
document.getElementById('auth-logoutlink').addEventListener('click', function(){
FB.logout();
});
}
function indexWithAttribute(array, attr, value) {
// Iterates over an array and returns the index of the element
// whose attribute matches the given value.
for(var i=0; i < array.length; i++) {
if(array[i][attr] === value) {
return i;
}
}
}
function showName(d) {
// Displays given d3 node's 'name' attribute.
document.getElementById('selected-friend-name').innerHTML = d['name'];
}
function getMutualFriends(id, friends, friendlinks) {
// Retrieves a Facebook API object containing mutual friends
// for a given user ID. Passes it to the getLinks() function.
FB.api('/me/mutualfriends/' + id, function (response) {
getLinks(response, id, friends, friendlinks); }
);
}
function getLinks(response, id, friends, friendlinks) {
// Calculates links between mutual friends and pushes them to an array.
// Displays percent of friend links completed in 'load-status' div.
var mutualFriends = response['data'];
var sourceIndex = indexWithAttribute(friends, 'id', id);
var completed = Math.round(100*(sourceIndex/friends.length));
document.getElementById('load-status').innerHTML = 'Calculating mutual friend links: ' + completed + '%'
for (i=0; i< mutualFriends.length; i++) {
friends[sourceIndex]['value'] = mutualFriends.length;
targetIndex = indexWithAttribute(friends, 'id', mutualFriends[i]['id']);
friendlinks.push({'source':sourceIndex,
'target':targetIndex,
'value':mutualFriends.length });
}
if (sourceIndex === friends.length - 1) {
graphFriends(friends, friendlinks); }
}
function getFriends(response) {
// Loads friend nodes as an array. Creates array to hold links between mutual friends.
var friends = response['data']
var friendlinks = []
for (i=0; i < friends.length; i++) {
var id = friends[i]['id'];
getMutualFriends(id, friends, friendlinks);
}
}
function graphFriends(friends, friendlinks) {
// Configures a d3 force-directed graph of friends and friend links.
document.getElementById('load-status').innerHTML = ''
// Set dimensions of svg
var width = window.innerWidth - 100,
height = window.innerHeight - 100;
// Set up a 10-color scale for node colors
var color = d3.scale.category10()
// Set up a linear scale to map number of mutual
// friends to node radius
var r = d3.scale.linear()
.domain([1,100])
.range([5,15])
// Set the initial parameters of the force() layout
var force = d3.layout.force()
.charge(-75)
.linkDistance(40)
.size([width / 1.2, height / 2])
// Add svg and start visualization
var svg = d3.select("#viz").append("svg")
.attr("width", width)
.attr("height", height);
// Pass in friends array as graph nodes and friendlinks
// array as graph edges.
force.nodes(friends)
.links(friendlinks)
.start();
var link = svg.selectAll("line.link")
.data(friendlinks)
.enter().append("line")
.attr("class", "link")
.style("stroke", "#eee")
.style("stroke-width", 1);
var node = svg.selectAll("circle.node")
.data(friends)
.enter().append("circle")
.attr("class", "node")
.attr("r", function(d) { return r(d.value); })
.style("stroke", "#eee")
.style("fill", function(d) { return color(d.value); })
.on("mouseover", function(d) { showName(d); })
.call(force.drag);
force.on("tick", function() {
link.attr("x1", function(d) { return d.source.x; })
.attr("y1", function(d) { return d.source.y; })
.attr("x2", function(d) { return d.target.x; })
.attr("y2", function(d) { return d.target.y; });
node.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; });
});
}
</code></pre>
<p>index.html:</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://d3js.org/d3.v2.js"></script>
<script type="text/javascript" src="http://connect.facebook.net/en_US/all.js">
</script>
<script type="text/javascript" src="friendgraph.js">
</script>
<title>d3.js Facebook friend visualization</title>
</head>
<body>
<div id="viz">
</div>
<div id="fb-root">
<div><p>
<h3>d3.js Facebook graph visualization</h3>
by <a href="http://twitter.com/ecmendenhall">ecmendenhall</a></p>
</div>
<div id="selected-friend-name"></div>
<div id="auth-status">
<div id="auth-loggedout">
<a href="#" id="auth-loginlink">Login</a>
</div>
<div id="auth-loggedin" style="display:none">
Logged in as <span id="auth-displayname"></span>
(<a href="#" id="auth-logoutlink">logout</a>)
</div>
<div id="load-status"></div>
</div>
</body>
</html>
</code></pre>
|
[] |
[
{
"body": "<p>I couldn't test out your application since I don't have a facebook account but here are some tips:</p>\n\n<h1>1) Use dot notation instead of bracket notation to access known property names.</h1>\n\n<p>Old Code: </p>\n\n<pre><code>friends[sourceIndex]['value'];\n</code></pre>\n\n<p>New Code:</p>\n\n<pre><code>friends[sourceIndex].value;\n</code></pre>\n\n<h1>2) Keep the operations peformed within a loop to the bare minimum.</h1>\n\n<p>For performance, it's best to avoid nested loops and function calls within a loop. </p>\n\n<p>From your code:</p>\n\n<pre><code>//...\nfunction indexWithAttribute(array, attr, value) {\n for (var i = 0; i < array.length; i++) {\n if (array[i][attr] === value) {\n return i;\n }\n }\n}\n//...\nfunction getLinks(response, id, friends, friendlinks) {\n//...\n for (i = 0; i < mutualFriends.length; i++) {\n friends[sourceIndex]['value'] = mutualFriends.length;\n targetIndex = indexWithAttribute(friends, 'id', mutualFriends[i]['id']);\n//...\n</code></pre>\n\n<p>The code above is bad for performance because the for loop contains calls to <code>indexWithAttribute()</code>, which contains another for loop.\nThe deeply nested iterations will result in O(N^2) completion time.</p>\n\n<p>One possible solution for this problem would be to create a hash table for the ids to index relationship. Hash tables take O(1) to find a value but require more memory, unlike a for loop O(n/2).</p>\n\n<p>Code:</p>\n\n<pre><code>/**\n* Returns a lookup table for the relationship (key)attribute to (value)index from an array of objects.\n* This function expects that all referenced attributes will have a unique value.\n* \n* @author Larry Battle <bateru.com/news>\n* @param [Array] arr - An array of objects.\n* @param [String] attr - A common property name amoung all the objects in `arr`.\n* @returns [Object]\n* @example\n\n var arr = [\n { id: 2 },\n { id: 12 },\n { id: 89 }\n ];\n var hash = createAttributeToIndexTable( arr, \"id\" );\n console.log( JSON.stringify( hash ) = '{\"2\":0,\"12\":1,\"89\":2}' );\n\n**/\nvar createAttributeToIndexTable = function( arr, attr ){\n var hash = {};\n for( var i = 0, len = arr.length; i < len; i++ ){\n hash[ arr[i][attr] ] = i;\n }\n return hash;\n};\n</code></pre>\n\n<p>Old code:</p>\n\n<pre><code>function getLinks(response, id, friends, friendlinks) {\n var mutualFriends = response['data'];\n var sourceIndex = indexWithAttribute(friends, 'id', id);\n var completed = Math.round(100*(sourceIndex/friends.length));\n\n document.getElementById('load-status').innerHTML = 'Calculating mutual friend links: ' + completed + '%' \n for (i=0; i< mutualFriends.length; i++) {\n friends[sourceIndex]['value'] = mutualFriends.length;\n targetIndex = indexWithAttribute(friends, 'id', mutualFriends[i]['id']);\n friendlinks.push({'source':sourceIndex, \n 'target':targetIndex,\n 'value':mutualFriends.length });\n } \n if (sourceIndex === friends.length - 1) { \n graphFriends(friends, friendlinks); \n } \n}\n</code></pre>\n\n<p>New code:</p>\n\n<pre><code>var createAttributeToIndexTable = function( arr, attr ){\n var hash = {};\n for( var i = 0, len = arr.length; i < len; i++ ){\n hash[ arr[i][attr] ] = i;\n }\n return hash;\n};\nfunction getLinks(response, id, friends, friendlinks) {\n var mutualFriends = response.data;\n var idToIndexTable = createAttributeToIndexTable( friends, 'id' );\n var sourceIndex = idToIndexTable[id];\n var completed = Math.round(100 * (sourceIndex / friends.length));\n document.getElementById('load-status').innerHTML = 'Calculating mutual friend links: ' + completed + '%'\n for (i = 0; i < mutualFriends.length; i++) {\n friends[sourceIndex].value = mutualFriends.length;\n targetIndex = idToIndexTable[ mutualFriends[i].id ];\n friendlinks.push({\n 'source' : sourceIndex,\n 'target' : targetIndex,\n 'value' : mutualFriends.length\n });\n }\n if (sourceIndex === friends.length - 1) {\n graphFriends(friends, friendlinks);\n }\n}\n</code></pre>\n\n<h1>3) Add a small delay to avoid locking up the webpage. Or use webworkers.</h1>\n\n<p>Old Code:</p>\n\n<pre><code>function getMutualFriends(id, friends, friendlinks) {\n FB.api('/me/mutualfriends/' + id, function (response) {\n getLinks(response, id, friends, friendlinks);\n });\n}\n</code></pre>\n\n<p>New Code:</p>\n\n<pre><code>function getMutualFriends(id, friends, friendlinks) {\n FB.api('/me/mutualfriends/' + id, function (response) {\n setTimeout(function(){\n getLinks(response, id, friends, friendlinks);\n }, 100);\n });\n}\n</code></pre>\n\n<p>Note:</p>\n\n<p>Find a way to simplify this section. I think there might be a way to append a clone of a line without recreating it everytime.</p>\n\n<p>Code:</p>\n\n<pre><code>force.nodes(friends).links(friendlinks).start();\nvar link = svg.selectAll(\"line.link\").data(friendlinks).enter().append(\"line\").attr(\"class\", \"link\").style(\"stroke\", \"#eee\").style(\"stroke-width\", 1);\nvar node = svg.selectAll(\"circle.node\").data(friends).enter().append(\"circle\").attr(\"class\", \"node\").attr(\"r\", function (d) {\n return r(d.value);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-21T20:38:41.943",
"Id": "15820",
"ParentId": "15396",
"Score": "9"
}
},
{
"body": "<p>You can also reduce the memory load and increase effeciency by converting your objects into arrays and accessing them with indexes.</p>\n\n<p>Instead of:</p>\n\n<pre><code>var data = [\n { \n source : {\n x: 101,\n y: 242\n }\n target : {\n x : 353,\n y : 456\n }\n x : 555,\n y : 654\n },\n ...\n]\n</code></pre>\n\n<p>use</p>\n\n<pre><code>var data = [\n [101,242,353,356,555,654],\n ...\n]\n</code></pre>\n\n<p>This does decrease readability but if you want to make things clearer you can use variables to represent the indexes, something like:</p>\n\n<pre><code>var i_source_x = 0,\n i_source_y = 1,\n i_target_x = 2,\n i_target_y = 3,\n i_x = 4,\n i_y = 5;\n\ndata[0][i_source_x] === 101 // true\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-09-21T16:01:38.093",
"Id": "142036",
"ParentId": "15396",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "15820",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-06T22:52:47.377",
"Id": "15396",
"Score": "8",
"Tags": [
"javascript",
"performance",
"graph",
"d3.js",
"facebook"
],
"Title": "D3 visualization of a Facebook friend graph"
}
|
15396
|
<p>I have to read in a file full of <code>int</code>s, print them in reverse order, and then calculate the median and the mode of the set.</p>
<p>At first I struggled with figure out a way to calculate the mode. It seemed so simple but I just couldn't translate the steps into code. I did come up with a solution and it works but because of my struggle at first I just wanted to get some feedback on if this was a good method or if there's better ways to do it.</p>
<pre><code>#include <iostream> //IO to the screen
#include <fstream> //File IO
#include <string> //String manipulation
using namespace std;
/*CONSTANTS*/
const int MAX_ELEMENTS = 100;
const string FILENAME = "data.dat";
/*TYPEDEFS*/
typedef int IntArr[MAX_ELEMENTS]; //data type for an integer array of 100 elements.
/*PROTOTYPES*/
void Print(const IntArr& outArr, int numFilled); //Prints the array in reverse order.
void Sort(IntArr& outArr, int numFilled);
int CalcMode(const IntArr& numArr, int numFilled);
void main()
{
/*VARIABLES*/
IntArr numArr; //Holds the integers read in from the file.
ifstream din;
din.open(FILENAME.c_str());
//The file exists.
if(!din)
{
cout << "ERROR: \"" << FILENAME << "\" not found. Program terminating." << endl;
abort();
}//End file exists check
int ind = 0; //The current index of the array to write to.
int num;
din >> num;
//While the last read was successfull
while(din)
{
//Place the num into the array, increment the index counter, and read the next int.
numArr[ind] = num;
ind++;
din >> num;
} //End while loop
Print(numArr, ind);
Sort(numArr, ind);
int median = (ind - 1) / 2;
cout << endl << "Median: " << numArr[median] << endl;
cout << "Mode: " << numArr[ CalcMode(numArr,ind) ] << endl;
} //End main method.
//Pre: outArr has been filled with integers from the file specified and numFilled is the number of filled indices.
//Post: outArr has been output to the screen in reverse order..
//Purpose: Print out the contents of an array to a screen in reverse order.
void Print(/*IN*/const IntArr& outArr, //Array to be printed
/*IN*/int numFilled) //Number of filled indices
{
//Iterate through the array in reverse order and output to the screen.
for(int i = numFilled - 1; i >= 0; i--)
{
cout << outArr[i] << endl;
}//End for loop
}//End Print()
//Pre: The array has been loaded with data from a file.
//Post: The array has been sorted.
//Purpose: To bubble sort the array.
void Sort(/*IN*/ IntArr& outArr, //Array to be sorted
/*IN*/ int numFilled) //number of filled indicies in the array
{
//Bubble sort because there's so few elements in the array... and I'm lazy.
bool sorted = false;
//Use a test flag to determine if the array is sorted.
//If not, continue looping
while(!sorted)
{
sorted = true;
//Iterate through every item in the array excluding the last.
for(int i = 0; i < numFilled - 1; i++)
{
//Check to see if the current num is larger than the next.
if(outArr[i] > outArr[i+1])
{
int temp = outArr[i];
outArr[i] = outArr[i+1];
outArr[i+1] = temp;
sorted = false;
}//End If
}//End For
}//End While
}//End Sort()
//Pre: The array passed in should already be sorted.
//Post: Returns the number that occurs the most.
//Purpose: Determine which number occurs most often in a sorted array.
int CalcMode(/*IN*/ const IntArr& numArr, //Sorted array to calculate the mode for.
/*IN*/ int numFilled) //Number of filled indices.
{
int modeArr[MAX_ELEMENTS][1];
//Initialize the int in the second dimension of every element.
for(int i = 0; i < MAX_ELEMENTS; i++)
modeArr[i][0] = 0;
//Count the number of occurences for each number in the array
for(int i = 0; i < numFilled - 1; i++)
modeArr[ numArr[i] ][0]++;
int modeInd = 0;
//Iterate through each index and find out what number had the most occurences.
for(int i = 0; i < numFilled - 1; i++)
{
if(modeArr[ numArr[i] ][0] > modeArr[ numArr[modeInd] ][0])
{
modeInd = i;
}//End if
}//End for
return modeInd;
}//End CalcMode();
</code></pre>
|
[] |
[
{
"body": "<p>Try not to use the built-in array unless you have a constant sized data.</p>\n\n<pre><code>typedef int IntArr[MAX_ELEMENTS];\n</code></pre>\n\n<p>What happens if you have more than MAX_ELEMENTS.<br>\nIn C++ you would generally use a vector to hold this information.</p>\n\n<pre><code> typedef std::vector<int> IntArr;\n</code></pre>\n\n<p>Don't see any benifit in putting the filename in a variable like this:</p>\n\n<pre><code>const string FILENAME = \"data.dat\";\n</code></pre>\n\n<p>Also it is traditional to reserve names that are all uppercase as MACROS. So you will confuse people that understand normal C++ into thinking these are macros names. So try and use camel case for you variable names (its also a lot nicer to read when code is not shooting at you).</p>\n\n<p>Your loop for reading is correct. Which is a bit of a surprise as just testing the stream like that is usually an anti-pattern. But we can make that loop simpler:</p>\n\n<pre><code> int num;\n din >> num;\n\n while(din)\n {\n numArr.push_back(num); // remember I changed this to a vector\n\n din >> num;\n }\n</code></pre>\n\n<p>First improvement: The result of the read operation (operator>>) is a stream (this allows chaining). But when a stream is used in a boolean context (like above) it is converted to a bool like value that can be testes. We can use and change the above loop to this:</p>\n\n<pre><code> int num;\n while(din >> num)\n { // If the read worked we enter the loop body.\n numArr.push_back(num);\n }\n</code></pre>\n\n<p>But using the C++ algorithm library we can reduce this one more time:</p>\n\n<pre><code> std::copy(std::istream_iterator<int>(din),\n std::istream_iterator<int>(),\n std::back_inserter(numArr));\n</code></pre>\n\n<p>Now you have a print specifically print an array in reverse order: We can use the algorithms to do that for you:</p>\n\n<pre><code>void Print(const IntArr& outArr, int numFilled);\n\n// can be replaced with:\n\n// Print the array in forward order\nstd::copy(numArr.begin(), numArr.end(), std::ostream_iterator<int>(std::cout, \"\\n\"));\n\n// Print the array in reverse order order\nstd::copy(numArr.rbegin(), numArr.rend(), std::ostream_iterator<int>(std::cout, \"\\n\"));\n</code></pre>\n\n<p>You can use the standard routines to sort the vector (or a normal array).</p>\n\n<pre><code>void Sort(IntArr& outArr, int numFilled);\n\n// can be replaced with:\n\nstd::sort(numArr.begin(), numArr.end());\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-07T00:15:25.760",
"Id": "24972",
"Score": "0",
"body": "Thanks for the answer. Unfortunately a lot of what you suggested is out of my control. The array is at the instruction of the professor. I asked last semester we're not allowed to use Vectors as far as I know, as they haven't covered them in class, plus having all those methods is the easy way out and they want us to do everything by hand for learning.\n\nSame thing goes for the capitals on the constants. Our class' documentation standards states that constants must be declared in all caps."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-07T00:25:53.907",
"Id": "24973",
"Score": "0",
"body": "OK. I understand about the learning stuff and I agree with that. But you can tell you professor that I said he was an idiot. Using all caps for constants will cause problems as macro names have no scope boundaries and those names are common enough that it is inevitable that they will be used."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-07T06:09:32.750",
"Id": "24979",
"Score": "1",
"body": "You can actually go even one more step in reading the data into the vector: initialize the vector from the iterators: `std::vector<int> numArray((std::istream_iterator<int>(din)), std::istream_iterator<int>());` (the seemingly redundant parens on the first argument prevent the most vexing parse). Since the sort seems to be used only to find the median, you can use `nth_element` instead."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-07T06:31:22.233",
"Id": "24981",
"Score": "0",
"body": "@JerryCoffin: The reason I don't like that technique is for maintainability. Having to explain why you need an extra set of paren can be painful. Thus I prefer to use one extra iterator."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-07T07:34:35.810",
"Id": "24983",
"Score": "0",
"body": "@JerryCoffin: I think using `::din` would be clearer than adding redundant parens."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-06T23:41:31.947",
"Id": "15398",
"ParentId": "15397",
"Score": "2"
}
},
{
"body": "<p>If you have a sorted array and want to determine the most frequently-occurring value, use the fact that all repetitions of the same value will be adjacent.</p>\n\n<p>Now you know what you're aiming for, can you write it yourself, or do you want to see the code?</p>\n\n<hr>\n\n<p>Hint: you don't need an associative store of counters off to the side, only:</p>\n\n<ul>\n<li>the most-occurring value so far (longest run seen)</li>\n<li>the number of times it occurred (run length)</li>\n<li>the value in the current run</li>\n<li>the length of the current run so far</li>\n<li>a working index to iterate over the input array</li>\n</ul>\n\n<p>It's a 1-pass algorithm with linear time and constant space overhead. It's actually related to run-length encoding, if that helps.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-10T12:10:19.707",
"Id": "25093",
"Score": "0",
"body": "This is what I was originally planning on doing but I couldn't figure out a way to properly implement it. The program isn't due until tomorrow morning so I'll give it another try. Thanks!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-10T12:56:50.993",
"Id": "25095",
"Score": "0",
"body": "Just finished implementing that algorithm. If I can, I'll edit the code into the question, if not it's here: http://pastebin.com/rsdm5txr"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-07T13:09:06.887",
"Id": "15411",
"ParentId": "15397",
"Score": "5"
}
},
{
"body": "<p>I suggest to avoid comments. Instead of them, try to write self-describing code. For example, I'd replace:</p>\n\n<pre><code>//Iterate through every item in the array excluding the last.\n for(int i = 0; i < numFilled - 1; i++)\n</code></pre>\n\n<p>with (<code>Idx</code> stands for <code>Index</code>)</p>\n\n<pre><code>int penultimateIdx = numFilled-1;\nfor(int itemIdx = 0; itemIdx < penultimateIdx; itemIdx++)\n</code></pre>\n\n<p>In the other hand <code>//Bubble sort because there's so few elements in the array... and I'm lazy.</code> is an example of good comment because it simply explains something instead of trying to describe code.</p>\n\n<p>Next example - code under following comment is so obvious that the comment is unnecessary and just clutters the code:</p>\n\n<pre><code>//Use a test flag to determine if the array is sorted.\n//If not, continue looping\n</code></pre>\n\n<p>Last example:</p>\n\n<pre><code>int ind = 0; //The current index of the array to write to.\n</code></pre>\n\n<p>Don't you think that the following is more readable?</p>\n\n<pre><code>int arrayIndex = 0;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-12-11T23:01:14.243",
"Id": "210526",
"Score": "0",
"body": "Yes, giving -1 is very easy. It's always harder to write a comment. Good luck."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-12-01T09:58:01.133",
"Id": "112431",
"ParentId": "15397",
"Score": "-1"
}
},
{
"body": "<p>I took Useless' useful advice and instead of populating a secondary array I just iterated through the sorted array and calculated run lengths. Here's the code I came up with for that:</p>\n\n<pre><code>//Pre: The array passed in should already be sorted.\n//Post: Returns the number that occurs the most.\n//Purpose: Determine which number occurs most often in a sorted array. \nint CalcMode(/*IN*/ const IntArr& numArr, //Sorted array to calculate the mode for.\n /*IN*/ int numFilled) //Number of filled indices.\n{\n int modeInd = 0; //Index of the Mode\n int modeRun = 0; //Run Length of the current Mode\n\n int currInd = 0; //Index of Current Test\n int currRun = 0; //Current Run Length\n\n int ind = 0; //Working Index\n\n //Count the run for the first number in the array and initialize the currInd\n //I had this as an if inside the next while loop but it only executes for the first\n //number so I just separated it so it wasn't a Kobayashi Maru, hence wasting processing.\n while(numArr[ currInd ] == numArr[ modeInd ])\n {\n modeRun++;\n currInd++;\n }\n\n //Iterate through every element.\n while(ind < numFilled - 1)\n {\n //Test if the working num is part of the current run:\n if(numArr[ ind ] == numArr[ currInd ])\n {\n currRun++;\n }//end consecutivity test.\n else\n {\n currInd = ind;\n currRun = 0;\n }//end non-consecutive branch.\n\n //Test if the current run is longer than the recorded mode:\n if(currRun > modeRun)\n {\n modeInd = currInd;\n modeRun = currRun;\n\n //Move the currInd to the NEXT working index.\n currInd = ind + 1;\n currRun = 0;\n }//End if\n\n ind++;\n }//End while\n\n return modeInd;\n}//End CalcMode();\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-12-02T18:49:52.477",
"Id": "112637",
"ParentId": "15397",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "15411",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-06T23:18:38.187",
"Id": "15397",
"Score": "4",
"Tags": [
"c++",
"array"
],
"Title": "Calculating the mode of a set of ints"
}
|
15397
|
<p>I am posting the <strong>a</strong> section of the model of my application.</p>
<p>Any/all feedback would be very helpful as I am trying to build my PHP skills, but I will ask a couple specific questions that might help others as well. </p>
<ol>
<li><p>Is my escaping, as is, effective enough?</p></li>
<li><p>I tried to separate my model into a file that will deal with functions exclusive to 'Groups' and a file that will deal with database functions used by all sections of the app. Is this a good strategy? </p></li>
<li><p>My Group model could use some more refactoring, but what do you think of the way I take and return data? (by using $data and $input, $data being the variable that is returned the controller and will be eventually sent to the view via JSON)</p></li>
<li><p>What are your thoughts about 'public function show_one($user_id, $group_id, $privacy)' which is meant to display one groups information, given proper privacy settings?</p></li>
<li><p>Any other input will be greatly appreciated. I am working hard to improve my programming skills everyday. </p></li>
</ol>
<p><strong>Group Model</strong></p>
<p>2) The Group Model:</p>
<pre><code><?php
require_once("database.php");
class model {
///data is returned to the controller
public $data = array(
'success'=>0,
'msg' =>'There was a small problem, try again soon.',
'data_type' => 'group',
'action' => '',
'results'=> array(),
);
//anything that will be put into the DB will be held in input
public $input = array();
public $exclude =array();
public function __construct($a) {
Global $db;
$db->escape($a);
$this->input = $db->escape($a);
@$this->data['action'] = $a['action'];
}
//move insert and data return up here
}
class create_group_model extends model {
public function insert_new_group($a) {
Global $db;
$b = $db->insert_array('group', $a, 'action');
if ($b['mysql_affected_rows']===1) {
$this->data['success'] = 1;
$this->data['msg'] = 'Congrats, you created a new group.';
array_push($this->data['results'], $b['mysql_insert_id']);
return $this->data;
} else {
$this->data['success'] = 0;
$this->data['msg'] = 'No group created, try again soon.';
return $this->data;
}
}
}
class search_group_model extends model {
public function default_list_groups() {
$this->list_groups($this->input['lat'], $this->input['lng'], 'group', 10, 30, $this->input['user_id'], 'all' );
$this->data['msg'] = 'Updated';
return $this->data;
}
public function custom_list_groups() {//add custom settings
$this->list_groups($this->input['lat'], $this->input['lng'], 'group', 10, 10);
}
public function my_list_groups($id){
Global $db;
//fix distance 10000 here, so it doesnt take into account distance
$b = $db->def_g_list($this->input['lat'], $this->input['lng'], 'group', 10000, 30, (int)$id, 'mine');
if ($b !== 0) {
$this->data['success'] = 1;
while ($row = mysql_fetch_array($b, MYSQL_ASSOC)) {
array_push($this->data['results'], $row);
}
$this->data['msg'] = 0;
return ($this->data);
} else {
$this->data['msg'] = 'There was a small problem, try again soon.';
$this->data['success'] = 0;
return ($this->data);
}
}
public function show_one($user_id, $group_id, $privacy) {
Global $db;
(bool)$confirm = FALSE;
if($privacy === 0){
$confirm = TRUE;
}else {
$confirm = FALSE;
$privacy = 1;
}
if(!$confirm){
$s = 'group_id';
$f = 'user_group_rel';
$w = sprintf("user_id =%d AND group_id=%d",$user_id, $group_id);
$b = $db->exists($s,$f,$w);
if(mysql_num_rows($b) ===1 && !is_num($b)) {
$confirm=true;
}
}
if($confirm){
$s = 'group_id,group_name,location_name,description,
user_id,lat,lng,created_by_name,state';
$f = 'group';
$w = sprintf("group_id=%d AND privacy=%d",(int)$group_id, (int)$privacy);
$b = $db->exists($s,$f,$w);
if(mysql_num_rows($b) ===1 && !is_int($b)) {
$this->data['success'] = 1;
$this->data['msg'] = 0;
while ($row = mysql_fetch_array($b, MYSQL_ASSOC)) {
array_push($this->data['results'], $row);
}
$this->data['results'][0]['people']= $this->group_mems($user_id, $group_id);
$this->data['results'][0]['total_people']= $this->group_mems_count($group_id);
return ($this->data);
}
}
$this->data['msg'] = 'There was a small problem, try again soon.';
$this->data['success'] = 0;
echo 'still going';
return ($this->data);
}
public function group_mems($me, $group_id) {
Global $db;
$result = array();
$q = sprintf("
SELECT
t1.group_id, t2.user_id, t2.username, t2.first_name, t2.last_name, t2.user_id = %d as me
FROM user_group_rel t1
LEFT JOIN users t2 ON t1.user_id = t2.user_id
WHERE group_id = %d and status = 1
ORDER BY me desc",
(int)$me, (int)$group_id);
$b = $db->query($q);
if ($b !== 0 and is_resource($b)) {
while ($row = mysql_fetch_array($b, MYSQL_ASSOC)) {
array_push($result, $row);
}
return $result;
} else {
return 'err';
}
}
public function group_mems_count($group_id) {
Global $db;
$result = array();
$q = sprintf("
SELECT
count(t1.user_id) as people
FROM user_group_rel t1
WHERE group_id = %d and t1.status = 1",
(int)$group_id);
$b = $db->query($q);
if ($b !== 0 and is_resource($b)) {
while ($row = mysql_fetch_array($b, MYSQL_ASSOC)) {
array_push($result, $row);
}
return $result[0]['people'];
} else {
return 'err';
}
}
private function list_groups($lat, $lng, $table, $distance, $limit, $id, $whos) {
Global $db;
$b = $db->def_g_list($lat, $lng, $table, $distance, $limit, (int)$id, $whos);
if ($b !== 0) {
$this->data['success'] = 1;
while ($row = mysql_fetch_array($b, MYSQL_ASSOC)) {
array_push($this->data['results'], $row);
}
return ($this->data);
} else {
$this->data['msg'] = 'There was a small problem, try again soon.';
$this->data['success'] = 0;
return ($this->data);
}
}
}
class join_group_model extends model {
public function join_group() {
Global $db;
$pass = 0;
if(array_key_exists('password', $this->input) && strlen($this->input['password'])>20) {
$pass = $db->pass_check('group', $this->input['group_id'],$this->input['password'] );
}
else {
$pass = $db->pass_check('group', $this->input['group_id'],'NULL' );
}
if($pass !==0) {
array_push($this->exclude, 'password', 'action');
$b = $db->insert_array('user_group_rel',$this->input, $this->exclude);
//echo print_r($b);
if ($b !== 0) {
$this->data['success'] = 1;
$this->data['results'] = $this->input['group_id'];
$this->data['msg'] = ' you joined a new group. ';
return ($this->data);
} else {
$this->data['msg'] = 'There was a small problem, try again soon.';
$this->data['success'] = 0;
return ($this->data);
}
}
}
public function unjoin_group() {
Global $db;
$b = $db->delete('user_group_rel', (int)$this->input['user_id'], (int)$this->input['group_id']);
if ($b !== 0) {
$this->data['success'] = 1;
$this->data['results'] = $this->input['group_id'];
$this->data['msg'] = ' you left that group. ';
return ($this->data);
} else {
$this->data['msg'] = 'There was a small problem, try again soon.';
$this->data['success'] = 0;
return ($this->data);
}
}
}
</code></pre>
<p><strong>Database</strong></p>
<p>3) Application wide database methods. A couple notes:</p>
<p>a) Probably the most glaring mistake here is not using PDO statements.</p>
<pre><code><?php
require_once('../config/config.php');
class MySQLDatabase {
private $connection;
public $last_query;
private $magic_quotes_active;
private $real_escape_string_exists;
function __construct() {
$this->open_connection();
$this->magic_quotes_active = get_magic_quotes_gpc();
$this->real_escape_string_exists = function_exists( "mysql_real_escape_string" );
}
public function open_connection() {
$this->connection = mysql_connect(DB_SERVER, DB_USER, DB_PASS);
if (!$this->connection) {
die("Database connection failed: " . mysql_error());
} else {
$db_select = mysql_select_db(DB_NAME, $this->connection);
if (!$db_select) {
die("Database selection failed: " . mysql_error());
}
}
}
public function close_connection() {
if(isset($this->connection)) {
mysql_close($this->connection);
unset($this->connection);
}
}
public function query($sql) {
$this->last_query = $sql;
$result = mysql_query($sql, $this->connection);
$this->confirm_query($result);
return $result;
}
public function escape($q) {
if(is_array($q))
foreach($q as $k => $v)
$q[$k] = $this->escape($v); //recursive
else if(is_string($q)) {
$q = mysql_real_escape_string($q);
}
return $q;
}
private function confirm_query($result) {
if (!$result) {
$output = "Database query failed: " . mysql_error() . "<br /><br />";
die( $output );
}
}
public function exists($s,$f, $w) {
//rewrite bottom 2 functions rid of this function
$q = sprintf("SELECT %s FROM %s WHERE %s LIMIT 1",$s,$f, $w);
//echo $q;
$result = $this->query($q);
if (mysql_num_rows($result)===0) {
return 0;
} else if (mysql_num_rows($result)===1) {
return $result;
} else{
return 0;
}
}
public function pass_check($t, $id, $p) {
if ($p==='NULL'){
$q = sprintf("SELECT * FROM %s WHERE %s_id = %s AND password is NULL", $t,$t,$id);
}
else{
$q = sprintf("SELECT * FROM %s WHERE %s_id = %s AND password = '%s'", $t,$t,$id,$p);
}
$result = $this->query($q);
if (mysql_num_rows($result)===0) {
return (int)0;
} else if (mysql_num_rows($result)>0) {
return $result;
}
}
public function insert_array($table, $data, $exclude = array()) {
$fields = $values = array();
if( !is_array($exclude) ) $exclude = array($exclude);
foreach( array_keys($data) as $key ) {
if( !in_array($key, $exclude) ) {
$fields[] = "`$key`";
$values[] = "'" .$data[$key] . "'";
}
}
$fields = implode(",", $fields);
$values = implode(",", $values);
if( mysql_query("INSERT INTO `$table` ($fields) VALUES ($values)") ) {
return array( "mysql_error" => false,
"mysql_insert_id" => mysql_insert_id(),
"mysql_affected_rows" => mysql_affected_rows(),
"mysql_info" => mysql_info()
);
} else {
echo print_r(array( "mysql_error" => mysql_error() ));
return 0;
}
}
public function def_g_list($lat, $lng, $table, $dist, $limit, $id, $whos='all') {
//either refactor to make this function more flexible or get rid of table variable
$where = '';
if(is_int($id) && $id>0 && $id < 100000 && $whos == 'all'){
//subquery used to display only groups the user is NOT IN- probably a better way to do this
$where = sprintf("
t2.group_id NOT IN (
SELECT user_group_rel.group_id
FROM user_group_rel
WHERE user_group_rel.user_id =%d)",
(int)$id);
} else if (is_int($id) && $id>0 && $id < 100000 && $whos == 'mine') {
$where = 't3.user_id = ' . (int)$id;
} else {
return 0;
}
$d_formula = $this->distance_formula($lat, $lng, 't1');
//sorry for this query
$q = sprintf("
SELECT
t1.group_id, t1.group_name, t1.location_name, t1.description, t1.lat, t1.lng, t1.privacy,t2.people, %s
FROM %s AS t1
JOIN (SELECT group_id, count(group_id) as people
FROM user_group_rel
GROUP BY group_id) t2
ON t1.group_id = t2.group_id
JOIN (SELECT user_group_rel.group_id, user_group_rel.user_id
FROM user_group_rel ) t3
ON t1.group_id = t3.group_id
WHERE %s
GROUP BY t1.group_id
HAVING distance < %s
ORDER BY distance
LIMIT %s",
$d_formula, $table, $where,$dist, $limit );
$result = $this->query($q);
if (mysql_num_rows($result)===0) {
return 0;
} else if (mysql_num_rows($result)>0) {
return $result;
}
}
function delete($table,$uid,$cid) {
$q = sprintf('
DELETE FROM `disruptly`.`%s`
WHERE `%s`.`user_id` = %d
AND `%s`.`group_id` = %d
',$table, $table, $uid,$table, $cid
);
//echo $q;
$result = $this->query($q);
if ($result===0) {
return 0;
} else if ($result===1) {
return $result;
}
}
public function distance_formula($lat, $lng, $table) {
//get rid of the round after'SELECT *,' for more accurate results
$q = sprintf("round(3956 * 2 * ASIN(SQRT( POWER(SIN((%s -abs(%s.lat)) * pi()/180 / 2),2) + COS(%s * pi()/180 ) * COS(abs(%s.lat) * pi()/180) * POWER(SIN((%s - %s.lng) * pi()/180 / 2), 2) )),2) as distance ", $lat, $table, $lat, $table, $lng, $table);
return $q;
}
}
$database = new MySQLDatabase();
$db =& $database;
</code></pre>
<p><strong>Edit</strong> - If anyone disagrees or has something to add, don't be shy.</p>
<p>I'm going to ask some follow-up questions:</p>
<ol>
<li><p>You said, "...these are models whose functionality is designed for its controller rather than a controller whose functionality is designed for its model." This was spot on. I started coding my "controller" in mind first, or rather what data will the view be requesting from the model. In the future, I should construct my model first? </p></li>
<li><p>Globals are evil, lesson (re)learned. Never again. No question here, just a fact.</p></li>
<li><p>You say, "Let me just say that this is not the implementation I am suggesting..." I imagine in reference to my overall structure. I'm not asking you to outline a new implementation, but how you would approach/think about it differently. (2-3 sentences is fine)</p></li>
<li><p>"Why are all of your methods returning the $data property?" It is a phonegap application, so the whole 'view' is already on the client. The controller sends $data(JSON) for each ajax request for the info to be filled in. This might be the root of the botched MVC pattern, this was my thinking:</p></li>
</ol>
<p>View: Client-side app, which has all the templates already loaded and fills them with requests to the controller via ajax</p>
<p>Controller: Skinny gatekeeper between client and model - not much going on here besides accepting get/post requests, validation(does username have 5 letters?) and forwarding data to the appropriate functions in the model. Then passing the model's data relatively untouched to the 'view'(will add an html sanitizing function).</p>
<p>Model (Group): All methods/classes pertaining to group functionality (SQL Statement prep, parse and return).</p>
<p>Model (Database): Where all the application wide sql queries actually get escaped, executed and returned 'untouched'</p>
<p>Q) Am I correct in my understanding that you're saying the Model(Group) looks more like a controller than a model because of the parsing? </p>
<ol>
<li>"There is no reason to typecast something that is already of the type you are trying to cast it to." My reasoning for using typcasting and sprintf(with %d) was perhaps a failed attempt at data integrity/security. For example, I expect user_id to be a number but what if someone sends a string or an sql injection technique? I thought those were 2 ways of potentially saving yourself from a 1=1. You say no not worth it? (probably the most correct answer is just use PDO).</li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-05T13:49:43.540",
"Id": "403958",
"Score": "0",
"body": "Curious why you limit error output instead of properly catching and handling exceptions - `@$this->data['action'] = $a['action'];`. If this buggers up, you'll never know."
}
] |
[
{
"body": "<p>This is better, still a bit long, but unavoidably so. I might reiterate a few things from my last answer, but it is only because I'm too lazy to read it again to make sure I'm not. Sounds kind of ironic, but I do find it easier to just write it, rather than read it :)</p>\n\n<p><strong>General Overview</strong></p>\n\n<p>First let's have a quick look at your before diving in. I count four model classes, and what appears to be a fifth, which I will ignore for now. Hopefully each class is in its own file and not saved all into one. If not, you might want to strongly consider it. None of those four classes resembles a \"true\" model. Instead what you have here appear to be three model-controllers. Esentially, that means these are models whose functionality is designed for its controller rather than a controller whose functionality is designed for its model. The reason this is bad is because it leaves room for repetition. A final model should not be broken up into multiple parts, it should be one functional whole. That's not to say that you can't have a base class and extend subclasses to get to that whole, just that you shouldn't need to call three separate models to accomplish the task of what one model can do.</p>\n\n<p><strong>Now, A Little More In Depth</strong></p>\n\n<p>The very first thing I see is a global. Globals are evil. Pretend you never saw them. You will NEVER need them. I repeat NEVER. Especially not in a class. That's what properties are for.</p>\n\n<pre><code>class model {\n public $db;//should actually be private or protected\n\n public function __construct() {\n $this->db = new MySQLDatabase();\n }\n}\n</code></pre>\n\n<p>Now every class that extends the model can use the same <code>$db</code> instance, and since it is a public property, you can also use that instance outside of the class once the model has been initialized. If you have an instance created before you initialize the model, and you want to use that one instead, then you should pass that instance to the constructor and set it as your property. The same holds true for regular functions as well: Pass it in, then return the modified version. However, this is not always the best solution. Sometimes, you can extend a class to accomplish the same thing.</p>\n\n<pre><code>//Using an existing instance\npublic function __construct( $db ) {\n $this->db = $db;\n}\n//Extending\nclass model extends MySQLDatabase() {\n //keep your current properties, they are fine\n public function __construct( $query ) {\n $this->input = $this->escape( $query );\n $this->data[ 'action' ] = isset( $a[ 'action' ] ) ? $a[ 'action' ] : NULL;\n }\n}\n</code></pre>\n\n<p>Let's look at what we did here. The first thing I did was rename your parameter. Don't use vague names like <code>$a</code>. What is <code>$a</code>? I had to go all the way to the <code>escape()</code> method just to find out. Don't make your readers, or yourself, have to figure out what something is. Be descriptive with your variables/properties/functions/methods. Not too descriptive, but descriptive enough that we can work with what is given. This is called self-documenting code and makes your code much easier to read and debug. Next, I removed that redundant <code>escape()</code>. That method only ever returns a value, therefore declaring it without setting it to some variable or property is pointless. Lastly, I removed that error suppression. Don't use error suppression in your code. It is a sign of bad coding and should be avoided. The only exception might be while debugging, but then it should promptly be removed. What I've demonstrated above is a ternary statement and should fix those warnings you were occasionally getting about \"action\" being undefined in <code>$a</code>. Its the same as an if/else statement (<code>if == ?, else == :</code>), only shorter. Maybe you've seen it before, maybe not. Either way, be careful using them as they are not always well liked because they can cause issues with legibility if used incorrectly. My rule of thumb is, no nesting, complex, or long ternary; as long as it's short and sweet it's just fine.</p>\n\n<p>Let me just say that this is not the implementation I am suggesting, I am just using this for demonstration. If just scanning the structure of these classes, as I did in the general overview, then the class and method names might look convincingly like a model's, but upon closer examination we find that it is actually a controller class. This would explain why I thought your models resembled model-controllers. And of course, a controller should not extend a model, of which your <code>MySQLDatabase</code> class is. As such, that very first example I showed you is the better choice here. Create a <code>$db</code> property and instantiate it in the constructor. It shouldn't be passed as an already existing instance because one shouldn't exist. It's the controller's job to instantiate the model.</p>\n\n<p>Now that we know that your first four classes are actually controllers, we can better understand how they should work together. I'm going to leave the structure of these classes alone for now, because that will make this answer quite a bit longer, but you should take another look at that as well. Just remember: Models read and manipulate the data; Controllers request those actions to be performed and parse it for the view; Views are templates that hold placeholders that the Controller fills in.</p>\n\n<p><strong>Ignoring MVC</strong></p>\n\n<p>From here on out, I'm going to ignore the MVC pattern and just focus on the actual code, I believe I got most of that anyways. That being said, there is already much here for you to look over, so I'm only going to scan over the rest of this and point out those things that do jump out at me.</p>\n\n<p>In your <code>default_list_groups()</code> method you dissect the <code>$input</code> property before passing it to the <code>list_groups()</code> method. Instead, it would make more sense to pass the entire <code>$input</code> array as a parameter and dissect it in the <code>list_groups()</code> method. This decreases your parameter list and makes your code easier to read. I noticed you use this same method in other methods without all the other <code>$input</code> parameters you used here. In order to compensate you will have to use checks or default values in the <code>list_groups()</code> method to determine if these parameters have been set.</p>\n\n<pre><code>$this->list_groups( $this->input, 'group', 10, 30, 'all' );\n</code></pre>\n\n<p>Why are all of your methods returning the <code>$data</code> property? Wait until you are ready to render your view and use the <code>render()</code> method to extract that for you. This reduces repetition and ensures there are no \"confusing\" return values. By the way, I see no <code>render()</code>-like method, so here is an example of what I am talking about, just in case.</p>\n\n<pre><code>public function render( $view ) {\n extract( $this->data );\n include $view;\n}\n</code></pre>\n\n<p>It appears that you only use the <code>$data[ 'msg' ]</code> property to report errors or track status. A better way would be to use an array that way you could track more than one at a time. Right now you overwrite this node with the last value that is processed, which can be pretty confusing if there were an error earlier but you can't see it because the last operation proved successful.</p>\n\n<pre><code>$this->data[ 'msg' ] = array();\n//etc...\n$this->data[ 'msg' ] [] = 'There was a small problem, try again soon.';//though this message should be more specific about what happened.\n</code></pre>\n\n<p>Don't recreate a boolean. That's what you are doing with your <code>$data[ 'success' ]</code> property. If you have a variable that switches between two states (on/off, 0/1, etc...), then use a TRUE/FALSE boolean. The TRUE state is commonly replaced with an actual return product. For example:</p>\n\n<pre><code>return isset( $val ) ? $val : FALSE;\n</code></pre>\n\n<p><code>array_push()</code> isn't really used much anymore. The more common way to append data onto an array is to use the following syntax:</p>\n\n<pre><code>$this->data[ 'results' ] [] = $row;\n</code></pre>\n\n<p>There is no reason to typecast something that is already of the type you are trying to cast it to. Typecasting is for converting a variable's type to something it's not. For example, using that switch example from above, if we typecast 0 to a bool, then we get FALSE. If we typecast 1 to a bool, we get TRUE, which is why its better to explicitly use a boolean rather than have PHP need to convert it for you. Typecasting is useful, but don't use it if you don't have to. Most of the typecasting I see here appears to be unnecessary, but I'm not going to examine each case. Just ask yourself this about each case, \"Is this necessary? Is this variable ever set to anything that is not of this type? Why am I typecasting it?\" The answer to these questions will help you determine how to proceed.</p>\n\n<p>Try not to use the \"not\" operator, unless you have to. If you have an if/else pair, then you can switch those statements around. Why not <code>not</code>? Sorry couldn't help myself :) Anyways, maybe this is just a stylistic choice, but it appears to be a commonly accepted one. Also, <code>$b</code> is a little easier to read than <code>!$b</code>, especially if you don't add spaces around the operator.</p>\n\n<pre><code>if( $b !== 0 ) {\n //if contents\n} else {\n //else contents\n}\n//Is the same as\nif( $b === 0 ) {\n //previous else contents\n} else {\n //previous if contents\n}\n</code></pre>\n\n<p>Of course, there is an even better way to do this. Assuming that your if/else statement has default values, you can just set those default values and then if the right condition is passed, the values are updated. For example:</p>\n\n<pre><code>$this->data['msg'] = 'There was a small problem, try again soon.';\n$this->data['success'] = 0;\n\nif ($b !== 0) {\n $this->data['success'] = 1;\n while ($row = mysql_fetch_array($b, MYSQL_ASSOC)) {\n array_push($this->data['results'], $row);\n }\n $this->data['msg'] = 0;\n}\n\nreturn $this->data;\n</code></pre>\n\n<p>Something else that may not be as obvious about the above example is that the return statement is no longer associated with either the if nor the else statements. It has been removed from both. We can do this because the return was the same in both instances, it was just its value that changed. So, if we follow the \"Don't Repeat Yourself\" (DRY) Principle, then we only need to do this once, at the very end of the method. As the name implies, the DRY principle means that your code shouldn't repeat. So, perhaps even those default values are unnecessary. I am unsure, it depends on how this is implemented. If those values already exist from when the class was first instantiated, or are somehow reset, then there is no reason to restate them. This principle is very important in OOP and can be applied to many things. Of equal importance is the Single Responsibility Principle, which you should also take a look at. Here's another violation of DRY. You have the below loop, in several different locations throughout the code, or one mostly identical to it. If this were a method, it would not need to be retyped each time. And since we are in a class, if the results are the same, you can just set this to a class property and use that property thereafter instead of needing to keep recreating it.</p>\n\n<pre><code>while ($row = mysql_fetch_array($b, MYSQL_ASSOC)) {\n array_push($this->data['results'], $row);\n}\n</code></pre>\n\n<p><code>sprintf()</code> is a special case function. If you can accomplish the same thing with just a normal string, you should use the normal string. <code>sprintf()</code> is just too slow to be worth it, not to mention it abstracts a concept that need not be abstracted. For example:</p>\n\n<pre><code>$w = sprintf(\"user_id =%d AND group_id=%d\",$user_id, $group_id);\n//is the same as\n$w = \"user_id=$user_id AND group_id=$group_id\";//easier to read\n//and the same as\n$w = 'user_id=' . $user_id . ' AND group_id=' . $group_id;//only slightly easier to read\n</code></pre>\n\n<p>There is a difference between the <code>&&</code> and <code>AND</code> operators and the <code>||</code> and <code>OR</code> operators. The <code>&&</code> and <code>||</code> pair have a higher precedence than the <code>AND</code> and <code>OR</code> pair. As such, using the lower precedence pairs could cause unforeseen issues and should be avoided. After five years I have never needed that second set, it is almost always preferable to use the first. When are these preferable? I honestly don't know, you'd have to ask someone a little bit wiser in their inner workings than me. I just know you will get many weird looks and will always be advised to use the others. Additionally, the <code>AND</code> and <code>OR</code> operators should always be capitalized when being using. Please note: This does not include the <code>AND</code> in MySQL, that is always <code>AND</code> and never <code>&&</code>.</p>\n\n<pre><code>if( $b !== 0 AND is_resource( $b ) ) {\n//should be\nif( $b !== 0 && is_resource( $b ) ) {\n</code></pre>\n\n<p>Avoid using <code>die()</code>. It is a very inelegant way of stopping script's execution. A much better way would be to identify the problem, log it, then create a nice error page that lets the user know something went wrong.</p>\n\n<pre><code>die( \"Database connection failed: \" . mysql_error() );\n//vs\nlog( mysql_error() );//for you\ninclude '404.php';//for the user\n</code></pre>\n\n<p>What is the point of <code>confirm_query()</code>? It would be one thing if this method were reused, but it is only being used by <code>query()</code>. Drop the unnecessary abstraction and just perform the checking inside the original method. Unless you plan on creating a common method, reused by many other methods, that logs errors and reports errors to the end user, which isn't a half bad idea. How it is currently I would not have expected the method to just die if something went wrong. Another good reason not to use <code>die()</code>, but that's not the main concern here.</p>\n\n<pre><code>$result = mysql_query($sql, $this->connection);\nif( ! $result ) {\n //log and report\n}\n</code></pre>\n\n<p>Please, always use braces on your statements, even one-liners. It makes your code much easier to read and update. It also ensures that there are no mistakes, because braceless statements can only be one line, it is very easy to forget to add those braces when you go to extend that statement to two lines. If the braces are always there it ensures that no such errors ever occur. Additionally, be consistent in your style. Below you have two statements that use no braces and then an else statement that does.</p>\n\n<pre><code>if(is_array($q)) \n foreach($q as $k => $v) \n $q[$k] = $this->escape($v); //recursive\nelse if(is_string($q)) {\n $q = mysql_real_escape_string($q);\n}\n</code></pre>\n\n<p>When you have a return statement that is essentially a FALSE value, use the actual FALSE value, unless the non-FALSE value is explicitly needed. For instance <code>1-1</code> should return a 0, but <code>! $results</code> should return a FALSE. Or NULL. Personally I prefer FALSE, but that's up to you. A zero would only make sense here if I explicitly wanted the number of results so that I could use it somewhere.</p>\n\n<p>Don't assign two variables at the same time. This makes it rather difficult to visually track down where the second variable came from.</p>\n\n<pre><code>$fields = $values = array();\n//should be\n$fields = array();\n$values = array();\n</code></pre>\n\n<p>There are reasons why you would sometimes need to explicitly use <code>array_keys()</code> in a foreach loop, but if you need both the key and value, then you should just do the following:</p>\n\n<pre><code>foreach( $data as $key => $value ) {\n if( ! in_array($key, $exclude) ) {\n $fields[] = \"`$key`\";\n $values[] = \"'$value'\";\n }\n}\n</code></pre>\n\n<p>Here are a couple of general comments about some things I found common throughout most of the code. Interior comments only add noise. If you wish to document your code, use PHPDoc comments. A bunch of interior comments can quickly lead to illegibility. Parenthesis are not always necessary. For example, <code>include, require, echo, return</code> and a few others don't require parenthesis. While this is a stylistic choice, many find it preferable because it makes legibility so much better, especially when using parameters that do require parenthesis.</p>\n\n<p>Sorry, I kind of flew over the last half of this review. I'm pretty sure there is more I could help you with, but this is already very large. Hopefully this helps you get started though. I believe I answered each of your questions in my review. If you have anything you'd like clarity on, just let me know.</p>\n\n<p><strong>Edit Per OP Edit</strong></p>\n\n<p>Sorry for the delay. Had a busy weekend.</p>\n\n<p>1) That quote was from the general overview. In it I was explaining how your code looked like a Model if we did not look too closely at it, later I explained these are actually Controllers. I was attempting to show you how easy it is to make that kind of mistake. Please see the step-by-step below for the second part of this question.</p>\n\n<p>3) I explained this in the same paragraph that quote came from. This is also where I explained that your Models were actually Controllers. In that quote I was saying that extending the base <code>MySQLDatabase</code> class was the wrong approach and that you should use the one above that, now also below for reference. The reasoning for this was that the <code>MySQLDatabase</code> class is a Model, and those classes you were calling Models were actually Controllers. Controllers should not extend Models, they should instantiate them when they are instantiated, such as in the constructor.</p>\n\n<pre><code>class model {\n public $db;//should actually be private or protected\n\n public function __construct() {\n $this->db = new MySQLDatabase();\n }\n}\n</code></pre>\n\n<p>4) Lets look at the typical Controller real quick: One instance is equal to one View, as such one Controller should correspond to one View. When you have multiple methods whose task is to \"render\" information to different Views, then you are creating unnecessary overhead. Phones aren't as quick or resourcefull as a regular computer. They need all the help they can get. So if you have methods that each of these controllers are going to need, you can create a parent class and extend it for each of these specific Controllers. So this quote is saying that only ONE method should return the render information. BTW: Your view of MVC appears right, but I don't know if that is just because you are using the right terms for the wrong things, or if you actually understand it. Read over my answer and the step-by-step below to make sure your idea corresponds. I believe the only problem you had was mixing up your Controllers and Models.</p>\n\n<p>5) PDO probably would be the best bet, but isn't the only thing here. Typecasting isn't helpful if the original value wasn't already of a similar type. For instance, typecasting the string \"25\" to an int is acceptable because it is easily translateable, but typecasting the string \"twenty-five\" to an int is not because its just a string. We, as people might understand the conversion, but PHP will not. Besides, a better method would be typehinting. Its where you declare a variable's type in the parameter list and if not passed the right type it will throw an error and cancel execution. The only problem with this is that you cannot use scalar types, such as int and string. I wouldn't be too worried about that though, pretty much anything can be converted to a string or int OTF. For those instances where it can't, <code>strval()</code> and <code>intval()</code>, or the typecasting equivalent, are acceptable. However, the variable's type should be confirmed and maintained during sanitization and validation, so typecasting should be unnecessary.</p>\n\n<pre><code>public function test( Array $array ) {//$array must now contain an array, else execution quits\n</code></pre>\n\n<p><strong>My Step-By-Step To MVC</strong></p>\n\n<p>The following is my step-by-step approach to creating an MVC framework. It serves me well, but it is not the ONLY way. Any way that works for you is the right way. There's no ONE right way to do anything. Take suggestions and test them and expirement, but don't get stuck trying to force yourself to do something one way because that is the only way you were shown. That's like being forced to use your non-dominant hand because your parents don't want a {insert-dominant-hand-here}y. That's what happened to me for a while (not the hand thing, though that did too and now my handwriting is attrocious), and I started despising MVC because of it. Everyone was saying, \"start by creating the Model, its the ONLY logical first step\". Then one day I sat down and said, \"Damnit, there's got to be a better, easier way!\" This is the one I found:</p>\n\n<ol>\n<li>Start with the View. Lay it out, and style it however you want. Statically add all of the information and make sure everything looks right.</li>\n<li>Extract the dynamic parts from the view and replace them with variables, and maybe some simple if and for/foreach statements.</li>\n<li>Create a Controller with a render method containing the variables and an include for the view. Make sure to declare the variables before the include so the View can use them.</li>\n<li>Create a Model with the appropriate methods to return each of those values and replace the Controller's variables with calls to those methods. If necessary create methods in the Controller for recursive calls to Model methods and repeat tasks.</li>\n<li>Flesh out and tidy up the rest of your Model and Controller. As you add more Controllers that use that Model, the Model may grow, but make sure those methods aren't repeating or similar and can be used in any controller.</li>\n</ol>\n\n<p>There, you are done. There's a little more to it than this, but this scaffolding should get you started. And the best part is that you can test it at any point and it should always work. In fact, you should not notice a difference at all.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-07T20:29:43.897",
"Id": "15421",
"ParentId": "15400",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "15421",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-07T02:06:11.793",
"Id": "15400",
"Score": "4",
"Tags": [
"php",
"database",
"mvc"
],
"Title": "How can I improve my PHP model for my HTML5/JS mobile app?"
}
|
15400
|
<p>I am developing a WinForm application that extracts data from our database and draws a tree like structure on the form. For the users to get a better idea of how the data is structured.</p>
<p>The database is designed in such a way, that data looks like tree structures. Based on that I can fetch the data and draw the tree structure.</p>
<p>I am using <code>GraphicsPath</code> objects to draw the nodes and the links between them, and to do hit testing.</p>
<p>Here is the Node class:</p>
<pre><code>public class OINode
{
#region Const
public int NodeDiamenter = 55;
private string FontString = "Tahoma";
private FontFamily GPFont = new FontFamily("Tahoma");
private float GPFontSize = 11.0f;
#endregion
#region Graphics
private GraphicsPath GPNode;
private GraphicsPath GPLabels;
private Point TopLeft;
private Size NodeSize;
private Point _Top;
private Point _Bottom;
private bool Selected = false;
private bool didHit = false;
#endregion
#region Properties
private string _ID = "ID";
private string _Type = "Type";
private string _SubType = "SubType";
private string _KnownByID = "SubType";
private string _InternalStatus = "InternalStatus";
private Point _Location = new Point(0, 0);
private Color _NodePen = Color.Black;
private Color _NodeBrush = Color.White;
private Color _NodeSelectPen = Color.Yellow;
private Color _NodeSelectBrush = Color.WhiteSmoke;
private int _AssignedLevel = -1;
public string ID { get { return _ID; } set { _ID = value; } }
public string Type { get { return _Type; } set { _Type = value; } }
public string SubType { get { return _SubType; } set { _SubType = value; } }
public string KnownByID { get { return _KnownByID; } set { _KnownByID = value; } }
public string InternalStatus { get { return _InternalStatus; } set { _InternalStatus = value; } }
public Point Location { get { return _Location; } set { _Location = value; ConstuctNode(); } }
public Color NodePen { get { return _NodePen; } set { _NodePen = value; } }
public Color NodeBrush { get { return _NodeBrush; } set { _NodeBrush = value; } }
public Color NodeSelectPen { get { return _NodeSelectPen; } set { _NodeSelectPen = value; } }
public Color NodeSelectBrush { get { return _NodeSelectBrush; } set { _NodeSelectBrush = value; } }
public Point Top { get { return _Top; } set { } }
public Point Bottom { get { return _Bottom; } set { } }
public int AssignedLevel { get { return _AssignedLevel; } set { _AssignedLevel = value; } }
#endregion
#region Links
public ArrayList ChildLinks = new ArrayList();
#endregion
public OINode(string id, string type, string subType, string knownByID, string internalStatus)
{
ID = id;
Type = type;
SubType = subType;
KnownByID = knownByID;
InternalStatus = internalStatus;
}
~OINode()
{
if (GPNode != null)
{
GPNode.Dispose();
}
if (GPLabels != null)
{
GPLabels.Dispose();
}
}
public override string ToString()
{
return string.Format("ID = {0} Type = {1} SubType = {2}, KnownByID = {3} IS = {4}", ID, Type, SubType, KnownByID, InternalStatus);
}
private void Initilzie()
{
TopLeft = new Point(Location.X - NodeDiamenter, Location.Y - NodeDiamenter);
NodeSize = new Size(NodeDiamenter * 2, NodeDiamenter * 2);
_Top = new Point(Location.X, Location.Y - NodeDiamenter);
_Bottom = new Point(Location.X, Location.Y + NodeDiamenter);
}
private void ConstuctNode()
{
Initilzie();
GPNode = new GraphicsPath();
GPNode.AddEllipse(new Rectangle(TopLeft, NodeSize));
GPNode.CloseFigure();
StringFormat sf = new StringFormat();
sf.Alignment = StringAlignment.Center;
sf.LineAlignment = StringAlignment.Center;
int[] lines = FindLineForLable();
GPLabels = new GraphicsPath();
GPLabels.AddString(ID.Substring(9, 9), GPFont, (int)FontStyle.Regular, GPFontSize, BuildCenteredRectangle(ID.Substring(9, 9), lines[0]), sf);
GPLabels.AddString(Type, GPFont, (int)FontStyle.Regular, GPFontSize, BuildCenteredRectangle(Type, lines[1]), sf);
GPLabels.AddString(SubType, GPFont, (int)FontStyle.Regular, GPFontSize, BuildCenteredRectangle(SubType, lines[2]), sf);
GPLabels.AddString(KnownByID, GPFont, (int)FontStyle.Regular, GPFontSize, BuildCenteredRectangle(KnownByID, lines[3]), sf);
GPLabels.AddString(InternalStatus, GPFont, (int)FontStyle.Regular, GPFontSize, BuildCenteredRectangle(InternalStatus, lines[4]), sf);
GPLabels.CloseFigure();
}
private Rectangle BuildCenteredRectangle(string text, int line)
{
Size textSize = TextRenderer.MeasureText(text, new Font(FontString, GPFontSize));
Rectangle rect = new Rectangle(Location.X - (textSize.Width / 2), line, textSize.Width, textSize.Height);
return rect;
}
private int[] FindLineForLable()
{
int TopOfNode = Top.Y;
int BottomOfNode = Bottom.Y;
int TextHeight = TextRenderer.MeasureText(ID + Type + SubType + KnownByID + InternalStatus, new Font(FontString, GPFontSize)).Height - 4;
int[] lines = new int[5];
lines[0] = TopOfNode + TextHeight;
lines[1] = TopOfNode + TextHeight * 2;
lines[2] = TopOfNode + TextHeight * 3;
lines[3] = TopOfNode + TextHeight * 4;
lines[4] = TopOfNode + TextHeight * 5;
return lines;
}
public void Draw(Graphics g)
{
foreach (OILink link in ChildLinks)
{
link.Draw(g);
}
Paint(g);
}
private void Paint(Graphics g)
{
if (Selected)
{
g.FillPath(ConvertColorToBrush(NodeSelectBrush), GPNode);
g.DrawPath(new Pen(NodeSelectPen, 2.5f), GPNode);
g.FillPath(Brushes.Black, GPLabels);
g.DrawPath(new Pen(Color.Black, 1f), GPLabels);
}
else
{
g.FillPath(ConvertColorToBrush(NodeBrush), GPNode);
g.DrawPath(new Pen(NodePen, 2.5f), GPNode);
g.FillPath(Brushes.Black, GPLabels);
g.DrawPath(new Pen(Color.Black, 1f), GPLabels);
}
}
public bool HitTest(Graphics g, MouseEventArgs e)
{
bool neededUpdated = false;
if (GPNode.IsVisible(e.Location))
{
if (!didHit)
{
didHit = true;
if (!Selected)
{
Selected = true;
neededUpdated = true;
foreach (OILink link in ChildLinks)
{
link.isHit(g, Selected);
}
Paint(g);
}
}
}
else
{
if (didHit)
{
didHit = false;
Selected = false;
neededUpdated = true;
foreach (OILink link in ChildLinks)
{
link.isHit(g, Selected);
}
Paint(g);
}
}
if (!neededUpdated)
{
foreach (OILink link in ChildLinks)
{
if (link.HitTest(g, e))
{
neededUpdated = true;
}
}
}
return neededUpdated;
}
private Brush ConvertColorToBrush(Color color)
{
return new SolidBrush(color);
}
public void AddChildNode(OINode childNode, string internalStatus, bool repeatLink)
{
bool found = false;
if (repeatLink)
{
foreach (OILink link in childNode.ChildLinks)
{
if (link.ChildNode.ID == ID)
{
link.Repeat = true;
found = true;
break;
}
}
}
else
{
found = false;
}
if (!found)
{
ChildLinks.Add(new OILink(this, childNode, internalStatus));
}
}
public void isHit(Graphics g, bool hit)
{
Selected = hit;
foreach (OILink link in ChildLinks)
{
link.isHit(g, Selected);
}
Paint(g);
}
}
</code></pre>
<p>And here is the link class:</p>
<pre><code>public class OILink
{
#region Const
private const float LinkWidth = 2f;
private const int GPLinkWidth = 5;
#endregion
#region Graphics
private GraphicsPath GPLink;
private bool Selected = false;
public bool Repeat = false;
private bool didHit = false;
#endregion
#region Properties
private string _InternalStatus = "InternalStatus";
private Color _Start = Color.LightBlue;
private Color _End = Color.Salmon;
private Color _StartSelected = Color.Blue;
private Color _EndSelected = Color.Red;
public string InternalStatus { get { return _InternalStatus; } set { _InternalStatus = value; } }
public Color Start { get { return _Start; } set { _Start = value; } }
public Color End { get { return _End; } set { _End = value; } }
public Color StartSelected { get { return _StartSelected; } set { _StartSelected = value; } }
public Color EndSelected { get { return _EndSelected; } set { _EndSelected = value; } }
#endregion
#region Nodes
public OINode ParentNode;
public OINode ChildNode;
#endregion
public OILink(OINode parentNode, OINode childNode, string internalStatus)
{
InternalStatus = internalStatus;
ParentNode = parentNode;
ChildNode = childNode;
}
~OILink()
{
if (GPLink != null)
{
GPLink.Dispose();
}
}
public override string ToString()
{
return string.Format("PID = {0} CID = {1} LIS = {2}", ParentNode.ID, ChildNode.ID, InternalStatus);
}
private void ConstuctLink()
{
if ((ParentNode.Location.X != 0) && (ParentNode.Location.Y != 0) && (ChildNode.Location.X != 0) && (ChildNode.Location.Y != 0))
{
GPLink = new GraphicsPath();
GPLink.AddLine(ParentNode.Bottom.X - GPLinkWidth, ParentNode.Bottom.Y, ParentNode.Bottom.X + GPLinkWidth, ParentNode.Bottom.Y);
GPLink.AddLine(ParentNode.Bottom.X + GPLinkWidth, ParentNode.Bottom.Y, ChildNode.Top.X + GPLinkWidth, ChildNode.Top.Y);
GPLink.AddLine(ChildNode.Top.X + GPLinkWidth, ChildNode.Top.Y, ChildNode.Top.X - GPLinkWidth, ChildNode.Top.Y);
GPLink.AddLine(ChildNode.Top.X - GPLinkWidth, ChildNode.Top.Y, ParentNode.Bottom.X - GPLinkWidth, ParentNode.Bottom.Y);
GPLink.CloseFigure();
}
}
public void Draw(Graphics g)
{
ConstuctLink();
if (GPLink != null)
{
Paint(g);
ChildNode.Draw(g);
}
}
private void Paint(Graphics g)
{
if (Selected)
{
LinearGradientBrush brush = new LinearGradientBrush(ParentNode.Location, ChildNode.Location, StartSelected, EndSelected);
g.FillPath(brush, GPLink);
g.DrawPath(new Pen(brush, LinkWidth), GPLink);
brush.Dispose();
}
else
{
LinearGradientBrush brush = new LinearGradientBrush(ParentNode.Location, ChildNode.Location, Start, End);
g.FillPath(brush, GPLink);
g.DrawPath(new Pen(brush, LinkWidth), GPLink);
brush.Dispose();
}
}
public bool HitTest(Graphics g, MouseEventArgs e)
{
bool neededUpdated = false;
if (GPLink != null)
{
if (GPLink.IsVisible(e.Location))
{
if (!didHit)
{
didHit = true;
neededUpdated = true;
if (!Selected)
{
Selected = true;
ChildNode.isHit(g, Selected);
Paint(g);
}
}
}
else
{
if (didHit)
{
didHit = false;
Selected = false;
neededUpdated = true;
ChildNode.isHit(g, Selected);
Paint(g);
}
}
if (!neededUpdated)
{
if (ChildNode.HitTest(g, e))
{
neededUpdated = true;
}
}
}
return neededUpdated;
}
private Brush ConvertColorToBrush(Color color)
{
return new SolidBrush(color);
}
private bool CheckForRepeatLinks(OINode parentNode, OINode childNode)
{
foreach (OILink link in childNode.ChildLinks)
{
if (link.ChildNode == childNode)
{
Repeat = true;
link.Repeat = Repeat;
return Repeat;
}
}
Repeat = false;
return Repeat;
}
public void isHit(Graphics g, bool hit)
{
Selected = hit;
ChildNode.isHit(g, Selected);
Paint(g);
}
}
</code></pre>
<p>With these two classes I can make tree structures like so:</p>
<pre><code>OINode node1 = new Node("node1", "", "", "", "");
OINode node2 = new Node("node2", "", "", "", "");
OINode node3 = new Node("node3", "", "", "", "");
OINode node4 = new Node("node4", "", "", "", "");
OINode node5 = new Node("node5", "", "", "", "");
OINode node6 = new Node("node6", "", "", "", "");
node1.AddChildNode(node2, "", false);
node2.AddChildNode(node3, "", false);
node2.AddChildNode(node4, "", false);
node3.AddChildNode(node5, "", false);
node4.AddChildNode(node6, "", false);
</code></pre>
<p>Then I draw this onto <code>Bitmap</code>, witch displays in a <code>PictureBox</code>, allowing me to scroll with bigger trees structures.</p>
<p>How the drawing works: All the <code>OINodes</code> objects are link by the <code>OILink</code> objects. So all I have to do, is call the first node <code>node1.HitTest(...)</code> and it will loop through all its children links and nodes. Each one calling the <code>Paint(...)</code> method to redraw itself if need be. If the hit has proven to be true <code>if (GPNode.IsVisible(e.Location))</code> (see the <code>HitTest(...)</code> method)</p>
<p>Question:
This work well for not too big structures, as soon as it gets bigger it lags a lot to redraw the structures.</p>
<p>Is there a better design I can follow, to render the structure?</p>
<p>Also to keep in mind, I want to extend on this application to allow the user to interact with the nodes and links. By clicking on the objects the user can view other data associated with that object in the database. I was thinking of an interactive hover menu. When the mouse hovers or the user clicks on an object, it display basic information about the object, and has buttons (on the hover menu), that the user can click on to bring up more detailed information</p>
<p>I was thinking of using, user controls, for the node and link objects, but it was suggested to me an the Stack Overflow Chat to inherit from <code>Control</code> class instead.</p>
<p><strong>EDIT</strong></p>
<p>Here is the code used to draw the structure. I am using a user control that has a Panel and in the panel is has a picture box as suggested in the comments of my previous post <a href="https://stackoverflow.com/questions/11361477/c-sharp-better-way-to-scroll-custom-graphic-to-reduce-flickering">here</a></p>
<p>The Code:</p>
<pre><code> private void DrawPicture(int Width, int Height)
{
TreeStructure = new Bitmap(Width, Height, PixelFormat.Format24bppRgb);
Graphics g = this.CreateGraphics();
g = Graphics.FromImage(TreeStructure);
// Just draws the background
DrawBack(g, Width, Height);
Construct(g);
StructurePictureBox.Size = new Size(Width, Height);
StructurePictureBox.Image = TreeStructure;
g.Dispose();
}
private void Construct(Graphics g)
{
// edit for this post
node1.Draw(g);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-07T14:02:07.663",
"Id": "25003",
"Score": "0",
"body": "have I overlooked something, or is it true that each node's `Location` has to be manually assigned?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-07T14:23:19.167",
"Id": "25004",
"Score": "0",
"body": "@codesparkle you are right, but that piece of code is irelavent to this question. I have other classes that set the location."
}
] |
[
{
"body": "<p>First things first, lose the #region tags. They do nothing but clutter up your code.</p>\n\n<p>I would make all of the class variables that are assigned at the top of OINode constants</p>\n\n<pre><code>public const int NodeDiamenter = 55;\nprivate const string FontString = \"Tahoma\";\nprivate readonly FontFamily GPFont = new FontFamily(\"Tahoma\");\nprivate const float GPFontSize = 11.0f;\n</code></pre>\n\n<p>Your class variables do not follow standardized naming conventions. They should be camel case, prefixed with a _</p>\n\n<pre><code>private GraphicsPath _gpNode;\nprivate GraphicsPath _gpLabels;\nprivate Point _topLeft;\nprivate Size _nodeSize;\nprivate Point _top;\nprivate Point _bottom;\nprivate bool _selected;\nprivate bool _didHit;\n</code></pre>\n\n<p>All of the properties can be set as autoproperty:</p>\n\n<pre><code>public string ID { get; set; }\npublic string Type { get; set; }\npublic string SubType { get; set; }\npublic string KnownByID { get; set; }\npublic string InternalStatus { get; set; }\npublic Point Location { get; set; }\npublic Color NodePen { get; set; }\npublic Color NodeBrush { get; set; }\npublic Color NodeSelectPen { get; set; }\npublic Color NodeSelectBrush { get; set; }\npublic int AssignedLevel { get; set; }\n</code></pre>\n\n<p>Then set defaults in the constructor:</p>\n\n<pre><code>Location = new Point(0, 0);\nNodePen = Color.Black;\nNodeBrush = Color.White;\nNodeSelectPen = Color.Yellow;\nNodeSelectBrush = Color.WhiteSmoke;\nAssignedLevel = -1;\n</code></pre>\n\n<p>If you want a readonly property, just don't put the set in:</p>\n\n<pre><code>public Point Top { get { return _top; } }\npublic Point Bottom { get { return _bottom; } }\n</code></pre>\n\n<p>I would change the ChildLinks ArrayList to a list of OILink and make it a readonly property:</p>\n\n<pre><code>public List<OILink> ChildLinks { get; private set; }\n</code></pre>\n\n<p>Use the var keyword and object initializer where ever possible:</p>\n\n<pre><code>var sf = new StringFormat\n {\n Alignment = StringAlignment.Center, \n LineAlignment = StringAlignment.Center\n };\n</code></pre>\n\n<p>The localvariable in FindLineForLable</p>\n\n<pre><code>var bottomOfNode = Bottom.Y;\n</code></pre>\n\n<p>is not used. Remove it to avoid confusion.</p>\n\n<p>Your Paint method has duplicate code. I would assign the brush then do the paint</p>\n\n<pre><code>private void Paint(Graphics g)\n{\n var fillBrush = _selected ? NodeSelectBrush : NodeBrush;\n\n g.FillPath(ConvertColorToBrush(fillBrush), _gpNode);\n g.DrawPath(new Pen(NodePen, 2.5f), _gpNode);\n\n g.FillPath(Brushes.Black, _gpLabels);\n g.DrawPath(new Pen(Color.Black, 1f), _gpLabels);\n}\n</code></pre>\n\n<p>HitTest has too many nested ifs.</p>\n\n<p>I would do it something like this</p>\n\n<pre><code>public bool HitTest(Graphics g, MouseEventArgs e)\n{\n var neededUpdated = _gpNode.IsVisible(e.Location) ? ProcessNodeIfNotHit(g) : ProcessNodeIfHit(g);\n\n Paint(g);\n\n if (!neededUpdated)\n {\n neededUpdated = ChildLinks.Any(l => l.HitTest(g, e));\n }\n\n return neededUpdated;\n}\n\nprivate bool ProcessNodeIfNotHit(Graphics g)\n{\n if (!_didHit)\n {\n _didHit = true;\n\n if (!_selected)\n {\n _selected = true;\n\n UpdateNodeHitStatus(true, g);\n }\n\n return true;\n }\n\n return false;\n}\n\nprivate bool ProcessNodeIfHit(Graphics g)\n{\n if (_didHit)\n {\n UpdateNodeHitStatus(g);\n\n return true;\n }\n\n return false;\n}\n\nprivate void UpdateNodeHitStatus(bool status, Graphics g)\n{ \n _didHit = status;\n _selected = status;\n\n foreach (OILink link in ChildLinks)\n {\n link.isHit(g, _selected);\n }\n}\n</code></pre>\n\n<p>AddChildNode has an unneccessary loop in it, the linq FirstOrDefault is a much more efficient and clean way of finding one element. You could also use SingleOrDefault if you think that will work better:</p>\n\n<pre><code>public void AddChildNode(OINode childNode, string internalStatus, bool repeatLink)\n{\n var found = false;\n\n if (repeatLink)\n {\n var link = childNode.ChildLinks.FirstOrDefault(l => l.ChildNode.ID == ID);\n\n if (link != null)\n {\n link.Repeat = true;\n found = true;\n }\n }\n\n if (!found)\n {\n ChildLinks.Add(new OILink(this, childNode, internalStatus));\n }\n\n}\n</code></pre>\n\n<p>The method isHit should be changed to IsHit to keep with C# coding standards.</p>\n\n<p>For OILink class variables and properties, see above.</p>\n\n<p>In ConstructLink, I would change this if statement and pull it out into its own method. The method name would better portray what the if statement is checking, that way when you come back to fix something in the code, you can glance over it instead of trying to figure out what it does:</p>\n\n<pre><code>if ((ParentNode.Location.X != 0) && (ParentNode.Location.Y != 0) && (ChildNode.Location.X != 0) && (ChildNode.Location.Y != 0))\n{\n // CODE HERE\n}\n</code></pre>\n\n<p>to</p>\n\n<pre><code>if (ListHasNotSizeSet())\n{\n return;\n}\n\n// CODE HERE\n\nprivate bool ListHasNotSizeSet()\n {\n return ParentNode.Location.X == 0 || ParentNode.Location.Y == 0 || ChildNode.Location.X == 0 ||\n ChildNode.Location.Y == 0;\n }\n</code></pre>\n\n<p>In draw, check for null then return if its found. This will reduce nesting in your class.</p>\n\n<pre><code>public void Draw(Graphics g)\n{\n ConstuctLink();\n\n if (GPLink == null)\n {\n return;\n }\n\n Paint(g);\n\n ChildNode.Draw(g);\n}\n</code></pre>\n\n<p>In your Paint method, it would be better to determine the brushes, then set up the paint. You should also create the LinearGradientBrush using the using keyword. This will eliminate duplication and unneccesary code:</p>\n\n<pre><code>private void Paint(Graphics g)\n{\n var startBrush = Selected ? StartSelected : Start;\n var endBrush = Selected ? EndSelected : End;\n\n using (var brush = new LinearGradientBrush(ParentNode.Location, ChildNode.Location, startBrush, endBrush))\n {\n g.FillPath(brush, GPLink);\n g.DrawPath(new Pen(brush, LinkWidth), GPLink);\n }\n}\n</code></pre>\n\n<p>For HitTest, see above.</p>\n\n<p>in CheckForRepeatLinks, there is a number of things you can do. The parameter parentNode is not used, get rid of it. You can use the .FirstOrDefault linq statement instead of a foreach loop:</p>\n\n<pre><code>private bool CheckForRepeatLinks(OINode childNode)\n{\n var link = childNode.ChildLinks.FirstOrDefault(l => l.ChildNode == childNode);\n\n if (link == null)\n {\n Repeat = false;\n return Repeat;\n }\n\n link.Repeat = true;\n Repeat = true;\n return Repeat;\n}\n</code></pre>\n\n<p>As for the code that draws the picture, I would again use the using keyword for the Graphics variable. I also noticed you are assigning g twice in 2 lines, is that really necessary?</p>\n\n<pre><code>private void DrawPicture(int Width, int Height)\n{\n TreeStructure = new Bitmap(Width, Height, PixelFormat.Format24bppRgb);\n using (var g = Graphics.FromImage(TreeStructure))\n {\n // Just draws the background\n DrawBack(g, Width, Height);\n\n Construct(g);\n StructurePictureBox.Size = new Size(Width, Height);\n StructurePictureBox.Image = TreeStructure;\n } \n}\n</code></pre>\n\n<p>As for creating the classes, because you now have defaults in the constructor, you only have to pass in the parts needed</p>\n\n<pre><code>var node1 = new Node(\"node1\");\nvar node2 = new Node(\"node2\");\nvar node3 = new Node(\"node3\");\nvar node4 = new Node(\"node4\");\nvar node5 = new Node(\"node5\");\nvar node6 = new Node(\"node6\");\n\nnode1.AddChildNode(node2, \"\", false);\nnode2.AddChildNode(node3, \"\", false);\nnode2.AddChildNode(node4, \"\", false);\nnode3.AddChildNode(node5, \"\", false);\nnode4.AddChildNode(node6, \"\", false);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-07T19:53:52.227",
"Id": "25015",
"Score": "0",
"body": "My misunderstanding the :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-07T20:00:57.100",
"Id": "25017",
"Score": "0",
"body": "Removed the comment on string.Concat"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-08T07:04:00.197",
"Id": "25031",
"Score": "0",
"body": "so if I do your suggestions, you think this will increase my performance in redrawing the tree structure?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-08T19:14:07.967",
"Id": "25040",
"Score": "0",
"body": "I would assume so, just by taking out some of the loops and unneeded code. Try it and see :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-09T13:10:53.520",
"Id": "25047",
"Score": "0",
"body": "Ok will give it a try, let you know what happens. I thought I had to do a redisgn."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-10T05:42:06.243",
"Id": "25078",
"Score": "0",
"body": "Vsnzella, why must I use the var keyword?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-10T15:53:33.360",
"Id": "25104",
"Score": "1",
"body": "Using var is a generally accepted practice to keep your code looking clean: http://stackoverflow.com/questions/41479/use-of-var-keyword-in-c-sharp"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-13T10:31:22.100",
"Id": "25284",
"Score": "0",
"body": "Its the first time I see this type of code: `ChildLinks.Any(l => l.HitTest(g, e));` what does it do?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-13T16:06:04.587",
"Id": "25313",
"Score": "1",
"body": "It checks if any of the elements in ChildLinks pass HitTest http://msdn.microsoft.com/en-us/library/bb337697.aspx"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-14T05:52:57.757",
"Id": "25352",
"Score": "0",
"body": "Well I did your suggestions, with not must improvement, did learn a thing about making my code more readable tho. I have to do a redesign, gonna try Olivier Jacot-Descombes architecture, and maybe use `Control`, so each node is responsible for drawing its self, and not looping though the whole tree."
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-07T17:41:38.680",
"Id": "15418",
"ParentId": "15406",
"Score": "2"
}
},
{
"body": "<p>I am not going to look at the details of your code (Jeff did that already); rather, I want to make some comments on the architecture here.</p>\n\n<p>Recently I had the task of drawing a tree structure (an organigram to be precise) starting with Excel data. I split my program into several components, each one of them responsible for one aspect of the task. The idea is to have a greater flexibility. E.g. the customer might want to retrieve the data from a database in future, instead of an Excel worksheet. In my case I had to change the graphics technology. I started by creating the organigram through Visio automation. I worked but was extremely slow. Now I am creating SVG graphics. This is much faster and the graphic can be opened in Visio. The change was easy to implement, thanks to my good architecture.</p>\n\n<p>I split my logic into these tasks, each one of them realized as a separate component:</p>\n\n<ol>\n<li>Read the data source </li>\n<li>Build a logical tree structure</li>\n<li>Layout the tree</li>\n<li>Draw the diagram</li>\n</ol>\n\n<p>The point here is that the layouter does not need to know which technology is used for drawing the graphic. The layouter creates a list of shapes using technology independent shapes.</p>\n\n<pre><code>public interface IShape\n{\n double Top { get; }\n double Left { get; }\n double Height { get; }\n double Width { get; }\n\n // Calculated\n double Right { get; }\n double Bottom { get; }\n\n void Render(); // This method does all the technology dependent stuff.\n}\n\npublic interface ILine : IShape\n{\n LineOrientation Orientation { get; }\n Color LineColor { get; }\n double LineWidth { get; }\n}\n</code></pre>\n\n<p>And so on. I have polygon shapes, text shapes, rectangle shapes and more. An important part is the shape factory. Concrete shape factories will produce technology dependent shapes like Visio shapes or SVG shapes.</p>\n\n<pre><code>public interface IShapeFactory\n{\n IDiagram CreateDiagram(List<IShape> shapes);\n ILine CreateLine(PointD p0, PointD p1, Color lineColor, double lineWidth);\n IPolygon CreatePolygon(List<PointD> points, Color fillColor,\n Color borderColor, double borderWidth);\n IRectangle CreateRectangle(RectangleD rect, Color fillColor,\n Color borderColor, double borderWidth,\n double cornerRadius);\n ISymbol CreateSymbol(RectangleD rect, IService<IDiagramNode> service);\n IText CreateText(RectangleD rect, string text, string fontName,\n double pointSize, Color color, TextAlignment alignment,\n TextStyle style, TextOrientation orientation);\n}\n</code></pre>\n\n<p>The layouter creates the requested shapes through an <code>IShapeFactory</code> that is injected through its constructor and does not need to know which graphics system will be used.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-13T10:48:15.090",
"Id": "25285",
"Score": "0",
"body": "I like you architecture, I always strive to develop my programs like this. But I think my components 2, and 4 (Build a logical tree structure, and Draw the diagram) are in one. My next step after I improve the speed of drawing the structure is too allow the users to interact with the Nodes. So I am not simply develop just graphics, but more like controls."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-13T15:41:31.703",
"Id": "25304",
"Score": "0",
"body": "My step 1 (read the data source) yields a list objects (persons in the case of an organigram). Step 2 (build a logical tree structure) creates a tree of objects in memory (only references are set, no coordinates). Step 3 (layout the tree) calculates the coordinates of the objects and creates junction lines in memory. The last step (#4) finally creates a graphics. The reason step 4 is a separate step is to allow all previous steps to have no reference to types referring to a specific graphics technology. But of cause, you must adapt the architecture to your needs."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-14T05:47:10.930",
"Id": "25351",
"Score": "0",
"body": "Well thank you for your input, it has been helpful, and I think I most likely have to do redesign of my program, not getting the results I want anyway (speed wise). And your architecture is a step in the right direction I believe."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-14T17:51:28.160",
"Id": "25389",
"Score": "0",
"body": "Enabling double buffering can help speed up drawing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-17T05:39:44.573",
"Id": "25488",
"Score": "0",
"body": "I have already done that, but this is clearly an architecture issue."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-09T14:12:02.630",
"Id": "15447",
"ParentId": "15406",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-07T07:57:10.820",
"Id": "15406",
"Score": "3",
"Tags": [
"c#",
"optimization"
],
"Title": "Drawing Tree Structures"
}
|
15406
|
<p>I wrote this little script in PHP a bit ago. It takes a .csv file and outputs a .txt file with certain data arranged in a "psuedo-array" looking format. I recently started messing around with Ruby so I decided to redo it. It wound up essentially as an exact translation, though.</p>
<p>Is there a simpler / more Ruby way to do this?</p>
<pre><code>require "csv"
class ArrayGenerator
def initialize( file )
@file = file
open_csv
end
private
def open_csv
File.open("#{@file}" + "_output.txt", 'w') do |file|
CSV.foreach(@file) do |row|
lat = row[6]
lon = row[7]
img = "#{row[0]}".downcase
part = "#{row[2]}"
loc = "#{row[5]}"
country = "#{row[4]}"
focus = "#{row[3]}"
desc = "#{row[8]}"
link = "#{row[9]}"
file.write("[#{lat}, #{lon}, #{img}, #{part}, #{loc}, #{focus}, #{country}, #{desc}, #{link}],
")
end
end
end
end
ARGV.each do |file|
g = ArrayGenerator.new( file )
end
</code></pre>
|
[] |
[
{
"body": "<pre><code>img = \"#{row[0]}\".downcase\npart = \"#{row[2]}\"\nloc = \"#{row[5]}\"\ncountry = \"#{row[4]}\"\nfocus = \"#{row[3]}\"\ndesc = \"#{row[8]}\"\nlink = \"#{row[9]}\"\n</code></pre>\n\n<p>The only difference between writing <code>\"#{ expression }\"</code> (without anything else in the string) and just writing <code>expression</code> is that the former converts the result of the expression to a string. If that is your intent, you should write <code>expression.to_s</code> instead because that way it's clearer what's going on.</p>\n\n<p>However in your case the values in <code>row</code> are already string, so there's no need to convert them to strings, so using <code>\"#{}\"</code> here is just redundant. You can just write <code>img = row[0].downcase</code>, <code>part = row[2]</code> etc.</p>\n\n<p>Instead of taking each column out of the <code>row</code> array individually, you can also write this:</p>\n\n<pre><code>CSV.foreach(@file) do |img, _, part, focus, country, loc, lat, lon, desc, link|\n img = img.downcase\n file.puts(\"[#{lat}, #{lon}, #{img}, #{part}, #{loc}, #{focus}, #{country}, #{desc}, #{link}],\")\nend\n</code></pre>\n\n<p>Note that I've used the variable name <code>_</code> to denote a variable we're not going to use because you never used <code>row[1]</code> in your code (<code>_</code> is conventionally used in Ruby to denote variables that aren't used and is in fact the only variable name that's allowed to appear multiple times in a parameter list).</p>\n\n<p>I've also replaced <code>write</code> with <code>puts</code> which automatically inserts a newline after the string, so you don't have to include the newline in the string.</p>\n\n<hr>\n\n<p>A couple of more general design notes:</p>\n\n<p>I think <code>open_csv</code> is rather misleadingly named. It does a lot more than just opening the csv file.</p>\n\n<p>I also think it's a bad idea to call <code>open_csv</code> in your constructor. Generally the constructor should only set up the object, so that it's in a usable state. It should not do any actual work. The way you designed it, everything the object is ever going to do is done in the constructor. That's why when you use it, you create the object with <code>ArrayGenerator.new</code> and then never do anything with the object - because everything that can be done with the object has already been in the constructor. Another sign of this is that the only public method in your class is <code>initialize</code>. This is a very strange way to use objects.</p>\n\n<p>On a related note there's no point in creating a <code>g</code> variable if you're not going to use it.</p>\n\n<p>You should either redesign your class to behave more like an actual class, with a usage more like this:</p>\n\n<pre><code>g = ArrayGenerator.new( file )\ng.generate\n</code></pre>\n\n<p>Or you could get rid of your class altogether and instead define a stand-alone method that could be used like this:</p>\n\n<pre><code>generate_array( file )\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-07T15:57:53.677",
"Id": "15415",
"ParentId": "15413",
"Score": "10"
}
}
] |
{
"AcceptedAnswerId": "15415",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-07T15:21:04.360",
"Id": "15413",
"Score": "8",
"Tags": [
"ruby",
"csv"
],
"Title": "Outputting a .txt file from a .csv file"
}
|
15413
|
<p>I'd like your opinion on something. I have the following class:</p>
<pre><code>public class ApplicationClock
{
void tick(object _)
{
lock (tickLock)
{
try
{
MessageBroker.Publisher.Publish(new Tick());
}
catch (Exception e)
{
this.Logger().Error("Application clock tick error", e);
//who knows why this happened, let's try and restart
if (ticker != null) ticker.Dispose();
Start();
}
}
}
readonly Object tickLock = new Object();
Timer ticker = null;
public ApplicationClock Start()
{
ticker = new Timer(tick, null, 0, 60*1000);
return this;
}
}
</code></pre>
<p>launched from the MvcApplication bootstrapper</p>
<pre><code>...
ApplicationClock clock;
protected void Application_Start()
{
//...
clock = new ApplicationClock().Start();
}
</code></pre>
<p>I realize that a service and some sort of inter-process communication (whether windows inter-process communication, HTTP, or something else) is more standard and reliable but I have a frequently changing team and don't want to add another step that is necessary to run the app.</p>
<p>This seems to work but I've only launched it in a dev scenario. Am I missing anything that would cause problems in production?</p>
<p>That's a System.Threading.Timer by the way.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-07T19:27:14.117",
"Id": "25013",
"Score": "0",
"body": "If it's launched from the bootstrapper and there is only ever one instance launched at app start is there any need to provide locking?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-07T19:58:01.700",
"Id": "25016",
"Score": "0",
"body": "@dreza - just a precaution if it is in the process of crashing and restarts, or if a tick takes longer than a minute for some reason."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-08T00:06:23.903",
"Id": "25033",
"Score": "1",
"body": "Why exactly are you even trying to do this? Also... The System.Diagnostics.Stopwatch class is great for measuring time taken."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-24T16:43:24.320",
"Id": "96573",
"Score": "0",
"body": "I am doing a similar project and used the Stopwatch. http://codereview.stackexchange.com/questions/55059/prewarmcache-for-mvc-application-with-stopwatch-infinite-loop"
}
] |
[
{
"body": "<p>Looks mostly ok, just some issues around coupling:</p>\n\n<p>Consider one of the following</p>\n\n<ol>\n<li>Pass <code>MessageBroker.Publisher</code> via the <code>ApplicationClock</code> constructor as an external dependency (preferably an interface). This will make the current implicit dependency explicit and visible which should yield in better maintenance in the future and easier unit testing. </li>\n<li>Pass the tick handler in as an <code>Action</code> parameter - no dependency on a specific object at all.</li>\n<li>Expose a <code>ClockTick</code> event and raise the event handler on tick. This way anyone interested in the clock can subscribe and the clock doesn't need to know about them at all.</li>\n</ol>\n\n<p>Also your tick interval is hard coded, it should be passed in as parameter.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T09:20:40.940",
"Id": "36043",
"ParentId": "15414",
"Score": "5"
}
},
{
"body": "<p>A few limitations that I've discovered since then.</p>\n\n<p>This will work. However, it is subject to all the Asp.Net (currently 4.5) limitations. </p>\n\n<ul>\n<li>You have no control over when IIS might decide to kill your process. Do not run anything in this manner that <em>has</em> to run to completion</li>\n<li>You have no control over whether your App Pool is running at any given time. If your application has not received any requests in a while, IIS might shut it down. When it is started by IIS at the next request the Tick timer will start again, but it might have been hours or even days since it ran last.</li>\n</ul>\n\n<p>In other words, this methodology is good for idempotent, non-mandatory tasks such as \"clean up the temp directory\" or \"remove any unused profile images from the file system\"</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-13T22:47:07.723",
"Id": "108232",
"Score": "1",
"body": "when setting IIS startMode to alwaysRunning it seem the problem is resolved"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-14T02:38:33.047",
"Id": "108261",
"Score": "0",
"body": "@Sherlock I don't see how that is possible. Something can still throw an exception that would crash the process. Can you explain a bit about how it would work?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-14T04:06:26.273",
"Id": "108267",
"Score": "0",
"body": "the exception can happen any ways try to catch it and handle that, putting the app pool to alwaysrunning, will make sure the tick will still run even if there are no requests"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-14T04:36:39.127",
"Id": "108268",
"Score": "0",
"body": "Ah I see. I would probably not depend on that but that does sound handy. Eg. I probably wouldn't depend on that to send weekly invoices but it sounds good for cleanup and non-critical sync-ing processes."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-24T18:22:21.313",
"Id": "55156",
"ParentId": "15414",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "55156",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-07T15:35:44.163",
"Id": "15414",
"Score": "4",
"Tags": [
"c#",
"multithreading",
"asp.net-mvc-4"
],
"Title": "Using a recurring System.Threading.Timer in an Mvc Application"
}
|
15414
|
<p>I haven't done Java coding in years, but I thought I would give it a shot for a job interview. I have a few questions:</p>
<ol>
<li><p>Why is this error handling considered poor? How am I supposed to be doing it?</p></li>
<li><p>What error catching should I be doing in a <code>finally</code> clause?</p></li>
<li><p>How am I masking exceptions?</p></li>
</ol>
<pre><code>package jGet;
/**
* Problem
*
* Create a very simple Java class that will retrieve the resource of any URL (using the HTTP protocol)
* and save the contents as seen by the browser, to a file.
*
* Restrictions
*
* You are free to use any library/technique, except for java.net.Url, java.net.URI or java.net.UrlConnection.
* Solutions using these classes will not be accepted.
* You are free to change the class signature for better error handling and readability.
*
* Initial Class outline
*
* public JGet extends Object {
* public JGet( String urlToPage, String saveToFilename ) {
* }
* public Object getContents() {
* }
* }
*
* Sample Test cases
*
* The class should be able to download the following sample URL's to a file:
* http://www.bing.com/
* http://www.aw20.co.uk/images/logo.png
*
* Time Allowance
*
* This took me a long time to complete (longer than 30 minutes).
* I returned the completed .java file to the person who invited me to take this, and
* this is the feedback I got back:
* 1) Poor exception handling
* 2) No finally clause in case of errors
* 3) getContents() returns a void
* 4) You should never throw a NullPointerException
* 5) Exception masking
* 6) Constructor calls the function getContents() no matter what
* 7) Poor layout
*
*/
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
public class JGet {
private final String urlToPage;
private final String saveToFileName;
/**
* @param urlToPage
* @param saveToFilename
*/
public JGet(String urlToPage, String saveToFilename) {
if (urlToPage == null) {
throw new IllegalArgumentException("The URL must not be null");
}
if (saveToFilename == null) {
throw new IllegalArgumentException(
"The name of the destination file must not be null");
}
if (urlToPage.length() == 0) {
throw new IllegalArgumentException("The URL must not be blank");
}
if (saveToFilename.length() == 0) {
throw new IllegalArgumentException(
"The name of the destination file must not be blank");
}
this.saveToFileName = saveToFilename;
this.urlToPage = urlToPage;
try {
getContents();
} catch (IOException e) {
throw new IllegalArgumentException("The ability to save to the destination file must not be blocked");
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException("The URL must not be malformed");
}
}
/**
* @throws IOException
* @throws IllegalArgumentException
*/
public void getContents() throws IOException, IllegalArgumentException {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(this.urlToPage);
HttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
IOUtils.copy(entity.getContent(), new FileOutputStream(this.saveToFileName));
}
/**
* @param args
*/
public static void main(String[] args) {
new JGet(null, "bing.html");
new JGet("http://www.bing.com/", null);
new JGet("", "bing.html");
new JGet("http://www.bing.com/", "");
new JGet("http://www.bing.com/", "readonly.html");
new JGet("Malformed URL", "bing.html");
new JGet("http://www.bing.com/", "bing.html");
new JGet("http://www.aw20.co.uk/a/img/logo.png", "logo.png");
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-07T20:29:43.017",
"Id": "25018",
"Score": "0",
"body": "Was there any indication as to why `getContents` should return `Object`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-07T21:53:08.863",
"Id": "25019",
"Score": "0",
"body": "Nope, and I got dinged for returning void. :-/"
}
] |
[
{
"body": "<p>Let me start off by saying how ridiculous the restrictions are:</p>\n\n<pre>\nYou are free to use any library/technique, except for java.net.Url, java.net.URI \nor java.net.UrlConnection.\nSolutions using these classes will not be accepted.\n</pre>\n\n<p>The fact is that the apache libraries which you are using internally use <code>java.net.Url</code> and <code>java.net.URI</code>. </p>\n\n<hr>\n\n<p>There are a few things that I'd like to point out about your code:</p>\n\n<ol>\n<li><p>There is some redundancy that can be avoided in the argument validation:</p>\n\n<pre><code>if (urlToPage == null) {\n throw new IllegalArgumentException(\"The URL must not be null\");\n}\nif (saveToFilename == null) {\n throw new IllegalArgumentException(\n \"The name of the destination file must not be null\");\n}\nif (urlToPage.length() == 0) {\n throw new IllegalArgumentException(\"The URL must not be blank\");\n}\nif (saveToFilename.length() == 0) {\n throw new IllegalArgumentException(\n \"The name of the destination file must not be blank\");\n}\n</code></pre>\n\n<p>Why don't we express this repeated logic in a validation method:</p>\n\n<pre><code>private static void validate(Object argument, Object illegal, String message){\n // reference == to avoid NullPointerException\n if (argument == illegal || argument.equals(illegal))\n throw new IllegalArgumentException(message);\n}\n</code></pre>\n\n<p>This cleans up that part of the constructor considerably:</p>\n\n<pre><code>validate(urlToPage, null, \"The URL must not be null\");\nvalidate(saveToFileName, null, \"The name of the destination file must not be null\");\nvalidate(urlToPage.length(), 0, \"The URL must not be blank\");\nvalidate(saveToFileName.length(), 0, \"The destination file name must not be blank\");\n</code></pre></li>\n<li><p>The criticism <code>Constructor calls the function getContents() no matter what</code> is justified in the sense that your constructor shouldn't do any complex work (such as file downloading) at all. So just set the two fields and be done. The file download should be explicitly started after creation of an instance.</p></li>\n<li><p>The try-catch at the end of your constructor <em>does</em> hide <code>IOException</code> as <code>IllegalArgumentException</code>. Avoid ever throwing <code>IllegalArgumentException</code> if it isn't right at the start of your method, or you will confuse your callers. Remove all this as you shouldn't be doing the download in the constructor anyway.</p></li>\n<li><p>You are right: <code>Object</code> is not an adequate return type for <code>getContents</code>. In this situation it would have been important to demand an explanation as to what kind of return is expected!<br>\nHowever: if you change the method to return <code>void</code>, you also need to change the name as <code>get</code> is no longer an accurate verb. I'd simply go with <code>download</code>.</p></li>\n<li><p>This may be a bit subjective, but I wouldn't specify Exceptions in the <code>throws</code> clause unless they are checked exceptions and therefore have to be included. So I'd leave out the <code>throws IllegalArgumentException</code>. The <code>finally</code> criticism was presumably referring to the unclosed output stream:</p>\n\n<pre><code>public void download() throws IOException {\n HttpClient httpClient = new DefaultHttpClient();\n HttpResponse response = httpClient.execute(new HttpGet(urlToPage));\n HttpEntity entity = response.getEntity();\n FileOutputStream stream = null;\n try {\n stream = new FileOutputStream(this.saveToFileName);\n IOUtils.copy(entity.getContent(), stream);\n }\n finally{\n if (stream != null) \n stream.close();\n }\n}\n</code></pre></li>\n</ol>\n\n<p>All in all, I don't consider this exercise to be effective in showing if someone is a good programmer or not. The object-orientation is contrived; a static utility class would be a lot more suitable for task. Who wants to instantiate a new object for every download, especially when <em>none</em> of the features of object-orientation (inheritance, polymorphism, ...) are used beneficially? </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-07T22:55:18.843",
"Id": "25020",
"Score": "2",
"body": "I like your `validate` method - I stole it for a revision to my answer, and in return I give you an upvote."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-07T22:19:01.197",
"Id": "15426",
"ParentId": "15420",
"Score": "11"
}
},
{
"body": "<p>There are a few things I see that I would want to refactor if I were working on this</p>\n\n<ol>\n<li>The <code>getContents()</code> method throws exceptions, which are simply caught and re-thrown in the <code>JGet</code> constructor in a way that modifies the error message, but doesn't include the cause (the original exception). This can make troubleshooting the code more difficult because you're obscuring information about where the problem originated. When throwing a new exception you can pass in the exception that caused it as an extra parameter.</li>\n<li>It's questionable whether or not the catching and re-throwing the exception(s) from <code>getContents()</code> is actually necessary. It might be helpful if the modified error message helps the programmer know the context of why it's an Illegal argument, but maybe not. In this case you're catching an IOException and re-throwing it as an <code>IllegalArugumentException</code>, while assuming that the only thing that could cause the IOException in the first place is that the destination file is not available. This is the kind of thing I'm talking about when I say that you're obscuring the root cause. Catching the <code>IllegalArgumentException</code> and then re-throwing it immediately with the, <code>\"The URL must not be malformed\"</code> message also possibly obscures something and in this case and appears completely redundant since you're not changing the type of exception or adding any useful information. Just let the exception roll up the chain as it naturally would.</li>\n<li>The first half (or so) of the <code>JGet</code> constructor is functionality that should be wrapped in its own method for readability reasons (you might later alter what defines an \"illegal\" argument, but you'll want to keep that definition contained within a method that does that job of determining if it's illegal).</li>\n</ol>\n\n<p>So, I would refactor this as something like:</p>\n\n<pre><code>/** Does what a JGet does (this is a joke comment)\n * \n * @param uriToPage The URL to the page you want\n * @param saveToFilename The full or relative path to the file you want to save to\n *\n * @throws IllegalArgumentException if the either the urlToPage or saveToFilename\n * parameters are null or blank.\n * @throws IOException if an I/O problem occurs either retrieving the results from the URL or saving the results to the file.\n */\npublic JGet(String urlToPage, String saveToFilename) throws IllegalAgumentException, IOException {\n this.saveToFileName = saveToFilename;\n this.urlToPage = urlToPage;\n\n validate();\n getContents();\n}\n\n/** Some useful documentation...\n */\nprivate void validate() throws IllegalArgumentException {\n // your code for checking for invalid arguments\n}\n\n\n...the rest of it...\n</code></pre>\n\n<p>I think the restrictions are pretty ridiculous as well, but you could re-use an OS tool, assuming it was available and call out to <code>curl -L [URL]</code> or something like that.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-07T22:33:47.370",
"Id": "15427",
"ParentId": "15420",
"Score": "10"
}
},
{
"body": "<p>Here are a few notes which were not mentioned earlier. Firstly, some about the specification:</p>\n\n<ol>\n<li><p>The <code>jGet</code> package name does not follow the usual conventions:</p>\n\n<ul>\n<li><a href=\"http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-135099.html#367\" rel=\"nofollow\">Code Conventions for the Java Programming Language, 9 - Naming Conventions</a></li>\n<li><em>Effective Java, 2nd edition</em>, <em>Item 56: Adhere to generally accepted naming conventions</em></li>\n</ul></li>\n<li><p>The <code>extends Object</code> is unnecessary here:</p>\n\n<pre><code>public JGet extends Object\n</code></pre>\n\n<p>It's the default.</p></li>\n<li><p><code>JGet</code> is not a good class name. From <em>Clean Code</em>, page 25: </p>\n\n<blockquote>\n <p>Classes and objects should have noun or noun phrase names like <code>Customer</code>, <code>WikiPage</code>,\n <code>Account</code>, and <code>AddressParser</code>. [...] A class name should not be a verb.</p>\n</blockquote></li>\n</ol>\n\n<p>Others already mentioned the questionable <code>Object</code> return type of the <code>getContents</code> method. They might expect that candidates start arguing about the specification although their answers does not suggest this.</p>\n\n<p>Some notes about the code:</p>\n\n<ol>\n<li><p>Comments like this are unnecessary:</p>\n\n<pre><code>/**\n * @param urlToPage\n * @param saveToFilename\n */\n</code></pre>\n\n<p>It says nothing more than the code already does, it's rather noise. (<em>Clean Code</em> by <em>Robert C. Martin</em>: <em>Chapter 4: Comments, Noise Comments</em>)</p></li>\n<li><p>I'd use the existing libraries for input checks.</p>\n\n<pre><code>checkArgument(StringUtils.isNotBlank(urlToPage), \"urlToPage cannot be blank\");\ncheckArgument(StringUtils.isNotBlank(saveToFilename), \"saveToFilename cannot be blank\");\n</code></pre>\n\n<p>It uses <a href=\"http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Preconditions.html\" rel=\"nofollow\"><code>Preconditions</code> from Guava</a> and <a href=\"http://commons.apache.org/lang/api-2.5/org/apache/commons/lang/StringUtils.html\" rel=\"nofollow\"><code>StringUtils</code> from Apache Commons Lang</a>.</p>\n\n<p>See also: <em>Effective Java, 2nd edition</em>, <em>Item 47: Know and use the libraries</em></p></li>\n<li><p>I don't agree with that that <em>you should never throw a <code>NullPointerException</code></em>. If the constructor gets a <code>null</code> reference it's usually an error in the client code. NPEs are fine for these situations. (See also: <em>Effective Java, 2nd edition</em>, <em>Item 38: Check parameters for validity</em> and <em>Item 60: Favor the use of standard exceptions</em>)</p></li>\n<li><p>A note about the <code>length()</code> check:</p>\n\n<pre><code>if (urlToPage.length() == 0) { ... }\n</code></pre>\n\n<p>The following is the same and easier to read:</p>\n\n<pre><code>if (urlToPage.isEmpty()) { ... }\n</code></pre></li>\n<li><p>Calling overridable methods (like <code>getContents</code>) from constructors usually is not a good practice. See <a href=\"http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Preconditions.html\" rel=\"nofollow\">What's wrong with overridable method calls in constructors?</a> and <em>Effective Java 2nd Edition, Item 17: Design and document for inheritance, or else prohibit it</em></p></li>\n<li><p>Please note that <code>HttpEntity</code> has a <a href=\"http://hc.apache.org/httpcomponents-core-ga/httpcore/apidocs/org/apache/http/HttpEntity.html#writeTo%28java.io.OutputStream%29\" rel=\"nofollow\"><code>writeTo</code></a> method. You could use this instead of <code>IOUtils.copy</code>. Anyway, if you don't use <code>writeTo</code> you should <code>close</code> the <code>InputStream</code> which was returned from <code>entity.getContent()</code> (as the <a href=\"http://hc.apache.org/httpcomponents-core-ga/httpcore/clover/org/apache/http/util/EntityUtils.html?line=195#src-195\" rel=\"nofollow\"><code>EntityUtils.toString()</code> method</a> does, for example).</p>\n\n<pre><code>InputStream contentStream = null;\nFileOutputStream fileOutputStream = null;\ntry {\n contentStream = entity.getContent();\n fileOutputStream = new FileOutputStream(saveToFileName);\n IOUtils.copy(contentStream, fileOutputStream);\n} finally {\n IOUtils.closeQuietly(contentStream);\n fileOutputStream.close(); // do NOT ignore output errors\n}\n</code></pre>\n\n<p>It would be simpler with with the <code>writeTo</code> method:</p>\n\n<pre><code>final FileOutputStream fileOutputStream = new FileOutputStream(saveToFileName);\ntry {\n entity.writeTo(fileOutputStream);\n} finally {\n fileOutputStream.close();\n}\n</code></pre></li>\n<li><p>In the <code>getContents</code> you could use <code>urlToPage</code> instead of <code>this.urlToPage</code> and <code>saveToFileName</code> instead of <code>this.saveToFileName</code>. Modern IDEs use highlighting to separate local variables from instance variables.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-08T19:56:32.760",
"Id": "25041",
"Score": "1",
"body": "very good points."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-08T19:40:56.580",
"Id": "15439",
"ParentId": "15420",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "15426",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-07T20:01:25.350",
"Id": "15420",
"Score": "11",
"Tags": [
"java",
"interview-questions",
"exception-handling",
"http"
],
"Title": "Exception handling, et al - How do I make this web downloader not \"poor\"?"
}
|
15420
|
<p>Currenty coding a PHP script that will have a CRON to auto run it.
The point is that it checks the user in Mysql and if it has expired, it will delete it from the admin table and set status to expired.
I have used time() and then when it gets INSERT When his trial starts, it starts for example "1347054850" in the "Start" and then i add "900" on it using +, and the result is "1347055750", So the trial is for 15 minutes.
But the point, will this scipt work propery or does it have issues?</p>
<pre><code><?php
$Sql = new mysqli("localhost", "root", "*******", "serveradmin");
if ($Sql->connect_error) { die("Sorry, Could not connect (".$Sql->connect_errno.") ".$Sql->connect_error);}
$Data = $Sql->query("SELECT * FROM trial");
while ($q = $Data->fetch_assoc()) {
$Start = $q['Start'];
$Stop = $q['Stop'];
$Steam = $q['Steam'];
$Result = $Start - $Stop;
$Time = time();
if ($q['Expired'] == "True") {echo "All expired \n";} else {
if ($Stop <= $Time) {
echo "Deleted ".$Steam." From trial Reason: Expired";
$Sql->Query("DELETE FROM `sm_admins` WHERE `identity` = '".$Steam."'");
$Sql->Query("UPDATE trial SET `Expired` = 'True' WHERE `Steam` = '".$Steam."'");
}
else
{
echo "All ok, 0 deleted";
}
}
}
?>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-11T07:43:54.517",
"Id": "429670",
"Score": "0",
"body": "what is steam in $steam =$q['steam'];?"
}
] |
[
{
"body": "<ol>\n<li><p>Proper and consistent indentation would improve the readability a lot. Here is mine:</p>\n\n<pre><code><?php\n $Sql = new mysqli(\"localhost\", \"root\", \"*******\", \"serveradmin\");\n if ($Sql->connect_error) { \n die(\"Sorry, Could not connect (\" . $Sql->connect_errno . \") \" . $Sql->connect_error);\n }\n $Data = $Sql->query(\"SELECT * FROM trial\");\n while ($q = $Data->fetch_assoc()) {\n $Start = $q['Start'];\n $Stop = $q['Stop'];\n $Steam = $q['Steam'];\n $Result = $Start - $Stop;\n $Time = time();\n if ($q['Expired'] == \"True\") {\n echo \"All expired \\n\";\n } else {\n if ($Stop <= $Time) { \n echo \"Deleted \" . $Steam . \" From trial Reason: Expired\"; \n $Sql->Query(\"DELETE FROM `sm_admins` WHERE `identity` = '\" . $Steam . \"'\");\n $Sql->Query(\"UPDATE trial SET `Expired` = 'True' WHERE `Steam` = '\" . $Steam . \"'\");\n } else { \n echo \"All ok, 0 deleted\"; \n }\n }\n }\n?>\n</code></pre></li>\n<li><p>These conditions are good candidates for guard clauses:</p>\n\n<pre><code>if ($q['Expired'] == \"True\") {\n echo \"All expired \\n\";\n} else {\n</code></pre>\n\n<p>and</p>\n\n<pre><code>if ($Stop <= $Time) { \n</code></pre>\n\n<p>Here is the modified version:</p>\n\n<pre><code>while ($q = $Data->fetch_assoc()) {\n $Start = $q['Start'];\n $Stop = $q['Stop'];\n $Steam = $q['Steam'];\n $Result = $Start - $Stop;\n $Time = time();\n if ($q['Expired'] == \"True\") {\n echo \"All expired \\n\";\n continue;\n }\n if ($Stop > $Time) { \n echo \"All ok, 0 deleted\"; \n continue;\n }\n echo \"Deleted \" . $Steam . \" From trial Reason: Expired\"; \n $Sql->Query(\"DELETE FROM `sm_admins` WHERE `identity` = '\" . $Steam . \"'\");\n $Sql->Query(\"UPDATE trial SET `Expired` = 'True' WHERE `Steam` = '\" . $Steam . \"'\");\n}\n</code></pre>\n\n<p>References: <em>Replace Nested Conditional with Guard Clauses</em> in <em>Refactoring: Improving the Design of Existing Code</em>; <a href=\"http://www.codinghorror.com/blog/2006/01/flattening-arrow-code.html\" rel=\"nofollow noreferrer\">Flattening Arrow Code</a></p></li>\n<li><p>Furthermore, if you are not interested in those records whose <code>Expired</code> flag is <code>True</code> and <code>Stop</code> attribute is bigger than the current time you could modify the SQL query to filter those records, for example:</p>\n\n<pre><code>$Data = $Sql->query(\"SELECT * FROM trial WHERE Expired != `True` AND Stop > \" . $Time);\n</code></pre>\n\n<p>(If you are using string concatenation to create SQL commands be careful about SQL injections attacks. The value of <code>$Time</code> comes from the <code>time()</code> function so it can't contain any malicious data here.)</p></li>\n<li><p>I'd consider using MySQL's datetime attributes for storing the date informations and using MySQL's date and time functions for the comparison. I'd improve the database structure and make the raw data readable. You might want to prepare for situations when the current time is different between the webserver and the database server.</p></li>\n<li><p><code>$mysql->query</code> has a return value. You might want to check whether it's <code>FALSE</code> and print a proper error message.</p></li>\n<li><p>PHP functions are not case sensitive, but according to <a href=\"https://stackoverflow.com/a/5643544/843804\">this answer</a> you might want to modify <code>->Query(...)</code> to <code>->query(...)</code>.</p></li>\n<li><p>This line seems unnecessary, since the <code>$Result</code> variable is not used:</p>\n\n<pre><code>$Result = $Start - $Stop;\n</code></pre></li>\n<li><p>The delete and update statement uses the <code>$Steam</code> variable as the part of the query without escaping it. I think it could cause <a href=\"https://stackoverflow.com/a/9828040/843804\">2nd order SQL attacks</a>.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-09T14:53:51.893",
"Id": "15448",
"ParentId": "15425",
"Score": "5"
}
},
{
"body": "<p>Everything must be done on the <em>database level</em>.\nIt is incomparably resource-friendly. Instead of fetching all the data from database and looping over many rows most of which do not even meet the condition, we must set this condition right in the query, to fetch the only rows we need. </p>\n\n<p>Better yet, instead of deleting and updating rows one by one, we must delete and update based on the condition as well.</p>\n\n<p>The logic with information messages is also a bit flawed so I fixed it as well. You cannot tell \"All ok, 0 deleted\" if <em>only one</em> row is OK.</p>\n\n<p>And as a last stroke, lets make the <a href=\"https://phpdelusions.net/mysqli/mysqli_connect\" rel=\"nofollow noreferrer\">mysqli connection</a> more robust and also put it in a separate file.</p>\n\n<pre><code><?php\ninclude 'mysqli.php';\n\n$time = time();\n$res = $mysqli->query(\"SELECT Steam FROM trial WHERE Stop <= $time\");\n$expired = $res->fetch_all();\n\nif ($expired) {\n $mysqli->query(\"UPDATE trial SET `Expired` = 'True' WHERE Stop <= $time\");\n $mysqli->query(\"DELETE FROM sm_admins a, trial t \n WHERE t.Expired='True' AND a.identity = t.Steam\");\n foreach ($expired as $row) {\n echo \"Deleted $row[0] From trial Reason: Expired\\n\"; \n }\n} else { \n echo \"All ok, 0 deleted\"; \n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-11T11:37:49.133",
"Id": "429683",
"Score": "0",
"body": "It might be worth a note justifying how you trust `$time` to be interpolated, which would normally ring query-injection alarm bells."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-11T08:58:07.180",
"Id": "222067",
"ParentId": "15425",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "15448",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-07T21:56:28.663",
"Id": "15425",
"Score": "3",
"Tags": [
"php",
"mysql"
],
"Title": "PHP Check user and delete if expired"
}
|
15425
|
<p>My original code is:</p>
<pre><code>let (upPosition, downPosition, leftPosition, rightPosition) =
match myMove.MyDirection with
| Direction.Up -> (GoUp y, y, GoLeft x, GoRight x)
| Direction.Down-> (y, GoDown y, GoLeft x, GoRight x)
| Direction.Left -> (GoUp y, GoDown y, GoLeft x, x)
| Direction.Right -> (GoUp y, GoDown y, x, GoRight x)
| _ -> (y, y, x, x)
</code></pre>
<p>Basically, there is an object on the 2D board. <code>myMove.MyDirection</code> dictates its next move, and x,y are its target position.</p>
<p>Once the object gets to x,y, it would cause some impacts on its front, left, right neighbours from its local rotational space. <code>GoUp</code>, ... , <code>GoRight</code> determines how far those neighbours could be.</p>
<p>So, ultimately, the code returns a "+" (cross) shape centred at x,y, so the minimum variable to describe this shape is (<code>x</code>, <code>y</code>, <code>upPosition</code>, <code>downPosition</code>, <code>leftPosition</code>, <code>rightPosition</code>).</p>
<p>The best solution I can think of to the previous code is the following. However, I feel there is more can be done to make it better. Is there any <code>map</code> function for <code>tuple</code> and is it costly?</p>
<pre><code>let Reverse = function
| Direction.Up -> Direction.Down
| Direction.Down -> Direction.Up
| Direction.Left -> Direction.Right
| Direction.Right -> Direction.Left
| _ -> raise (ArgumentException("Not Vaild Move!"))
let Go myDirection filter pos =
match myDirection, filter with
| a,b when a=b -> pos
| Direction.Up , _ -> GoUp pos
| Direction.Down , _ -> GoDown pos
| Direction.Left , _ -> GoLeft pos
| Direction.Right , _ -> GoRight pos
| _ -> pos
let (upPosition, downPosition, leftPosition, rightPosition) =
let rev = Reverse myMove.MyDirection
(Go Direction.Up rev y, Go Direction.Down rev y, Go Direction.Left rev x, Go Direction.Right rev x)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-07T23:23:20.107",
"Id": "25021",
"Score": "0",
"body": "I have to say, I'm a bit puzzled by this code. Why are there 4 values to represent a position? And why does the original code call both `GoLeft` and `GoRight` when the input is `Direction.Up`? Can you comment it a bit?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-07T23:45:47.493",
"Id": "25022",
"Score": "0",
"body": "@TomasPetricek Updated, Hopefully it is now better explained"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-08T15:46:06.127",
"Id": "25035",
"Score": "0",
"body": "Can you add the definition of your `Direction` type? Also, where is the `myMove` variable coming from (it's not defined in the code you have here)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-08T17:38:19.700",
"Id": "25036",
"Score": "0",
"body": "@JackP. Direction is a Enum with 4 directions.... the only arguments for this code is myMove.MyDirection, x,y"
}
] |
[
{
"body": "<p>It's tough to review only <em>part</em> of the code, because there are often small improvements which could be made but they depend on knowing the structure of the entire program -- for example, why are you using a tuple to pass around the positions (<code>(upPosition, downPosition, leftPosition, rightPosition)</code>)? You'd likely be better off using a record type to encapsulate those values, since you'd only have to pass one variable around (the record) and it also facilitates structural matching which'll allow you to clean up some of your other functions.</p>\n\n<p>The <code>Direction</code> enum would be much better as a discriminated union type (see the code below). Even though enums can define certain values (e.g., Up, Down, Left, Right) they can also take on <em>any</em> integer value by casting the value to the enum type. Discriminated union types also allow you to define a fixed set of values, but the F# type system ensures that your variables can have <em>only</em> the defined values -- which in turn, keeps you from having to use the wildcard pattern (<code>_</code>) to check for error conditions in your <code>match</code> statements.</p>\n\n<p>Here's my version of your code -- it's largely the same, but I've changed <code>Direction</code> into a union type and moved the <code>Reverse</code> function into a new <code>Direction</code> module.</p>\n\n<pre><code>type Direction =\n | Up\n | Down\n | Left\n | Right\n\n[<RequireQualifiedAccess; CompilationRepresentation(CompilationRepresentationFlags.ModuleSuffix)>]\nmodule Direction =\n /// Reverses a specified direction.\n [<CompiledName(\"Reverse\")>]\n let rev = function\n | Direction.Up ->\n Direction.Down\n | Direction.Down ->\n Direction.Up\n | Direction.Left ->\n Direction.Right\n | Direction.Right ->\n Direction.Left\n\n\n[<CompiledName(\"Go\")>]\nlet go myDirection filter pos =\n match myDirection with\n | x when x = filter ->\n pos\n | Direction.Up ->\n GoUp pos\n | Direction.Down ->\n GoDown pos\n | Direction.Left ->\n GoLeft pos\n | Direction.Right ->\n GoRight pos\n\nlet (upPosition, downPosition, leftPosition, rightPosition) =\n match myMove.MyDirection with\n | Direction.Up ->\n (GoUp y, y, GoLeft x, GoRight x)\n | Direction.Down->\n (y, GoDown y, GoLeft x, GoRight x)\n | Direction.Left ->\n (GoUp y, GoDown y, GoLeft x, x)\n | Direction.Right ->\n (GoUp y, GoDown y, x, GoRight x)\n\nlet (upPosition, downPosition, leftPosition, rightPosition) =\n let rev = Direction.rev myMove.MyDirection\n (go Direction.Up rev y, go Direction.Down rev y, go Direction.Left rev x, go Direction.Right rev x)\n</code></pre>\n\n<p><strong>EDIT:</strong> Answers to your questions:</p>\n\n<ol>\n<li>Normally, you can't have a module and a type with the same name within a certain namespace, but the <code>[<CompilationRepresentation(...)>]</code> attribute I used adds \"Module\" to the name of the compiled module type. So in this case, the Direction module would be compiled to a type called DirectionModule.</li>\n<li><p>You could make <code>rev</code> a member function of the Direction type. However, in F# it's easier (in general) to <em>consume</em> module-based functions instead of type members because it works much better with F#'s type inference mechanism. In our example, if you had an instance of Direction you wouldn't be able to call <code>myDirection.Reverse()</code> unless you declared <code>myDirection</code> as a variable of type <code>Direction</code> (or the F# compiler was able to figure it out another way); if you call the module-based function (<code>Direction.rev myDirection</code>) F# can easily infer the type of the <code>myDirection</code> variable so you don't need any explicit type annotations.</p>\n\n<p>If you're consuming this code from C#, then I'd write the code like this to get the best of both worlds:</p>\n\n<pre><code>type Direction =\n | Up\n | Down\n | Left\n | Right\n\n member this.Reverse () =\n match this with\n | Direction.Up ->\n Direction.Down\n | Direction.Down ->\n Direction.Up\n | Direction.Left ->\n Direction.Right\n | Direction.Right ->\n Direction.Left\n\n[<RequireQualifiedAccess; CompilationRepresentation(CompilationRepresentationFlags.ModuleSuffix)>]\nmodule internal Direction =\n /// Reverses a specified direction.\n [<CompiledName(\"Reverse\")>]\n let inline rev (dir : Direction) =\n dir.Reverse ()\n</code></pre>\n\n<p>In this version of the code, I've defined <code>Reverse</code> as a member on the direction type (making it easy to consume from C#), but I also have the module-based function which is easier to consume from F#. Note the module-based function is now marked <code>inline</code>; as it only calls the <code>Reverse()</code> member it makes sense for the F# compiler to emit code which directly calls <code>Reverse()</code>. Another way to think about this is that within this version of the code, the module-based <code>rev</code> function is only useful for type-inference purposes (but it <em>is</em> useful if you're using it from within F#).</p></li>\n<li><p><code>[<CompiledName(...)>]</code> is an attribute specific to F#; when you use it on a function, the F# compiler will compile the function so it has the name you've specified in the attribute. This is primarily used when you want to consume some F# code from C#; you can define your F# functions with idiomatic F# names (e.g., <code>rev</code>), but by applying this attribute the methods in the compiled assembly can have idiomatic C# names (e.g., <code>Reverse</code>) to make them easier to consume.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-10T09:34:28.530",
"Id": "25088",
"Score": "0",
"body": "Thx for the reply, I have a few questions based on ur code :) (a) Is it valid to declare module the same name as an existing type ? I thought as they are both classes in .net when i access from c#, they need to be named differently. (b) why not make rev as a member function of Direction type? (c) What is [<CompiledName(\"...\")>] and what's the purpose of it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-10T14:50:01.263",
"Id": "25101",
"Score": "0",
"body": "Hi @colinfang -- I've edited my response to include answers to your questions."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-09T14:04:10.267",
"Id": "15446",
"ParentId": "15428",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "15446",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-07T22:06:22.017",
"Id": "15428",
"Score": "5",
"Tags": [
"f#",
"coordinate-system"
],
"Title": "Determining directions for a 2D boad"
}
|
15428
|
<p>I realised that <a href="https://codereview.stackexchange.com/q/15316/6313">what I was doing</a> wasn't particularly smart, so I switched to a different approach. This costs more dynamic allocations but has a much simpler implementation:</p>
<pre><code>#pragma once
#include <boost/utility.hpp>
#include <set>
#include <map>
//! A map of types to values.
//!
//! Associative container which allows mapping of types to values of that
//! type.
class TypeMap : boost::noncopyable {
typedef void (*destruct_func)(void*);
class TypeMapStaticInstance : boost::noncopyable {
destruct_func destroy_;
std::map<TypeMap const*, void*> map_;
public:
TypeMapStaticInstance(destruct_func f)
: destroy_(f) {}
void*& get(TypeMap const* tm) {
return map_[tm];
}
void const* cget(TypeMap const* tm) const {
auto element = map_.find(tm);
if (element != map_.end())
return element->second;
return nullptr;
}
void remove(TypeMap const* tm) {
auto element = map_.find(tm);
destroy_(element->second);
map_.erase(element);
}
};
template<typename T>
class TypeMapDetail {
TypeMapDetail() = delete;
static void destroy_impl(void* p) {
delete static_cast<T*>(p);
}
public:
static TypeMapStaticInstance map_;
static T& get(TypeMap const* p) {
auto& element = map_.get(p);
if (!element)
element = new T();
return *static_cast<T*>(element);
}
static T const* cget(TypeMap const* p) {
return static_cast<T const*>(map_.cget(p));
}
};
std::set<TypeMapStaticInstance*> members_;
public:
//! Retrieve the data associated with the given type.
template<typename T>
T& get() {
members_.insert(&TypeMapDetail<T>::map_);
return TypeMapDetail<T>::get(this);
}
template<typename T>
T const* cget() const {
return TypeMapDetail<T>::cget(this);
}
~TypeMap() {
for (auto m : members_) {
m->remove(this);
}
}
};
template<typename T>
TypeMap::TypeMapStaticInstance TypeMap::TypeMapDetail<T>::map_(TypeMap::TypeMapDetail<T>::destroy_impl);
</code></pre>
<p>Comments:</p>
<ul>
<li>One of the reasons I think this approach may be better is that I don't see any undefined behaviour being invoked. Am I correct about this?</li>
<li>Now that standard containers can have stateful allocators, would having each contain <code>destruct_func</code> (and probably <code>construct_func</code>) make sense?</li>
</ul>
<p>Other issues as always welcome.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-19T17:56:27.210",
"Id": "450242",
"Score": "4",
"body": "Can you please provide example code to use this in a small program?"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-08T07:55:40.883",
"Id": "15431",
"Score": "9",
"Tags": [
"c++",
"c++11",
"boost",
"hash-map"
],
"Title": "Take two on type to instance map"
}
|
15431
|
<p>I've written a project for handling various Facebook things and I ran into the issue where one project named the users profile <code>Profile</code> while normally they would be named <code>UserProfile</code>. When I was checking if the <code>FacebookUser</code> model was related to a <code>User</code>, I could just <code>User.objects.get(userprofile__facebook=facebook_user)</code> so I come up with a way to get the name, but it seems pretty ugly. Is there a cleaner way?</p>
<pre><code>from django.conf import settings
from django.contrib.auth.models import User
from better_facebook.models import FacebookUser
# Get the name of the AUTH profile so that we can check if the user
# has a relationship with facebook. Is there a neater way of doing this?
_lowercase_profile_name = settings.AUTH_PROFILE_MODULE.split(".")[1].lower()
_facebook_relation = '{0}__facebook'.format(_lowercase_profile_name)
class FacebookBackend(object):
"""
Authenticate against a facebook_user object.
"""
def authenticate(self, facebook_user):
assert(isinstance(facebook_user, FacebookUser))
try:
return User.objects.get(**{_facebook_relation: facebook_user})
except User.DoesNotExist:
return None
def get_user(self, user_id):
try:
return User.objects.get(pk=user_id)
except User.DoesNotExist:
return None
</code></pre>
|
[] |
[
{
"body": "<p>You can use django.contrib.auth.get_user_model() instead of importing User directly. Note that I also explicitly included the ObjectDoesNotExist exception.</p>\n\n<p><a href=\"https://docs.djangoproject.com/en/2.2/topics/auth/customizing/\" rel=\"nofollow noreferrer\">https://docs.djangoproject.com/en/2.2/topics/auth/customizing/</a></p>\n\n<pre><code>from django.conf import settings\nfrom django.contrib.auth import get_user_model\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom better_facebook.models import FacebookUser\n\n\nclass FacebookBackend(object):\n \"\"\"\n Authenticate against a facebook_user object.\n \"\"\"\n def authenticate(self, facebook_user):\n assert(isinstance(facebook_user, FacebookUser))\n try:\n UserModel = get_user_model()\n return UserModel.objects.get(userprofile__facebook=facebook_user)\n except ObjectDoesNotExist:\n return None\n\n def get_user(self, user_id):\n try:\n UserModel = get_user_model()\n return UserModel.objects.get(pk=user_id)\n except ObjectDoesNotExist:\n return None\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-22T09:34:23.687",
"Id": "224660",
"ParentId": "15432",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-08T10:58:57.410",
"Id": "15432",
"Score": "7",
"Tags": [
"python",
"django"
],
"Title": "Finding the profile name for a join in my Facebook auth backend"
}
|
15432
|
<p>Please review for any unnecessary casting, memory leaks, wrong use of pthread call, or validation problems in the given code.</p>
<pre><code>/**********************************************************************
* FILENAME :thread_1.c
* DESCRIPTION:Contains Code for a program that demonstrates the
* use of pthread calls.The created threads will accept an
* argument and return the argument after adding a number.
****************************************************************************/
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
void *thread_entry(void *arg)
{
int *p;
p=(int*)arg;
*p = (*p) + 10;
pthread_exit(p);
}
int main(int argc, char* argv[])
{
pthread_t* threads;
int t,ret,numthreads = 0,thread_success = 0,*iptr;
void* thread_result;
if ( argc < 2 )
{
printf("Less number of Args -Pl. enter a valid number of threads to be created\n");
exit(1);
}
numthreads = atoi(argv[1]);
if ( 0 > numthreads )
{
printf("Pl. enter a valid number of threads to be created\n");
exit(1);
}
threads = calloc(numthreads, sizeof(pthread_t));
if (NULL == threads)
{
printf("Failed to alocate memory in malloc\n");
exit(1);
}
/*Creating the Threads*/
for(t=0; t < numthreads; t++)
{
printf("Creating Thread\n");
iptr = (int*)malloc(sizeof(int));
*iptr = t;
ret = pthread_create(&threads[t],NULL,thread_entry,(void*)iptr);
if(ret )
{
printf("Printf Error Creating Thread");
free(iptr);
}
else
{
thread_success++;
}
}
//Now waiting for all the threads
//thread_success is the number of successfully created threads
for(t=0; t < thread_success; t++)
{
ret = pthread_join(threads[t],&thread_result);
if (ret)
{
printf("Error joining a thread");
}
else
{
printf("Joined thread returned %d\n", *((int*)thread_result));
free(thread_result);
}
}
free(threads);
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<p>Align your code better.<br>\nIt probably has tabs (replace them with space before pasting) in it that make reading it hard on a website.</p>\n\n<p>Please declare one variable per line:</p>\n\n<pre><code>int t,ret,numthreads = 0,thread_success = 0,*iptr;\n</code></pre>\n\n<p>You are not saving anything be doing this. But you are making it harder to read fot the next person. Anyway when you get a job (sorry I assume you are in college (forgive me if I am wrong)) no company coding standard will let you get away with it. So best not to get in the habit to start with.</p>\n\n<p>Your detection of bad input is spread over two print statements. Do all the tests that make the input bad in one place then use one print statements. Whose normal content is a description of usage. If you want to be fancy describe what they did wrong. But most people just do it wrong in the first place to see the useage comment.</p>\n\n<pre><code>if ( argc < 2 )\n {\n printf(\"Less number of Args -Pl. enter a valid number of threads to be created\\n\");\n exit(1);\n}\nnumthreads = atoi(argv[1]);\nif ( 0 > numthreads )\n{\n printf(\"Pl. enter a valid number of threads to be created\\n\");\n exit(1);\n}\n\n// I would have done:\n\nif (( argc < 2 ) || ((numthreads = atoi(argv[1])) == 0))\n{\n printf(\"Usage: %s <number>\\nThe number represents the number of threads to start\\n\", argv[0]);\n exit(1);\n}\n</code></pre>\n\n<p>Your only bug (that I can see) next:</p>\n\n<pre><code>ret = pthread_create(&threads[t],NULL,thread_entry,(void*)iptr);\n</code></pre>\n\n<p>You can't see it until you read further and note you are joining on threads[t] even if not all the threads worked. So you need some method to track which threads actually failed and pass that information forward to the join section (what I did below) or you need to re-use the <code>t</code> slot in the thread array (If you loop over the array using <code>thread_success</code> as the limit then you can not leave any blank slots in the array).</p>\n\n<pre><code>typedef struct ThreadAndData\n{\n pthread_t thread; // Keep all thread info in one place\n int value; // That way the master can potentially look at the value\n int status; // while the thread is running.\n} ThreadAndData;\nthreads = calloc(numthreads, sizeof(ThreadAndData));\n\n\nthreads[t].status = pthread_create(&threads[t].thread,NULL,thread_entry,(void*)&threads[t].value);\nif(threads[t].status)\n{\n printf(\"Printf Error Creating Thread\");\n}\n\n\n// Now in the joining phase.\n// You only need to to join on threads that have a 0 status.\nif (thread[t].status == 0)\n{\n ret = pthread_join(threads[t].thread,&thread_result);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-08T17:46:44.947",
"Id": "25037",
"Score": "0",
"body": "Thanks a lot Loki for your time. Your review comments are excellent."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-08T18:24:31.697",
"Id": "25038",
"Score": "0",
"body": "One more issue: numthreads = 0 seems to be permitted. Not sure that makes sense."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-08T18:29:06.260",
"Id": "25039",
"Score": "0",
"body": "@GlennRogers: You have space for your own answer below. But not only does it make sense it is required. The result of atoi() may be undefined if the input is not a number."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-08T16:58:38.103",
"Id": "15436",
"ParentId": "15434",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "15436",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-08T12:10:44.683",
"Id": "15434",
"Score": "4",
"Tags": [
"c",
"casting",
"pthreads"
],
"Title": "Demonstration of pthread calls"
}
|
15434
|
<p>I'd like to hear some thoughts on my simple anagram finder, written in Scala. I mainly wrote this as a first go at writing some serious Scala, and I wanted to try out the Scalaz library.</p>
<p>I'm coming from a Java background, with minimal experience with functional languages. Things I'd ideally like feedback on:</p>
<ul>
<li>Any improvements to make it less imperative</li>
<li>Any other uses of library code, like Scalaz</li>
</ul>
<p>I know that I've not covered all test cases, but this was enough to get me up and running.</p>
<h3>General algorithm:</h3>
<ul>
<li>Parse a list of words. Turn each word into lower case, sort alphabetically and treat that as the 'signature' of the word.</li>
<li>Insert signature and word into a map, with the key being the signature, and the value being a set (or list) of words with the same signature</li>
<li>Retrieval is simply looking up a word based on its signature</li>
</ul>
<h3>Signature class</h3>
<pre><code>case class Stem(word: String) {
val stem: List[Char] = word.toLowerCase.trim.toList.sortWith((e1, e2) => (e1 < e2))
override def equals(p1: Any) = p1 match {
case s: Stem => s.stem == stem
case _ => false
}
override def hashCode = stem.hashCode
override def toString = stem.mkString("Stem(", "", ")")
}
</code></pre>
<p><strong>Notes</strong>:</p>
<p>I'm sure I'd be able to take the word as a parameter and manipulate it to be in alphabetical order, rather than having a <code>stem</code> field. I'm sure I'd have been able to omit the <code>equals</code> and <code>hashCode</code> methods then, but I couldn't work out how to do that. I think maybe because I'm using a <code>case class</code> here?</p>
<h3>Anagram Finder class</h3>
<pre><code>import scalaz._
import Scalaz._
class AnagramFinder(words: List[String]) {
implicit def string2Stem(s: String): Stem = Stem(s)
val mapping = createMapping(words)
def createMapping(words: List[String]) = {
var anagrams: Map[Stem, Set[String]] = Map()
words.foreach(s => anagrams = anagrams |+| Map(Stem(s) -> Set(s)))
anagrams
}
def find(word: String): Option[Set[String]] = mapping.get(word)
}
</code></pre>
<p><strong>Notes</strong>:</p>
<p>I really wanted to just have <code>anagrams |+| Map(Stem(s) -> Set(s))</code> in my <code>foreach</code>, but that required (a) using a mutable map instead, which I'd be fine with, but (b) having to write my own semigroup implementation for the mutable Map, which I struggled with.</p>
<p>Also, <code>anagrams |+| Map(Stem(s) -> Set(s))</code> isn't picking up my implicit String to Stem method. Why?</p>
<h3>Anagrams object</h3>
<pre><code>object Anagrams {
def apply(wordListFile: String, word: String) = {
val finder = new AnagramFinder(scala.io.Source.fromFile(wordListFile).mkString.split('\n').toList)
finder.find(word)
}
}
</code></pre>
<p><strong>Notes</strong>: I know I should initialise the word list into a <code>val</code> field on the object which can be reused between calls, but this was really just to get me started.</p>
<h3>Appendix: Tests</h3>
<pre><code>class StemTest extends org.scalatest.FunSuite {
test("Stem of noel is e,l,n,o") {
assert(Stem("noel").stem == List('e','l','n','o'))
}
test("Stem of Hello is H,e,l,l,o") {
assert(Stem("Hello").stem == List('H', 'e', 'l', 'l', 'o'))
}
test("Stems of abc and cba are equal") {
assert(Stem("abc") == Stem("cba"))
}
}
class AnagramFinderTest extends FunSuite {
test("List of words should create appropriate map") {
val testMap:Map[Stem, Set[String]] = Map(Stem("abc") -> Set("cba"), Stem("def") -> Set("def"), Stem("ggz") -> Set("zgg"))
val givenList = List("cba", "def", "zgg")
val mapping = new AnagramFinder(givenList).mapping
assert(mapping == testMap)
}
test("Same stemmed words should both exist in the map") {
val testMap:Map[Stem, Set[String]] = Map(Stem("abc") -> Set("abc", "cba"))
val givenList = List("abc", "cba")
val mapping = new AnagramFinder(givenList).mapping
assert(mapping == testMap)
}
test("Finding words") {
val givenList = List("abc", "cba", "bob", "bca")
val anagramFinder = new AnagramFinder(givenList)
val foundAnagrams = anagramFinder.find("abc").get
val expected = Set("abc", "bca", "cba")
assert(foundAnagrams.forall(s => expected contains s))
assert(expected.forall(s => foundAnagrams contains s))
}
test("Full test") {
val expected = Some(Set("act", "cat", "Cat"))
val actual = Anagrams("/usr/share/dict/words", "cat")
assert(expected == actual)
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Some suggestions to improve your code:</p>\n\n<p><code>xs.sortWith((e1, e2) => (e1 < e2))</code> is identical to <code>xs.sorted</code></p>\n\n<p>If you are not interested in <code>Stem.word</code> you can place it into companions' apply-method:</p>\n\n<pre><code>object Stem {\n def apply(word: String): Stem = {\n val stem: List[Char] = word.toLowerCase.trim.toList.sorted\n new Stem(stem)\n }\n}\n\ncase class Stem private(stem: List[Char])\n</code></pre>\n\n<hr>\n\n<p><code>source.mkString.split('\\n')</code> is identical to <code>source.getLines</code></p>\n\n<hr>\n\n<p>Whenever you want to sum-up something or use an accumulator, <code>fold</code> is what you are searching for:</p>\n\n<pre><code>(Map.empty[Stem, Set[String]] /: words) {\n case (map, word) => map + (Stem(word) -> Set(word))\n}\n</code></pre>\n\n<p>With help of scalaz:</p>\n\n<pre><code>words.map(word => Map(Stem(word) -> Set(word))) reduceLeft { _|+|_ }\n</code></pre>\n\n<p><code>reduce</code> is a <code>fold</code>: <code>xs.tail.fold(xs.head)(f)</code></p>\n\n<p><code>/:</code> is a synonym for <code>foldLeft</code>: <code>(init /: xs)(f) == (xs foldLeft init)(f)</code></p>\n\n<hr>\n\n<p>Your implicit conversion <code>String => Stem</code> doesn't work in <code>string -> set</code> because <code>-></code> already needs an implicit conversion and you are not allowed to apply multiple ones at once. When you use tuple notation <code>(string, set)</code>, your implicit conversion is applied.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-09T11:02:57.907",
"Id": "15445",
"ParentId": "15437",
"Score": "14"
}
}
] |
{
"AcceptedAnswerId": "15445",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-08T17:10:39.503",
"Id": "15437",
"Score": "16",
"Tags": [
"scala",
"scalaz"
],
"Title": "Simple anagram finder using Scala and some Scalaz"
}
|
15437
|
<p>I have written some code to simple add/mod/del to a table called person. I would like comments on where this code could be comprising on security. I have used the PDO library in php.</p>
<p>GetPerson.php ( use this to retrieve details of a person using ajax )</p>
<pre><code><?php
include '../classes/person.php';
include '../classes/avaaz_mysql_db.php';
include '../config.php';
try
{
if(isset($_POST['id']))
{
$id = $_POST['id'];
//clean variable //clean further
settype($id, 'string');
$id = strip_tags($id);
//decode
$id = base64_decode($id);
//remove salt string
$id = str_replace($config['salt_string'], '', $id);
//clean again
settype($id, 'integer');
//get the person details and output as json
$db = new avaaz_mysql_db($config['db_connection_string'],$config['db_user_name'],$config['db_password']);
$row = $db->get_person($id);
$arr_peron_details = $row[0];
//clean data returned from db
foreach ($arr_peron_details as $key => $value)
{
$arr_peron_details[$key] = htmlentities($value);
}
echo json_encode(array($arr_peron_details));
}
}
catch (Exception $e)
{
echo "Getting person details: ".$e->getMessage();
}
?>
</code></pre>
<p><strong>Person.php ( class that represents a person)</strong></p>
<pre><code><?php
class person
{
private $id;
private $first_name;
private $last_name;
private $country;
private $city;
private $address;
private $email;
public function set_id($tmp_id)
{
//data type checking and validation happens here
settype($tmp_id, "integer");
if((!isset($tmp_id)) || $tmp_id==0)
{
throw new Exception('Incorrect person id');
}
$this->id = $tmp_id;
}
public function get_id()
{
return $this->id;
}
public function set_first_name($tmp_first_name)
{
//data type checking and validation happens here
settype($tmp_first_name, "string");
if((!isset($tmp_first_name)) || $tmp_first_name=='')
{
throw new Exception('First name cannot be empty');
}
$tmp_first_name = strip_tags($tmp_first_name);
if(!$this->is_only_letters_and_spaces($tmp_first_name))
{
throw new Exception('Only letters and spaces allowed in first name');
}
$this->first_name = $tmp_first_name;
}
public function set_last_name($tmp_last_name)
{
//data type checking and validation happens here
settype($tmp_last_name, "string");
if(!isset($tmp_last_name) || $tmp_last_name=='')
{
throw new Exception('Last name cannot be empty');
}
$tmp_last_name = strip_tags($tmp_last_name);
if(!$this->is_only_letters_and_spaces($tmp_last_name))
{
throw new Exception('Only letters and spaces allowed in last name');
}
$this->last_name = $tmp_last_name;
}
public function set_country($tmp_country)
{
//data type checking and validation happens here
settype($tmp_country, "string");
if(!isset($tmp_country) || $tmp_country=='')
{
throw new Exception('Country cannot be empty');
}
$tmp_country = strip_tags($tmp_country);
if(!$this->is_only_letters_and_spaces($tmp_country))
{
throw new Exception('Only letters and spaces allowed in country');
}
$this->country = $tmp_country;
}
public function set_city($tmp_city)
{
//data type checking and validation happens here
settype($tmp_city, "string");
if(!isset($tmp_city) || $tmp_city=='')
{
throw new Exception('City cannot be empty');
}
$tmp_city = strip_tags($tmp_city);
if(!$this->is_only_letters_and_spaces($tmp_city))
{
throw new Exception('Only letters and spaces allowed in city');
}
$this->city = $tmp_city;
}
public function set_address($tmp_address)
{
//data type checking and validation happens here
settype($tmp_address, "string");
if(!isset($tmp_address) || $tmp_address=='')
{
throw new Exception('Address cannot be empty');
}
$tmp_address = strip_tags($tmp_address);
$this->address = $tmp_address;
}
public function set_email($tmp_email)
{
//data type checking and validation happens here
settype($tmp_email, "string");
if(!isset($tmp_email) || $tmp_email=='')
{
throw new Exception('Email cannot be empty');
}
$tmp_email = strip_tags($tmp_email);
//check if first name contains only letters
if(!$this->is_valid_email($tmp_email))
{
throw new Exception('Invalid email address');
}
$this->email = $tmp_email;
}
public function get_first_name()
{
return $this->first_name;
}
public function get_last_name()
{
return $this->last_name;
}
public function get_country()
{
return $this->country;
}
public function get_city()
{
return $this->city;
}
public function get_address()
{
return $this->address;
}
public function get_email()
{
return $this->email;
}
//can later be moved to another helper classs
public function is_only_letters_and_spaces($string)
{
return preg_match('~^[a-zA-Z ]*$~', $string);
}
//can later be moved to another helper classs
public function is_valid_email($email)
{
if(!filter_var($email, FILTER_VALIDATE_EMAIL))
{
return false;
}
else
{
return true;
}
}
}
?>
</code></pre>
<p><strong>avaaz_mysql_db.php ( database layer )</strong></p>
<pre><code><?php
include_once('person.php');
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
class avaaz_mysql_db
{
//used to validate sory by variable
private $fields = array('first_name','last_name','country','city','address','email');
private $connection_string;
private $user_name;
private $password;
public function avaaz_mysql_db($tmp_connection_string,$tmp_user_name,$tmp_password)
{
$this->connection_string = $tmp_connection_string;
$this->user_name = $tmp_user_name;
$this->password = $tmp_password;
}
public function add_person($person)
{
$first_name = '';
$last_name = '';
$country = '';
$city = '';
$address = '';
$email = '';
try
{
//check if a person with the same name already exists
if($this->does_same_name_exist($person))
{
throw new Exception('Person with the same name already exists');
}
//check if a person with the same email already exists
if($this->does_email_exist($person))
{
throw new Exception('Person with the same email already exists');
}
//prepare db and pdo statement
$db = new PDO($this->connection_string,$this->user_name,$this->password);
$stmt = $db->prepare("INSERT INTO persons (first_name, last_name, country, city, address, email ) VALUES (:first_name, :last_name, :country, :city, :address, :email )");
$stmt->bindParam(':first_name', $first_name);
$stmt->bindParam(':last_name', $last_name);
$stmt->bindParam(':country', $country);
$stmt->bindParam(':city', $city);
$stmt->bindParam(':address', $address);
$stmt->bindParam(':email', $email);
// insert one row
$first_name = $person->get_first_name();
$last_name = $person->get_last_name();
$country = $person->get_country();
$city = $person->get_city();
$address = $person->get_address();
$email = $person->get_email();
$stmt->execute();
}
catch(Exception $e)
{
throw new Exception($e->getMessage());
}
}
public function edit_person($person)
{
$first_name = '';
$last_name = '';
$country = '';
$city = '';
$address = '';
$email = '';
//check if a person with the same name already exists
try
{
if($this->does_same_name_exist($person))
{
throw new Exception('Person with the same name already exists');
}
//check if a person with the same email already exists
if($this->does_email_exist($person))
{
throw new Exception('Person with the same email already exists');
}
//db and pdo statements
$db = new PDO($this->connection_string,$this->user_name,$this->password);
$stmt = $db->prepare("update persons set first_name=:first_name, last_name=:last_name, country=:country, city=:city, address=:address, email=:email where id = :person_id");
$stmt->bindParam(':first_name', $first_name);
$stmt->bindParam(':last_name', $last_name);
$stmt->bindParam(':country', $country);
$stmt->bindParam(':city', $city);
$stmt->bindParam(':address', $address);
$stmt->bindParam(':email', $email);
$stmt->bindParam(':person_id', $person_id);
// insert one row
$person_id = $person->get_id();
$first_name = $person->get_first_name();
$last_name = $person->get_last_name();
$country = $person->get_country();
$city = $person->get_city();
$address = $person->get_address();
$email = $person->get_email();
$stmt->execute();
}
catch(Exception $e)
{
throw new Exception($e->getMessage());
}
}
public function delete_person($person)
{
try
{
//check if a person with the same first name and last name already exists
$db = new PDO($this->connection_string,$this->user_name,$this->password);
$id = $person->get_id();
$statement = $db->prepare("delete from persons where id = :id");
$statement->bindParam('id', $id);
$statement->execute();
}
catch(Exception $e)
{
throw new Exception($e->getMessage());
}
}
public function get_persons($limit = 10, $offset = 0, $sort='first_name', $sort_type = 'asc')
{
//validate offet, limit, sort, sorttype , try catch should come here
try
{
if($limit>100)
{
throw new Exception('Cannot return more than 100 records at a time');
}
if(!in_array($sort, $this->fields))
{
throw new Exception('Sort field is not in the database');
}
if($sort_type!='asc' && $sort_type!='desc')
{
throw new Exception('Incorrect sort type');
}
//prepare db and prepare statment to get people from the db
$db = new PDO($this->connection_string,$this->user_name,$this->password);
$statement = $db->prepare("select * from persons order by $sort $sort_type limit $offset,$limit ");
$statement->execute();
$rows = $statement->fetchAll();
return $rows;
}
catch(Exception $e)
{
throw new Exception($e->getMessage());
}
}
public function does_same_name_exist($person)
{
try
{
//check if a person with the same first name and last name already exists
$db = new PDO($this->connection_string,$this->user_name,$this->password);
$first_name = $person->get_first_name();
$last_name = $person->get_last_name();
if($person->get_id()==0 || $person->get_id()=='') //check if any person exists with the same name
{
$statement = $db->prepare("select id from persons where first_name = :first_name and last_name = :last_name");
}
else //check if any person besides the one who's is specified exists with the same name
{
$statement = $db->prepare("select id from persons where first_name = :first_name and last_name = :last_name and id!=:id");
$id = $person->get_id();
$statement->bindParam('id', $id);
}
$statement->bindParam('first_name', $first_name);
$statement->bindParam('last_name', $last_name);
$statement->execute();
$rows = $statement->fetchAll();
if(sizeof($rows)>=1)
{
return true;
}
else
{
return false;
}
}
catch (Exception $e)
{
throw new Exception($e->getMessage());echo $e->getMessage();
}
}
public function does_email_exist($person )
{
//check if a person with the same first name and last name already exists
try
{
$db = new PDO($this->connection_string,$this->user_name,$this->password);
if($person->get_id()==0 || $person->get_id()=='') //check if any person exists with the same name
{
$statement = $db->prepare("select id from persons where email = :person_email");
}
else //check if any person besides the one who's is specified exists with the same name
{
$statement = $db->prepare("select id from persons where email = :person_email and id!=:id");
$id = $person->get_id();
$statement->bindParam('id', $id);
}
$email = $person->get_email();
$statement->bindParam('person_email',$email);
$statement->execute();
$rows = $statement->fetchAll();
if(sizeof($rows)>=1)
{
return true;
}
else
{
return false;
}
}
catch(Exception $e)
{
throw new Exception($e->getMessage());
}
}
public function get_person($id)
{
//variable validation happens here
settype($id,'integer');
try
{
$db = new PDO($this->connection_string,$this->user_name,$this->password);
$statement = $db->prepare("select * from persons where id= :id");
$statement->bindParam('id', $id);
$statement->execute();
$row = $statement->fetchAll();
if(sizeof($row)>=1)
{
return $row;
}
else
{
throw new Exception('Person with the id not found');
}
}
catch(Exception $e)
{
throw new Exception("get_person: ".$e->getMessage());
}
}
}
</code></pre>
<p>?></p>
|
[] |
[
{
"body": "<p>It's been a while since I've done any major php code; so I may be a bit rusty.</p>\n\n<h2>GetPerson.php</h2>\n\n<ul>\n<li><p><strong><code>$id</code> validations</strong><br>\nThis isn't bad really; mostly because the final state is integer. If the final state was a String, then you would have to add more <code>strip_tags</code> calls after <code>base64_decode</code> and <code>str_repalce</code>.</p></li>\n<li><p><strong>What is the purpose of the salt?</strong> </p>\n\n<pre><code>$id = str_replace($config['salt_string'], '', $id);\n</code></pre>\n\n<p>You do not really check for its existence, or if it's valid. You simply remove it without looking back. A malicious user can more or less ignore it as well. </p></li>\n<li><p><strong>Is there a reason why the salt needs to be part of <code>$_POST['id']</code>?</strong><br>\nIt would make validations simpler to have it as a standalone field. Then you could simply do,</p>\n\n<pre><code>$id = $_POST['id'];\nsettype($id, 'integer');\n</code></pre></li>\n<li><p><strong>In general can you elaborate more on the use of a salt here?</strong><br>\nDepending on your intended use, you may be able to improve your implementation. At a high-level, a salt is typically used when hashing a password. As much as possible it needs to be unique. Your implementation however does not appear to be using a unique salt.</p></li>\n<li><p><strong>Top-level catch block</strong> </p>\n\n<pre><code>catch (Exception $e) \n{ \n echo \"Getting person details: \".$e->getMessage(); \n} \n</code></pre>\n\n<ol>\n<li><p><strong>Exception details sent to user</strong><br>\nWhile it is convenient for troubleshooting, the exact error message can give too much information. This is especially true for DB errors.<br>\nYou code also uses exceptions to relay errors back to the user.</p>\n\n<p>To avoid disclosing too much data I suggest using a white-list approach.<br>\nCreate a new type of exception called <code>BusinessRulesException</code> that you explicitly catch and pass the error message back to the user.<br>\nFor the catch-all <code>Exception</code> block you can log the exception internally (log file perhaps), tell the user \"an unexpected error occurred\", and give some kind of unique reference so they can refer to the exact problem that you recorded internally for analysis.</p></li>\n<li><p><strong>Unescaped output</strong><br>\nYou should call <code>htmlentities()</code> on <code>$e->getMessage()</code>. When it comes to XSS you should code defensively; validating inbound and outbound data. Even for exceptions. </p>\n\n<p>If you take my above suggestion to use a <code>BusinessRuleExcpeption</code>, make sure you call <code>htmlentities()</code> there are well.</p></li>\n</ol></li>\n</ul>\n\n<h2>Person.php</h2>\n\n<ul>\n<li><p><strong>Many of your set methods check for 0-length string before calling strip_tags.</strong><br>\nTheoretically it may be possible for a malicious user to submit some HTML tags, have them stripped out, and end up with a 0-length value which you try to disallow. </p>\n\n<p>I would rewrite this as,</p>\n\n<pre><code>public function set_first_name($tmp_first_name) \n{ \n settype($tmp_first_name, \"string\"); \n $tmp_first_name = strip_tags($tmp_first_name); \n if((!isset($tmp_first_name)) || $tmp_first_name=='') \n { \n throw new Exception('First name cannot be empty'); \n } \n\n if(!$this->is_only_letters_and_spaces($tmp_first_name)) \n { \n throw new Exception('Only letters and spaces allowed in first name'); \n } \n $this->first_name = $tmp_first_name; \n}\n</code></pre>\n\n<p>Note that I moved <code>strip_tags</code> to before the first <code>if</code> statement.<br>\nThis same problem exists for the following methods as well.</p>\n\n<ul>\n<li><code>set_last_name($tmp_last_name)</code></li>\n<li><code>set_country($tmp_country)</code></li>\n<li><code>set_city($tmp_city)</code></li>\n<li><p><code>set_address($tmp_address)</code></p></li>\n<li><p><code>set_email($tmp_email)</code> has the same problem, although <code>is_valid_email</code> will return false on a 0-length value. I would still move the <code>strip_tags</code> call as detailed above though. </p></li>\n</ul></li>\n<li><p><strong>The method <code>is_only_letters_and_spaces</code> will evaluate true for 0-length strings.</strong> </p>\n\n<p>If this is expected I would rename the method to <code>is_only_letters_and_spaces_allow_empty_string()</code> </p>\n\n<p>If this is not expected I would rewrite as,</p>\n\n<pre><code>public function is_only_letters_and_spaces($string)\n {\n return preg_match('^[a-zA-Z ]+$', $string);\n }\n</code></pre>\n\n<p>Note the change to the regex, replaced <code>*</code> (zero or more) with <code>+</code> (one or more). </p>\n\n<p>I also removed the <code>~</code> (tilde) delimiters. As you are not specifying any options, I find this easier to read. That's more of a preference though.</p></li>\n</ul>\n\n<h2>avaaz_mysql_db.php</h2>\n\n<ul>\n<li><p><strong>Improper validation of <code>$limit</code> and <code>$offset</code></strong><br>\nYou do not properly validate <code>$limit</code> and <code>$offset</code> before their direct inclusion in the SQL.<br>\nI would suggest rewriting this method as, </p>\n\n<pre><code>public function get_persons($limit = 10, $offset = 0, $sort='first_name', $sort_type = 'asc')\n{\n try\n {\n settype($limit, 'integer'); // explicit cast removes non-int values\n settype($offset, 'integer'); // explicit cast removes non-int values\n settype($sort, 'string');\n settype($sort_type, 'string');\n\n if($limit <= 0 || $limit>100) \n {\n $limit = 10;\n }\n if($offset < 0) {\n $offset = 0;\n }\n if(!in_array($sort, $this->fields))\n {\n $sort = 'first_name';\n }\n if($sort_type!='asc' && $sort_type!='desc')\n {\n $sort_type = 'asc';\n }\n\n $db = new PDO($this->connection_string,$this->user_name,$this->password);\n $statement = $db->prepare(\"select * from persons order by $sort $sort_type limit $offset,$limit \");\n $statement->execute();\n $rows = $statement->fetchAll();\n return $rows;\n }\n catch(Exception $e)\n {\n throw new Exception($e->getMessage());\n }\n}\n</code></pre>\n\n<p>Note that I explicitly cast <code>$limit</code> and <code>$offset</code> as integers and added some range validations as well.</p>\n\n<p>I also changed the validations to reset the value to its default, instead of throwing an exception.<br>\nIn your original code you employ a fail-fast methodology when handling incorrect parameters.<br>\nIn this scenario I find it easier/better to just reset the value, but this may not work for your specification or expected implementation.</p></li>\n<li><p><strong><code>bindParam()</code> missing leading : (colon) on parameter</strong></p>\n\n<pre><code>$statement->bindParam('id', $id);\n</code></pre>\n\n<p>should be rewritten as, </p>\n\n<pre><code>$statement->bindParam(':id', $id);\n</code></pre>\n\n<p>Note the leading : (colon) in <code>':id'</code>. </p>\n\n<p>While the original code does execute without issue, the documentation does not explicitly indicate that this is allowed. It would be better to always use a leading : (colon). </p>\n\n<p>Some of your methods follow this, while others do not. Affected functions are, </p>\n\n<ul>\n<li><code>public function delete_person($person)</code></li>\n<li><code>public function does_same_name_exist($person)</code></li>\n<li><code>public function does_email_exist($person )</code></li>\n<li><code>public function get_person($id)</code></li>\n</ul></li>\n<li><p><strong>Potential for Exception details sent to user</strong><br>\nIt looks like you left an extra echo in the catch block of <code>does_same_name_exist($person)</code>. </p>\n\n<pre><code>catch (Exception $e)\n{\n throw new Exception($e->getMessage());echo $e->getMessage();\n}\n</code></pre>\n\n<p>You would never reach it currently because of a throw immediately prior, but I would still remove the echo none-the-less. </p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-09T20:30:30.427",
"Id": "15453",
"ParentId": "15438",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-08T18:42:19.740",
"Id": "15438",
"Score": "2",
"Tags": [
"php",
"security"
],
"Title": "Is this simple add/mod/del/jquery code secure enough?"
}
|
15438
|
<p>I'm not sure if this is the right way to do this, but I want to simply this script and hopefully use CSS3 animations. The code is really large, and parts are very irrelevant, so I'm wondering if I should first get rid of all the irrelevant parts, then go from there?</p>
<p>Here's the code:</p>
<pre><code>var _target = null,
_dragx = null,
_dragy = null,
_rotate = null,
_resort = null;
var _dragging = false,
_sizing = false,
_animate = false;
var _rotating = 0,
_width = 0,
_height = 0,
_left = 0,
_top = 0,
_xspeed = 0,
_yspeed = 0;
var _zindex = 1000;
jQuery.fn.touch = function (settings) {
// DEFINE DEFAULT TOUCH SETTINGS
settings = jQuery.extend({
animate: false,
sticky: false,
dragx: true,
dragy: true,
rotate: false,
resort: false,
scale: false
}, settings);
// BUILD SETTINGS OBJECT
var opts = [];
opts = $.extend({}, $.fn.touch.defaults, settings);
// ADD METHODS TO OBJECT
this.each(function () {
this.opts = opts;
this.ontouchstart = touchstart;
this.ontouchend = touchend;
this.ontouchmove = touchmove;
this.ongesturestart = gesturestart;
this.ongesturechange = gesturechange;
this.ongestureend = gestureend;
});
};
function touchstart(e) {
_target = this.id;
_dragx = this.opts.dragx;
_dragy = this.opts.dragy;
_resort = this.opts.resort;
_animate = this.opts.animate;
_xspeed = 0;
_yspeed = 0;
$(e.changedTouches).each(function () {
var curLeft = ($('#' + _target).css("left") == 'auto') ? this.pageX : parseInt($('#' + _target).css("left"));
var curTop = ($('#' + _target).css("top") == 'auto') ? this.pageY : parseInt($('#' + _target).css("top"));
if (!_dragging && !_sizing) {
_left = (e.pageX - curLeft);
_top = (e.pageY - curTop);
_dragging = [_left, _top];
if (_resort) {
_zindex = ($('#' + _target).css("z-index") == _zindex) ? _zindex : _zindex + 1;
$('#' + _target).css({
zIndex: _zindex
});
}
}
});
};
function touchmove(e) {
if (_dragging && !_sizing && _animate) {
var _lastleft = (isNaN(parseInt($('#' + _target).css("left")))) ? 0 : parseInt($('#' + _target).css("left"));
var _lasttop = (isNaN(parseInt($('#' + _target).css("top")))) ? 0 : parseInt($('#' + _target).css("top"));
}
$(e.changedTouches).each(function () {
e.preventDefault();
_left = (this.pageX - (parseInt($('#' + _target).css("width")) / 2));
_top = (this.pageY - (parseInt($('#' + _target).css("height")) / 2));
if (_dragging && !_sizing) {
if (_animate) {
_xspeed = Math.round((_xspeed + Math.round(_left - _lastleft)) / 1.5);
_yspeed = Math.round((_yspeed + Math.round(_top - _lasttop)) / 1.5);
}
if (_dragx || _dragy) $('#' + _target).css({
position: "absolute"
});
if (_dragx) $('#' + _target).css({
left: _left + "px"
});
if (_dragy) $('#' + _target).css({
top: _top + "px"
});
$('#' + _target).css({
backgroundColor: "#4B880B"
});
$('#' + _target + ' b').text('WEEEEEEEE!!!!');
}
});
};
function touchend(e) {
$(e.changedTouches).each(function () {
if (!e.targetTouches.length) {
_dragging = false;
if (_animate) {
_left = ($('#' + _target).css("left") == 'auto') ? this.pageX : parseInt($('#' + _target).css("left"));
_top = ($('#' + _target).css("top") == 'auto') ? this.pageY : parseInt($('#' + _target).css("top"));
var animx = (_dragx) ? (_left + _xspeed) + "px" : _left + "px";
var animy = (_dragy) ? (_top + _yspeed) + "px" : _top + "px";
if (_dragx || _dragy) $('#' + _target).animate({
left: animx,
top: animy
}, "fast");
}
}
});
$('#' + _target + ' b').text('I am sad :(');
$('#' + _target).css({
backgroundColor: "#0B4188"
});
setTimeout(changeBack, 5000, _target);
};
function gesturestart(e) {
_sizing = [$('#' + this.id).css("width"), $('#' + this.id).css("height")];
};
function gesturechange(e) {
if (_sizing) {
_width = (this.opts.scale) ? Math.min(parseInt(_sizing[0]) * e.scale, 300) : _sizing[0];
_height = (this.opts.scale) ? Math.min(parseInt(_sizing[1]) * e.scale, 300) : _sizing[1];
_rotate = (this.opts.rotate) ? "rotate(" + ((_rotating + e.rotation) % 360) + "deg)" : "0deg";
$('#' + this.id).css({
width: _width + "px",
height: _height + "px",
webkitTransform: _rotate
});
$('#' + this.id + ' b').text('TRANSFORM!');
$('#' + this.id).css({
backgroundColor: "#4B880B"
});
}
};
function gestureend(e) {
_sizing = false;
_rotating = (_rotating + e.rotation) % 360;
};
function changeBack(target) {
$('#' + target + ' b').text('Touch Me :)');
$('#' + target).css({
backgroundColor: "#999"
});
}
</code></pre>
|
[] |
[
{
"body": "<blockquote>\n <p>I'm wondering if I should first get rid of all the irrelevant parts</p>\n</blockquote>\n\n<p>Yes. Especially since source control will keep any code you may want in the future. If it is not being used it is just taking up resources to maintain it. <em>(e.g. everytime you read this section of code you have to remember what is and isn't relevant.)</em></p>\n\n<p>If these are Constants I would suggest capitalising them. then your code will read a little easier. If they are default settings put them in an object. <em>(If they are global variables...)</em></p>\n\n<pre><code>var _target = null,\n _dragx = null,\n _dragy = null,\n _rotate = null,\n _resort = null;\nvar _dragging = false,\n _sizing = false,\n _animate = false;\nvar _rotating = 0,\n _width = 0,\n _height = 0,\n _left = 0,\n _top = 0,\n _xspeed = 0,\n _yspeed = 0;\nvar _zindex = 1000;\n</code></pre>\n\n<p>your style uses <code>_variablename</code> but javascript normally has the <code>camelCase</code> style for variables, <code>CamelCase</code> for classes and previously mentioned <code>ALLCAPS</code> for constants. Consistency is good but unless there is a reason not to i would suggest sticking with standards. <em>(esp if others maintain it after you)</em></p>\n\n<pre><code>_left = (e.pageX - curLeft);\n_top = (e.pageY - curTop);\n_dragging = [_left, _top];\n</code></pre>\n\n<p>statements like:</p>\n\n<pre><code> $('#' + _target).css({\n backgroundColor: \"#4B880B\"\n });\n $('#' + _target + ' b').text('WEEEEEEEE!!!!');\n</code></pre>\n\n<p>can be chained like:</p>\n\n<pre><code> $('#' + _target)\n .css({\n backgroundColor: \"#4B880B\"\n })\n .find('b')\n .text('WEEEEEEEE!!!!');\n</code></pre>\n\n<p>When you use the same selector more than once its best to put it in a variable so you don't make jQuery work harder.</p>\n\n<pre><code>if (_dragx || _dragy) $('#' + _target).css({\n position: \"absolute\"\n});\nif (_dragx) $('#' + _target).css({\n left: _left + \"px\"\n});\nif (_dragy) $('#' + _target).css({\n top: _top + \"px\"\n});\n</code></pre>\n\n<p>can become:</p>\n\n<pre><code>var $target = $('#' + _target);\n\nif (_dragx || _dragy) $target.css({\n position: \"absolute\"\n});\nif (_dragx) $target.css({\n left: _left + \"px\"\n});\nif (_dragy) $target.css({\n top: _top + \"px\"\n});\n</code></pre>\n\n<p>the if form you use here is unusual.</p>\n\n<pre><code>if (_dragy) $target.css({\n top: _top + \"px\"\n});\n</code></pre>\n\n<p>Might just be a matter of taste but I find it puts greater cognitive load (make me think too hard) when there are two statements per line:</p>\n\n<pre><code> if(_dragy)\n {\n $target.css({\n top: _top + \"px\"\n });\n }\n</code></pre>\n\n<p>Achieves the same and is much easier to read through.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-10T00:39:04.173",
"Id": "15455",
"ParentId": "15441",
"Score": "8"
}
},
{
"body": "<p>Building upon James' Answer, you should also collapse the multiple <code>css</code> calls into one call:</p>\n\n<pre><code>// touchmove\ncssObject = { backgroundColor: \"#4b880b\" };\nif (_dragx || _dragy) cssObject.position = \"absolute\";\nif (_dragx) cssObject.left = _left + \"px\";\nif (_dragy) cssObject.top = _top + \"px\";\n$target.css(cssObject)\n\n// gesturechange\n$target.css({\n width: _width + \"px\",\n height: _height + \"px\",\n webkitTransform: _rotate,\n backgroundColor: \"#4B880B\"\n});\n</code></pre>\n\n<p>Speaking of, <code>$target</code> is defined as <code>$('#'+this.id)</code>, which only works for elements with an ID. A broader solution would be to set target using '$(this)':</p>\n\n<pre><code>$target = $(this);\n</code></pre>\n\n<p>You use have several obtuse checks around <code>left</code> and <code>top</code>. These can be slimmed down significantly. </p>\n\n<pre><code>// Before\nvar curLeft = ($('#' + _target).css(\"left\") == 'auto') ? this.pageX : parseInt($('#' + _target).css(\"left\"));\nvar _lastleft = (isNaN(parseInt($('#' + _target).css(\"left\")))) ? 0 : parseInt($('#' + _target).css(\"left\"));\n_left = ($('#' + _target).css(\"left\") == 'auto') ? this.pageX : parseInt($('#' + _target).css(\"left\"));\n\n// After\nvar curLeft = parseInt($target.css(\"left\")) || this.pageX\nvar _lastLeft = parseInt($target.css(\"left\")) || 0\n_left = parseInt($target.css(\"left\")) || this.pageX\n</code></pre>\n\n<p>Finally, you have several <a href=\"http://en.wikipedia.org/wiki/Magic_number_%28programming%29#Unnamed_numerical_constants\">magic numbers</a>. To make code maitenance easier, define variables for constants like colors, strings, and timeouts.</p>\n\n<pre><code>var END_COLOR = \"#0B4188\",\n READY_COLOR = \"#999\",\n MOVING_COLOR = \"#4B880B\";\nvar END_TIMEOUT = 5000;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-10T03:40:56.987",
"Id": "15466",
"ParentId": "15441",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "15455",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-08T23:55:28.990",
"Id": "15441",
"Score": "4",
"Tags": [
"javascript",
"jquery",
"event-handling"
],
"Title": "Handling a dragging gesture using jQuery"
}
|
15441
|
<p>I want to randomly permute a finite list in the most effective and efficient way in C#. My attempt is as follows.</p>
<pre><code>/*===================================*
* Compile it to produce Shuffle.exe *
* ==================================*/
using System;
using System.Collections.Generic;
using System.IO;
namespace Shuffle
{
class Program
{
static void Main(string[] args)
{
int Columns = int.Parse(args[0]);
int Rows = int.Parse(args[1]);
int Seed = int.Parse(args[2]);
string OutputFilename = args[3];
List<string> OrderedList = new List<string>();
for (int x = 0; x < Columns; x++)
for (int y = 0; y < Rows; y++)
OrderedList.Add(string.Format("{{{0},{1}}}", x, y));
Random rnd = new Random(Seed);
List<string> ShuffledList = new List<string>();
for (int i = 0; i < Columns * Rows; i++)
{
int x = rnd.Next(OrderedList.Count);
ShuffledList.Add(OrderedList[x]);
OrderedList.RemoveAt(x);
}
using (StreamWriter sw = new StreamWriter(OutputFilename))
{
foreach (string s in ShuffledList)
sw.WriteLine(s);
}
}
}
}
</code></pre>
<p>This program will be used in <a href="https://tex.stackexchange.com/a/70511/9467">my production</a>. Could you review whether or not my code is already the most efficient and effective in C#?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-14T14:28:40.610",
"Id": "34870",
"Score": "0",
"body": "For what it's worth, there's [a library](http://www.codeproject.com/Articles/26050/Permutations-Combinations-and-Variations-using-C-G) which can do this for you."
}
] |
[
{
"body": "<p>Here's what I came up with, it needs to be cleaned up and documented some more, but here's the gist. </p>\n\n<p>Since the random accesses into Lists<> turn out to be slow (especially removing items), we can get rid of that.</p>\n\n<p>So, make an array of numbers. </p>\n\n<p>Assign those numbers randomly to the elements in the List if they haven't been used before. </p>\n\n<p>Now you have a Dictionary where the string is the original elements, and the \nint is the random position.</p>\n\n<p>Now sort the Dictionary by value (the random location).</p>\n\n<p>Now return it as a List again.</p>\n\n<pre><code> private static void randomizeList3(List<string> OrderedList, \n List<string> ShuffledList, Random rnd)\n {\n int count = OrderedList.Count;\n int twoCount = 2 * count;\n\n bool[] usedNums = new bool[twoCount];\n\n Dictionary<String, int> dicto = new Dictionary<string, int>(count);\n\n int nextPos;\n\n foreach (string s in OrderedList)\n {\n nextPos = rnd.Next(twoCount);\n while (usedNums[nextPos] == true)\n {\n nextPos = rnd.Next(twoCount);\n }\n usedNums[nextPos] = true;\n\n dicto.Add(s, nextPos);\n }\n\n List<KeyValuePair<string, int>> myList = dicto.ToList();\n\n myList.Sort(\n delegate(KeyValuePair<string, int> firstPair,\n KeyValuePair<string, int> nextPair)\n {\n return firstPair.Value.CompareTo(nextPair.Value);\n }\n );\n\n foreach (KeyValuePair<string, int> p in myList)\n {\n ShuffledList.Add(p.Key);\n }\n\n }\n</code></pre>\n\n<p>I use a usedNums array which is twice as big, so that the chance of randomly choosing an already used element is only 50%.</p>\n\n<p>Anyway, after timing on an instance of 200 cols, 200 rows:</p>\n\n<pre><code>Original Approach takes 12,805 milliseconds\n randomizeList3 takes 214 milliseconds\n</code></pre>\n\n<p>on a grid 2000 by 2000, </p>\n\n<pre><code> randomizeList3 takes 4,425 milliseconds.\n</code></pre>\n\n<p>I'm sure this could be improved.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-10T04:21:16.630",
"Id": "25068",
"Score": "0",
"body": "I agree with the accepted answer, but downvoters should leave a reason. OP's solution is quadratic O( n^2 ) at best, since List<>.remove() requires copying elements in the array. My solution is O( n log(n) ), a good improvement over OPs and was the first solution offered. Accepted solution is O( n ), which is an improvement over mine."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-10T16:14:49.380",
"Id": "25106",
"Score": "0",
"body": "If the down-voter wanted to leave a reason he would have done so already; complaining about it is silly given the context. This has been argued many/many times on meta and it always comes back to it should always be optional. http://meta.stackexchange.com/q/119570/138817"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-10T16:17:07.520",
"Id": "25107",
"Score": "0",
"body": "PS. I also tempted to down vote you as you are not answering the question based on the sites parameters. You are supposed to review and comment the code provided not provide a solution (this is not SO). Your answer provides very little useful feedback to the OP in this context."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-10T22:25:51.150",
"Id": "25126",
"Score": "0",
"body": "Thanks for the feedback. I am used to SO, and just starting with CR."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-09T18:34:36.903",
"Id": "15451",
"ParentId": "15449",
"Score": "-1"
}
},
{
"body": "<p>Don't waste time on <a href=\"http://www.codinghorror.com/blog/2009/01/the-sad-tragedy-of-micro-optimization-theater.html\" rel=\"noreferrer\">micro-optimizations</a>. Use the simplest possible techniques that are known to perform well. In your specific case, it means replacing your multiple lists with one single array and using the standard fisher-yates-shuffle.</p>\n<h2>Naming conventions</h2>\n<p>In good C# code, local variables are <code>camelCase</code> beginning with a lower case letter. I renamed most of your variables to better express intent.</p>\n<hr />\n<h2>Generating the strings</h2>\n<p>You'll get a performance increase of about 30%-40% by using an array instead of a list (not much to be gained here).</p>\n<p>Don't bother with string concatenation instead of <code>string.Format</code>, there is hardly any measurable difference in speed, but a <em>huge</em> difference in readability and maintainability.</p>\n<pre><code>string[] elements = new string[columns * rows];\nfor (int column = 0; column < columns; column++)\n for (int row = 0; row < rows; row++)\n elements[columns * row + row] = string.Format("{{{0},{1}}}", column, row); \n</code></pre>\n<hr />\n<h2>Shuffling them</h2>\n<p>Whenever you remove from a list, all the remaining elements have to be shifted to fill the gap. Use your array instead and use the <a href=\"https://stackoverflow.com/a/1287572/1106367\">fisher-yates-shuffle</a>; <strong>don't</strong> attempt inventing your own.</p>\n<pre><code>for (int i = elements.Length - 1; i > 0; i--)\n{\n int swapIndex = random.Next(i + 1);\n string tmp = elements[i];\n elements[i] = elements[swapIndex];\n elements[swapIndex] = tmp;\n}\n</code></pre>\n<p>This runs about 160 times as fast as your shuffling implementation.</p>\n<hr />\n<h2>Don't reinvent the wheel</h2>\n<p>When saving the results to disk, use <code>File.WriteAllLines</code> which does exactly what you were doing with the <code>StreamWriter</code> - in a single line.</p>\n<pre><code>File.WriteAllLines(outputFilename, elements);\n</code></pre>\n<hr />\n<h2>Complete code <sup><em>(argument parsing omitted)</em></sup></h2>\n<p>Once you've realized that a few milliseconds more or less don't matter, it would be good to split this up into several methods that each do exactly one thing. I'll leave that as an exercise to you.</p>\n<pre><code>string[] elements = new string[columns * rows];\nfor (int column = 0; column < columns; column++)\n for (int row = 0; row < rows; row++)\n elements[column*rows + row] = string.Format("{{{0},{1}}}", column, row);\n\nRandom random = new Random(seed);\nfor (int i = elements.Length - 1; i > 0; i--)\n{\n int swapIndex = random.Next(i + 1);\n string tmp = elements[i];\n elements[i] = elements[swapIndex];\n elements[swapIndex] = tmp;\n}\n\nFile.WriteAllLines(outputFilename, elements);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-10T02:57:12.613",
"Id": "25066",
"Score": "0",
"body": "Your code has been applied to my production whose link was given in my question. Thank you."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-10T03:34:59.837",
"Id": "25067",
"Score": "0",
"body": "Is it better to declare the `swapIndex` before the loop `for`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-10T07:43:03.410",
"Id": "25080",
"Score": "1",
"body": "@GarbageCollector no, things like that are optimized by the compiler. Declare variables as close to their usage as possible (in the innermost scope) to increase readability and prevent side-effects."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-13T12:19:29.500",
"Id": "34798",
"Score": "0",
"body": "I must say I was impressed by the quality of your given answer. I was about to provide an answer until I saw yours and nothing more valuable could be added. Only thing I would do is extract the code for the shuffling and put it into an extension-method."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-13T13:10:31.900",
"Id": "34802",
"Score": "0",
"body": "@Abbas Thanks, that's a very good suggestion. I'd make it an extension method on `IList<T>` (and I'd extract another one for the swap)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-13T14:49:25.567",
"Id": "34806",
"Score": "0",
"body": "I provided an answer with my findings about this little conversation. Feel free to write what you think of it. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-02T07:29:54.777",
"Id": "38020",
"Score": "0",
"body": "`int swapIndex = random.Next(i + 1);` should be `int swapIndex = random.Next(i);` and `for (int i = elements.Length - 1; i >= 0; i--)` should be `for (int i = elements.Length - 1; i > 0; i--)`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-02T09:12:50.407",
"Id": "38025",
"Score": "0",
"body": "@Karl'sstudents you're right about the `>=`. Why would you only do `random.Next(i)` though? Then, `i` would never be selected as a swap index, and an element would never remain in the same position, which would be [an implementation error](http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#Implementation_errors)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-02T09:23:44.307",
"Id": "38028",
"Score": "0",
"body": "@codesparkle: Ah... I thought swapping the same element is trivial."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-09T20:11:32.517",
"Id": "15452",
"ParentId": "15449",
"Score": "14"
}
},
{
"body": "<p>This is an answer in addition to the answer of \"codesparkle\". His answer brings the best answer to this question but in the comments we talked further. The code below is my result of this:</p>\n\n<pre><code>//This is an extension method using the Fisher-Yates-shuffle\npublic static void Shuffle<T>(this IList<T> list)\n{\n Random random = new Random(DateTime.Now.Millisecond);\n\n for (int i = list.Count - 1; i >= 0; i--)\n {\n int r = random.Next(i + 1);\n T value = list[r];\n list[r] = list[i];\n list[i] = value;\n }\n}\n</code></pre>\n\n<p>The code of swapping could also be done within a while-loop, but after a little research I found that a for-loop is more performant when putting the 'list.Count' inside the statement. This makes sure the max value is already known and the bounds-check doesn't have to be done during the iteration. (<a href=\"https://stackoverflow.com/questions/552766/for-and-while-loop-in-c-sharp\"><strong>Source</strong></a>)</p>\n\n<p>Following code achieves the same as above, only here the swap is also extracted to an extension method. This extension method makes it easy to swap two elements from any IList.</p>\n\n<pre><code>public static void Shuffle<T>(this IList<T> list)\n{\n Random random = new Random(DateTime.Now.Millisecond);\n\n for (int i = list.Count - 1; i >= 0; i--)\n {\n int r = random.Next(i + 1);\n list.Swap(r, i);\n }\n}\n\npublic static void Swap<T>(this IList<T> list, int index1, int index2)\n{\n T value = list[index1];\n list[index1] = list[index2];\n list[index2] = value;\n}\n</code></pre>\n\n<p>Altough I'm not completely sure if calling Swap() in a loop is as performant as the first way of randomizing, as you're passing the complete list to the Swap-method every time. Either way, it is a nice extension method to swap elements in a list.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-13T17:27:54.023",
"Id": "34815",
"Score": "1",
"body": "No need to worry about \"passing the complete list\" as this is not the case — only a *reference* is copied. Your source of randomness is *fundamentally flawed*, however: [`DateTime.Now.Millisecond`](http://goo.gl/mMPTW) is always a value between 0 and 999, a horribly small range for a seed. Use the default constructor (implemented with `DateTime.Now.Ticks`) or, better yet, follow [Jon Skeet's advice](http://goo.gl/n8jvg) and pass in an instance of `Random` as a parameter to your extension method."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-13T17:29:43.757",
"Id": "34816",
"Score": "1",
"body": "Additionally, if `Shuffle` is called often in rapid succession, it may yield the same resulting lists as the instances of `Random` will have the same seed."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-14T08:29:38.820",
"Id": "34849",
"Score": "0",
"body": "Thanks for your comment, I didn't know that yet! ;)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-13T14:47:54.180",
"Id": "21664",
"ParentId": "15449",
"Score": "0"
}
},
{
"body": "<p>If performance is not really critical I would probably prefer the following solution to randomize elements in any enumerable:</p>\n\n<pre><code>public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> list)\n{\n Random random = new Random();\n return list.OrderBy(arg => random.Next(int.MaxValue));\n}\n</code></pre>\n\n<p>In a quick test this method was about 3 times slower than shuffling in-place using random element swapping (@Abbas solution).</p>\n\n<p>Note that strictly speaking it is not equivalent to other solutions since it creates a new enumerable rather than shuffling elements within existing list.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-14T13:30:42.660",
"Id": "22708",
"ParentId": "15449",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "15452",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-09T16:17:58.293",
"Id": "15449",
"Score": "7",
"Tags": [
"c#",
"algorithm",
"random"
],
"Title": "Randomly Permute Elements in a List"
}
|
15449
|
<p>In an attempt to begin learning Scala, I've taken a stab at creating a simple wrapper around Java's File & FileInputStream in order to read lines from a file. This functionality already exists in the Source class and is just a learning exercise. </p>
<p>If you were building this wrapper in Scala, is there anything you might change? Are there any best practices I'm overlooking?</p>
<pre><code>////////// Driver.scala ////////////////
object Driver {
def main(args: Array[String]): Unit = {
val uri = File.classpathResource("sample.txt")
val fileReader = FileReader.open(uri)
println("Reading File: " + fileReader.file.name() )
for( val line <- fileReader.lines() ) {
println(line)
}
fileReader.close()
}
}
////////// File.scala ////////////////
import java.io.{File => JavaFile}
import java.net.URI
/** This object provides convenience methods for working with local file resources */
object File {
/** Helper method to resolve a URI for a resource on the classpath
*
* @param the resource's path name
* @return the resource's URI
*/
def classpathResource(pathName: String): URI = {
val url = this.getClass().getClassLoader().getResource(pathName)
url.toURI()
}
}
/** This class represents a file on the file system */
class File(val javaFile: JavaFile) {
def this(pathName: String) = this(new JavaFile(pathName))
def this(uri: URI) = this(new JavaFile(uri))
/** Get the file's file name */
def name(): String = javaFile.getName()
/** Get the file's absolute path */
def path(): String = javaFile.getAbsolutePath()
/** Open a new file reader. Call FileReader.close() once you have finished
* using the file reader.
*
* @return a new file reader instance
* @throws FileNotFoundException if the file cannot be opened for reading
*/
def openReader(): FileReader = {
new FileReader(this)
}
}
////////// FileReader.scala ////////////////
import java.io.FileInputStream
import java.net.URI
/** This object provides convenience methods for reading files */
object FileReader {
/** Creates and opens a FileReader class instance for a given file's path name
*
* @param the file's path name
* @return an instance of the File class
* @throws FileNotFoundException if the file cannot be opened for reading
*/
def open(pathName: String): FileReader = this open new File(pathName)
/** Creates and opens a FileReader class instance for a given file's URI
*
* @param the file's URI
* @return an instance of the File class
* @throws FileNotFoundException if the file cannot be opened for reading
*/
def open(uri: URI): FileReader = this open new File(uri)
/** Creates and opens a FileReader class instance for a given File instance
*
* @param a File instance
* @return an instance of the FileReader class
* @throws FileNotFoundException if the file cannot be opened for reading
*/
def open(file: File): FileReader = new FileReader(file)
}
class FileReader(val file: File) {
private val inputStream = new FileInputStream(file.javaFile)
private val lineIterator = new BufferedLineIterator(inputStream);
/** Read the file's lines using a string iterator
*
* @return file's line iterator (Iterator[String])
*/
def lines(): Iterator[String] = lineIterator
/** Closes the file reader */
def close(): Unit = inputStream.close()
}
////////// BufferedLineIterator.scala ////////////////
import scala.collection.Iterator
import java.io.BufferedReader
import java.io.InputStreamReader
import java.io.InputStream
class BufferedLineIterator(inputStream: InputStream) extends Iterator[String] {
/** Buffered reader for reading lines from the file */
private val bufferedReader: BufferedReader = {
val inputStreamReader = new InputStreamReader(inputStream)
new BufferedReader(inputStreamReader)
}
/** Stores the next line waiting to be returned from the next() method */
private var nextLine: String = null
/** Identifies if the file has another line to read
*
* @return boolean identifying if the file has another line to read
*/
override def hasNext(): Boolean = {
if( nextLine == null ) {
nextLine = bufferedReader.readLine
}
nextLine != null
}
/** Reads the next line from the file
*
* @return the line
*/
override def next(): String = {
try {
if(hasNext) {
nextLine
} else {
Iterator.empty.next
}
} finally {
nextLine = null
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-10T08:45:24.893",
"Id": "25085",
"Score": "0",
"body": "Looks pretty good! The only big thing I found out is in the for-comprehension: don't use `val` there. In 2.10 it's use is forbidden. ;)"
}
] |
[
{
"body": "<p>Looks ok. A <code>Traversable</code> is a more interesting way to do this, since you can then auto-close the resource. There's one thing I took an issue to:</p>\n\n<pre><code>private val inputStream = new FileInputStream(file.javaFile)\n\nprivate val lineIterator = new BufferedLineIterator(inputStream);\n\ndef lines(): Iterator[String] = lineIterator\n</code></pre>\n\n<p>The first two being <code>val</code> means this cannot be reused. However, if you turn them into <code>def</code>, then <code>lines</code> will already return a valid iterator.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-26T12:59:20.870",
"Id": "15956",
"ParentId": "15457",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-10T00:40:32.950",
"Id": "15457",
"Score": "12",
"Tags": [
"scala"
],
"Title": "Simple wrapper around Java's File & FileInputStream"
}
|
15457
|
<p>I have a simple inheritance framework:</p>
<pre><code>class BaseValidator
{
protected virtual void Validate()
{
// Base validator code .....
}
}
class PhoneValidator:BaseValidator
{
public override void Validate()
{
base.Validate();
// custom validation logic...
}
}
class EmailValidator:BaseValidator
{
public override void Validate()
{
base.Validate();
// custom validation logic...
}
}
</code></pre>
<p>The problem is in <code>//custom validation logic</code>. The more <code>custom validation logic</code> code that is written , the more unwieldy the
<code>Validate()</code> function becomes. I can organize custom validation logic into separate functions, but that would be another mess.</p>
<pre><code>public override void Validate()
{
base.Validate();
CustomValidation1();
CustomValidation2();
CustomValidation3();
...
}
</code></pre>
<p>What are other patterns\practices that I can use to manage the <code>Validate()</code> function? Sometimes I feel this is a the problem with inheritance, but suggestions are welcome in any direction.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-06T21:47:57.533",
"Id": "25058",
"Score": "0",
"body": "Will you always call base.Validate(); from the sub-classes?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-06T22:06:47.407",
"Id": "25059",
"Score": "0",
"body": "yes. I have to call the base's validate method"
}
] |
[
{
"body": "<p>Well, there are probably several good solutions, but the first one that comes to mind is to shift to an <em>interface-based</em> approach rather than an inheritance based one. You might define an IValidation interface that defines a Validation method, which each class implementor could then customize as necessary. </p>\n\n<p>You could even construct an abstract base class to implement the interface, and provide a basic Validation mechanism that could be called from child classes.</p>\n\n<p>Something like (and this is kinda rough):</p>\n\n<pre><code>interface IValidateData\n{\n void Validate();\n}\n\npublic abstract class BaseValidator:IValidateData\n{\n public void DefaultValidation()\n { \n }\n\n void Validate()\n {\n //Custom validation here\n }\n }\n\n public class ConcreteValidator:BaseValidator\n {\n override void Validate()\n {\n this.DefaultValidation();\n\n //my custom validation here\n }\n }\n</code></pre>\n\n<p>As I said, that's only a very rough sketch of how you might approach an interface-based structure with an abstract class to provide a base implementation from which other concrete classes could be derived. The details here might not be perfect, but I think the concept is at least there. </p>\n\n<p>Hope that's helpful in some way. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-06T16:09:53.340",
"Id": "25060",
"Score": "0",
"body": "Thanks Dave. I feel that interfaces deal with how we expose the validation logic to the outside world, but I am not sure how it solves the internal structural inefficiency of Validator."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-06T16:19:53.403",
"Id": "25061",
"Score": "0",
"body": "Well, instead of having CustomValidationX, each implementor provides their own implementation, and calls the base (default) method only if they want to. What, specifically, are you thinking of in terms of inefficiency?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-06T15:53:12.330",
"Id": "15459",
"ParentId": "15458",
"Score": "0"
}
},
{
"body": "<p>I think your best chance in this is to use the Chain Of Responsiblity pattern, also know as pipeline.</p>\n\n<p>Your class hierarchy is good, however i'd add an extra property to the base class</p>\n\n<pre><code>public bool IsValid {get; set;}\n</code></pre>\n\n<p>Then you would have your pipeline defined like this</p>\n\n<pre><code>List<BaseValidator> validationPipeline;\n</code></pre>\n\n<p>in this collection you have to add all the validators you require for a specific scenario, with the following rule, if an object cannot validate the input (because it's not its reponsibilty) then it treats the input as valid and passes the input to the next object in the pipeline, if at the end of the iterarion you have a valid result, then the input is ok, otherwise you can break the validation cycle at the first invalid result</p>\n\n<p>the validation sequence code should be something like this</p>\n\n<pre><code>bool valid = true;\nforeach (var validator in validationPipeline)\n{\n validator.Validate();\n valid = validator.IsValid;\n if(!valid)\n break;\n}\n//If valid == true at this point, the input is valid\n</code></pre>\n\n<p>In this way you can split your validation logic in several classes without compromising the desing or coupling it so much, the important things to keep in mind are:</p>\n\n<ul>\n<li>The order of the validators is important (the most likely to fail should go first)</li>\n<li>If a validator doesn't have to handle the input it should treat it as valid and leave it for another validator down the chain</li>\n</ul>\n\n<p>A quick & dirty example would be a credit card number validator, with the following validation sequence</p>\n\n<ol>\n<li>Validate credit card number (with the standard algortihm)</li>\n<li>If the credit card is VISA, check something with VISA's system</li>\n<li>If the credit card is Mastercard, check something with Mastercard's systems</li>\n</ol>\n\n<p>And four scenarios can occur</p>\n\n<p>1- The credit card number is invalid, the first validator runs and stops the iteration because if the number isn't right you shouldn't waste time doing anything else.</p>\n\n<p>2- The credit card is valid, and its a visa card, so the second validator runs against some services and it is successful control is passed to the mastercard validator that sould return that its valid because its not its resposiblity to handle visa cards.</p>\n\n<p>3- The credit card is valid, and its a mastercard, so the second validator returns its valid because it only handles visa cards, and the third validator runs and determines the outcome of the validation process</p>\n\n<p>4- Suppose its a valid credit card number, but it's neither visa nor mastercard, lets say its an American Express card, you could add a fourth validator that would return always false because you only accept visa or mastercard.</p>\n\n<p>Hope it's clear and that it's helpful to you or anyone out there</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-06T18:19:59.237",
"Id": "15460",
"ParentId": "15458",
"Score": "1"
}
},
{
"body": "<p>So I think what you are trying to solve is how to elegantly group separate custom validation checks (each custom validation method) for different uses (email, or phone, etc.).</p>\n\n<p>The issue is you have to declare this information somewhere, and as your existing class structure for the validation uses is good - ie. grouped accordingly to your needs and inheriting from a base class so there is a common signature between all the different validator classes - I don't necessarily think the solution is to change that. So using the Chain of Responsibility pattern, although a nice pattern for validation, isn't really solving the problem as you still need to declare the collection of validators for each validation use.</p>\n\n<p>So I think the answer comes down to declarative preference; would you like to declare them as you do via method calls (simple), attributes on a class using reflection, or a Dictionary of <code>Func</code>s / <code>Action</code>s? Or as configuration somewhere? You have to declare this information somewhere. Maybe there are some other requirements which impact how you might declare these relationships?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-07T03:48:49.417",
"Id": "25062",
"Score": "0",
"body": "Thanks for the suggestion . Declaring a dictionary of Func\\Action could be one way to go. The Validate() function just grows for every business added and I could not think of any better classification than to say all are validations."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-07T04:01:17.703",
"Id": "25063",
"Score": "0",
"body": "A little introspection tells me that I can probably graph out similarities between the business validation rules. Thanks for pointing in that direction too."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-07T01:09:26.780",
"Id": "15461",
"ParentId": "15458",
"Score": "2"
}
},
{
"body": "<p>Take a look at the <a href=\"http://www.martinfowler.com/apsupp/spec.pdf\" rel=\"nofollow\">specification pattern (pdf)</a>. </p>\n\n<p>In particular, Microsoft has already implemented <a href=\"http://msdn.microsoft.com/en-us/library/ff650484.aspx\" rel=\"nofollow\">this kind of framework</a> as part of one of their (old) application blocks. You can look there for many related ideas.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-07T04:02:10.293",
"Id": "25064",
"Score": "0",
"body": "This application already uses the EnterpriseLibrary FM. Just that no one thought of using the validation block. Thanks"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-07T01:26:03.103",
"Id": "15462",
"ParentId": "15458",
"Score": "4"
}
},
{
"body": "<p>I was inspired by @theringostars's suggestion to use to dictionary of actions to clean the validate function . Here is the completed sample. This is a community wiki, so feel free to edit. </p>\n\n<pre><code>using System;\nusing System.Reflection;\nusing System.Collections.Generic;\n\nnamespace ValidatorPattern\n{\n //classfication of you custom validations.\n enum ValidatorType\n {\n CustomValidation1,\n CustomValidation2\n }\n\n //attribute applied to all customvalidation methods.\n class ValidatorAttribute : Attribute\n {\n public ValidatorType ValidatorType { get; set; }\n\n public ValidatorAttribute(ValidatorType validatorType)\n {\n ValidatorType = validatorType;\n }\n }\n\n abstract class BaseValidator\n {\n //key:List of custom validation Actions to be performed\n protected List<Action<string>> customValidations = new List<Action<string>>();\n\n public BaseValidator()\n {\n InitializeValidators();\n }\n\n public virtual void Validate()\n {\n Console.WriteLine(\"BaseValidator was called\");\n }\n\n private void InitializeValidators()\n {\n Type emailValidator = this.GetType();\n foreach (MethodInfo emailValidatorTypeMethod in emailValidator.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))\n {\n foreach (Attribute a in Attribute.GetCustomAttributes(emailValidatorTypeMethod))\n {\n if (a.GetType() == typeof(ValidatorAttribute))\n customValidations.Add((Action<string>)emailValidatorTypeMethod.Invoke(this, null));\n }\n }\n }\n\n }\n\n class EmailValidator : BaseValidator\n {\n //Comment: Validate() method looks clean. No matter how many custom validation logics are added.\n public override void Validate()\n {\n Console.WriteLine(\"EmailValidator was called\");\n base.Validate();//call base validations\n\n //loops thru all validators marked with 'ValidatorAttribute' in the current class.\n foreach (KeyValuePair<Tuple<ValidatorType, string>, Action<string>> validation in customValidations)\n {\n validation.Value(\"email string\");\n }\n }\n\n [Validator(ValidatorType.CustomValidation1)]\n private Action<string> CustomValidation1()\n {\n Action<string> customValiation1 = (x) => { Console.WriteLine(\"CustomValidation1 was called\"); };\n return customValiation1;\n }\n\n [Validator(ValidatorType.CustomValidation2)]\n private Action<string> CustomValidation2()\n {\n Action<string> customValiation2 = (x) => { Console.WriteLine(\"CustomValidation2 was called\"); };\n return customValiation2;\n }\n }\n\n class Client\n {\n static void Main()\n {\n BaseValidator emailValidator = new EmailValidator();\n emailValidator.Validate();\n\n }\n }\n}\n</code></pre>\n\n<p>PS: Also, explore Microsoft's entlib standard as metioned by @jordao</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-07T22:40:12.857",
"Id": "15463",
"ParentId": "15458",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "15462",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-06T15:44:51.047",
"Id": "15458",
"Score": "1",
"Tags": [
"c#",
"design-patterns",
".net",
"validation"
],
"Title": "Solving an unwieldy inheritance framework function"
}
|
15458
|
<p>We have a hidden div in a master page. When we want to display a message, we send a function a message to display, and it turns that div from .Visible false to .Visible true, and fills the div with the message. For all intents and purposes, this works and we haven't really had much trouble with it. I just feel that there must be a more "standard" way of doing this. There are two downsides, which I'll detail at the end, but neither is site-breakingly critical.</p>
<p><strong>ControlHelper.cs</strong></p>
<pre><code>public static void DisplayNotificationMessage(MasterPage master, List<string> errormessages, string title, MessageBoxImages imgtype)
{
if (master.FindControl("divmsgpanel") != null)
{
master.FindControl("divmsgpanel").Visible = true;
}
if (master.FindControl("divdimmer") != null)
{
master.FindControl("divdimmer").Visible = true;
}
Label titlelabel = (Label)master.FindControl("lblmsgpaneltitle");
if (titlelabel != null)
{
titlelabel.Text = title;
}
TextBox thetxtbox = (TextBox)master.FindControl("txtboxmsgcontents");
if (thetxtbox != null)
{
thetxtbox.Text = String.Empty;
foreach (string x in errormessages)
{
thetxtbox.Text += x + "\n\n";
}
}
Image icon = (Image)master.FindControl("imgmessageicon");
switch (imgtype)
{
case MessageBoxImages.Info:
icon.ImageUrl = "~/images/icons/ico-msginfo96x96.png";
break;
case MessageBoxImages.Warning:
icon.ImageUrl = "~/images/icons/ico-msgwarning96x96.png";
break;
case MessageBoxImages.Error:
icon.ImageUrl = "~/images/icons/ico-msgerror96x96.png";
break;
default:
icon.ImageUrl = "~/images/icons/ico-msginfo96x96.png";
break;
}
}
</code></pre>
<p>divdimmer is what we use to make the "background" go dark, so that the error message sticks out to the user. Here is a cropped screenshot of the final product:</p>
<p><img src="https://i.stack.imgur.com/gGnNA.png" alt="message"></p>
<p>As you can see, the "content" of the site (the page the user interacts with) goes dark, and the notification message appears.</p>
<p>In the master page, the following code-behind method "closes" the message box:</p>
<pre><code>protected void btnmsgcloser_Click(object sender, EventArgs e)
{
divmsgpanel.Visible = false;
divdimmer.Visible = false;
}
</code></pre>
<p>And then in each content page, we can call the method to display the message box with dynamic content very easily:</p>
<pre><code>public void Save()
{
List<string> errormessages = ValidateInput();
if (errormessages.Count == 0)
{
//no error, do work
}
else
{
ControlHelper.DisplayNotificationMessage(Master.Master, errormessages, "Failure", MessageBoxImages.Error);
}
}
</code></pre>
<p>As I mentioned, there's a downside. One of the design requirements was for, upon successful submission of a page, to re-direct to some other page AND show a "success" message.</p>
<p>For example, we have a page with a calendar (calendar.aspx), and a page for event creation (addevent.aspx). The idea is that when you submit something via addevent.aspx, that you get re-directed to calendar.aspx, and you see a message like "Event creation successful!"</p>
<p>The only way I can figure out how to make both re-direct AND display a message is to use a query string. So for example, at the end of the event creation in addevent.aspx, we have:</p>
<pre><code>Response.Redirect("calendar.aspx?createsuccess=true");
</code></pre>
<p>Then in the code-behind for calendar.aspx, on Page_Load, we check for a querystring and display the appropriate message:</p>
<pre><code>protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["deletesuccess"] == "true")
{
List<string> successmessage = new List<string>();
successmessage.Add("The event has been deleted.");
ControlHelper.DisplayNotificationMessage(Master.Master, successmessage, "Success", MessageBoxImages.Info);
}
else if (Request.QueryString["editsuccess"] == "true")
{
List<string> successmessage = new List<string>();
successmessage.Add("The event has been edited.");
ControlHelper.DisplayNotificationMessage(Master.Master, successmessage, "Success", MessageBoxImages.Info);
}
else if (Request.QueryString["createsuccess"] == "true")
{
List<string> successmessage = new List<string>();
successmessage.Add("The event has been created.");
ControlHelper.DisplayNotificationMessage(Master.Master, successmessage, "Success", MessageBoxImages.Info);
}
}
</code></pre>
<p>Once again, this works. But it has <strong>two</strong> downsides:</p>
<p>1) it splits the related code between two locations (we send the code from addevent.aspx and then pick it up via query string in calendar.aspx)</p>
<p>2) as the querystring is part of the URL, if the page is re-loaded, each time it will display the same message. For example, let's say we have a user who does the following:</p>
<ul>
<li>visits calendar.aspx</li>
<li>clicks the "Add Event" button and is re-directed to addevent.aspx</li>
<li>submits a new event in addevent.aspx</li>
<li>is re-directed back to calendar.aspx?createsuccess=true</li>
<li>user thinks, "hey this is pretty handy, I'll bookmark this page."</li>
<li>they've just bookmarked "calendar.aspx?createsuccess=true", and therefore every time they open the bookmark, they're going to get a "The event has been created." message.</li>
</ul>
<p>I would list our requirements/needs/goals, but we're actually pretty flexible, as long as we can avoid a spaghetti code monster. We previously messed around with jquery. I was probably doing something wrong, but I didn't find it easy to pass a message/alert box dynamic content from the code-behind. I vaguely remember getting something up and running at the beginning of the project, but it was a huge mess between hidden elements in the .aspx page, code-behind, and javascript. It seemed overly verbose and not very easy to maintain, which is what led us to create our own solution (detailed above), in which we have one central method called throughout the entire site.</p>
|
[] |
[
{
"body": "<p>Not actually 100% sure if this will work for you but could you use Session variables to achieve what you are after?</p>\n\n<pre><code> public sealed class MessageInfo\n {\n private readonly string title;\n\n private readonly string text;\n\n public MessageInfo(string title, string text)\n {\n this.title = title;\n this.text = text;\n }\n\n public string Title\n {\n get\n {\n return this.title;\n }\n }\n\n public string Text\n {\n get\n {\n return this.text;\n }\n }\n }\n\n public sealed class MessageBox\n {\n private readonly Page parent;\n\n public MessageBox(Page parent)\n {\n if (parent == null)\n {\n throw new ArgumentNullException(\"parent\");\n }\n\n this.parent = parent;\n }\n\n private MessageInfo Message\n {\n get\n {\n return this.parent.Session[\"MessageBox\"] as MessageInfo;\n }\n\n set\n {\n this.parent.Session[\"MessageBox\"] = value;\n }\n }\n\n public void NextMessage(string title, string message)\n {\n NextMessage(new MessageInfo(title, message));\n }\n\n public void NextMessage(MessageInfo msgInfo)\n {\n Message = msgInfo;\n }\n\n private void Clear()\n {\n NextMessage(null);\n }\n\n public bool CanShow()\n {\n return !string.IsNullOrEmpty(Message.Text);\n }\n\n public void Show()\n {\n if (!CanShow())\n {\n return; // do nothing or perhaps throw exception?\n }\n\n ControlHelper.DisplayNotificationMessage(this.parent.Master.Master, Message.Text, Message.Title, MessageBoxImages.Info);\n }\n\n public void ShowOnce()\n {\n Show();\n\n // clear immediately\n Clear();\n }\n }\n</code></pre>\n\n<p>and used in your target page like:</p>\n\n<pre><code>protected void Page_Load(object sender, EventArgs e)\n{\n var msgBox = new MessageBox(this);\n if(msgBox.CanShow())\n {\n msgBox.ShowOnce();\n }\n}\n</code></pre>\n\n<p>and set from your calling page like:</p>\n\n<pre><code>protected void Deleted(object sender, EventArgs e)\n{\n new MessageBox(this).NextMessage(\"Success\", \"The event has been deleted\");\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-10T20:15:01.113",
"Id": "25117",
"Score": "0",
"body": "I certainly hope they stick to your intents :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-10T20:44:35.497",
"Id": "25119",
"Score": "0",
"body": "@JesseC.Slicer yes definitely! Although whether my intent was in a good direction is another question :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-11T19:31:23.833",
"Id": "25190",
"Score": "0",
"body": "I've used a similar solution for an MVC site when moving between views on a checkout.\n\nUsing Session also means that you could have the message persist between pages, until the user has dismissed it. Only downside is situations where Session is not available/not sticky."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-13T18:57:17.343",
"Id": "25328",
"Score": "1",
"body": "By using the session the user cannot use this particular page in two tabs in parallel. This is an indicator of session misuse."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-10T09:21:20.060",
"Id": "15471",
"ParentId": "15464",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "15471",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-10T01:20:10.537",
"Id": "15464",
"Score": "7",
"Tags": [
"c#",
".net",
"asp.net"
],
"Title": "ASP.Net, C#, and alert/display messages"
}
|
15464
|
<p>Today I built a <code>linspace</code> function in Python's C API:</p>
<pre><code>static PyObject *
linspace(PyObject * self, PyObject * args)
{
int n, i;
double start, end;
if (!PyArg_ParseTuple(args, "ddi:linspace", &start, &end, &n))
return NULL;
if (n <= 1)
return Py_BuildValue("[d]", end);
double h;
PyObject *pylist = PyList_New(n);
h = (end - start) / (n - 1);
for (i = 0; i < n; i++)
PyList_SetItem(pylist, i, Py_BuildValue("d", (start + h * i)));
return Py_BuildValue("O", pylist);
}
</code></pre>
<p>It behaves how I would like it to behave, however, when I benchmarked it against NumPy's <code>linspace</code> it was slower by about a factor of 80.</p>
<p>I have a few questions that I think may be affecting performance, but I can't seem to find help online:</p>
<ul>
<li>Is there a memory leak? Or am I not incrementing or decrementing any references that I should be?</li>
<li>Can I do this with a C double array and then return that as a Python Object? Would this even be faster (I think it may)?</li>
<li>Am I missing something? I am new to the C API and I am not confident in it yet.</li>
</ul>
|
[] |
[
{
"body": "<ol>\n<li><p>I can't see any obvious memory leaks. If you're worried, then you might start out by seeing what <a href=\"http://docs.python.org/library/sys.html#sys.getrefcount\" rel=\"nofollow\"><code>sys.getrefcount</code></a> tells you.</p></li>\n<li><p>You will need to package up your array-of-doubles as a new type of Python object. See <a href=\"http://docs.python.org/extending/newtypes.html\" rel=\"nofollow\">section 2 of the Extending/Embedding manual</a>.</p></li>\n<li><p>Since you know that you are creating <code>float</code> objects, you could speed things up slightly by using <a href=\"http://docs.python.org/c-api/float.html#PyFloat_FromDouble\" rel=\"nofollow\"><code>PyFloat_FromDouble</code></a> instead of the generic <a href=\"http://docs.python.org/c-api/arg.html#Py_BuildValue\" rel=\"nofollow\"><code>Py_BuildValue</code></a> (which has to parse its first argument and then dispatch). But this is not going to beat NumPy, because packaging up an array-of-numbers as a new type of Python object is exactly what NumPy does, and that's why it runs so fast: it doesn't have to allocate a new Python object for every position in the list.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-10T11:27:06.770",
"Id": "15475",
"ParentId": "15465",
"Score": "3"
}
},
{
"body": "<p>There's one memory leak:</p>\n\n<pre><code>return Py_BuildValue(\"O\", pylist);\n</code></pre>\n\n<p><code>pylist</code> has a reference count of 1 before this line and <code>Py_BuildValue</code> increment it to 2. Subsequent code will only ever reduce it to 1, so it never gets freed. Instead just do</p>\n\n<pre><code>return pylist;\n</code></pre>\n\n<hr>\n\n<p>An efficient implementation using on Python built-in types would probably use the <a href=\"https://docs.python.org/3/library/array.html\" rel=\"nofollow noreferrer\"><code>array</code> module</a> instead of a list and a <a href=\"https://docs.python.org/3/c-api/memoryview.html\" rel=\"nofollow noreferrer\"><code>memoryview</code></a> to access it. I'd expect this to be comparable in speed with <code>numpy</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-03-13T10:23:19.610",
"Id": "157632",
"ParentId": "15465",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "15475",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-10T02:32:58.947",
"Id": "15465",
"Score": "7",
"Tags": [
"python",
"c",
"native-code"
],
"Title": "Linspace method build in Python's C API"
}
|
15465
|
<p>I need comments on my JPA code. Am I doing it correctly? I need some advice on best practices in Java.</p>
<p>I have this method below:</p>
<pre><code>public Comics add(Comics comics) {
EntityManager em = EMF.get().createEntityManager();
EntityTransaction tx = null;
try{
tx = em.getTransaction();
tx.begin();
em.persist(comics);
tx.commit();
}catch(Exception ex){
ex.printStackTrace();
if(tx != null && tx.isActive())
tx.rollback();
} finally{
em.close();
}
return comics;
}
</code></pre>
<p>When I called the method, I just have:</p>
<pre><code>ComicsAccess access = new ComicsAccess();
access.add( comics );
</code></pre>
<p>I got no error on the above code, what I want are some suggestions on my coding style. Is the above good code if used in production?</p>
|
[] |
[
{
"body": "<p>The way you are handling the exception will result in the method returning normally whether or not the method has succeeded. This is bad API design. Better design would be to either return some special value to indicate failure or (better) to allow the exception to propagate, or throw a different one.</p>\n\n<p>Catching <code>Exception</code> is usually a bad idea. The problem is that you may end up catching all sorts of unexpected exceptions.</p>\n\n<p>Unconditionally writing stacktraces to standard output is bad practice. Use a logging system; e.g. java.util.logging, log4j, etcetera.</p>\n\n<p>Here is an alternative version that avoids these problems:</p>\n\n<pre><code>public Comics add(Comics comics) throws ... {\n EntityManager em = EMF.get().createEntityManager();\n EntityTransaction tx = null;\n try {\n tx = em.getTransaction();\n tx.begin();\n em.persist(comics);\n tx.commit();\n } finally {\n try {\n if (tx != null && tx.isActive()) {\n tx.rollback();\n }\n } finally {\n em.close();\n }\n }\n return comics; \n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-10T05:14:26.293",
"Id": "25077",
"Score": "0",
"body": "should it throws `Exception`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-12T08:07:17.070",
"Id": "25213",
"Score": "1",
"body": "No ... it should list the checked exceptions that are not being caught. Declaring a method as throwing Exception means that the caller has no clue what to expect."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-18T10:32:44.343",
"Id": "25539",
"Score": "0",
"body": "why can't we just removed the nested `try` and `finally` in `finally` block?"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-10T05:08:09.097",
"Id": "15468",
"ParentId": "15467",
"Score": "5"
}
},
{
"body": "<p>There is no silver bullet, no universal best practice, imho, but i would write code like that:</p>\n\n<pre><code>public Comics add(Comics comics) throws PersistenceException {\n EntityManager em = EMF.get().createEntityManager();\n // we have PersistenceContext \"resource\" em\n try {\n EntityTransaction tx = em.getTransaction();\n // we have \"resource\" tx : lifecycle have 2 final states - committed or rolled back\n try {\n tx.begin();\n em.persist(comics);\n tx.commit(); // final state 1\n } finally {\n if (tx.isActive())\n tx.rollback(); // or final state 2\n }\n // free \"resource\" em\n } finally {\n em.close();\n }\n return comics;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-19T08:58:31.523",
"Id": "25579",
"Score": "1",
"body": "is the nested `try` and `finally` block necessary?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-21T14:08:43.210",
"Id": "25724",
"Score": "0",
"body": "Welcome to Code Review! Please try to explain the choices behind the code: the code itself is not enough here IMHO."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-14T07:51:50.977",
"Id": "15603",
"ParentId": "15467",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-10T03:29:13.350",
"Id": "15467",
"Score": "8",
"Tags": [
"java",
"exception-handling"
],
"Title": "Coding style and best practice regarding exception-handling"
}
|
15467
|
<p>I have written a piece of code by taking help from <a href="http://oswaldatwork.thetaoofamp.com/2009/10/scaling-images-in-php-done-right/" rel="nofollow">this link</a>. For generating thumbnail, I create a temporary scaled image and then copy from that image. I am assuming that it is resource intensive. </p>
<p>Settings: the maximum values for target dimensions of scale images are predefined. Also, the thumbnail is always square and its side's value is also predefined.</p>
<p>The logic for my code is:
Maximum Target dimensions - 700X524
Thumbnail - 90X90</p>
<ol>
<li>Get source image dimensions</li>
<li>Check if either of height or width is larger than 524 & 700 respectively
If yes,</li>
<li>Check if height> width.If yes,set height=524 and scaled width;else set width=700 and scale height.</li>
<li>create true color image from imagecreatettruecolor.</li>
<li>Generate scaled image with new dimensions from the original image</li>
</ol>
<p>For thumbnail:</p>
<ol>
<li>Check if either of scaled height and width is greater than 90</li>
<li>If yes, scale the shorter side to 90 and longer side accordingly.</li>
<li>Create a true color canvas of the further scaled dimensions.</li>
<li>Create a short image with the shorter side being 90 and larger one scaled accordingly</li>
<li>Create a true color canvas of dimensions 90X90</li>
<li>Copy thumbnail image to this canvas from the recently created shorter scaled image.</li>
</ol>
<p>The code:</p>
<pre><code><?php
// default dimensions
//height : 524px
//width: 700px
$source_image = imagecreatefromjpeg("bg.jpg");
$source_imagex = imageSX($source_image);
$source_imagey = imagesy($source_image);
//destination image size calculation, should not exceed the target
//check if height and width are larger than required and then scale
if($source_imagey>524 || $source_imagex > 700) {
if($source_imagey>$source_imagex){
$new_height = 524;
$new_width = 524/$source_imagey*$source_imagex;
}else{
$new_width = 700;
$new_height = 700/$source_imagex*$source_imagey;
}
}
$dest_image = imagecreatetruecolor($new_width, $new_height);
//poor quality but fast
imagecopyresized($dest_image, $source_image, 0, 0, 0, 0, $new_width,
$new_height, $source_imagex, $source_imagey);
imagejpeg($dest_image,"final.jpg", 80);
//better quality but slow
imagecopyresampled($dest_image, $source_image, 0, 0, 0, 0, $new_width,
$new_height, $source_imagex, $source_imagey);
imagejpeg($dest_image, 'final2.jpg', 80);
//create square thumbnail
// resize image to scale shorter side to 90px
if($new_width>90 || $new_height>90) {
if($new_height>$new_width)
{
$thumb_height = (90/$new_width)*$new_height;
$thumb_width = 90;
$top = ($tHeight - 90)/2;
$left = 0;
}else{
$thumb_width = (90/$new_height)*$new_width;
$thumb_height = 90;
$left = ($thumb_width-90)/2;
$top = 0;
}
}
$image_t = imagecreatetruecolor($thumb_width,$thumb_height);
imagecopyresampled($image_t, $dest_image, 0, 0, 0, 0, $thumb_width,
$thumb_height, $new_width, $new_height);
$thumb_image = imagecreatetruecolor(90,90);
imagecopy($thumb_image, $image_t, 0, 0, $left, $top,
$thumb_width,$thumb_height);
imagejpeg($thumb_image, 'thumb.jpg', 80);
imagedestroy($thumb_image);
imagedestroy($dest_image);
imagedestroy($image_t);
</code></pre>
<p>Is this approach of creating a temporary image of smaller size and then copying thumbnail from it, correct ? Is there an alternative to this ? How can it be further optimized ?</p>
<p><strong>UPDATE:</strong> The class that I have created, with the above code and some help and insight gained from the link at nettuts, can be found on <a href="https://github.com/gentrobot/PHP-image-scale" rel="nofollow">github</a></p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-10T09:50:28.973",
"Id": "25089",
"Score": "1",
"body": "This is a small recommendation. You should wrap this all in a class. This makes everything modular so you can easily reference the image source without having to manually go through everything."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-10T10:54:54.713",
"Id": "25090",
"Score": "0",
"body": "@KeiranLovett: Thanks for the suggestion. I too intend to wrap this in the class. Even inside the class, whether this approach is right or not, or is there a better way to do it ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-10T13:32:33.400",
"Id": "25097",
"Score": "0",
"body": "I've had to do something similar to this twice. I found using a premade class and tweaking it to better suit your needs is better. As people here like to say again and again \"Why reinvent the wheel?\"\n\nI'd recommend taking a look at this here - if you think net-tuts has a better approach then use it!\n\nhttp://net.tutsplus.com/tutorials/php/image-resizing-made-easy-with-php/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-12T10:10:27.090",
"Id": "25219",
"Score": "0",
"body": "@KeiranLovett: I have created a class, as you suggested. I am yet to add a method to generate the thumbnails."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-12T20:30:15.907",
"Id": "25235",
"Score": "1",
"body": "Instead of using the file extension to determine which image function you should be using, I would suggest looking at the [exif_imagetype](http://www.php.net/manual/en/function.exif-imagetype.php) function. This function returns one of the IMAGETYPE_XXX constants, which you can use to determine which one of the image functions to use. This will be more accurate, because even if someone renames a JPEG as .gif, it will still return the correct image type."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-13T09:31:32.600",
"Id": "25281",
"Score": "0",
"body": "@AndrewR: Thanks for the suggestion. Added it to the class. :)"
}
] |
[
{
"body": "<p>Please don't count this as an answer. I've never done anything with any of the image libraries before, so I can't help you with the specifics. I would have put this into a comment, but its obviously too big. However, here are a few things to ponder.</p>\n\n<p>First, in regards to the comments Keiran Lovett made, a class may make this a little simpler to work with, but it may also add an unnecessary level of overhead or abstraction. This seems like a relatively simple application, thus the overhead and abstraction that a class would introduce may not be worth it. It depends on a number of things, but the main ones I would contemplate are if I were going to be doing a lot of different things with these images, or how much simpler or faster/slower it would make it. Either way, I definitely would start using functions, and then if you decide to use a class it will make the transition easier.</p>\n\n<p>Your maximum width and height should be made into constants, or at the very least variables. This avoids the \"magic numbers\" and makes it easier to use and update these values should you ever decide to change them.</p>\n\n<pre><code>define( 'MAX_Y', 524 );\ndefine( 'MAX_X', 700 );\n</code></pre>\n\n<p>How do you treat images that have been rotated? An image flipped to a different aspect ratio would result in a smaller image on one axis and a skewed thumbnail. Or at least, so it would seem to me. I'm not sure how to do this, but it is something you may want to look in to.</p>\n\n<p>And finally, in regards to how memory intensive this is going to be, I don't know. The best way to find out would be to run some tests and profile it. Create 100 (or more) oversize images and run the necessary code in a loop to convert each one. This is where having functions would be handy.</p>\n\n<pre><code>$start = microtime( TRUE );\nfor( $i = 0; $i < 100; $i++ ) {\n //functions to scale and convert\n}\n$total = microtime( TRUE ) - $start;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-10T17:59:18.100",
"Id": "25112",
"Score": "0",
"body": "I really am not sure whether to accept this as an answer, but you really gave me very valuable suggestions. I simply wish I could upvote it more than once :D"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-10T18:13:25.887",
"Id": "25113",
"Score": "0",
"body": "I don't believe I understand the basic elements of this enough for it to count as an answer. If you disagree, that's fine, I just don't feel it should count as an answer. Glad I could be of some help though :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-10T17:06:24.223",
"Id": "15490",
"ParentId": "15470",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "15490",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-10T08:53:09.010",
"Id": "15470",
"Score": "4",
"Tags": [
"php",
"optimization",
"algorithm"
],
"Title": "PHP code to scale images and generate thumbnails"
}
|
15470
|
<p>Can you please provide a general review the following PHP code (with MySQLi)?</p>
<p>The query involves an <code>INSERT INTO</code> statement:</p>
<pre><code>public function __i($table, $arr) { $c=$this->connection;
foreach ( $arr as $name => $val):
$param1.=$name . ",";
$param2.="?,";
endforeach;
$PARAM1 = substr_replace($param1, '', -1);
$PARAM2 = substr_replace($param2, '', -1);
$query = 'INSERT INTO '.$table.' ('.$PARAM1.') VALUES ('.$PARAM2.')';
echo $query;
foreach ( $arr as $name => $val):
if ( is_int($val)) :
$param = 'i';
endif;
if ( is_string($val)) :
$param = 's';
endif;
if ( is_double($val)) :
$param = 'd';
endif;
$binds.=$param;
$values.="'".$arr[$name]."',";
endforeach;
$values = substr_replace($values, '', -1);
echo "BINDS ARE: ".$binds . "<br>";
echo "VALUES ARE: ".$values."<br>";
if ( $s = $c->prepare($query)):
$args = $binds + $values;
call_user_func_array(array($s, 'bind_param'), array($binds, $values));
$s->execute();
$s->close();
endif;
}
</code></pre>
|
[] |
[
{
"body": "<p>Well, there's no context, so I can't be sure of exactly what you want, so I will assume a general review. In the future, please provide a little intro, even if its only to say, \"please review and tell me how I can do better.\" Just dumping code is rather vague, for instance, this question could just as easily been about a better way to insert, of which I have no idea.</p>\n\n<p>First, your method and variable names could use some work. What is <code>__i()</code>? A little more descriptive please. I can assume, based on the title of this post that this is an <code>insert()</code> method, but without any context this would be very difficult to determine. Additionally, I would avoid using double-spaced method names, those are usually reserved for PHP magic methods, such as <code>__construct()</code>. A single space is good enough, though that usually refers to a private or protected method.</p>\n\n<p>Start your method's body on a newline, rather that the same one that the method was started on. I don't know if this was just a formatting issue with SO, or if its actually like that in your code. And, as above, what is <code>$c</code>? Connection can be inferred, but anyone reading this should not have to guess. <code>$conn</code> is a typical shortening and is widely accepted. Or you could spell it out completely, or use the root word \"connect\". As long as its somehow logically connected with the intent.</p>\n\n<pre><code>public function __i($table, $arr) {\n $conn = $this->connection;\n</code></pre>\n\n<p>Why are you using the standard template syntax for your statements and loops? In templates (Views or HTML files with PHP in them) this is fine, but it is quite odd and a little difficult to read in normal class structures. The preferred method is to use normal syntax, like so:</p>\n\n<pre><code>if() {\n}\n//AND\nforeach() {\n}\n</code></pre>\n\n<p>Where did <code>$param1</code> and <code>$param2</code> come from? They were not passed in as parameters to the method, which makes their names a little confusing. I would assume these are either globals, which are bad, or just undefined variables, which are also bad. If the later, then on the first iteration of this foreach loop those two variables will produce warnings about not being defined, or, god forbid, should there be globals assigned with those names, then you might just start appending on to them. To prevent this kind of mistake, it is best to define them before trying to use them. Also, any variable with a number after it is typically frowned upon. Use that variable's intent to better name them.</p>\n\n<pre><code>$param1 = '';\n//etc...\n$param1 .= $name . \",\";\n</code></pre>\n\n<p>I know what these two <code>substr_replace()</code> lines are for, but they might be a little confusing to others. Perhaps a better method would be to use <code>rtrim()</code> to explicitly remove the last comma. This will make it more obvious what you are trying to do, and slightly decrease the size of that line. I don't know if its any faster or slower, but I don't think the difference will matter much here.</p>\n\n<pre><code>$PARAM1 = rtrim( $param1, ',' );\n</code></pre>\n\n<p>Your <code>$param</code> is not always set. This means that should <code>$val</code> not be an int, string, or double, then it will use the last known value of <code>$param</code> from the previous iteration. This can result in unforeseen results. Instead, you should either set up a default value or use an if/elseif/else structure. Here's a simple example assuming string as a default, you can always extend else in the following example to another elseif and use a final else to throw an error if you don't want to default.</p>\n\n<pre><code>if( is_int( $val ) ) {\n $param = 'i';\n} elseif( is_double( $val ) ) {\n $param = 'd';\n} else {\n $param = 's';\n}\n//which can easily be rewritten to use a default as\n$param = 's';\nif( is_int( $val ) {\n $param = 'i';\n} elseif( is_double( $val ) ) {\n $param = 'd';\n}\n</code></pre>\n\n<p>Don't define a variable in an if statement. It is too easy to accidentally do so when you don't mean to and will not always be obvious that you did not mean to perform a comparison instead.</p>\n\n<pre><code>$s = $c->prepare( $query ):\nif( $s ) {\n //etc...\n}\n</code></pre>\n\n<p>I'm not really sure how I feel about the <code>call_user_func_array()</code>, It could be a little confusing to someone who's never seen it before, but that's your call.</p>\n\n<p>Finally, you might want to break up this method into multiple smaller methods. Use the Single Responsibility and \"Don't Repeat Yourself\" (DRY) Principles as a guideline. For example, to help you get started you can move that first foreach loop and those two <code>substr_replace()</code> lines into a new method called <code>getParams()</code> or something more aptly named. This will make it easier to reuse this code should you ever need to and make it easier to read.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-10T15:43:51.783",
"Id": "15486",
"ParentId": "15474",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2012-09-10T11:05:38.820",
"Id": "15474",
"Score": "2",
"Tags": [
"php",
"mysqli"
],
"Title": "PHP MySQLI Insert Command"
}
|
15474
|
<p>I have written code which does the following:</p>
<ol>
<li><p>The main goal is to fetch emails from inbox and spam folders and store them in a database. It fetches emails from Gmail, GMX, web.de, Yahoo and Hotmail.</p>
<p>The following attributes are stored in a MySQL database:</p>
<p><code>Slno</code>, <code>messagedigest</code>, <code>messageid</code>, <code>foldername</code>, <code>dateandtime</code>, <code>receiver</code>, <code>sender</code>, <code>subject</code>, <code>cc</code>, <code>size</code> and <code>emlfile</code>.</p>
</li>
<li><p>For Gmail, GMY and web.de, I have used the JavaMail API because email from it can be fetched with IMAP.</p>
</li>
<li><p>For Yahoo and Hotmail, I have used an HTML parser and HTTP client to fetch emails from the spam folder, and for the inbox folder, I have used the POP3 JavaMail API.</p>
</li>
</ol>
<p>I want to have a proper class hierarchy which makes my code efficient and easily reusable. I am sure it can still be improved, so I would like to have different opinions on it.</p>
<p>I have the following classes and methods as of now:</p>
<ol>
<li><p><code>MainController</code> - Here I pass <code>emailid</code>, <code>password</code> and <code>foldername</code> from which emails have to be fetched.</p>
</li>
<li><p>Abstract class - <code>EmailProtocol</code></p>
<p>Abstract methods of it (all methods except <code>executeParser</code> contains method definition):</p>
<ul>
<li><code>connectImap()</code> - used by GMX, Gmail and web.de email IDs</li>
<li><code>connectPop3()</code> - used by Hotmail and Yahoo to fetch emails from the inbox folder</li>
<li><code>createMessageDigest</code> - used by every email provider (GMX, Gmail, web.de, Yahoo, and Hotmail)</li>
<li><code>establishDBConnection</code> - used by every email</li>
<li><code>emailAlreadyExists</code> // used by every email which checks whether email already exists in db or not, if not then store it.</li>
<li><code>storeemailproperties</code> - used by every email to store emails properties to MySQL database</li>
<li><code>executeParser</code> - nothing written in it. Overridden and used by just Hotmail and Yahoo to fetch emails from the spam folder.</li>
</ul>
</li>
<li><p><code>Imap extends EmailProtocol</code></p>
<p>There's nothing in it, but I have to have it to access methods of <code>EmailProtocol</code>. This is used to fetch emails from Gmail, GMX and web.de. I know this is really a bad way but don't know how to do it another way.</p>
</li>
<li><p><code>Hotmail extends EmailProtocol</code></p>
<p>Methods:</p>
<ul>
<li><code>executeParser()</code> - This is used by just a Hotmail email ID.</li>
<li><code>fetchjunkemails()</code> - This is also very specific for only a Hotmail email ID.</li>
</ul>
</li>
<li><p><code>Yahoo extends EmailProtocol</code></p>
<p>Methods:</p>
<ul>
<li><code>executeParser()</code></li>
<li><code>storeEmailtotemptable()</code></li>
<li><code>MoveEmailtoInbox()</code></li>
<li><code>getFoldername()</code></li>
<li><code>nullorEquals()</code></li>
</ul>
<p>All above methods are specific for a Yahoo email ID.</p>
</li>
<li><p><code>public DateTimeFormat(class)</code></p>
<ul>
<li><code>format()</code> - This formats datetime of GMAX, Gmail and web.de emails.</li>
<li><code>formatYahoodate</code> - This formats datetime of Yahoo email.</li>
<li><code>formatHotmaildate</code> - This formats datetime of a Hotmail email.</li>
</ul>
</li>
<li><p><code>public StringFormat</code></p>
<ul>
<li><code>ConvertStreamToString()</code> - Accessed by every class except the <code>DateTimeFormat</code> class.</li>
<li><code>formatFromTo()</code> - Accessed by every class except the <code>DateTimeFormat</code> class.</li>
</ul>
</li>
<li><p><code>public Class CheckDatabaseExistance</code></p>
<pre><code> public static void checkForDatabaseTablesAvailability()
</code></pre>
<p>(This method checks at the beginning whether the database and required tables exist in MySQL or not. If not, it creates them.)</p>
</li>
</ol>
<p>Please see my <code>MainController</code> class so that you can have an idea about how I use different classes.</p>
<pre><code>public class MainController {
public static void main(String[] args) throws Exception {
ArrayList<String> web_de_folders = new ArrayList<String>();
web_de_folders.add("INBOX");
web_de_folders.add("Unbekannt");
web_de_folders.add("Spam");
web_de_folders.add("OUTBOX");
web_de_folders.add("SENT");
web_de_folders.add("DRAFTS");
web_de_folders.add("TRASH");
web_de_folders.add("Trash");
ArrayList<String> gmx_folders = new ArrayList<String>();
gmx_folders.add("INBOX");
gmx_folders.add("Archiv");
gmx_folders.add("Entwürfe");
gmx_folders.add("Gelöscht");
gmx_folders.add("Gesendet");
gmx_folders.add("Spamverdacht");
gmx_folders.add("Trash");
ArrayList<String> gmail_folders = new ArrayList<String>();
gmail_folders.add("Inbox");
gmail_folders.add("[Google Mail]/Spam");
gmail_folders.add("[Google Mail]/Trash");
gmail_folders.add("[Google Mail]/Sent Mail");
ArrayList<String> pop3_folders = new ArrayList<String>();
pop3_folders.add("INBOX");
CheckDatabaseExistance.checkForDatabaseTablesAvailability();
EmailProtocol imap = new Imap();
System.out.println("CHECKING FOR NEW EMAILS IN WEB.DE...(IMAP)");
System.out.println("*********************************************************************************");
imap.connectImap("email@web.de", "pwd", web_de_folders);
System.out.println("\nCHECKING FOR NEW EMAILS IN GMX.DE...(IMAP)");
System.out.println("*********************************************************************************");
imap.connectImap("email@gmx.de", "pwd", gmx_folders);
System.out.println("\nCHECKING FOR NEW EMAILS IN GMAIL...(IMAP)");
System.out.println("*********************************************************************************");
imap.connectImap("email@gmail.com", "pwd", gmail_folders);
EmailProtocol yahoo = new Yahoo();
Yahoo y=new Yahoo();
System.out.println("\nEXECUTING YAHOO PARSER");
System.out.println("*********************************************************************************");
y.executeParser("http://de.mc1321.mail.yahoo.com/mc/welcome?ymv=0","email@yahoo.de","pwd");
System.out.println("\nCHECKING FOR NEW EMAILS IN INBOX OF YAHOO (POP3)");
System.out.println("*********************************************************************************");
yahoo.connectPop3("email@yahoo.de","pwd",pop3_folders);
System.out.println("\nCHECKING FOR NEW EMAILS IN INBOX OF HOTMAIL (POP3)");
System.out.println("*********************************************************************************");
yahoo.connectPop3("email@hotmail.com","pwd",pop3_folders);
EmailProtocol hotmail = new Hotmail();
Hotmail h=new Hotmail();
System.out.println("\nEXECUTING HOTMAIL PARSER");
System.out.println("*********************************************************************************");
h.executeParser("https://login.live.com/ppsecure/post.srf","email@hotmail.com","pwd");
}
}
</code></pre>
<p>I have kept the <code>DatetimeFormat</code> and <code>StringFormat</code> classes <code>public</code> so that I can access their <code>public</code> methods by just <code>DatetimeFormat.formatYahoodate</code> for e.g. from different methods.</p>
|
[] |
[
{
"body": "<p>Well, for starters, I would put the mailbox information into a configuration file, properties file, database table, etc. Anywhere besides hard coded.</p>\n\n<p>Second, your <code>main()</code> method is totally out of control and needs to be broken up. I would suggest reading up about refactoring in general, but <a href=\"http://www.devdaily.com/java/refactoring-extract-method-java-example\" rel=\"nofollow\">here</a> is a bit that discusses <em>Extract Method</em> which is one of your more basic and crucially important refactorings.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-10T15:02:01.973",
"Id": "15484",
"ParentId": "15480",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-10T13:49:12.857",
"Id": "15480",
"Score": "7",
"Tags": [
"java",
"beginner",
"email"
],
"Title": "Fetching emails from various clients to store in a database"
}
|
15480
|
<p>The statement of the problem is there are 2 files, one has a set of intervals i.e. 0-10, 3-40, etc which may be repetitive. The second file has a set of numbers which are also repetitive. The exercise is to get a count of the intervals, a number in the 2nd file would fit into.</p>
<p>Intervals.txt</p>
<pre><code>0 12
2 36
6 98
2 36
</code></pre>
<p>Numbers.txt</p>
<pre><code>2
4
123
20
</code></pre>
<p>What I thought of as a possible solution was keep a count of intervals when you populate a map of intervals. So if you encounter an interval 3-40 5 times, you keep the count as 5 so you don't try to populate a map 5 times with the same interval. How it helps downstream is, if a number is in a specific interval you can count its existence in 5 intervals. Secondly there is a map of found numbers in your previous iterations, so that you don't loop through the intervals again.</p>
<p>I have been told, by some random guy, that my implementation is ok but not what he desires. No further explanations. I have tried raking my brain but haven't got any further. Any pointers or help would be much appreciated. Any further clarifications, please ask.</p>
<pre><code>void generateCounts(const string& fname1, const string& fname2)
{
std::ifstream file(fname1.c_str());
string line;
map<int, pair<int, int> > extents;
map<int, pair<int, int> >::iterator it;
std::string left;
std::string right;
if(file.is_open())
{
while(file.good())
{
getline(file, line);
string::size_type pos = line.find(' ');
left = line.substr(0, pos);
right = line.substr((++pos));
int ll = atoi(left);
int up = atoi(right);
it = extents.find(ll);
if(it != extents.end())
{
if(it->second.first != up){
extents.insert(make_pair<const int, pair<int, int> >(ll, make_pair<int, int>(up, ++count)));
}
else{
it->second.second += 1 ;
}
}
else
{
extents.insert(make_pair<const int, pair<int, int> >(ll, make_pair<int, int>(up, ++count)));
}
count = 0;
}
}
fclose(inp_file);
std::ifstream file1(fname2.c_str());
map<int, int> found;
map<int, int>::iterator it1;
string str;
if(file1.is_open())
{
while(file1.good())
{
count = 0;
getline(file1, str);
if(str.empty()) continue;
int var = atoi(str.c_str());
it1 = found.find(var);
if (it1 == found.end())
{
for(it = extents.begin(); it != extents.end(); ++it)
{
if((var >= it->first ) && (var <= it->second.first))
{
count += it->second.second ;
}
}
found.insert(make_pair(var, count));
}
else
count = it1->second;
cout << count << "\n";
str.clear();
}
file1.close();
}
</code></pre>
|
[] |
[
{
"body": "<p>OK. Since this is homework I am going to limit my points to hints (I may add more in a week or so).</p>\n\n<ol>\n<li><p>Why are you doing this?</p>\n\n<pre><code>if(file.is_open())\n</code></pre></li>\n<li><p>This is an anti-pattern (in every language not just C++):<br>\nRemember the eof (part of not being good) does not happen until you read past the end of line.</p>\n\n<p>Lots of examples on SO (go look it up).</p>\n\n<pre><code> while(file.good())\n {\n getline(file, line);\n</code></pre></li>\n<li><p>You are doing too much work here:</p>\n\n<p>There is an easy way to read integers from a stream. Lots of examples on SO (go look it up).</p>\n\n<pre><code> getline(file, line);\n string::size_type pos = line.find(' '); \n left = line.substr(0, pos);\n right = line.substr((++pos)); // Also this is wrong if no space was found.\n int ll = atoi(left);\n int up = atoi(right);\n</code></pre></li>\n<li><p>Why do a 2-phase compare?</p>\n\n<pre><code> if(it != extents.end()) \n {\n if(it->second.first != up){\n extents.insert(make_pair<const int, pair<int, int> >(ll, make_pair<int, int>(up, ++count)));\n }\n else{\n it->second.second += 1 ;\n }\n }\n else\n {\n extents.insert(make_pair<const int, pair<int, int> >(ll, make_pair<int, int>(up, ++count)));\n }\n</code></pre>\n\n<p>If you make the <strong>key</strong> <code>std::pair&lt;left, right&gt;</code> then you only need to do one test. Not this complicated mess. It also makes more sense to keep the left and right together.</p></li>\n<li><p>Don't do this: (see <a href=\"https://codereview.stackexchange.com/q/540/507\">Implementation using fstream failed evaluation</a>)</p>\n\n<pre><code>fclose(inp_file);\n</code></pre>\n\n<p>Same comments about the second loop:</p>\n\n<p>This is not wrong. But when I compare a number against two others of a range I put the value that is being tested for inclusion in the range in the middle of the comparison. I personally find it nicer to read this way:</p>\n\n<pre><code> if((var >= it->first ) && (var <= it->second.first))\n\n // I prefer\n\n if ((it->first <= var) && (var <= it->second.first))\n</code></pre></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-10T16:17:13.817",
"Id": "25108",
"Score": "0",
"body": "Thanks for your help, but this ain't any homework, to make it clear."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-10T16:19:57.543",
"Id": "25109",
"Score": "0",
"body": "OK. Then I will add more explanation tomorrow. But I will give you a chance to do some self learning."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-10T16:21:48.957",
"Id": "25110",
"Score": "0",
"body": "3)-> There is always going to be a space. That is the input. 4)-> There maybe the same starting first limit, but not necessarily the upper limit would be the same. e.g. 0 89 isn't the same as 0 56. Other points seems reasonable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-10T16:24:31.843",
"Id": "25111",
"Score": "0",
"body": "@DumbCoder: 3) Yes. There is still a much better way built into the language io libraries (hint: atoi() is old school C). 4) Yes exactly why the **key** should be `std::pair<left, right>` so the find() can find an exact mach without you doing extra work. ie the map is `std::map<std::pair<left, right>, count>`"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-10T16:05:48.473",
"Id": "15488",
"ParentId": "15482",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-10T14:37:31.007",
"Id": "15482",
"Score": "1",
"Tags": [
"c++",
"optimization",
"interval"
],
"Title": "Getting a count of intervals"
}
|
15482
|
<p>Three radio buttons and a text box, grouped in one group box... Just when I select one of those radio button the text box gets enabled, for the other two radio buttons it should be disabled. Here is the code that comes to mind at first, but it looks ugly to me becuase I have copy pasted the same AllowMissingData() method to Change evnt of each radio button. I was wondering if there is a better way of writing it:</p>
<pre><code>private void RequiredRadioButton_CheckedChanged(object sender, EventArgs e)
{
AllowMissingData();
}
private void AllowBlankRadioButton_CheckedChanged(object sender, EventArgs e)
{
AllowMissingData();
}
private void SuppressRadioButton_CheckedChanged(object sender, EventArgs e)
{
AllowMissingData();
}
private void AllowMissingData()
{
if (AllowBlankRadioButton.Checked)
{
MissingDataValueTextBox.Enabled = true;
}
else
{
MissingDataValueTextBox.Text = System.String.Empty;
MissingDataValueTextBox.Enabled = false;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>This cleans it up a little. Removes the if statement at least:</p>\n\n<pre><code>private void AllowMissingData()\n{\n MissingDataValueTextBox.Enabled = AllowBlankRadioButton.Checked;\n MissingDataValueTextBox.Text = AllowBlankRadioButton.Checked ? MissingDataValueTextBox.Text : System.String.Empty;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-10T15:51:38.310",
"Id": "15487",
"ParentId": "15483",
"Score": "3"
}
},
{
"body": "<p>Did you realize that multiple RadioButtons can all point to the same event handler? </p>\n\n<p><em>(simply use the Visual Studio Properties Editor in the designer to assign the same handler. Alternatively, you could apply <code>+= AnyRadioButton_CheckedChanged</code> to each of the RadioButtons' <code>CheckedChanged</code> events.)</em></p>\n\n<pre><code>private void AnyRadioButton_CheckedChanged(object sender, EventArgs e)\n{\n if (allowBlankRadioButton.Checked)\n {\n missingDataValueTextBox.Enabled = true;\n }\n else\n {\n missingDataValueTextBox.Enabled = false;\n missingDataValueTextBox.Text = string.Empty;\n }\n}\n</code></pre>\n\n<p>I actually find the if-else very readable, so I resisted the urge to incorporate Jeff's concise answer. In my opinion, the more elaborate version is clearer about what it does. </p>\n\n<p>I renamed all your controls to follow the <code>camelCase</code> naming convention (because <code>PascalCase</code> should be reserved for type names, etc). </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-10T17:14:09.983",
"Id": "15491",
"ParentId": "15483",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "15491",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-10T14:52:43.270",
"Id": "15483",
"Score": "3",
"Tags": [
"c#"
],
"Title": "A shorter way of Enablling/Disabling a text box from RadioButton selections"
}
|
15483
|
<p>I have developed a prototype framework (MVVM) where control on the form is bound to a model property using a naming convention and its UI behavior is controlled using custom attributes.</p>
<ol>
<li><p>As of now the control name is divided into two parts - 3 part prefix and then the Name of the property in model to bind to. </p>
<p>For eg <code>txtFirstName</code> textbox is bound to <code>FirstName</code> in model. During construction/load, all controls are looped through - </p>
<pre><code>BaseEdit baseEdit = (BaseEdit) control;
baseEdit.DataBindings.Add("EditValue", viewModelBindingSource,
baseEdit.Name.Remove(0, 3),
true, DataSourceUpdateMode.OnPropertyChanged);
</code></pre>
<p>There are some other attributes such as <strong>[ReadOnly], [Unbound]</strong> which are used to control the UI behavior.</p>
<pre><code>baseEdit.Properties.ReadOnly = Util.GetReadOnlyAttributeValue(
control.Name.Remove(0, 3), viewModel.GetType());
</code></pre>
<p>I am thinking of doing the looping the other way around, ie the Model properties, using a <code>Bound</code> attribute. <code>Bound[ControlName, PropertyName]</code></p>
<pre><code>Bound["txtFirstName", "EditValue"]
FirstName
</code></pre></li>
<li><p>All the dropdown type controls, combobox, dropdown, checkeddropdown etc <strong>are autofilled by using a 'Key' from their tag property</strong>.</p>
<pre><code>if (control.GetType() == typeof(LookUpEdit) &&
!string.IsNullOrEmpty(Convert.ToString(control.Tag))) //Exact match
{
LookUpEdit lookUpEdit = (LookUpEdit)control;
DataBinding.InitializeLookUpEdit(lookUpEdit, lookUpEdit.Tag.ToString());
}
</code></pre>
<p>I took the biggest data-entry form with around 45 controls and tested the framework. </p></li>
</ol>
<p>Is the above approach suitable for a big project? Any suggestions for improving the framework?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T09:55:05.753",
"Id": "40609",
"Score": "1",
"body": "Do you have a sample project so that it can be tested?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T17:34:27.077",
"Id": "73027",
"Score": "0",
"body": "This question appears to be off-topic because it is about an architectural review as opposed to a code review."
}
] |
[
{
"body": "<p>IMHO Anything that relies on controls' <code>Tag</code> property is fishy. In 15 years of VB4-5-6/VBA and then WinForms development, every single time I saw the <code>Tag</code> property assigned, there was a better way to solve the problem. I think using that property more often than not violates the <em>principle of least surprise (POLS)</em>, because it's not <em>typical</em> to put anything in there - if anything it means a control is begging to be derived from that control's class, and featured with the relevant properties - which is obviously too much trouble to be worth the while.</p>\n<p>That's my rant against using the <code>Tag</code> property. That said it looks rather clean, much cleaner than <a href=\"https://codereview.stackexchange.com/q/23847/23788\">this similar question</a>, but it suffers from the same issue:</p>\n<blockquote>\n<p>WinForms applications are better off with the <strong>Model-View-Presenter</strong> pattern.\n[...] if you want to simulate WPF behavior in WinForms, the <em>real thing</em> will be much less trouble, and leave you with much cleaner code.</p>\n<p>Sorry if that's not what you wanted to hear...</p>\n</blockquote>\n<p>For a big project I'd seriously consider either MVP or MVVM with WPF.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-23T10:03:54.433",
"Id": "58687",
"Score": "0",
"body": "The overall architecture is MVP-VM, with a base framework for automatic databinding. Working nicely right now."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-22T23:39:29.043",
"Id": "35949",
"ParentId": "15485",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "35949",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-10T15:23:17.570",
"Id": "15485",
"Score": "3",
"Tags": [
"c#",
"winforms",
".net-2.0"
],
"Title": "Automatic Databinding of controls to Model"
}
|
15485
|
<p>I am looking for some different approaches to this following OOP scenario.</p>
<pre><code> Dim pb As Object = Nothing
If radCars.Checked = True Then
Dim productBase As ProductsBase(Of CarColumns)
productBase = New Cars(fileLocation)
pb = productBase
ElseIf radTrucks.Checked = True Then
Dim productBase As ProductsBase(Of TruckColumns)
productBase = New Truck(fileLocation)
pb = productBase
End If
pb.Parse()
pb.AddRows()
....
</code></pre>
<p>Having to declare the object above and losing intelisense seems off. The base class if using generics because the Truck and Car classes use different column classes for the parsing and adding of columns in the db.</p>
<p><strong>Base Class:</strong></p>
<pre><code>Public MustInherit Class ProductsBase(Of T)
Sub New(filePathString As String)
FilePath = filePathString
End Sub
MustOverride Sub Parse()
MustOverride Sub DeleteRows()
MustOverride Sub AddRows(ByVal rows As IEnumerable(Of T), pageNumber As Integer)
Property ParseResult As ProductLookupContainer(Of T)
End Class
</code></pre>
<p><strong>Car Class:</strong></p>
<pre><code>Public Class Cars
Inherits ProductsBase(Of CarColumns)
Sub New(filePath As String)
MyBase.New(filePath)
End Sub
Public Overrides Sub AddRows(rows As IEnumerable(Of CarColumns), pageNumber As Integer)
DatabaseHelper.AddItemsToDB(Of CarProduct)(ConnectionString, rows, pageNumber)
End Sub
Public Overrides Sub DeleteRows()
DatabaseHelper.DeleteRows(ConnectionString, "CarProducts")
End Sub
Public Overrides Sub Parse()
Dim pf As New ParseFile(FilePath)
Dim result = New ProductLookupContainer(Of CarColumns)
result = pf.ParseCars
'Set object
ParseResult = result
End Sub
End Class
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-10T20:39:21.677",
"Id": "25118",
"Score": "0",
"body": "I'm not a VB.Net guy, but instead of object, why don't you make pb a ProductsBase?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-11T13:51:07.583",
"Id": "25178",
"Score": "0",
"body": "That would work perfectly, but because of the generics involved with the Add and Parse it fails. Dim foo as ProductsBase(Of ?) Setting the productbase in the if will break the cast."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-11T15:58:02.317",
"Id": "25182",
"Score": "0",
"body": "ahh, so the (of [classname]) is a generic :) Like I said, not a VB.Net guy"
}
] |
[
{
"body": "<p>I would agree that defining pb as an object is a code smell and should be eliminated. </p>\n\n<p>Either in addition or instead of having Cars and Trucks inherit from ProductsBase(of T) it should implement an interface. </p>\n\n<p>Suggested Interface:</p>\n\n<pre><code>Public Interface IProducts\n\n Sub DeleteRows()\n Sub Parse()\n\nEnd Interface\n</code></pre>\n\n<p>Then you would declare pb as IProducts. Add any other public properties that will be used by all the derived classes of ProductsBase. </p>\n\n<p>I'd also suggest creating a class or modules that contains factory methods to generate the new objects. </p>\n\n<p>Suggested Factory Class: </p>\n\n<pre><code>Public Class ProductsFactory\n\n Public Shared Function CreateTruck(fileLocation as string) As IProducts\n Return New Truck(fileLocation)\n End Function\n\n Public Shared Function CreateCar(fileLocation as string) As IProducts\n Return New Car(fileLocation)\n End Function\n\nEnd Class\n</code></pre>\n\n<p>The final code would look like this:</p>\n\n<pre><code> Dim pb As IProducts \n\n If radCars.Checked = True Then \n pb = ProductsFactory.CreateCar(fileLocation)\n ElseIf radTrucks.Checked = True Then\n pb = ProductsFactory.CreateTruck(fileLocation)\n End If\n\n pb.Parse()\n pb.AddRows()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-11T02:41:53.953",
"Id": "25148",
"Score": "0",
"body": "Why don't you move the if statement inside the factory class? Then you could have 1 Create method that returns an IProducts."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-11T05:20:58.530",
"Id": "25156",
"Score": "0",
"body": "I agree. Set the `Tag` property of each checkbox to the implementation name and call `ProductsFactory.Create(selectedCheckbox.Tag)`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-11T23:22:57.137",
"Id": "25201",
"Score": "0",
"body": "I would agree with the use of selectedcheckbox.tag in most cases and moving the if statement into a single create function. I was mostly being lazy. I didn't want to write out the extra code required to do so. \nJust make sure the value stored in .Tag isn't a string. Using a string to tell a factory method what to create is almost always a bad idea."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-10T21:46:10.233",
"Id": "15502",
"ParentId": "15489",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "15502",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-10T16:41:57.553",
"Id": "15489",
"Score": "3",
"Tags": [
".net",
"object-oriented",
"design-patterns",
"vb.net",
"generics"
],
"Title": "OOP: Need tips of my approach in .Net"
}
|
15489
|
<p>I just wanted to gather your opinion on my little JavaScript library. It features <code>Math</code>, <code>String</code>, <code>Array</code>, <code>canvas</code> and <code>location</code> extensions, as well as some useful animation and timing classes I came up with:</p>
<pre><code>/* ====================== */
/* ======= Math ========= */
/* ====================== */
// Random number
Math.rand = function(min, max, float) {
var random = Math.random() * (max-min) + min;
return float ? random : Math.round(random);
};
// Random number with seed (not fully functional)
Math.srand = function(seed, min, max, float) {
var code = 0;
for (var i = 0, l = seed.length; i < l; i++) { code += seed.charCodeAt(i); }
while (code > 1) { code/= 10; }
var mod = code;
var MAX_INT = Math.pow(2,32) - 1;
var min = min != null ? min : -MAX_INT;
var max = max != null ? max : MAX_INT;
var random = mod * (max-min) + min;
return float ? random : Math.round(random);
};
// 3.141592653589793 -> 180°
Math.toDegrees = function(angle) {
return angle * (180 / Math.PI);
};
// 180° -> 3.141592653589793
Math.toRadians = function(angle) {
return angle * (Math.PI / 180);
};
/* ====================== */
/* ======= String ======= */
/* ====================== */
// string -> String
String.prototype.capitalize = function() {
return this.charAt(0).toUpperCase() + this.slice(1);
};
// "test".charAt(2, "oa") -> "toast"
String.prototype.charAt = function(index, replacement) {
if (replacement == null) { return this.substr(index, 1); }
else { return this.substr(0, index-1) + replacement + this.substr(index); }
};
/* ====================== */
/* ======= Array ======== */
/* ====================== */
// Compares values to an array object and returns the index
Array.prototype.compare = function(values) {
for (var i = 0, l = this.length; i < l; i++) {
var matches = [];
for (var ii = 0, ll = values.length; ii < ll; ii++) {
if (this[i][values[ii][0]] == values[ii][1]) { matches.push(true); }
}
if (matches.length == values.length) { return i; }
}
};
// Reaplces values in a numeric array
Array.prototype.replace = function(a, b) {
for (var i = 0, l = this.length; i < l; i++) {
if (this[i] == a) { this[i] = b; }
}
};
/* ====================== */
/* ======= Animation ==== */
/* ====================== */
// An advanced interval class which also calculates delta and fps
var Loop = function(callback, fps) {
var _this = this;
this.fps = fps ? fps : 60;
this.real_fps = null;
this.delta = 1;
this.lastTime = +new Date;
this.request = null;
this.callback = callback;
this.setFPS = function(fps) { this.fps = fps; };
this.start = function() {
// Timeout is used to specify a framerate
this.request = setTimeout(function() {
requestAnimFrame(function() {
_this.start();
_this.delta = (+new Date - _this.lastTime) / (1000 / _this.fps);
_this.real_fps = Math.round((1 + (1-_this.delta))*_this.fps);
_this.callback();
_this.lastTime = +new Date;
});
}, 1000 / this.fps);
};
this.stop = function() {
clearTimeout(this.request);
};
};
// An advanced timeout class which also calculates the current progress
var Ticker = function(start, duration, callback) {
var _this = this;
this.start = start;
this.duration = duration;
// TODO easing options
this.reverse = false;
this.auto_reset = false;
this.auto_reverse = false;
this.callback = callback ? callback : null;
this.timeout = callback ? setTimeout(function() {
_this.callback();
if (_this.auto_reset || _this.auto_reverse) { _this.reset(); }
}, this.duration) : null;
this.status = function() {
var end = this.start + this.duration;
var current = +new Date;
var duration = end - this.start;
var difference = current - this.start;
var progress = this.reverse ? 1 - (difference / duration) : (difference / duration);
if (current >= end) { progress = this.reverse ? 0 : 1; }
return progress;
};
this.reset = function() {
if (this.auto_reverse) { this.reverse = this.reverse ? false : true; }
this.timeout = this.callback ? setTimeout(function() {
_this.callback();
if (_this.auto_reset || _this.auto_reverse) { _this.reset(); }
}, this.duration) : null;
this.start = +new Date;
};
};
// Unifies the HTML5 requestAnimationFrame function
window.requestAnimFrame = (function() {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback) { window.setTimeout(callback, 1000 / 60); };
})();
/* ====================== */
/* ======= Canvas ======= */
/* ====================== */
CanvasRenderingContext2D.prototype.center = function() {
return {
x: Math.round(this.canvas.width / 2),
y: Math.round(this.canvas.height / 2)
};
};
// Extends the canvas fillRect function to be able to draw round corners
CanvasRenderingContext2D.prototype.fillRect = function(x, y, w, h, r1, r2, r3, r4) {
if (r1 == null) {
this.beginPath();
this.moveTo(x, y);
this.lineTo(x + w, y);
this.lineTo(x + w, y + h);
this.lineTo(x, y + h);
this.closePath();
this.fill();
} else {
var r2 = r2 == null ? r1 : r2;
var r3 = r3 == null ? r1 : r3;
var r4 = r4 == null ? r2 : r4;
r4 = r4 == null ? r1 : r4;
this.beginPath();
this.moveTo(x, y + r1);
this.quadraticCurveTo(x, y, x + r1, y);
this.lineTo(x + w - r2, y);
this.quadraticCurveTo(x + w, y, x + w, y + r2);
this.lineTo(x + w, y + h - r3);
this.quadraticCurveTo(x + w, y + h, x + w - r3, y + h);
this.lineTo(x + r4, y + h);
this.quadraticCurveTo(x, y + h, x, y + h - r4);
this.closePath();
this.fill();
}
};
// Extends the canvas strokeRect function to be able to draw round corners
CanvasRenderingContext2D.prototype.strokeRect = function(x, y, w, h, r1, r2, r3, r4) {
if (r1 == null) {
this.beginPath();
this.moveTo(x, y);
this.lineTo(x + w, y);
this.lineTo(x + w, y + h);
this.lineTo(x, y + h);
this.closePath();
this.stroke();
} else {
var r2 = r2 == null ? r1 : r2;
var r3 = r3 == null ? r1 : r3;
var r4 = r4 == null ? r2 : r4;
r4 = r4 == null ? r1 : r4;
this.beginPath();
this.moveTo(x, y + r1);
this.quadraticCurveTo(x, y, x + r1, y);
this.lineTo(x + w - r2, y);
this.quadraticCurveTo(x + w, y, x + w, y + r2);
this.lineTo(x + w, y + h - r3);
this.quadraticCurveTo(x + w, y + h, x + w - r3, y + h);
this.lineTo(x + r4, y + h);
this.quadraticCurveTo(x, y + h, x, y + h - r4);
this.closePath();
this.stroke();
}
};
/* ====================== */
/* ======= Document ===== */
/* ====================== */
// Simple cookie handling object
var Cookie = {
set: function(name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name + "=" + value + expires + "; path=" + location.pathname;
},
unset: function(name) { Cookie.set(name, "", -1); },
get: function(name) {
var search = new RegExp(name + "=([^;]*);");
var result = search.exec(document.cookie);
return result ? result[1] : null;
}
};
// Returns the value of the specified GET parameter (equivalent to PHP's $_GET[name])
location.get = function(name) {
var search = new RegExp(encodeURIComponent(name) + "=([^&]*)&?");
var result = search.exec(location.search);
return result ? result[1] : null;
};
function include(file) {
var dir = document.getElementsByTagName("script")[0].getAttribute("src").match(/([\w_-]+)\/[\w_-]+\.js/)[1];
var script = document.createElement("script");
script.setAttribute("src", dir + "/" + file);
document.getElementsByTagName("head")[0].appendChild(script);
}
function createRequestObject() {
var request, browser = navigator.appName;
if (browser == "Microsoft Internet Explorer")
{ request = new ActiveXObject("Microsoft.XMLHTTP"); }
else
{ request = new XMLHttpRequest(); }
return request;
}
</code></pre>
|
[] |
[
{
"body": "<p>Here are some tips.</p>\n\n<h1>1)</h1>\n\n<p>Avoid using java keywords. In Math.rand, there is a variable called <code>float</code>.\nTry calling it <code>toFloat</code>.</p>\n\n<h1>2)</h1>\n\n<p>It's best not to browser sniff. Detect for features instead.</p>\n\n<p>Old Code:</p>\n\n<pre><code>function createRequestObject() {\n\n var request, browser = navigator.appName;\n\n if (browser == \"Microsoft Internet Explorer\")\n { request = new ActiveXObject(\"Microsoft.XMLHTTP\"); }\n else\n { request = new XMLHttpRequest(); }\n\n return request;\n}\n</code></pre>\n\n<p>New Code:</p>\n\n<pre><code>function createRequestObject() {\n var request;\n if (ActiveXObject) {\n request = new ActiveXObject(\"Microsoft.XMLHTTP\");\n } else {\n request = new XMLHttpRequest();\n }\n return request;\n}\n</code></pre>\n\n<h1>3)</h1>\n\n<p>Try not to repeat yourself.</p>\n\n<p>Old Code:</p>\n\n<pre><code>CanvasRenderingContext2D.prototype.strokeRect = function(x, y, w, h, r1, r2, r3, r4) {\n if (r1 == null) { \n this.beginPath();\n //...\n this.closePath();\n this.stroke();\n } else {\n //...\n this.beginPath();\n //...\n this.closePath();\n this.stroke();\n }\n};\n</code></pre>\n\n<p>New Code:</p>\n\n<pre><code>CanvasRenderingContext2D.prototype.strokeRect = function(x, y, w, h, r1, r2, r3, r4) {\n this.beginPath();\n if (r1 == null) { \n this.moveTo(x, y);\n //...\n } else {\n //...\n }\n this.closePath();\n this.stroke();\n};\n</code></pre>\n\n<h1>4)</h1>\n\n<p>Make functions as small as possible. Try adding functions to the prototype instead of creating them inside the constructor.</p>\n\n<p>Old Code:</p>\n\n<pre><code>var Loop = function(callback, fps) {\n// ...\n this.start = function() {\n\n // Timeout is used to specify a framerate\n this.request = setTimeout(function() {\n requestAnimFrame(function() {\n _this.start();\n _this.delta = (+new Date - _this.lastTime) / (1000 / _this.fps);\n _this.real_fps = Math.round((1 + (1-_this.delta))*_this.fps);\n _this.callback();\n _this.lastTime = +new Date;\n });\n }, 1000 / this.fps);\n };\n\n//...\n};\n</code></pre>\n\n<p>New Code:</p>\n\n<pre><code>Loop.prototype.start = function () {\n // Timeout is used to specify a framerate\n var _this = this;\n this.request = setTimeout(function () {\n requestAnimFrame(function () {\n _this.start();\n _this.delta = (+new Date() - _this.lastTime) / (1000 / _this.fps);\n _this.real_fps = Math.round((1 + (1 - _this.delta)) * _this.fps);\n _this.callback();\n _this.lastTime = +new Date();\n });\n }, 1000 / this.fps);\n};\n</code></pre>\n\n<h1>5)</h1>\n\n<p>Rename <code>String.prototype.charAt</code> to <code>String.prototype.replaceByIndex</code></p>\n\n<h1>6)</h1>\n\n<p><code>this.fps = fps ? fps : 60;</code> is the same as <code>this.fps = fps || 60;</code> </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-11T09:12:14.273",
"Id": "25164",
"Score": "0",
"body": "Thanks a bunch! One question though: In the prototype example, how do I create the necessary reference `_this` used to have ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-11T14:36:52.700",
"Id": "25179",
"Score": "0",
"body": "@elias94xx Create a reference outside the function to `this` called `_this`. Refer to the updated code example."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-11T14:51:52.680",
"Id": "25181",
"Score": "0",
"body": "Oh of course, got confused a little. :)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-10T20:35:52.163",
"Id": "15498",
"ParentId": "15492",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "15498",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-10T17:28:49.500",
"Id": "15492",
"Score": "6",
"Tags": [
"javascript",
"library"
],
"Title": "JavaScript library for Math, String, Array, canvas and location extensions"
}
|
15492
|
<p>I have a library that accepts a file-like object but assumes that it has a valid <code>.name</code> unless that name is <code>None</code>. This causes it to break when I pass e.g. <code>someproc.stdout</code> as it has a name of <code><fdopen></code>. Unfortunately the attribute cannot be deleted or overwritten.</p>
<p>So I've written this simple wrapper to return <code>None</code> in case the <code>name</code> attribute is requested.</p>
<pre><code>class InterceptAttrWrapper(object):
def __init__(self, obj, attr, value):
self.obj = obj
self.attr = attr
self.value = value
def __getattribute__(self, name):
ga = lambda attr: object.__getattribute__(self, attr)
if name == ga('attr'):
return ga('value')
return getattr(ga('obj'), name)
</code></pre>
<p>This seems to work fine, I'm using it like this: </p>
<pre><code>proc = subprocess.Popen(..., stdout=subprocess.PIPE)
some_func(InterceptAttrWrapper(proc.stdout, 'name', None))
</code></pre>
<p>However, I wonder if:</p>
<ul>
<li>My <code>InterceptAttrWrapper</code> object is missing something that could cause problems.</li>
<li>There is a better way to access attributes within <code>__getattribute__</code>. That lambda I'm using right now looks pretty ugly.</li>
</ul>
|
[] |
[
{
"body": "<p>Something to watch out for with your approach is that Python calls certain special methods without looking them up via <code>__getattribute__</code>. For example, the <code>__iter__</code> method:</p>\n\n<pre><code>>>> w = InterceptAttrWrapper(open('test'), 'attr', 'value')\n>>> for line in w: print line\n... \nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nTypeError: 'InterceptAttrWrapper' object is not iterable\n</code></pre>\n\n<p>See the documentation on \"<a href=\"http://docs.python.org/reference/datamodel.html#new-style-special-lookup\" rel=\"nofollow\">Special method lookup for new-style classes</a>\". If this affects you, then you'll need to add to your wrapper class all the special methods that you need to support (in my example, <code>__iter__</code>, but when wrapping other objects one might need to implement <code>__getitem__</code>, <code>__repr__</code>, <code>__hash__</code>, or others).</p>\n\n<p>Here's a slightly more readable way to get at the wrapper object's own data, together with support for intercepting multiple attributes:</p>\n\n<pre><code>class InterceptAttrWrapper(object):\n \"\"\"\n Wrap an object and override some of its attributes.\n\n >>> import sys\n >>> stdin = InterceptAttrWrapper(sys.stdin, name = 'input')\n >>> stdin.mode # Pass through to original object.\n 'r'\n >>> stdin.name # Intercept attribute and substitute value.\n 'input'\n \"\"\"\n def __init__(self, obj, **attrs):\n self._data = obj, attrs\n\n def __getattribute__(self, name):\n obj, attrs = object.__getattribute__(self, '_data')\n try:\n return attrs[name]\n except KeyError:\n return getattr(obj, name)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-25T16:59:31.127",
"Id": "15917",
"ParentId": "15494",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-10T18:33:34.687",
"Id": "15494",
"Score": "6",
"Tags": [
"python"
],
"Title": "Intercept read access to a certain object attribute"
}
|
15494
|
<p>Only current and next element (<code>cNum</code>) is to be shown; in case it is the last element in the structure - the first element should be shown.</p>
<pre><code>var childNum = $('#h').roundabout("getChildInFocus");
var cNum = (Number(childNum)) + 2;
if (cNum == 5) cNum = 1;
$("#h li").hide();
$("#h li:nth-child(" + cNum + ")").show();
if (cNum == 4) {
$("#h li:nth-child(1)").show();
} else {
$("#h li:nth-child(" + (Number(cNum) + 1).toString() + ")").show();
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-10T19:27:35.837",
"Id": "25114",
"Score": "1",
"body": "What is cNum used for? It's really confusing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-21T14:09:42.307",
"Id": "25725",
"Score": "0",
"body": "Welcome to Code Review! With a jsFiddle or live html page, you would get more answers. :)"
}
] |
[
{
"body": "<p>Here are a few tips.</p>\n\n<h2>1)</h2>\n\n<p><code>childNum</code> is not needed since it's only used once.</p>\n\n<p>Old Code:</p>\n\n<pre><code>var childNum = $('#h').roundabout(\"getChildInFocus\");\nvar cNum = (Number(childNum)) + 2;\n</code></pre>\n\n<p>New Code: </p>\n\n<pre><code>var cNum = $('#h').roundabout(\"getChildInFocus\") + 2;\n</code></pre>\n\n<h2>2)</h2>\n\n<p>In general, adding a object to a string results in a string.\nAnd adding a object to a number results in a number.\nUse parentheses to make the conversion clear.</p>\n\n<p>Old Code:</p>\n\n<pre><code>$(\"#h li:nth-child(\" + (Number(cNum) + 1).toString() + \")\").show();\n</code></pre>\n\n<p>New Code:</p>\n\n<pre><code>$(\"#h li:nth-child(\" + (1 + cNum) + \")\").show(); \n</code></pre>\n\n<h2>3)</h2>\n\n<p>Cache commonly referenced elements.\nOld Code:</p>\n\n<pre><code>$(\"#h li:nth-child(\" + cNum + \")\").show();\n</code></pre>\n\n<p>New Code:</p>\n\n<pre><code>var $lis = $(\"#h li\");\n$lis.find(\":nth-child(\" + cNum + \")\").show();\n</code></pre>\n\n<h2>4)</h2>\n\n<p>Combine operations on selectors.\nOld Code:</p>\n\n<pre><code>$(\"#h li\").hide();\n$(\"#h li:nth-child(\" + cNum + \")\").show();\n</code></pre>\n\n<p>New Code:</p>\n\n<pre><code>$(\"#h li\").hide().find(\":nth-child(\" + cNum + \")\").show();\n</code></pre>\n\n<h2>5)</h2>\n\n<p>Resetting the value of <code>cNum</code> to get rid of the else condition gives the following.</p>\n\n<p>Old Code:</p>\n\n<pre><code>if (cNum == 4) {\n $(\"#h li:nth-child(1)\").show();\n} else {\n $(\"#h li:nth-child(\" + (1+cNum) + \")\").show();\n}\n</code></pre>\n\n<p>New Code 1:</p>\n\n<pre><code>if (cNum == 4) {\n cNum = 0;\n} \n$(\"#h li:nth-child(\" + (1+cNum) + \")\").show();\n</code></pre>\n\n<p>New Code 2:</p>\n\n<pre><code>if (cNum == 5) {\n cNum = 1;\n} \n$(\"#h li:nth-child(\" + cNum + \")\").show(); \n</code></pre>\n\n<p>As you can see <code>New Code 2</code> is the same from the new code in tip 4. \nSo you can delete this redundant code.</p>\n\n<h2>Final Code:</h2>\n\n<pre><code>var cNum = 2 + $('#h').roundabout(\"getChildInFocus\");\nif (cNum == 5){\n cNum = 1;\n}\n$(\"#h li\").hide().find(\":nth-child(\" + cNum + \")\").show();\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-10T19:55:41.760",
"Id": "15497",
"ParentId": "15495",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "15497",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-10T18:35:02.580",
"Id": "15495",
"Score": "3",
"Tags": [
"javascript",
"jquery"
],
"Title": "Hiding all list items except the current and next element"
}
|
15495
|
<p>I've finally gotten around to learning Lisp/functional programming. However, what I've noticed is that I'm trying to bring ideas back into JavaScript.</p>
<h1>Example</h1>
<h2>Before</h2>
<pre><code>var myPlacemark,
myLineString;
myLineString = ge.createLineString('');
myLineString.setLatitude(100);
myLineString.setLongitude(-100);
myPlacemark = ge.createPlacemark('');
myPlacemark.setGeometry(placemark);
</code></pre>
<h2>After</h2>
<pre><code>var myPlacemark;
myPlacemark = (function(point, placemark){
point.setLatitude(100);
point.setLongitude(-100);
placemark.setGeometry(point);
return placemark;
})(ge.createPoint(''), ge.createPlacemark(''));
</code></pre>
<p>Is there any reason I shoudn't be doing it the 2nd way?</p>
|
[] |
[
{
"body": "<p>While using a closure to prevent polluting the global namespace is a good idea, you shouldn't be passing in random data like that. The way you are doing it, you are forcing the reader to scroll to the bottom of the function call before reading the function body - that's just plain confusing for no good reason.</p>\n\n<p>Instead, declare the variables regularly within the closure, and assign their values right then and there. That way, it's much easier to read (and maintain), while still keeping the global namespace intact.</p>\n\n<hr>\n\n<p>In addition, Crockford suggests that you put the calling parentheses inside the wrapping parenthesis.</p>\n\n<hr>\n\n<p>With all that in mind, here's your code, refactored:</p>\n\n<pre><code>var myPlacemark = (function() {\n\n var point = ge.createPoint(''),\n placemark = ge.createPlacemark('');\n\n point.setLatitude(100);\n point.setLongitude(-100);\n\n placemark.setGeometry(point);\n\n return placemark;\n\n}());\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-21T09:55:11.913",
"Id": "25701",
"Score": "0",
"body": "Plus this would finally become a real **closure**, not just a function object, since it closes over the `ge` from the outer scope. Strangely enough, this namespace pollution prevention is **easier in java** using simple **nested block** `{}`, since it creates a sub-scope – in **javascript** it doesn't."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-11T00:59:44.193",
"Id": "15508",
"ParentId": "15496",
"Score": "4"
}
},
{
"body": "<p>What you have there is actually just a fancy assignment operation. The closure there plays no role. And if you would need to set another placemark, you would have to repeat the code or wrap in one more function.</p>\n\n<p>IMHO, it would be much more pragmatic to use a lot simpler approach:</p>\n\n<pre><code>var createPlacemark = function (point, placemark) {\n point.setLatitude(100);\n point.setLongitude(-100);\n placemark.setGeometry(point);\n return placemark;\n },\n myPlacemark = createPlacemark(ge.createPoint(''), ge.createPlacemark(''));\n</code></pre>\n\n<p>This way you get reusable routine with a clear name. And if goal of this all was to prevent external sources from adding placemarks, just warp it all in the standard:</p>\n\n<pre><code>(function () {\n\n}());\n</code></pre>\n\n<p>The bottom line is: <strong>you were over-thinking it</strong>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-11T04:21:11.320",
"Id": "25154",
"Score": "0",
"body": "I'm aware that it's not exactly helping my code readability. My question was more so regarding the performance penalties that might result from going 'closure crazy'."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-11T04:38:36.660",
"Id": "25155",
"Score": "0",
"body": "In your example there would be no performance penalty. The processing costs for closures are negligible. What you have to worry about sometimes is the memory leaks. You can end up binding variables with large amount of data (common mistake in dealing with XHR), which is never garbage-collected. But that does not seem possible in your situation."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-11T20:50:49.647",
"Id": "25192",
"Score": "0",
"body": "I tend to agree with what you're saying @teresko, except for 1 thing: if the OP doesn't wrap the lot in a function, there is one more global being created in the first version, and that's one too many IMO"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-11T21:12:12.243",
"Id": "25194",
"Score": "0",
"body": "If you are referring to `createPlacemark`, then it is just a different way of defining function. But if you are talking about `myPlacemark` not having `var` in front of it, then you missed the comma in previous line. Basically, I do not get what you meant with the \"one more global\"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-12T03:06:45.213",
"Id": "25204",
"Score": "0",
"body": "@tereško The scope of `myLineString` is global. The scope of `point` is the function. So in the second example the global variable `myLineString` doesn't exist."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-11T02:02:32.203",
"Id": "15509",
"ParentId": "15496",
"Score": "13"
}
},
{
"body": "<p>It would be a real closure only if you had done one of the following:</p>\n\n<pre><code>function createPlacemark(placemark, point, latitude, longitude) {\n point.setLatitude(latitude);\n point.setLongitude(longitude);\n placemark.setGeometry(point);\n return placemark;\n}\n\nfunction closure1(point, placemark) {\n return function(latitude, longitude) {\n return createPlacemark(placemark, point, latitude, longitude);\n };\n}\n\nfunction closure2(latitude, longitude) {\n return function(point, placemark) {\n return createPlacemark(placemark, point, latitude, longitude);\n };\n}\n\nvar myPlacemark1 = closure1(ge.createPoint(''), ge.createPlacemark(''))(100, 100);\nvar myPlacemark2 = closure2(100, 100)(ge.createPoint(''), ge.createPlacemark(''));\n</code></pre>\n\n<p>i.e. capture context variables in a closure. A function object is not necessarily a closure.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-11T17:34:33.913",
"Id": "15525",
"ParentId": "15496",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "15509",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-10T19:47:16.603",
"Id": "15496",
"Score": "7",
"Tags": [
"javascript",
"functional-programming"
],
"Title": "Overusing JavaScript closures?"
}
|
15496
|
<p>I got the solution for the question asked <a href="https://stackoverflow.com/questions/12286998/uiviewcontroller-do-not-rotate-to-landscape">here</a>, but I don't like how the code is written.</p>
<p>This part of the code rotates the screen if it's in landscape and sets the size to match the screen. I don't like the <code>if</code> and the 7x <code>else if</code>. Can you suggest something more readable? Something like <code>(appOrientation - fromInterfaceOrientation) == 2</code> than <code>angle (M_PI / 2.0)</code>? </p>
<pre><code>- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
UIInterfaceOrientation appOrientation = [UIApplication sharedApplication].statusBarOrientation;
float width = self.view.bounds.size.width;
float height = self.view.bounds.size.height;
//NSLog(@"width %3.0f, height: %3.0f", width, height);
// UIInterfaceOrientationPortrait = UIDeviceOrientationPortrait,
// UIInterfaceOrientationPortraitUpsideDown = UIDeviceOrientationPortraitUpsideDown,
// UIInterfaceOrientationLandscapeLeft = UIDeviceOrientationLandscapeRight,
// UIInterfaceOrientationLandscapeRight = UIDeviceOrientationLandscapeLeft
CGFloat angle = 0;
// rotate from Portait
if((fromInterfaceOrientation == UIInterfaceOrientationPortrait) && (appOrientation == UIInterfaceOrientationLandscapeLeft)){
angle = -(M_PI / 2.0);
}
else if((fromInterfaceOrientation == UIInterfaceOrientationPortrait) && (appOrientation == UIInterfaceOrientationLandscapeRight)){
angle = (M_PI / 2.0);
}
// rotate from PortraitUpsideDown
else if((fromInterfaceOrientation == UIInterfaceOrientationPortraitUpsideDown) && (appOrientation == UIInterfaceOrientationLandscapeLeft)){
angle = (M_PI / 2.0);
}
else if((fromInterfaceOrientation == UIInterfaceOrientationPortraitUpsideDown) && (appOrientation == UIInterfaceOrientationLandscapeRight)){
angle = -(M_PI / 2.0);
}
//rotate from Landscape:
else if((fromInterfaceOrientation == UIInterfaceOrientationLandscapeLeft) && (appOrientation == UIInterfaceOrientationPortrait)){
// search for exactly the inverse...
}
// must be something more elgant code
CGAffineTransform transform = self.view.transform;
transform = CGAffineTransformRotate(transform, angle);
self.view.transform = transform;
[self.view setBounds:CGRectMake(0, 0, height, width)];
</code></pre>
|
[] |
[
{
"body": "<p>I think that you can rewrite the code in a more OO way, with the help of an <a href=\"https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSDictionary_Class/Reference/Reference.html#//apple_ref/occ/cl/NSDictionary\" rel=\"nofollow\">NSDictionary</a> and setting up a sort of command pattern.</p>\n\n<p>You can store a sum of the two enumerator value as a key of the Dictionary in this way : </p>\n\n<pre><code>NSDictionary *dicAngles = [[NSDictionary alloc] initWithObjectsAndKeys: \n (UIInterfaceOrientationPortrait + UIInterfaceOrientationLandscapeLeft), -(M_PI / 2.0), (UIInterfaceOrientationPortrait + UIInterfaceOrientationLandscapeRight), (M_PI / 2.0), \n(UIInterfaceOrientationPortraitUpsideDown + UIInterfaceOrientationLandscapeLeft), (M_PI / 2.0), \n(UIInterfaceOrientationPortraitUpsideDown + UIInterfaceOrientationLandscapeRight), -(M_PI / 2.0),\n nil];\n</code></pre>\n\n<p>Once you have the dictionary you can avoid the if - else control flow in this way : </p>\n\n<pre><code> CGFloat angle = 0;\n //Retrieve the angle from the dictionary \n angle = [dicAngles objectForKey: ( fromInterfaceOrientation + appOrientation )];\n</code></pre>\n\n<p>It is only an example and <strong>not tested</strong>, but could be a more elegant solution i think ...</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-10T14:10:44.737",
"Id": "25121",
"Score": "0",
"body": "How are you storing using a `float` as a key - an `NSDictionary` requires an object that implements `NSCopying` which I'm pretty sure a `float` doesn't!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-10T14:13:52.030",
"Id": "25122",
"Score": "0",
"body": "You can wrap it in an Object, it's only an untested example as stated in the answer, but could give an idea of a possible way to avoid the if ..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-11T09:00:27.167",
"Id": "25162",
"Score": "0",
"body": "This is very error-prone solution. Not readable at all."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-10T14:05:26.340",
"Id": "15500",
"ParentId": "15499",
"Score": "1"
}
},
{
"body": "<pre><code>//Angle of every orientation\ndouble orientationAngles[] = {\n orientationAngles[UIDeviceOrientationPortrait] = 0.0,\n orientationAngles[UIDeviceOrientationLandscapeLeft] = (M_PI / 2.0),\n orientationAngles[UIDeviceOrientationPortraitUpsideDown] = M_PI,\n orientationAngles[UIDeviceOrientationLandscapeRight] = -(M_PI / 2.0)\n};\n\n//What you want is the difference between adjancent angles\ndouble angle = orientationAngles[fromInterfaceOrientation] - orientationAngles[appOrientation];\n\n//Putting the result into the requested interval\nif (angle > M_PI / 2) {\n angle -= 2 * M_PI;\n}\nelse if (angle < - M_PI / 2) {\n angle += 2 * M_PI;\n}\n</code></pre>\n\n<p>Another possible solution, less math, more ifs.</p>\n\n<pre><code>UIDeviceOrientation orientations[] = {\n UIDeviceOrientationPortrait,\n UIDeviceOrientationLandscapeLeft,\n UIDeviceOrientationPortraitUpsideDown,\n UIDeviceOrientationLandscapeRight,\n};\n\nfor (int i = 0; i < 4; i++) {\n //UIDeviceOrientation previous = (i == 0) ? orientations[3] : orientations[i - 1];\n UIDeviceOrientation next = (i == 3) ? orientations[0] : orientations[i + 1];\n UIDeviceOrientation current = orientations[i];\n\n if (current == appOrientation) {\n if (fromInterfaceOrientation == next) {\n angle = (M_PI / 2.0);\n }\n else { //(fromInterfaceOrientation == previous)\n angle = -(M_PI / 2.0);\n }\n\n break;\n }\n}\n\n</code></pre>\n\n<p>As you can see, both solutions are using an array to hold the sequence of orientations. If you know the possible transitions, everything else is simple.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-11T08:57:54.457",
"Id": "15514",
"ParentId": "15499",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "15500",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-10T13:33:30.167",
"Id": "15499",
"Score": "4",
"Tags": [
"objective-c",
"image"
],
"Title": "Adjusting a landscape screen"
}
|
15499
|
<p>I have a third party component that I am trying to write unit tests around. The problem is that I can't mock the object and there is no interface. </p>
<p>I decided to create an interface and a wrapper class calling into the code for the sake of mocking. I looked into the class definition that is generated by Visual Studio using the meta data and noticed a few things:</p>
<ul>
<li>The class has two constructors (one takes a parameter)</li>
<li>The class inherits from <code>IDisposable</code></li>
</ul>
<p>My questions are:</p>
<ol>
<li>Does my implementation below look right?</li>
<li>Did I handle the <code>IDisposable</code> implementation correctly in the proxy class?</li>
<li>Do I need the second constructor in the proxy class since the interface does not support constructor definitions? I use dependency injection in my code and I assume unless I tell my DI framework to use the second constructor I don't really need it but I am not sure.</li>
</ol>
<p>The meta data looks like (slimmed down version):</p>
<pre><code>public class PopClient : IDisposable
{
public const int DefaultPort = 110;
public const int DefaultSSLPort = 995;
public PopClient();
public PopClient(AddressFamily addressFamily);
public bool HasTimeStamp { get; }
public List<string> Capability();
public void Connect(string host);
protected override void GetServerGreeting();
}
</code></pre>
<p>Based on the meta data, my interface looks like (after removing methods/properties/access modifiers that are invalid in an interface definition):</p>
<pre><code>public interface IPopClient : IDisposable
{
bool HasTimeStamp { get; }
List<string> Capability();
void Connect(string host);
void ConnectSSL(string host);
}
</code></pre>
<p>Based on the interface, I then created the wrapper class:</p>
<pre><code>public class PopClientProxy : IPopClient
{
private readonly Pop3 pop3;
public PopClientProxy()
this.pop3 = new Pop3();
public PopClientProxy(AddressFamily addressFamily)
this.pop3 = new Pop3(addressFamily);
public bool HasTimeStamp
get { return pop3.HasTimeStamp; }
public List<string> Capability()
return pop3.Capability();
public void Connect(string host)
pop3.Connect(host);
public void Dispose()
{
if (pop3 != null)
pop3.Dispose();
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Congratulations! You have successfully utilized the object-oriented design pattern known as the <a href=\"https://en.wikipedia.org/wiki/Adapter_pattern\">Adapter Pattern</a>. I think that looks perfectly good. Though, I wouldn't check <code>pop3</code> for <code>null</code> in the <code>Dispose()</code> method as it will be guaranteed to not be null by the constructors and the <code>readonly</code> field modifier:</p>\n\n<pre><code>public void Dispose()\n{\n pop3.Dispose();\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T23:13:09.757",
"Id": "66580",
"Score": "0",
"body": "I'm by no means an expert about `IDisposable`, but isn't there a risk that the thread gets aborted while the constructor runs, and the object subsequently gets disposed by the garbage collector, in which case `pop3` may be `null` ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-20T23:54:14.687",
"Id": "66585",
"Score": "2",
"body": "If your constructor aborts, the constructor will throw an exception. `pop3` will either be picked up by the garbage collector or, if it were `null`, won't matter, because the `Dispose()` won't get called because the full `PopClient` object isn't created and is a null value (the `using` statement won't call `Dispose()` on a null object)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-10T21:50:20.777",
"Id": "15503",
"ParentId": "15501",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "15503",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-10T21:29:26.467",
"Id": "15501",
"Score": "9",
"Tags": [
"c#",
"unit-testing"
],
"Title": "Creating a wrapper class to use for mocking that uses IDisposable"
}
|
15501
|
<p>I really don't get why it has to take so much to make such a little function. Here's what I have.</p>
<pre><code>template <typename A, typename B> auto add(A a, B b) -> decltype(a + b) {
return a + b;
}
</code></pre>
<p>Is there a way to shrink this code while maintaining its ability to take different arguments? For a comparison, here is it in Python; there is a big difference between the two.</p>
<pre><code>def add(a, b):
return a + b
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-10T22:38:46.283",
"Id": "25127",
"Score": "3",
"body": "I think 3 lines is relatively short for a piece of code that supports all types that can be used with `operator +`. Without the declytype it would be infinitely long as you need to declare one for each combination."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-10T23:26:04.477",
"Id": "25129",
"Score": "3",
"body": "There is a lot of difference between the two. In C++ you will see an error at compile time. In python you will not see the problem until it tries to execute the line. You pay for the convenience (and speed of C++)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-11T06:53:50.363",
"Id": "25160",
"Score": "0",
"body": "@Loki While all of that is true, none of that justifies the verbosity. It *could* be made much terser (and maybe the next version will actually support this)."
}
] |
[
{
"body": "<p>You may want to take a look at <a href=\"http://pfultz2.github.com/Pythy/\" rel=\"nofollow\">Pythy</a>. </p>\n\n<p>What you want seems a lot like:</p>\n\n<pre><code>PYTHY(add, x, y) (\n return x + y;\n)\n</code></pre>\n\n<p>Make sure to read this part of the article, as pointed out by Konrad:</p>\n\n<blockquote>\n <p>It appears that we are derefencing a null pointer. Remember in C++\n when dereferencing a null pointer, undefined behavior occurs when\n there is an rvalue-to-lvalue conversion. However, since a\n non-capturing lambda closure is almost always implemented as an object\n with no members, undefined behavior never occurs, since it won't\n access any of its members. Its highly unlikely that a non-capturing\n lambda closure could be implemented another way since it must be\n convertible to a function pointer. But perhaps not?</p>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-11T06:50:10.320",
"Id": "25159",
"Score": "0",
"body": "Indeed – but why not add a short example inline here? (And maybe mention the caveat, buried deep below in the blog post, that this is UB.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-11T16:19:16.117",
"Id": "25184",
"Score": "0",
"body": "Thanks for reminding me of that bit; I had read it thought \"sounds reasonable\", and entirely forgotten. :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-11T06:11:14.100",
"Id": "15511",
"ParentId": "15504",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "15511",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-10T22:22:15.213",
"Id": "15504",
"Score": "4",
"Tags": [
"c++"
],
"Title": "How do I make this simple addition code less verbose?"
}
|
15504
|
<p>I got some homework in which I had to take the novel War and Peace and put it into a HashSet and TreeSet respectively. I had to time it, to check differences and my question is whether my implementation is good or not.
If the way I calculate time is even accurate. I am using</p>
<pre><code>System.currentMillis()
</code></pre>
<p>but I was debating with myself whether</p>
<pre><code>System.nanoTime()
</code></pre>
<p>would be a better choice. I might just have misunderstood something about the assignment since this just seems way too easy to be the actual solution.</p>
<p>Just to clarify: The code works. I am questioning the efficiency of my implementation.</p>
<pre><code>package SetExercise;
import java.io.*;
import java.util.*;
public class FileToSet {
public static void main(String[] args) {
HashSet<String> hs = new HashSet<>();
TreeSet<String> ts = new TreeSet<>();
long start = System.currentTimeMillis();
fileToHashSet("war-and-peace.txt", hs);
long end = System.currentTimeMillis();
long elapsed = end - start;
System.out.println("Total time HashSet (ms): " + elapsed);
start = System.currentTimeMillis();
fileToTreeSet("war-and-peace.txt", ts);
end = System.currentTimeMillis();
elapsed = end - start;
System.out.println("Total time TreeSet (ms): " + elapsed);
}
static void fileToHashSet(String path, HashSet<String> set) {
try {
BufferedReader in = new BufferedReader(new FileReader(path));
while(in.readLine() != null) {
String line = in.readLine();
set.add(line);
}
in.close();
} catch(FileNotFoundException fnfe) {
System.out.println(fnfe.getMessage());
} catch(IOException ioe) {
System.out.println(ioe.getMessage());
}
}
static void fileToTreeSet(String path, TreeSet<String> set) {
try {
BufferedReader in = new BufferedReader(new FileReader(path));
while(in.readLine() != null) {
String line = in.readLine();
set.add(line);
}
in.close();
} catch(FileNotFoundException fnfe) {
System.out.println(fnfe.getMessage());
} catch(IOException ioe) {
System.out.println(ioe.getMessage());
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>To measure the time taken, you should use <a href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/System.html#nanoTime%28%29\"><code>System.nanoTime</code></a>. That should <em>only</em> be used for \"stopwatch\" type operations - never for taking the \"current system time\" in a wall-clock way. Conversely, <code>System.currentTimeMillis</code> should <em>not</em> be used for \"stopwatch\" type operations, as it can be affected by system clock changes etc.</p>\n\n<p>From the docs for <code>nanoTime</code>:</p>\n\n<blockquote>\n <p>This method can only be used to measure elapsed time and is not related to any other notion of system or wall-clock time. The value returned represents nanoseconds since some fixed but arbitrary origin time (perhaps in the future, so values may be negative). The same origin is used by all invocations of this method in an instance of a Java virtual machine; other virtual machine instances are likely to use a different origin.</p>\n</blockquote>\n\n<p>Note that the important point isn't the difference in granularity here - it's the difference in <em>purpose</em>. They could both be returning milliseconds, and it would still make sense to have two different calls.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-10T23:32:18.883",
"Id": "25132",
"Score": "0",
"body": "I see. Makes sense. So the way that I do it, is still correct though? Instead of using currentMillis() I should just use nanoTime()?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-10T23:34:02.470",
"Id": "25134",
"Score": "1",
"body": "@Vipar: Sort of - but you should do this in a loop, and take the file system out of the equation. Load the file into memory first, e.g. into a `List<String>`. Chances are with your current code, IO will form the bulk of the time."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-10T23:36:54.557",
"Id": "25135",
"Score": "0",
"body": "I think I have to load the file directly into either set though. Wouldn't first loading the file into a list then into a set, be kind of \"cheating\" if you had to check the time it took for either to successfully load a file into a set?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-10T23:38:37.613",
"Id": "25136",
"Score": "0",
"body": "@Vipar: You should measure the time to load the data from a file, basically. That's unless you want to run one test loading into a HashSet, then clear out the file system cache etc before loading it into a TreeSet..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-10T23:39:55.600",
"Id": "25137",
"Score": "0",
"body": "Would that have different results? If so, how would I go about clearing the cache before trying to add it to a treeset?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-10T23:44:26.577",
"Id": "25138",
"Score": "1",
"body": "@Vipar: It would entirely depend on the operating system, but basically it's a pain. But yes, it would have very different results from not clearing the cache. Try it - I expect you'll see that whichever kind of set you test first, that will have poorer performance (the first time you run it after boot, at least). You need to work out what you care about: IO, or set performance. The IO is likely to drown out the set performance."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-10T23:28:41.480",
"Id": "15506",
"ParentId": "15505",
"Score": "27"
}
},
{
"body": "<p>I'm afraid you aren't actually reading the entire file into either <code>Set</code>. In fact, you're quite lucky this code isn't throwing an <code>IOException</code>.</p>\n\n<blockquote>\n<pre><code>while(in.readLine() != null) {\n String line = in.readLine();\n set.add(line);\n}\n</code></pre>\n</blockquote>\n\n<p>This loop, present in both <code>fileToHashSet</code> and <code>fileToTreeSet</code>, is actually reading <em>two</em> lines every iteration. You're only placing every other line into either <code>Set</code>, which may or may not be significant. Try a loop like the below instead...</p>\n\n<pre><code>String line;\nwhile ((line = in.readLine()) != null) {\n set.add(line);\n}\n</code></pre>\n\n<hr>\n\n<p>Aside from that, I believe you should be timing <em>several</em> trials and averaging these to get a more resilient statistic. Otherwise, your results might be too influenced by other factors. Benchmark accuracy is important, right? As you have it now, you're potentially even giving an advantage to the second benchmark, since the first may require slower disk I/O, while the second might be benefit from the OS caching the file in memory.</p>\n\n<p>Other potential factors that may disadvantage the first are early VM initialization ocurring simultaneously, VM analysis \"priming\" the just-in-time compiler to allow better dynamic optimizations further along during the VM life, etc. </p>\n\n<hr>\n\n<p>And, lastly, a small notice... if you have two <code>catch</code> blocks that do identical work, only differing in exception type, I suggest you take advantage of one of the newer features of Java 7 -- <a href=\"http://docs.oracle.com/javase/tutorial/essential/exceptions/catch.html\" rel=\"nofollow\">catching multiple exception types</a>. In fact, you should probably also use the (also a recent addition) <a href=\"http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html\" rel=\"nofollow\"><em>try-with-resources</em></a></p>\n\n<pre><code>try (final BufferedReader in = new BufferedReader(new FileReader(path))) {\n String line;\n while ((line = in.readLine()) != null) {\n set.add(line);\n }\n} catch (final FileNotFoundException | IOException ex) {\n System.err.println(ex);\n}\n</code></pre>\n\n<p>Note you should probably not catch exceptions unless you actually plan to use them. Let them propagate out of <code>main</code>, where they will be printed to <code>System.err</code>, anyways.</p>\n\n<p>There's also no reason to have two separate methods here, either; both are <code>Set<String></code> -- why not make your method polymorphic?</p>\n\n<p>P.S. use <code>System.err</code> for printing error messages rather than <code>System.out</code>.</p>\n\n<p>P.P.S. I'll give an educated guess that <code>HashSet</code> will be faster than <code>TreeSet</code> by virtue of the underlying implementation... one necessitates a total order, after all.</p>\n\n<p>P.P.P.S. Listen to Jon and use <code>nanoTime</code> here :-)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-11T00:16:15.633",
"Id": "25139",
"Score": "0",
"body": "Thanks for your answer. Now that you mention it you are right, I probably never load the entire file x)\n\nThanks again!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-11T03:28:11.710",
"Id": "25150",
"Score": "0",
"body": "http://pastebin.com/30a6mTKC This is what I ended up with. The HashSet seems to win consistently with about 20 to 25 ms."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-11T03:32:27.587",
"Id": "25151",
"Score": "0",
"body": "@Vipar I wouldn't hold a reference to `cache`. Aside from that, you should be averaging over hundreds if not thousands of trials. You shouldn't keep summing `start` and `end` like that... just find the time before the iterations, compute the elapsed duration, and divide by 1,000 or how many iterations you expect to do. Aside from that, use `Set.clear` over initializing a new `Set` each iteration."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-11T03:40:28.577",
"Id": "25152",
"Score": "0",
"body": "here: http://pastebin.com/KbMqEdbi Would you say this is more accurate?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-11T04:03:38.157",
"Id": "25153",
"Score": "0",
"body": "@Vipar sure; [here](http://pastie.org/4699599) is my attempt."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-10T23:53:58.857",
"Id": "15507",
"ParentId": "15505",
"Score": "26"
}
},
{
"body": "<pre><code>final long[] tabTime = new long[6];\ntabTime[0] = System.nanoTime();\nSet<String> set;\n// Java 7 used, no need to have HashSet<String>(5000)\nset = new HashSet<>(5000); // numberOfLines\n// set = new TreeSet<>(5000); // numberOfLines\ntry {\n tabTime[1] = System.nanoTime();\n final BufferedReader in = new BufferedReader(new FileReader(\n System.getProperty(\"user.home\") + \"/WarAndPeace.txt\"));\n tabTime[2] = System.nanoTime();\n String s;\n while ((s = in.readLine()) != null) {\n set.add(s);\n }\n tabTime[3] = System.nanoTime();\n in.close();\n} catch (final FileNotFoundException fnfe) {\n System.out.println(fnfe.getMessage());\n} catch (final IOException ioe) {\n System.out.println(ioe.getMessage());\n}\ntabTime[4] = System.nanoTime();\nfinal Set treeSet = new TreeSet(set);\ntabTime[5] = System.nanoTime();\nfor (int i = 1, n = tabTime.length; i < n; i++) {\n System.out.format(\"%d.%d%n\", (tabTime[i] - tabTime[0]) / 1000000,\n (tabTime[i] - tabTime[0]) % 1000000);\n}\n</code></pre>\n\n<p>The test I've done show that putting <em>String s</em> outside the <em>while</em> is faster<br>\nBut Scanner, in this case, it very slow (but it is very powerful and useful for managing input)<br>\n<em>Hash</em> is naturally faster than <em>Tree</em>, above all if they are opened with good size, and you have to put outside the time scope the print to have real results</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-11T09:53:37.923",
"Id": "25166",
"Score": "4",
"body": "Just visually, this code looks chaotic and not readable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-11T12:10:36.070",
"Id": "25172",
"Score": "0",
"body": "@KonradRudolph it is the same than *Vipar* one with tool to trace time consumption. So he can play with `HashSet/TreeSet` and put the `String` in and out the `while` to look what's happen, no more. No intention to be verbose."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-11T07:06:47.733",
"Id": "15512",
"ParentId": "15505",
"Score": "2"
}
},
{
"body": "<p>If you want to test differences between <code>HashSet<E></code> and <code>TreeSet<E></code>, you should put <strong>all</strong> the other code out of the measured region — that includes any <strong>file I/O</strong>, <strong>stdout/stderr I/O</strong>, and possibly also <strong>set initialization</strong> (be it <code>new</code> or <code>clear()</code>) — to factor out the variability of interaction with OS and devices.</p>\n\n<p>The measured region should contain only a loop in which you add the <strong>preloaded</strong> data into the set. You should therefore load the file first and keep it in a memory construct, e.g. <code>String[]</code>.</p>\n\n<p>If you decide to include the set initialization in the measurement, don't use <code>clear()</code>. In a real-world scenario, the set is usually used only once, hence use <code>new</code>. This is specifically important in the case of \n<code>HashSet<E></code>, where additions of elements can result in extending the capacity of internal storage structure (a <code>HashMap<K,V></code>) once a <strong>load threshold</strong> is exceeded. Calling subsequently <code>clear()</code> leaves the set capacity extended, thus it modifies conditions for all following measurement repetitions.</p>\n\n<p>Speaking of the load threshold, you also have to decide upon the <strong>initial capacity</strong>, because when you set it too low (or leave it as default), the aforementioned <code>HashSet<E></code> capacity extension may occur, resulting in a time-expensive <strong><em>rehashing</em></strong> (a repeated insertion) of all elements present in the set. Of course, this as well can be exactly what you want to include in the measurement / comparison.</p>\n\n<p>A minor point would be the <strong>type parameter</strong> of a set, as the compiler generates some casts and bridge methods under the hood, but this is not meant to advocate the use of a raw type.</p>\n\n<p>The core of the solution then should look like this:</p>\n\n<pre><code>public static void main(String[] args) {\n final String[] data = preload(args[0]); // skipped for brevity\n final long count = Long.valueOf(args[1]);\n final Consumer<String> log = System.out::println;\n\n log.accept(\"Total time HashSet (ns): \" + measure(HashSet::new, data, count));\n log.accept(\"Total time TreeSet (ns): \" + measure(TreeSet::new, data, count));\n}\n\nstatic <E> long measure(Supplier<Set<E>> factory, E[] data, long count) {\n return Stream.generate(factory)\n .limit(count)\n .mapToLong(set -> {\n final Stream<E> stream = Stream.of(data);\n final long start = System.nanoTime();\n stream.forEach(set::add);\n return System.nanoTime() - start;\n }).sum();\n}\n</code></pre>\n\n<p>Or if you opt for the <code>clear()</code> initialization method anyway:</p>\n\n<pre><code>static <E> long measureClear(Supplier<Set<E>> factory, E[] data, long count)) {\n final Set<E> set = factory.get();\n set.addAll(Arrays.asList(data)); // ensure capacity to avoid rehashing\n return measure(() -> {set.clear(); return set;}, data, count);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-11T14:55:27.967",
"Id": "15522",
"ParentId": "15505",
"Score": "11"
}
},
{
"body": "<p>A few libraries that you could use:</p>\n\n<ul>\n<li><a href=\"http://commons.apache.org/io/api-release/org/apache/commons/io/FileUtils.html#readLines%28java.io.File,%20java.nio.charset.Charset%29\" rel=\"nofollow\"><code>FileUtils.readLines</code></a> from <a href=\"http://commons.apache.org/io/\" rel=\"nofollow\">Apache Commons IO</a> or <a href=\"http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/io/Files.html#readLines%28java.io.File,%20java.nio.charset.Charset%29\" rel=\"nofollow\"><code>Files.readLines(File, Charset)</code></a> from <a href=\"http://guava-libraries.googlecode.com/\" rel=\"nofollow\">Guava</a> if you want to preload the file to the memory before adding the lines to the sets.</li>\n<li><p><a href=\"http://commons.apache.org/io/api-release/org/apache/commons/io/FileUtils.html#lineIterator%28java.io.File,%20java.lang.String%29\" rel=\"nofollow\"><code>FileUtils.lineIterator(File file, String encoding)</code></a> from <a href=\"http://commons.apache.org/io/\" rel=\"nofollow\">Apache Commons IO</a> otherwise. </p></li>\n<li><p><a href=\"http://commons.apache.org/lang/api-release/org/apache/commons/lang3/time/StopWatch.html\" rel=\"nofollow\"><code>StopWatch</code></a> from <a href=\"http://commons.apache.org/lang/\" rel=\"nofollow\">Apache Commons Lang</a> or <a href=\"http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Stopwatch.html\" rel=\"nofollow\"><code>Stopwatch</code></a> from Guava for the timing. </p></li>\n</ul>\n\n<p>See also: <em>Effective Java, 2nd edition</em>, <em>Item 47: Know and use the libraries</em></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-20T22:25:28.320",
"Id": "25665",
"Score": "0",
"body": "Well, but *Josh Bloch* talks there explicitly about **standard java libraries**, not 3rd-party ones. Even if you can consider various Apache projects as 'common', there is quite many of them, in various quality and applicability, you can't keep track of them all. Using a 3rd-party library for just one call (that you can reimplement faster than you can find a suitable library) is a kind of an overkill..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-16T11:58:04.160",
"Id": "32979",
"Score": "0",
"body": "Oftentimes the only third-party libraries students can use are ones provided by their professor."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-11T19:51:19.007",
"Id": "15526",
"ParentId": "15505",
"Score": "4"
}
},
{
"body": "<p>To the time measurements, I like the math in the way you compute the elapsed time by summing:</p>\n\n<pre><code>long start = 0;\nlong end = 0;\nfor(int i = 0; i < count; i++) {\n start += System.nanoTime();\n fileToSet(path,hs);\n end += System.nanoTime();\n hs.clear();\n}\nlong average = (end - start) / count;\n</code></pre>\n\n<p>Why you should not do this, however, is that you can quickly run out of the <code>long</code> range. Slightly refined:</p>\n\n<pre><code>long elapsed = 0;\nfor(int i = 0; i < count; i++) {\n long start = System.nanoTime();\n fileToSet(path,hs);\n elapsed += System.nanoTime() - start;\n hs.clear();\n}\nlong average = elapsed / count;\n</code></pre>\n\n<p>But what can happen here is that if the <code>fileToSet()</code> is faster than the system time granularity, you may end up summing zeroes. That's why you'd be better using an inverse approach instead — measure all operations <strong>outside</strong> the benchmarked code, then substract this from the total time:</p>\n\n<pre><code>long start = System.nanoTime();\nlong end = start;\nlong exclude = 0;\nfor(int i = 0; i < count; i++) {\n exclude += System.nanoTime() - end;\n fileToSet(path,hs);\n end = System.nanoTime();\n hs.clear();\n}\nlong elapsed = (end - start) - exclude;\nlong average = elapsed / count;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-12T09:06:20.217",
"Id": "15533",
"ParentId": "15505",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "15507",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-10T23:22:57.783",
"Id": "15505",
"Score": "26",
"Tags": [
"java",
"homework",
"set",
"benchmarking"
],
"Title": "HashSet and TreeSet"
}
|
15505
|
<p>Now this is something I've looked into, and while I have a "working" solution, I don't like it.</p>
<p><strong>Background:</strong></p>
<p>Through our intranet website, we want to run a process that copies a file from another machine, unzips it, and then analyzes the content. As the file is large, this takes some time (usually around 5-6 minutes). Rather than have the user just hit a Button and pray that they get a success message in 5-6 minutes, we want to show the progress via updates to a TextBox.</p>
<p><strong>What I've learned so far:</strong></p>
<p>This isn't as simple as putting everything into an UpdatePanel and updating it at various steps in the process. Seems like it would be, but it's not. I looked into threading as well, but I couldn't get it working. That is to say, I got the process to run on a separate thread, but while it was running, the interface wouldn't update. It would queue up everything, and then display it all at once, once the process finished. As I'm still relatively new, the possibility that I was just doing something wrong is high.</p>
<p><strong>What I have (which works, I guess...):</strong></p>
<p>Two .aspx pages, <em>DatabaseChecker.aspx</em> and <em>Processing.aspx</em></p>
<p>DatabaseChecker.aspx:</p>
<pre><code><form id="form1" runat="server">
<asp:Button ID="btnExecute" runat="server" onclick="btnExecute_Click"
style="height: 26px" Text="Execute" />
<iframe src="Processing.aspx" name="sample" width="100%" height="700px" style="border-style: none; overflow: hidden;">
</iframe>
</form>
</code></pre>
<hr>
<p>Processing.aspx:</p>
<pre><code><meta http-equiv="refresh" content="1" />
<form id="form1" runat="server">
<asp:TextBox ID="TextBox1" runat="server" Height="633px" TextMode="MultiLine"
Width="504px"></asp:TextBox>
</form>
</code></pre>
<p>The .aspx portion is very simple. DatabaseChecker.aspx simply has a button to begin the process, and it has Processing embedded as an iframe.</p>
<p>The result looks like this:</p>
<p><img src="https://i.stack.imgur.com/EN5Lc.png" alt="DatabaseChecker.aspx"></p>
<p>The TextBox1 in Processing.aspx is where the progress update goes.</p>
<p>Now let me just point out the dirty trick and the part I don't like right now. In Processing.aspx, there is a meta tag to refresh the page once per second.</p>
<p><strong>How it works (summary):</strong></p>
<p>When the process starts, a Session variable called ["Running"] is set to true. When the process ends, Session["Running"] is set to false. And since Processing.aspx refreshes once per second, what happens is it saves the current contents of TextBox1.Text to another Session variable called ["TextBoxContent"]. And then the Page_Load method for Processing.aspx fills the TextBox back up with the previous content, and adds a period.</p>
<p>So the output will begin simply looking like "Process Starting", but after 10 seconds it will look like "Process Starting.........." (one period per second).</p>
<p><strong>How it works (details):</strong></p>
<p>The process begins in DatabaseChecker.aspx's Execute button:</p>
<pre><code>protected void btnExecute_Click(object sender, EventArgs e)
{
Session["TextBoxContents"] = "Copying .zip file from other machine...";
Session["Running"] = true;
Thread thread = new Thread(new ThreadStart(TheProcess));
thread.IsBackground = true;
thread.Start();
}
private void TheProcess()
{
CopyFromOtherMachine();
UnzipFiles();
ConvertTextFilesToDataTables();
//and so on and so forth
Session["Running"] = false;
}
private void CopyFromOtherMachine()
{
if (File.Exists(Path.Combine(FileRootDirectory, DesiredFileName)))
{
Session["TextBoxContent"] += "Previous .zip file already detected. Deleting...";
File.Delete(Path.Combine(FileRootDirectory, DesiredFileName));
Session["TextBoxContent"] += "OK!" + Environment.NewLine;
}
Session["TextBoxContent"] += "Copying .zip from other machine...";
File.Copy(@"\\someothermachine\production\desiredfile.zip", Path.Combine(FileRootDirectory, DesiredFileName));
Session["TextBoxContent"] += "OK!" + Environment.NewLine;
}
// UnzipFile()
// ConvertTextFilesToDataTables()
// and so on
</code></pre>
<p>And then we have Processing.aspx's Page_Load method, which is where we display our progress:</p>
<pre><code>protected void Page_Load(object sender, EventArgs e)
{
if (Session["TextBoxContent"] != null)
{
TextBox1.Text = Session["TextBoxContent"].ToString();
if ((bool)Session["Running"] != false)
{
Session["TextBoxContent"] += ".";
}
}
}
</code></pre>
<p><strong>What I want to improve:</strong></p>
<p>Basically, everything. This whole thing feels like a really makeshift house of cards. In particular, I don't like that the page has to update once per second, particularly because the Windows mouse icon changes to loading and not loading cursors very fast. If the user knows the system and knows what's going on, then yeah big deal I guess, we can just deal with it because we know what's going on. But I think to the average user, the behavior is jarring, it feels like something might be wrong or something.</p>
<p>Hopefully I've made it clear what I'm trying to achieve overall, so I'm open to other ideas about how to go about it.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-31T13:09:25.300",
"Id": "407193",
"Score": "0",
"body": "did you tried using ***SignalR*** ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-08T09:35:06.413",
"Id": "412204",
"Score": "0",
"body": "async/await method better than `ThreadStart` ? or using https://www.hanselman.com/blog/TheMagicOfUsingAsynchronousMethodsInASPNET45PlusAnImportantGotcha.aspx"
}
] |
[
{
"body": "<p>Have you considered using <a href=\"http://signalr.net/\" rel=\"nofollow\">SignalR</a>?</p>\n\n<p>As their homepage states, it's a \"library for ASP.NET developers that makes it incredibly simple to add real-time web functionality to your applications. What is \"real-time web\" functionality? It's <strong>the ability to have your server-side code push content to the connected clients</strong> as it happens, in real-time.\"</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T09:13:20.817",
"Id": "41046",
"ParentId": "15510",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "41046",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-11T03:29:57.077",
"Id": "15510",
"Score": "2",
"Tags": [
"c#",
"asp.net"
],
"Title": "Making a page update based on the progress of a process"
}
|
15510
|
<p>I am trying to place <code>JButton</code>s from an array onto a <code>JFrame</code>. The way I'm doing it is having it test how many more buttons are left, and if buttons have been placed at the edge of the frame. The end result is an ugly piece of code.</p>
<pre><code>JButton[] grid = new JButton[2501];
JFrame MapFrame = new JFrame();
public void makeMap() {
MapFrame.setBounds(40, 0, 750, 773);
int x = 0;
int y = 0;
for (int i = 0; i < grid.length; i++) {
// grid is the JButton Array
if (x > 749) {
x = 0;
y = y + 15;
}
grid[i] = new JButton();
grid[i].setBounds(x, y, 15, 15);
MapFrame.add(grid[i]);
x = x + 15;
}
MapFrame.setVisible(true);
MapFrame.repaint();
}
</code></pre>
<p>The code just looks so bulky with variables being changed in different braces, and with so many braces. How could I make this more elegant? (Please don't recommend layouts, as, none of them fit my requirements.)</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-11T09:50:16.323",
"Id": "25165",
"Score": "1",
"body": "Make `15` a constant, calculate `749` from the MapFrame.bounds and it will be fine."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-12T10:33:29.787",
"Id": "25220",
"Score": "0",
"body": "not to use GridLayout"
}
] |
[
{
"body": "<p>In order to find a more elegant solution, we first need to <em>identify</em> the problems; only then can we <em>solve</em> them:</p>\n\n<ul>\n<li><p><strong>Magic Numbers</strong><br>\nOne of the confusing things about this snippet is that we <em>constantly</em> <sup>(pun intended)</sup> come across magic values such as <code>15</code> and <code>749</code>. What if the map gets bigger in the future, or the dimensions of the buttons change? <strong>Solution: Define constants.</strong><br>\n<sub>Note: I used the Java naming convention for constants, which is <code>SHOUTY_CASE</code>, although I dislike it, because unified coding standards when sharing code trump personal preferences.</sub></p>\n\n<pre><code>private static final int NUMBER_OF_BUTTONS = 2501;\nprivate static final int BUTTON_SIDE = 15;\n</code></pre></li>\n<li><p><strong>Unnecessary use of array</strong><br>\nWhy are you copying every button into your <code>grid</code> before adding them to the <code>mapFrame</code>? If you aren't accessing them from the array later on, you can get rid of all the access-by-index complexity.</p>\n\n<pre><code>JButton button = new JButton();\nbutton.setBounds(x, y, BUTTON_SIDE, BUTTON_SIDE);\nmapFrame.add(button); \n</code></pre></li>\n<li><p><strong>Function doing too many things</strong><br>\nThe empty lines that you have used to split your code into sections is a code smell: it indicates that your function is doing too many different things, and therefore needs to be divided into several functions, each doing <em>one thing</em>. To quote <a href=\"http://blog.objectmentor.com/articles/2009/09/11/one-thing-extract-till-you-drop\" rel=\"nofollow\">Robert C. Martin</a>, author of <a href=\"http://rads.stackoverflow.com/amzn/click/0132350882\" rel=\"nofollow\"><em><strong>Clean Code:</strong> A Handbook of Agile Software Craftsmanship</em></a>:</p>\n\n<blockquote>\n <p><strong>Functions should do one thing. They should do it well. They should do it only.</strong></p>\n</blockquote></li>\n<li><p><strong>Using complex syntax for simple things</strong><br>\nCode like the following two examples from your code snippet</p>\n\n<pre><code>x = x + 15;\ny = y + 15;\n</code></pre>\n\n<p>can be shortened by using the combined <code>+=</code> operator.</p></li>\n</ul>\n\n<hr>\n\n<h2>Refactored</h2>\n\n<pre><code>private static final int NUMBER_OF_BUTTONS = 2501;\nprivate static final int BUTTON_SIDE = 15;\nprivate JFrame mapFrame = new JFrame();\n\npublic void createAndShowMap() {\n mapFrame.setBounds(40, 0, 750, 773);\n addButtons();\n mapFrame.setVisible(true);\n}\n\nprivate void addButtons() {\n int leftOffset = 0;\n int topOffset = 0;\n for (int i = 0; i < NUMBER_OF_BUTTONS; i++) {\n if (isBeyondEndOfLine(leftOffset)) {\n leftOffset = 0;\n topOffset += BUTTON_SIDE;\n }\n addButtonAt(leftOffset, topOffset);\n leftOffset += BUTTON_SIDE;\n }\n}\n\nprivate boolean isBeyondEndOfLine(int x) {\n return x >= mapFrame.getBounds().width;\n}\n\nprivate void addButtonAt(int x, int y) {\n JButton button = new JButton();\n button.setBounds(x, y, BUTTON_SIDE, BUTTON_SIDE);\n mapFrame.add(button);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-11T11:45:43.263",
"Id": "25171",
"Score": "0",
"body": "My addition would be - make the `bounds` a parameter for the `create` method and calculate the number of buttons from the size of frame and size of one button."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-11T12:33:22.913",
"Id": "25173",
"Score": "0",
"body": "@codesparkle, A very well written answer, it might even be the best I've received on all the StackExchange sites! (If you read the section I deleted, never mind.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-11T12:36:39.393",
"Id": "26742",
"Score": "1",
"body": "@codesparkle, If I wouldn't be banned for sockpuppeting, I would upvote everything you've written. The book you recommended is amazing, and your code is an example of what the book considers perfect clean code. I have bookmarked this answer and set it as my background. I shall live and code by this standard. Long Live Codesparkle!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-11T11:18:02.373",
"Id": "15517",
"ParentId": "15513",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "15517",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-11T07:45:34.037",
"Id": "15513",
"Score": "5",
"Tags": [
"java",
"swing"
],
"Title": "How can I make placing JButtons from an array more elegant?"
}
|
15513
|
<p>How can I make this more readable, faster, and make the GUI more appealing? </p>
<p><strong><code>CreditCard</code> class:</strong></p>
<pre><code>import java.util.*;
public class CreditCards {
private String prefix;
private String length;
public CreditCards(String p, String l) {
prefix = p;
length = l;
}
public String getPrefix() {
return prefix;
}
public String getLength() {
return length;
}
}
</code></pre>
<p><strong><code>MasterCard</code> class:</strong></p>
<pre><code>public class MasterCard extends CreditCards {
public MasterCard(String prefix,String length) {
super(prefix,length);
}
public boolean isMaster() {
boolean pre = (getPrefix().equals("55") || getPrefix().equals("51"))? true:false;
boolean len = getLength().equals("16")? true:false;
if(pre && len) {
return true;
}
else {
return false;
}
}
}
</code></pre>
<p><strong><code>VisaCard</code> class:</strong></p>
<pre><code>public class VisaCard extends CreditCards {
public VisaCard(String pre,String len) {
super(pre,len);
}
public boolean isVisa() {
boolean pre = getPrefix().equals("4") ? true:false;
boolean len = (getLength().equals("16") || getLength().equals("13"))? true:false;
if(pre && len) {
return true;
}
return false;
}
}
</code></pre>
<p><strong>GUI:</strong></p>
<pre><code>import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class cardValidatorGUI{
JFrame frame;
JTextField cardNumField;
JComboBox creditCardBox;
JButton checkButton;
JButton clearButton;
String[] cards = {"Visa","Mastercard"};
String selected = null;
public static void main(String[] args) {
cardValidatorGUI r1 = new cardValidatorGUI();
r1.go();
}
public void go() {
frame = new JFrame();
JPanel cardPanel = new JPanel();
JPanel buttonPanel = new JPanel();
cardPanel.setLayout(new GridLayout(0,2));
buttonPanel.setLayout(new GridLayout(0,2));
creditCardBox = new JComboBox(cards);
cardNumField = new JTextField("",20);
checkButton = new JButton("check");
checkButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae) {
String selected = creditCardBox.getSelectedItem().toString();
if (checkCriteria(selected)){
if (checkSum(cardNumField.getText())) {
JOptionPane.showMessageDialog(null, "Your Credit Card is Valid");
}
else {
JOptionPane.showMessageDialog(null, "Your Credit Card is Not Valid");
}
}
else {
JOptionPane.showMessageDialog(null, "Your Credit Card is Not Valid");
}
}
});
clearButton = new JButton("clear");
cardPanel.add(creditCardBox);
cardPanel.add(cardNumField);
buttonPanel.add(checkButton);
buttonPanel.add(clearButton);
frame.getContentPane().add(BorderLayout.CENTER,cardPanel);
frame.getContentPane().add(BorderLayout.SOUTH,buttonPanel);
frame.setSize(250, 200);
frame.setVisible(true);
frame.pack();
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
}
public static boolean checkSum(String check){
int sum = 0;
String trimCheck = check.replaceAll(" ", "");
String reverse = new StringBuffer(trimCheck).reverse().toString();
for(int i =0;i<trimCheck.length();i++) {
int checkThis = Character.digit(reverse.charAt(i), 10);
if(i%2==0) {
sum+=checkThis;
}
else {
sum += checkThis *2;
if(checkThis >=5) {
sum-=9;
}
}
}
if(sum%10==0) {
return true;
}
else {
return false;
}
}
public boolean checkCriteria(String c) {
int length = cardNumField.getText().replaceAll(" ","").length();
String len = Integer.toString(length);
if (c.equals("Mastercard")) {
String pre = cardNumField.getText().substring(0,2);
MasterCard masters = new MasterCard(pre,len);
if(masters.isMaster()) {
return true;
}
}
if (c.equals("Visa")) {
String pre = cardNumField.getText().substring(0,1);
VisaCard visa = new VisaCard(pre,len);
if (visa.isVisa()) {
return true;
}
}
return false;
}
}
</code></pre>
|
[] |
[
{
"body": "<ol>\n<li><p>Construction like</p>\n\n<pre><code>boolean pre = getPrefix().equals(\"4\") ? true:false;\n</code></pre>\n\n<p>is redundant. The following is ok:</p>\n\n<pre><code>boolean pre = getPrefix().equals(\"4\");\n</code></pre>\n\n<p>just as </p>\n\n<pre><code>if(pre && len) {\n return true;\n}\nreturn false;\n</code></pre>\n\n<p>this could be just:</p>\n\n<pre><code>return pre && len;\n</code></pre></li>\n<li><p>Try to avoid 'magic numbers' like 55 or 4. Extract them as constants and give them a proper name. </p></li>\n<li><p>I don't think that you need to operate with <code>length</code> as a <code>String</code>.</p></li>\n<li><p>Use error dialog for invalid credit card number:</p>\n\n<pre><code>JOptionPane.showMessageDialog(frame, \"Your Credit Card is Valid\", \"Error\", JOptionPane.ERROR_MESSAGE);\n</code></pre>\n\n<p>and also use a parent frame as an argument, not <code>null</code>.</p></li>\n<li><p>I'd suggest to remove methods <code>isViza()</code> and <code>isMaster()</code> and add abstract <code>isValid()</code> method to <code>CreditCard</code> class and override it in both subclasses.</p></li>\n<li><p>Text on your buttons should start with the capital letter.</p></li>\n<li><p>Avoid method names like <code>go()</code>. You could name it like <code>initUI()</code>.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-11T11:31:57.663",
"Id": "25168",
"Score": "0",
"body": "btw, I made length as a String for removing the whitespaces. Can you give me an alternative?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-11T11:40:38.793",
"Id": "25170",
"Score": "0",
"body": "just try to parse it before using in other methods. By the way, you can restrict user to input letters - only digits. Here is the sample code for custom `JTextField`: http://www.devx.com/tips/Tip/14311"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-11T11:21:26.690",
"Id": "15518",
"ParentId": "15516",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "15518",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-11T10:30:56.997",
"Id": "15516",
"Score": "2",
"Tags": [
"java",
"validation",
"swing",
"e-commerce"
],
"Title": "GUI-based credit card checker"
}
|
15516
|
<p>How can I DRY these scopes?</p>
<pre><code> scope :reputed, -> {
joins{reputations.outer}.
where{['coalesce(rs_reputations.value, 0) > ? OR purchases.force_active = ?', LOWEST_VOTE, true]}
}
scope :reputed_or_mine, ->(user) {
joins{reputations.outer}.
where{['coalesce(rs_reputations.value, 0) > ? OR purchases.force_active = ? OR purchases.user_id = ?', LOWEST_VOTE, true, user.id]}
}
</code></pre>
|
[] |
[
{
"body": "<pre><code>'coalesce(rs_reputations.value, 0) > ? OR purchases.force_active = true OR (? AND purchases.user_id = ?)',\nLOWEST_VOTE,\n!user.id.nil?,\n(if user.id.nil? then -1 else user.id end)\n</code></pre>\n\n<p>This is semantically equivalent to both, but the AND in the third clause prevents it from having an effect when there is no user.id.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-24T05:44:04.613",
"Id": "25805",
"Score": "0",
"body": "No thanks. It's looks uglier and contains errors."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-24T17:30:34.943",
"Id": "25826",
"Score": "0",
"body": "@ck3g, can you be more specific about the errors?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-24T23:21:25.987",
"Id": "25842",
"Score": "0",
"body": "Sure. `user.id` will throw error `Undefined method id for NilClass` or `called id for nil...` if user will not passed. Your solution is based on this."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-25T01:04:18.057",
"Id": "25847",
"Score": "0",
"body": "@ck3g, Understood. In that case, I'd declare the `user` argument with a default value that has an id of `nil`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-21T06:59:11.543",
"Id": "43056",
"Score": "0",
"body": "with OR in there, you don't get much other options. I don't support collecting in several steps and merging afterwards, because that's what a relational database is usually the best at. So I'm upvoting this solution."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-18T04:59:11.397",
"Id": "15699",
"ParentId": "15520",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-11T12:39:33.173",
"Id": "15520",
"Score": "4",
"Tags": [
"ruby",
"ruby-on-rails"
],
"Title": "Scopes chaining by OR"
}
|
15520
|
<p>I've been working with the RaphaelJS '<a href="http://raphaeljs.com/australia.html" rel="nofollow">australia map</a>' example that displays text in a DIV when a state is clicked on. However I'm having difficulty working with it to create different events and functions. </p>
<p>I want to be able to duplicate the 'display text' function for two different element onClick events (i.e. have two different buttons (elements) that do the same thing). But the current code is a bit too complicated for me. Can somebody please help me <strong>simplify the code</strong> that displays the text in a DIV when an element is clicked on. </p>
<p>Any help would be much appreciated - this is what I'm currently working with <a href="http://jsfiddle.net/CSFwc/" rel="nofollow">jsfiddle</a>.</p>
<pre><code> window.onload = function () {
var R = Raphael("paper", 532, 500);
var attr = {
fill: "#0B0",
stroke: "#fff",
"stroke-width": 3,
};
var ctx = {};
ctx.btn_1 = R.path("M 180,130 L 340,130, L 392,212, L 128,212 z").attr(attr);
ctx.btn_2 = R.path("M 128,212 L 392,212, L 435,280, L 85,280 z").attr(attr);
var current = null;
for (var state in ctx) {
(function (st, state) {
st[0].style.cursor = "pointer";
st[0].onmousedown = function () {
current && (document.getElementById(current).style.display = "");
st.toFront();
R.safari();
document.getElementById(state).style.display = "block";
current = state;
};
})(ctx[state], state);
}
};
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-10T16:38:48.043",
"Id": "25174",
"Score": "2",
"body": "That is actually reasonably compact, straightforward code. Which part were you hoping to simplify, exactly? One thought: if the click handler is what you're focusing on, you can always declare the function independently and assign it by variable name, rather than reproducing it inline repeatedly."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-11T09:04:47.610",
"Id": "25175",
"Score": "0",
"body": "The part of code I'm hoping to simplify is the click handler (starting from `var current = null;` to the end of the code). The problem I'm having is trying to rebuild the click handler code - or even calling the function to be used elsewhere."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-11T09:06:33.593",
"Id": "25176",
"Score": "0",
"body": "@MarkThomas I'll try _codereview_ too, thanks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-11T09:41:06.697",
"Id": "25177",
"Score": "0",
"body": "You could user `Paper.set` and make an array of elements. I wouldn't add it to the context as class property. And btw, you can add `'cursor': 'pointer'` to your `attr`. And at last: Don't use `for..in`, because it's very vulnerable, try Google `:)`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-13T09:51:28.363",
"Id": "25283",
"Score": "0",
"body": "Great, thanks Dan Lee. I'll look into those more. Google to the rescue! :)"
}
] |
[
{
"body": "<p>I gave it a shot.</p>\n\n<pre><code>window.onload = function () {\n var R = Raphael(\"paper\", 532, 500),\n attrs = {\n fill: \"#0B0\",\n stroke: \"#fff\",\n \"stroke-width\": 3,\n cursor: \"pointer\"\n },\n paths = [\n {id: 'btn_1', p:\"M 180,130 L 340,130, L 392,212, L 128,212 z\"},\n {id: 'btn_2', p:\"M 128,212 L 392,212, L 435,280, L 85,280 z\"}\n ],\n current,\n max,\n i;\n\n for (i = 0, max = paths.length; i < max; i++) {\n initPath(paths[i].p, attrs, paths[i].id);\n }\n\n function initPath(pathStr, attrs, targetId) {\n\n var path = R.path(pathStr).attr(attrs),\n txElm = document.getElementById(targetId);\n\n path.click(function (e) {\n if (current) {\n if (current === txElm) {\n return;\n }\n current.style.display = '';\n }\n current = txElm;\n current.style.display = 'block';\n this.toFront();\n R.safari();\n });\n }\n }\n</code></pre>\n\n<p>Integrated <a href=\"https://codereview.stackexchange.com/questions/15521/simplify-raphael-js-code-display-text-in-div-on-click-event/19471#comment25177_15521\">Dan Lee's comments</a> and defined a function instead of making a new closure in each loop iteration.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-07T00:55:56.163",
"Id": "64669",
"Score": "0",
"body": "I see absolutely no problem with using `for... in` to enumerate object properties, Google did not help. The original `click` logic was idiomatic JavaScript, not sure why you changed it. Also, OP doesn't use jQuery (`[0]` comes from Raphaël)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-10T22:34:20.907",
"Id": "19471",
"ParentId": "15521",
"Score": "0"
}
},
{
"body": "<p>I agree with <a href=\"https://codereview.stackexchange.com/a/19471/2634\">tiffon</a> it's better to extract a function, but I don't agree with the rest of their edits, so here's what I would have done (I also kept the style intact).</p>\n\n<pre><code>var initPath = (function () {\n var currentEl;\n\n function init(el, path) {\n path.attr({\n fill: \"#0B0\",\n stroke: \"#fff\",\n \"stroke-width\": 3,\n });\n\n path[0].style.cursor = \"pointer\";\n path[0].onmousedown = function () {\n currentEl && (currentEl.style.display = \"\");\n\n path.toFront();\n path.paper.safari();\n\n el.style.display = \"block\";\n currentEl = el;\n };\n }\n\n return init;\n})();\n\nwindow.onload = function () {\n var R = Raphael(\"paper\", 532, 500);\n var paths = {\n 'btn_1': R.path(\"M 180,130 L 340,130, L 392,212, L 128,212 z\"),\n 'btn_2': R.path(\"M 128,212 L 392,212, L 435,280, L 85,280 z\")\n };\n\n for (var id in paths) {\n initPath(document.getElementById(id), paths[id]);\n }\n};\n</code></pre>\n\n<p>Firstly, I think <code>st</code> and <code>state</code> were confusing names, so I changed them to be <code>path</code> and <code>id</code>, respectively, and then changed <code>id</code> to <code>el</code> to avoid additional lookups.</p>\n\n<p>I separated the infrastructure (<code>current</code> and <code>initPath</code>) from the usage (<code>R</code>, <code>paths</code> and the loop).</p>\n\n<p>I also think an object literal looks better than a series of assignments, so I changed that.</p>\n\n<p>Finally, I like it better if I move <code>initPath</code> and <code>currentEl</code> into a closure of their own—after all, they don't depend on <code>window.onload</code> anymore.</p>\n\n<p>I left the inner <code>init</code> a named function so it is named in a stack trace, if there is an error.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-07T01:19:38.240",
"Id": "38729",
"ParentId": "15521",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-10T10:13:28.113",
"Id": "15521",
"Score": "2",
"Tags": [
"javascript",
"raphael.js"
],
"Title": "Simplify Raphael JS code: display text in DIV on click event"
}
|
15521
|
<p>I've been working on a class to handle dependency injection across some code akin to a micro-framework. This is also my first real dive into any sort of <em>wrapper</em> for dependency injection. I decided to write a pseudo-intelligent dependency provider that recursively constructs dependencies. I also included the ability to share objects, which seems to put it somewhere between design patterns.</p>
<p>The most abstract feature is the recursion in <code>make()</code>, where it uses reflection classes to automatically inject dependencies into the dependency it's currently creating.</p>
<p>I've got a couple of questions:</p>
<ul>
<li><p>My first question is whether or not this would be considered a "container" or a "registry" - Initially I named it a "provider" to stay close to literal meaning, but it seems most like a container to me. The class turned out to have components of a few design patterns (not exactly what i intended, but it's working), but I'm not looking to invent a mashup of design patterns...</p></li>
<li><p>Secondly (and more importantly), the shared object pool is dancing on a fine line with the global state, which I want to avoid. So far only a few classes get put into this pool, namely the input handler class, which handles superglobal interactions. Is there a more sophisticated way to ensure the same object is injected for certain classes, or is <em>almost-global-state</em> the only way to go?</p></li>
</ul>
<p>Recursively injecting dependencies has been <em>great</em> so far, cutting out a lot of code by eliminating the need to even recognize those dependencies. However it has caused some roadblocks along the way, where constructor parameters are limited to namespaced objects. I am slightly worried that this sort of requirement could cause major problems down the road, so I'm all ears for words of advice.</p>
<p>Finally, the code: </p>
<pre><code><?php
namespace Framework\Injection;
use Framework\Exception\InjectionProviderException;
/**
* Dependency provider class that will inject dependencies
* by either pulling them from the shared object pool,
* or by making a new object.
*
* @author Kevin O'Rourke
* @category Framework
* @package Injection
* @implements Injector
*/
class Provider implements Injector {
/**
* The shared object pool
*
* @var array
* @access protected
*/
protected $_sharedObjects = array();
/**
* Container used to gather info on classes, such as
* constructor parameters, and isInstantiable()
*
* @var ReflectionContainer
* @access protected
*/
protected $_reflectionContainer;
/**
* @access public
* @param ReflectionContainer $reflectionContainer
* @return void
*/
public function __construct(ReflectionContainer $reflectionContainer)
{
$this->_reflectionContainer = $reflectionContainer;
}
/**
* Called to inject a dependency - will either pull an object out of the shared
* pool, or create a new object. Sub-dependencies are resolved and instantiated
* automatically, provided they aren't a primitive type
*
* @access public
* @param mixed $class
* @return void
* @throws Exception\InjectionProviderException
*/
public function make($class)
{
//need to trim off the slashes, that's how they're stored in the shared array
if(isset($this->_sharedObjects[trim($class, "\\")]))
{
return $this->_sharedObjects[trim($class, "\\")];
}
/*
* This is an edge case where something is requesting a di provider
* through a di provider. This should ONLY happen when make() is called
* for a class that has a provide dependency in the constructor. The
* provider will automatically create all the dependencies for that
* constructor, including a provider.
*/
if($class === "\\" . __CLASS__)
{
return $this;
}
try {
$reflectionClass = $this->_reflectionContainer->get($class);
}
catch(\ReflectionException $e)
{
throw new InjectionProviderException("Provider failure: " . $e->getMessage());
}
if(false === $reflectionClass->isInstantiable())
{
throw new InjectionProviderException("Cannot instantiate " . ($reflectionClass->isInterface()? 'interface' : 'class') . " '$class'");
}
if( ! $reflectionClass->hasMethod('__construct'))
{
//$reflectionClass->newInstanceWithoutConstructor() requires php > 5.4, so just a plain instantiation
return new $class();
}
//If we're here, then the class has a constructor, so lets resolve the dependencies
$constructorParameters = $this->_getConstructorParameters($reflectionClass);
$paramsFinal = array();
foreach($constructorParameters as $paramClassName)
{
$paramsFinal[] = $this->make("\\" . $paramClassName);
}
return $reflectionClass->newInstanceArgs($paramsFinal);
}
/**
* Uses the reflectionContainer to assess the constructor of the given [reflection] class
*
* @access protected
* @param \ReflectionClass $reflectionClass
* @return void
*/
protected function _getConstructorParameters(\ReflectionClass $reflectionClass)
{
$params = $reflectionClass->getConstructor()->getParameters();
$paramClasses = array();
foreach($params as $param)
{
$class = $param->getClass();
if(null === $class)
{
throw new InjectionProviderException("Invalid/unknown constructor parameter(s) in '{$reflectionClass->getName()}'");
}
$paramClasses[] = $class->name;
}
return $paramClasses;
}
/**
* Shares an object with the shared object pool
*
* @access public
* @param mixed $object
* @return void
* @throws \InvalidArgumentException
*/
public function share($object)
{
if( ! is_object($object))
{
throw new \InvalidArgumentException("Invalid object passed to " . __CLASS__ . "/" . __METHOD__);
}
$this->_sharedObjects[get_class($object)] = $object;
}
/**
* Adds an object to the shared pool
*
* @access public
* @param mixed $class
* @return void
*/
public function isShared($class)
{
return array_key_exists($class, $this->_sharedObjects);
}
/**
* Removes an object from the shared pool
*
* @access public
* @param mixed $class
* @return void
*/
public function unShare($class)
{
if(array_key_exists($class, $this->_sharedObjects))
{
unset($this->_sharedObjects[$class]);
}
}
}
</code></pre>
<p>The reflection container class is very simple:</p>
<pre><code><?php
namespace Framework\Injection;
use ReflectionClass;
/**
* A reflection container for gathering information about
* arbitrary classes, namely isInstantiable() and their
* constructor parameters, if any
*
* @author Kevin O'Rourke
* @category Framework
* @package Injection
*/
class ReflectionContainer {
/**
* Holds the classes already processed, as to not re-make
* their respective reflections
*
* @var array
* @access protected
*/
protected $_classes = array();
/**
* If a reflection class of that type hasn't yet been
* processed, one is created and stored. Then that object
* (or the pre-existing one) is returned
*
* @access public
* @param string $class
* @return \ReflectionClass
*/
public function get($class)
{
if( ! isset($this->_classes[$class]))
{
$reflection = new ReflectionClass($class);
$this->_classes[$class] = $reflection;
}
return $this->_classes[$class];
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-12T21:01:43.717",
"Id": "25238",
"Score": "0",
"body": "TIL: DI Containers and Registry pattern. From my newly acquired understanding, this looks like both. Registry pattern by \"making\" classes, and a Container because there's a bunch (I'm still a bit iffy on the container bit). Here's a link I found for [Containers](http://fabien.potencier.org/article/12/do-you-need-a-dependency-injection-container), maybe it will help. I'm not sure about your implementation, mostly because I'm not sure what's going on here, but hopefully someone will answer, if not, I'll try again once I have a better understanding of the subject. Sorry I couldn't be of more help"
}
] |
[
{
"body": "<ol>\n<li>It depends on how you use it. Your \"sharedObjects\" part would probably fit Registry pattern if you start using it as global object. On the other hand usually Registry does not create objects, but rather store them. Your implementation is a proper container as long as you don't start passing it around or start using it globally (that would make it \"Service locator\" pattern).</li>\n<li>I wouldn't call that global state. I assume you need that to make sure your object gets instantiated only once. The way I used to do it in my C++ implementation of container is store a map of factories in it. That factory could be any kind of a \"callable\" function (lambda expression, pointer to function, functor, etc..) and it was wrapped in a \"ICreationStrategy\" interface. If I needed to create object only once - I used SingletonCreationStrategy which worked exactly the same way as Singleton design pattern does, but without using static variable. This way you can store object instance in CreationStrategy instead of container directly (although I don't really see a problem with storing it the way you did).</li>\n</ol>\n\n<p>I'll write an example when I'm gonna have more time.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-25T17:43:35.127",
"Id": "28542",
"Score": "0",
"body": "I've now been using this in a few cases over the last couple of months, with some successes and failures; A few times I've had to stop myself from passing this object around freely - just as you mentioned - but overall it's been a great little class. I'm still a little worried about it being present in more places that it should, which gives some credence to your note about the service locator pattern. On the subject of the shared objects, the only class I've been sharing consistently is an input class (a wrapper for superglobals, with filtering capabilities), which is \"global\" by nature"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-25T19:01:35.443",
"Id": "28547",
"Score": "0",
"body": "@orourkek If you feel the need to pass container at more than one place you are probably not using it the way it should be used. It only should be used at bootstrap logic. If you are passing it around because at some point in your code you have to create a class and you dont know its type beforehand you need to use a factory. Ideally you should write a factory and pass it to the class constructor that needs to create new instances of that class. All this gets wired only once - at bootstrap. It is okay to pass container to that factory in case you really need to, but you should still avoid it."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-24T21:12:54.133",
"Id": "17901",
"ParentId": "15527",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-11T19:57:45.287",
"Id": "15527",
"Score": "6",
"Tags": [
"php",
"dependency-injection"
],
"Title": "Dependency Injection Provider/Container"
}
|
15527
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.