body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>This is the first time I tried to write a back propagation ANN and I would like to know what more experienced people think of it. The code is meant to distinguish if text is written in English, French or Dutch.</p>
<p>I know my training set isn't very diverse but I just got the data from about 30 different texts, each containing 250 words in one of the 3 languages, so that's not my fault. I also know there are easier ways to do that but I wanted to learn something about ANNs.</p>
<p>I'd be glad if any of you would be kind enough to give me his thoughts on how I did this and how I could improve it.</p>
<pre><code>import math, time, random, winsound
global Usefull
LearningRate = 0.001
InWeight = [[],[],[],[],[],[]]
#Generate random InWeights
for i in range(6):
for j in range(21):
InWeight[i].append(random.uniform(0,1))
#21 Input Values
InNeuron = [0,0,0,0,0,0,0,
0,0,0,0,0,0,0,
0,0,0,0,0,0,0]
#6 Hidden Neurons
HiddenLayer = [0, 0, 0, 0, 0, 0]
#Used to calculate Delta
HiddenLayerNoSigmoid = [0, 0, 0, 0, 0, 0]
HiddenWeight = [[],[],[]]
#Generate random HiddenWeights
for i in range(3):
for j in range(6):
HiddenWeight[i].append(random.uniform(0,1))
#3 Output Neurons
OutNeuron = [0, 0, 0]
#Used to calculate Delta
OutNeuronNoSigmoid = [0, 0, 0]
#Learning Table
#Engels - Nederlands - Frans - Desired output
test = [[11, 4, 8, 1, 14, 8, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0]]
test += [[4, 0, 6, 0, 4, 6, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0]]
test += [[6, 0, 6, 0, 11, 8, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0]]
test += [[23, 0, 0, 0, 13, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0]]
test += [[18, 4, 4, 2, 14, 8, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0]]
test += [[14, 1, 6, 0, 10, 7, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0]]
test += [[19, 0, 2, 0, 18, 4, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0]]
test += [[13, 1, 1, 1, 15, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0]]
test += [[19, 3, 1, 0, 14, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0]]
test += [[0, 0, 0, 0, 0, 0, 0, 2, 0, 5, 6, 1, 1, 8, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0]]
test += [[0, 0, 0, 0, 0, 0, 0, 3, 0, 7, 1, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0]]
test += [[0, 0, 0, 0, 0, 0, 0, 1, 0, 12, 7, 8, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0]]
test += [[0, 0, 0, 0, 0, 0, 0, 4, 0, 5, 4, 4, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0]]
test += [[0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 5, 1, 13, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0]]
test += [[0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 7, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0]]
test += [[0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 7, 0, 13, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0]]
test += [[0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 14, 1, 8, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0]]
test += [[0, 0, 0, 0, 0, 0, 0, 4, 0, 2, 4, 9, 4, 3, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0]]
test += [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 3, 0, 6, 0, 8, 0, 0, 1]]
test += [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 2, 7, 0, 1, 0, 0, 0, 0, 1]]
test += [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 0, 1, 0, 2, 0, 1, 0, 0, 1]]
test += [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 0, 5, 2, 2, 0, 0, 0, 0, 1]]
test += [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 7, 0, 2, 0, 2, 0, 0, 1]]
test += [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 0, 7, 1, 1, 2, 3, 0, 0, 1]]
test += [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 8, 0, 2, 0, 2, 0, 0, 1]]
test += [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 4, 0, 3, 1, 3, 0, 0, 1]]
test += [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 1, 5, 1, 2, 0, 0, 0, 0, 1]]
def Sigmoid(Value):
return math.tanh(Value)
def DSigmoid(Value):
return 1.0 - Value**2
def UpdateHiddenNode():
global InNeuron, InWeight
for i in range(6):
e = 0
for j in range(21):
e += InWeight[i][j]*InNeuron[j]
HiddenLayerNoSigmoid = e
HiddenLayer[i] = Sigmoid(e)
def UpdateOutNeuron():
global HiddenLayer, HiddenWeight
for i in range(3):
e = 0
for j in range(3):
e += HiddenWeight[i][j]*HiddenLayer[j]
OutNeuron[i] = Sigmoid(e)
def UpdateDelta():
global Delta3, Delta4, Delta5, Delta6, Delta7, Delta8
Delta3 = Delta0*HiddenWeight[0][0]+Delta1*HiddenWeight[1][0]+Delta2*HiddenWeight[2][0]
Delta4 = Delta0*HiddenWeight[0][1]+Delta1*HiddenWeight[1][1]+Delta2*HiddenWeight[2][1]
Delta5 = Delta0*HiddenWeight[0][2]+Delta1*HiddenWeight[1][2]+Delta2*HiddenWeight[2][2]
Delta6 = Delta0*HiddenWeight[0][3]+Delta1*HiddenWeight[1][3]+Delta2*HiddenWeight[2][3]
Delta7 = Delta0*HiddenWeight[0][4]+Delta1*HiddenWeight[1][4]+Delta2*HiddenWeight[2][4]
Delta8 = Delta0*HiddenWeight[0][5]+Delta1*HiddenWeight[1][5]+Delta2*HiddenWeight[2][5]
def UpdateInWeights():
global Delta3, Delta4, Delta5, Delta6, Delta7, Delta8
for i in range(21):
InWeight[0][i] += LearningRate*Delta3*DSigmoid(HiddenLayerNoSigmoid[0])*InNeuron[i]
InWeight[1][i] += LearningRate*Delta4*DSigmoid(HiddenLayerNoSigmoid[1])*InNeuron[i]
InWeight[2][i] += LearningRate*Delta5*DSigmoid(HiddenLayerNoSigmoid[2])*InNeuron[i]
InWeight[3][i] += LearningRate*Delta6*DSigmoid(HiddenLayerNoSigmoid[3])*InNeuron[i]
InWeight[4][i] += LearningRate*Delta7*DSigmoid(HiddenLayerNoSigmoid[4])*InNeuron[i]
InWeight[5][i] += LearningRate*Delta8*DSigmoid(HiddenLayerNoSigmoid[5])*InNeuron[i]
def UpdateHiddenWeights():
global Delta0, Delta1, Delta2
for i in range(3):
HiddenWeight[0][i] += LearningRate*Delta0*DSigmoid(OutNeuronNoSigmoid[0])*HiddenLayer[i]
HiddenWeight[1][i] += LearningRate*Delta1*DSigmoid(OutNeuronNoSigmoid[1])*HiddenLayer[i]
HiddenWeight[2][i] += LearningRate*Delta2*DSigmoid(OutNeuronNoSigmoid[2])*HiddenLayer[i]
print("Learning...")
#Start playing Learning.wav if available, else play windows default sound
#ASYNC ensures the program keeps running while playing the sound
winsound.PlaySound("Learning.wav", winsound.SND_ASYNC)
#Start timer
StartTime = time.clock()
Iterations = 0
#Main loop
while Iterations <= 100000:
for i in range(len(test)):
for j in range(21):
InNeuron[j] = test[i][j]
UpdateHiddenNode()
UpdateOutNeuron()
Delta0 = test[i][21] - OutNeuron[0]
Delta1 = test[i][22] - OutNeuron[1]
Delta2 = test[i][23] - OutNeuron[2]
UpdateDelta()
UpdateInWeights()
UpdateHiddenWeights()
if Iterations % 1000 == 0:
PercentComplete = Iterations / 1000
print("Learning " + str(PercentComplete) + "% Complete")
Iterations += 1
#Stop playing any sound
winsound.PlaySound(None, winsound.SND_ASYNC)
print(Delta0, Delta1, Delta2)
#Save brain to SaveFile
SaveFileName = input("Save brain as: ")
SaveFile = open(SaveFileName+".txt", "w")
SaveFile.write(str(InWeight))
SaveFile.write(str(HiddenWeight))
SaveFile.close()
ElapsedTime = (time.clock() - StartTime)
print(str(ElapsedTime) + "seconds")
#Start playing Ready.wav if available, else play default windows sound
#ASYNC ensures the program keeps running while playing the sound
winsound.PlaySound("Ready.wav", winsound.SND_ASYNC)
def Input_Frequency(Document):
WantedWords = ["i", "you", "he", "are", "the", "and", "for",
"ik", "jij", "hij", "zijn", "het", "niet", "een",
"le", "tu", "il", "avez", "une", "alors", "dans"]
file = open(Document, "r")
text = file.read( )
file.close()
#Create dictionary
word_freq ={}
#Split text in words
text = str.lower(text)
word_list = str.split(text)
for word in word_list:
word_freq[word] = word_freq.get(word, 0) + 1
#Get keys
keys = word_freq.keys()
#Get frequency of usefull words
Usefull = []
for word in WantedWords:
if word in keys:
word = word_freq[word]
Usefull.append(word)
else:
Usefull.append(0)
return Usefull
def UseIt(Input):
for i in range(len(Input)):
InNeuron[i] = Input[i]
UpdateHiddenNode()
UpdateOutNeuron()
if OutNeuron[0] > 0.99:
return ("Engelse tekst")
if OutNeuron[1] > 0.99:
return ("Nederlandse tekst")
if OutNeuron[2] > 0.99:
return ("Franse tekst")
#Documents to investigate
#Error handling checks if you input a number
while True:
try:
NumberOfDocuments = int(input("Aantal te onderzoeken documenten: "))
break
except ValueError:
print("That was not a valid number.")
x = 0
while NumberOfDocuments > x:
#Error handling checks if document exists
while True:
try:
Document = str(input("Document: "))
file = open(Document, "r")
break
except IOError:
print(Document +" not found")
print(UseIt(Input_Frequency(Document)))
#Stop playing any sound
if x == (NumberOfDocuments - 1):
winsound.PlaySound(None, winsound.SND_ASYNC)
x += 1
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-17T22:06:57.523",
"Id": "9477",
"Score": "0",
"body": "You might want to cut the soundcode from the code, I just used it to warn me when the calculation was running and when it was done so I could test."
}
] |
[
{
"body": "<pre><code>import math, time, random, winsound\nglobal Usefull\n</code></pre>\n\n<p>A global statement outside of a function has no effect</p>\n\n<pre><code>LearningRate = 0.001\n</code></pre>\n\n<p>The python style guide recommends that global constants be in ALL_CAPS</p>\n\n<pre><code>InWeight = [[],[],[],[],[],[]]\n</code></pre>\n\n<p>The python style guide for local variable names is lower_case_with_underscores</p>\n\n<pre><code>#Generate random InWeights\nfor i in range(6):\n for j in range(21):\n InWeight[i].append(random.uniform(0,1))\n</code></pre>\n\n<p>Logic like this should always be in a function. Your main level should be restricted to defining functions/classes. Also you might want to consider looking into using numpy. With it you can do the above as <code>InWeight = numpy.random.random(6, 21)</code></p>\n\n<pre><code>#21 Input Values\nInNeuron = [0,0,0,0,0,0,0,\n 0,0,0,0,0,0,0,\n 0,0,0,0,0,0,0]\n</code></pre>\n\n<p>You can use InNeuron = [0] * 21. Speaking of this, the numbers 21 and 6 are showing up in multiple places. You should make them a global constant so you can change them from one place.</p>\n\n<pre><code>#6 Hidden Neurons\nHiddenLayer = [0, 0, 0, 0, 0, 0]\n#Used to calculate Delta \nHiddenLayerNoSigmoid = [0, 0, 0, 0, 0, 0]\nHiddenWeight = [[],[],[]]\n#Generate random HiddenWeights\nfor i in range(3):\n for j in range(6):\n HiddenWeight[i].append(random.uniform(0,1))\n#3 Output Neurons\nOutNeuron = [0, 0, 0]\n#Used to calculate Delta\nOutNeuronNoSigmoid = [0, 0, 0]\n</code></pre>\n\n<p>As before, no need to type out the entire table of zeros. </p>\n\n<pre><code>#Learning Table\n#Engels - Nederlands - Frans - Desired output\ntest = [[11, 4, 8, 1, 14, 8, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0]]\ntest += [[4, 0, 6, 0, 4, 6, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0]]\ntest += [[6, 0, 6, 0, 11, 8, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0]]\ntest += [[23, 0, 0, 0, 13, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0]]\ntest += [[18, 4, 4, 2, 14, 8, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0]]\ntest += [[14, 1, 6, 0, 10, 7, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0]]\ntest += [[19, 0, 2, 0, 18, 4, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0]]\ntest += [[13, 1, 1, 1, 15, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0]]\ntest += [[19, 3, 1, 0, 14, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0]]\ntest += [[0, 0, 0, 0, 0, 0, 0, 2, 0, 5, 6, 1, 1, 8, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0]]\ntest += [[0, 0, 0, 0, 0, 0, 0, 3, 0, 7, 1, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0]]\ntest += [[0, 0, 0, 0, 0, 0, 0, 1, 0, 12, 7, 8, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0]]\ntest += [[0, 0, 0, 0, 0, 0, 0, 4, 0, 5, 4, 4, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0]]\ntest += [[0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 5, 1, 13, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0]]\ntest += [[0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 7, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0]]\ntest += [[0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 7, 0, 13, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0]]\ntest += [[0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 14, 1, 8, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0]]\ntest += [[0, 0, 0, 0, 0, 0, 0, 4, 0, 2, 4, 9, 4, 3, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0]]\ntest += [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 3, 0, 6, 0, 8, 0, 0, 1]]\ntest += [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 2, 7, 0, 1, 0, 0, 0, 0, 1]]\ntest += [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 0, 1, 0, 2, 0, 1, 0, 0, 1]]\ntest += [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 0, 5, 2, 2, 0, 0, 0, 0, 1]]\ntest += [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 7, 0, 2, 0, 2, 0, 0, 1]]\ntest += [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 0, 7, 1, 1, 2, 3, 0, 0, 1]]\ntest += [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 8, 0, 2, 0, 2, 0, 0, 1]]\ntest += [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 4, 0, 3, 1, 3, 0, 0, 1]]\ntest += [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 1, 5, 1, 2, 0, 0, 0, 0, 1]]\n</code></pre>\n\n<p>Why do you use += many time instead of simply creating the list in one go? For this much data I'd also probably store it in an external file. </p>\n\n<pre><code>def Sigmoid(Value):\n return math.tanh(Value)\n\ndef DSigmoid(Value): \n return 1.0 - Value**2\n</code></pre>\n\n<p>The python style guide recommends lowercase_with_underscores for function names and the variables in them.</p>\n\n<pre><code>def UpdateHiddenNode():\n global InNeuron, InWeight\n</code></pre>\n\n<p>Avoid global variables. Stuff like this should really be in a class where InNeuron and InWeight would be attributes. </p>\n\n<pre><code> for i in range(6):\n e = 0\n</code></pre>\n\n<p>e is a cryptic variable name, considering expanding it</p>\n\n<pre><code> for j in range(21):\n e += InWeight[i][j]*InNeuron[j]\n HiddenLayerNoSigmoid = e\n HiddenLayer[i] = Sigmoid(e)\n</code></pre>\n\n<p>This entire function would probably be one line of code if you were using numpy. It would also run faster.</p>\n\n<pre><code>def UpdateOutNeuron():\n global HiddenLayer, HiddenWeight\n for i in range(3):\n e = 0\n for j in range(3):\n e += HiddenWeight[i][j]*HiddenLayer[j]\n OutNeuron[i] = Sigmoid(e)\n</code></pre>\n\n<p>These last two function seem to be doing basically the same thing. Can you combine them?</p>\n\n<pre><code>def UpdateDelta():\n global Delta3, Delta4, Delta5, Delta6, Delta7, Delta8\n Delta3 = Delta0*HiddenWeight[0][0]+Delta1*HiddenWeight[1][0]+Delta2*HiddenWeight[2][0]\n Delta4 = Delta0*HiddenWeight[0][1]+Delta1*HiddenWeight[1][1]+Delta2*HiddenWeight[2][1]\n Delta5 = Delta0*HiddenWeight[0][2]+Delta1*HiddenWeight[1][2]+Delta2*HiddenWeight[2][2]\n Delta6 = Delta0*HiddenWeight[0][3]+Delta1*HiddenWeight[1][3]+Delta2*HiddenWeight[2][3]\n Delta7 = Delta0*HiddenWeight[0][4]+Delta1*HiddenWeight[1][4]+Delta2*HiddenWeight[2][4]\n Delta8 = Delta0*HiddenWeight[0][5]+Delta1*HiddenWeight[1][5]+Delta2*HiddenWeight[2][5]\n</code></pre>\n\n<p>Surely all that repeating code looks ugly to you.Surely all that repeating code looks ugly to you.Surely all that repeating code looks ugly to you.Surely all that repeating code looks ugly to you.Surely all that repeating code looks ugly to you.Surely all that repeating code looks ugly to you.Surely all that repeating code looks ugly to you.Surely all that repeating code looks ugly to you.Surely all that repeating code looks ugly to you.</p>\n\n<p>If you make Delta a list instead of a collection of variables it should be easy to write a loop to handle it. In general, if you ever find yourself creating multiple variables differing only by a number, you should have a list or an array.</p>\n\n<pre><code>def UpdateInWeights():\n global Delta3, Delta4, Delta5, Delta6, Delta7, Delta8\n for i in range(21):\n InWeight[0][i] += LearningRate*Delta3*DSigmoid(HiddenLayerNoSigmoid[0])*InNeuron[i]\n InWeight[1][i] += LearningRate*Delta4*DSigmoid(HiddenLayerNoSigmoid[1])*InNeuron[i]\n InWeight[2][i] += LearningRate*Delta5*DSigmoid(HiddenLayerNoSigmoid[2])*InNeuron[i]\n InWeight[3][i] += LearningRate*Delta6*DSigmoid(HiddenLayerNoSigmoid[3])*InNeuron[i]\n InWeight[4][i] += LearningRate*Delta7*DSigmoid(HiddenLayerNoSigmoid[4])*InNeuron[i]\n InWeight[5][i] += LearningRate*Delta8*DSigmoid(HiddenLayerNoSigmoid[5])*InNeuron[i]\n</code></pre>\n\n<p>And again, you aren't lazy enough. You should be too lazy to repeat this much code. Rewrite this as a loop.</p>\n\n<pre><code>def UpdateHiddenWeights():\n global Delta0, Delta1, Delta2\n for i in range(3):\n HiddenWeight[0][i] += LearningRate*Delta0*DSigmoid(OutNeuronNoSigmoid[0])*HiddenLayer[i]\n HiddenWeight[1][i] += LearningRate*Delta1*DSigmoid(OutNeuronNoSigmoid[1])*HiddenLayer[i]\n HiddenWeight[2][i] += LearningRate*Delta2*DSigmoid(OutNeuronNoSigmoid[2])*HiddenLayer[i]\n</code></pre>\n\n<p>Be lazy. Don't repeat yourself.</p>\n\n<pre><code>print(\"Learning...\")\n#Start playing Learning.wav if available, else play windows default sound\n#ASYNC ensures the program keeps running while playing the sound\nwinsound.PlaySound(\"Learning.wav\", winsound.SND_ASYNC)\n#Start timer\nStartTime = time.clock() \nIterations = 0\n#Main loop\nwhile Iterations <= 100000:\n</code></pre>\n\n<p>Use a for loop</p>\n\n<pre><code> for i in range(len(test)):\n for j in range(21):\n InNeuron[j] = test[i][j]\n</code></pre>\n\n<p>Given that test[i] is a list, you could just say InNeuron = test[i]</p>\n\n<pre><code> UpdateHiddenNode()\n UpdateOutNeuron()\n Delta0 = test[i][21] - OutNeuron[0]\n Delta1 = test[i][22] - OutNeuron[1]\n Delta2 = test[i][23] - OutNeuron[2]\n</code></pre>\n\n<p>:(</p>\n\n<pre><code> UpdateDelta()\n UpdateInWeights() \n UpdateHiddenWeights()\n if Iterations % 1000 == 0:\n PercentComplete = Iterations / 1000\n print(\"Learning \" + str(PercentComplete) + \"% Complete\")\n</code></pre>\n\n<p>Print automatically stringify's things. You shouldn't need to call str here</p>\n\n<pre><code> Iterations += 1\n#Stop playing any sound\nwinsound.PlaySound(None, winsound.SND_ASYNC)\nprint(Delta0, Delta1, Delta2)\n#Save brain to SaveFile\nSaveFileName = input(\"Save brain as: \")\nSaveFile = open(SaveFileName+\".txt\", \"w\")\nSaveFile.write(str(InWeight))\nSaveFile.write(str(HiddenWeight))\nSaveFile.close()\nElapsedTime = (time.clock() - StartTime)\n</code></pre>\n\n<p>Usually I'd avoid recording time for user input here by stopping the time before the call to input above.</p>\n\n<pre><code>print(str(ElapsedTime) + \"seconds\")\n#Start playing Ready.wav if available, else play default windows sound\n#ASYNC ensures the program keeps running while playing the sound\nwinsound.PlaySound(\"Ready.wav\", winsound.SND_ASYNC)\n\ndef Input_Frequency(Document):\n WantedWords = [\"i\", \"you\", \"he\", \"are\", \"the\", \"and\", \"for\",\n \"ik\", \"jij\", \"hij\", \"zijn\", \"het\", \"niet\", \"een\",\n \"le\", \"tu\", \"il\", \"avez\", \"une\", \"alors\", \"dans\"]\n</code></pre>\n\n<p>Constant stuff like this should really be at the main level not in a function</p>\n\n<pre><code> file = open(Document, \"r\")\n text = file.read( )\n</code></pre>\n\n<p>Why gaping the whole in <code>read( )</code> It looks like you left the door open.</p>\n\n<pre><code> file.close()\n #Create dictionary \n word_freq ={}\n</code></pre>\n\n<p>Put a space before the <code>{}</code> to give it a nice balance</p>\n\n<pre><code> #Split text in words\n text = str.lower(text)\n word_list = str.split(text)\n\n for word in word_list:\n word_freq[word] = word_freq.get(word, 0) + 1\n</code></pre>\n\n<p>There is a class, collections.Counter, which makes counting stuff like this easier.</p>\n\n<pre><code> #Get keys \n keys = word_freq.keys()\n</code></pre>\n\n<p>No real reason to do this, just use <code>key in word_freq</code> instead of <code>key in keys</code></p>\n\n<pre><code> #Get frequency of usefull words\n Usefull = []\n for word in WantedWords:\n if word in keys:\n word = word_freq[word]\n Usefull.append(word)\n else:\n Usefull.append(0)\n</code></pre>\n\n<p>This would be shorter to say Usefull.append(word_freq.get(word, 0)) instead of that if</p>\n\n<pre><code> return Usefull\n\ndef UseIt(Input):\n for i in range(len(Input)):\n InNeuron[i] = Input[i]\n UpdateHiddenNode()\n UpdateOutNeuron()\n if OutNeuron[0] > 0.99:\n return (\"Engelse tekst\")\n if OutNeuron[1] > 0.99:\n return (\"Nederlandse tekst\")\n if OutNeuron[2] > 0.99:\n return (\"Franse tekst\")\n#Documents to investigate\n#Error handling checks if you input a number\nwhile True:\n try:\n NumberOfDocuments = int(input(\"Aantal te onderzoeken documenten: \"))\n break\n</code></pre>\n\n<p>Stylistically, I'd put the break in an else instead of here.</p>\n\n<pre><code> except ValueError:\n print(\"That was not a valid number.\")\nx = 0\nwhile NumberOfDocuments > x:\n #Error handling checks if document exists\n while True:\n try:\n Document = str(input(\"Document: \"))\n file = open(Document, \"r\")\n break\n except IOError:\n print(Document +\" not found\")\n print(UseIt(Input_Frequency(Document)))\n #Stop playing any sound\n if x == (NumberOfDocuments - 1):\n winsound.PlaySound(None, winsound.SND_ASYNC)\n</code></pre>\n\n<p>Why here instead of after the loop?</p>\n\n<pre><code> x += 1\n</code></pre>\n\n<p>Use a for loop, you should almost never use a while loop</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-18T03:10:57.403",
"Id": "6135",
"ParentId": "6126",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "6135",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-17T21:32:46.983",
"Id": "6126",
"Score": "4",
"Tags": [
"python",
"matrix",
"windows",
"natural-language-processing",
"neural-network"
],
"Title": "Back propagation neural network"
}
|
6126
|
<p>I have a user model.</p>
<p>It basically forwards get/create/delete requests into my database client.</p>
<p>The problem I have is the error handling, it screams not DRY to me, but I can't find an elegant way to clean it up.</p>
<pre><code>var UserModel = pd.make(Model, {
get: function _get(id, cb) {
// nano is a database client
this.nano.get(id,
// whitelist runs every error through the white list,
// if it fails (false) throw it
// if it succeeds (true) pass it to cb
// if the return value is undefined it does nothing
error.whitelist(function _errors(err) {
// getaddrinfo is a random DNS error I have to swallow
// no clue where the bug comes from, trying again is the easy fix
if (err.syscall === 'getaddrinfo') {
UserModel.get(id, cb);
} else if (err.error === "not_found") {
return true;
} else {
return false;
}
}, cb)
);
},
insert: function _create(json, cb) {
this.nano.insert(json, json._id,
error.whitelist(function _errors(err) {
if (err.syscall === 'getaddrinfo') {
UserModel.insert(json, cb);
} else if (err.error === "conflict") {
return true;
} else {
return false;
}
}, cb)
);
},
delete: function _delete(name, cb) {
var that = this;
this.get(name, function _getRev(err, body) {
that.nano.destroy(name, body._rev,
error.whitelist(function _errors(err) {
if (err.syscall === 'getaddrinfo') {
UserModel.delete(name, cb);
} else {
return false;
}
}, cb)
);
});
}
});
</code></pre>
<p><a href="https://github.com/Raynos/pd" rel="nofollow">pd</a>, <a href="https://github.com/Raynos/error" rel="nofollow">error</a>, <a href="https://github.com/dscape/nano" rel="nofollow">nano</a></p>
|
[] |
[
{
"body": "<p>Based on feedback from <a href=\"http://chat.stackoverflow.com/transcript/message/1900602#1900602\">JavaScript chat</a>. Credit to @Zirak and @Chris</p>\n\n<p>You want a hash of white listed error messages for each method</p>\n\n<pre><code>var whitelistMap = {\n \"get\": [\"not_found\"],\n \"insert\": [\"conflict\"],\n \"delete\": []\n}\n</code></pre>\n\n<p>You want a whitelist error handler factory. This will include the \"getaddrinfo\" code for every method which is basically a try again short cutting.</p>\n\n<p>It will check whether the error message is in the whitelistMap for that method and if so will let that error through.</p>\n\n<p>otherwise it simply throws</p>\n\n<pre><code>function makeWhitelistCallback(method, thing, cb) {\n return error.whitelist(function _errors(err) {\n if (err.syscall === \"getaddrinfo\") {\n UserModel[method](thing, cb);\n } else if (whitelistMap[method].indexOf(err.error) !== -1) {\n return true;\n } else {\n return false;\n }\n }, cb);\n}\n</code></pre>\n\n<p>And the rest of the code simply calls the whitelist callback factory</p>\n\n<pre><code>var UserModel = pd.make(Model,{\n get: function _get(id, cb) {\n this.nano.get(id, \n makeWhitelistCallback(\"get\", id, cb)\n );\n },\n insert: function _create(json, cb) {\n this.nano.insert(json, json._id, \n makeWhitelistCallback(\"insert\", json, cb)\n );\n },\n delete: function _delete(name, cb) {\n var that = this;\n this.get(name, function _getRev(err, body) {\n that.nano.destroy(name, body._rev, \n makeWhitelistCallback(\"delete\", name, cb)\n );\n });\n }\n});\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-17T22:19:58.723",
"Id": "6129",
"ParentId": "6127",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-17T21:45:57.810",
"Id": "6127",
"Score": "4",
"Tags": [
"javascript"
],
"Title": "Refactoring node.js database code"
}
|
6127
|
<p>Basically I'm writing a simple framework in php in order to learn more. This session class is extremely rudimentary. At this point I'm not even checking ip/user_agent to prevent session hijacking, it's just basic right now. Also, my <code>_serialize()</code> and <code>_unserialize</code> functions don't actually do anything special, but they might someday... haven't quite worked through that yet.</p>
<p>Before I started working on this mini framework, I had no idea what <code>static</code> was for or <code>get_instance()</code> as a Singleton pattern could do. It solved some of my original problems, but I get the feeling that I'm overusing it and I'd really like any explanations or ways to know when to work like that.</p>
<p>I justified setting the class up as I did so that I could, from anywhere in the application, simply call something like <code>Session::set('foo', 'bar);</code>, but I'm not sure if that is reason enough or if there is a better way to organize all of my classes.</p>
<p>The <code>Config::get()</code> simply fetches a configuration by key, it's sort of obvious what it's doing. The <code>Database:query()</code> does just what it says and returns an array of arrays, hence the place where I do something like <code>$result[0]['data'];</code></p>
<p>The session configuration looks like so:</p>
<pre><code>config['session'] = array(
'table' => 'sessions',
'match_ip' => TRUE,
'match_user_agent' => TRUE,
'cookie_expire' => time() + 60 * 60, // One hour
'cookie_path' => '/',
'expiration' => 60 * 15, // 15 minutes
'garbage_probability' => 10 // % of the time
);
</code></pre>
<p>The actual class looks like:
<pre><code>class Session {
private static $_instance;
private static $_id;
private static $_data = array();
private function __construct()
{
self::_start();
self::_garbage_collection();
}
private static function _start()
{
if (isset($_COOKIE['session']))
{
self::$_id = $_COOKIE['session'];
$statement = 'SELECT * FROM ' . Config::get('session', 'table') . " WHERE id='" . self::$_id . "'";
$result = Database::query($statement);
if ( ! $result)
{
self::_new_cookie();
}
self::$_data = self::_unserialize($result[0]['data']);
}
else
{
self::_new_cookie();
}
}
private static function _new_cookie()
{
self::$_id = self::_get_unique_id();
$statement = 'INSERT INTO ' . Config::get('session', 'table') . '(id, data, last_activity)' . " VALUES ('" . self::$_id . "', '" . self::_serialize(self::$_data) . "', " . time() . ')';
Database::query($statement);
setcookie('session', self::$_id, time() + Config::get('session', 'expiration'));
}
private static function _serialize($data)
{
return serialize($data);
}
private static function _unserialize($data)
{
return unserialize($data);
}
public static function set($name, $value)
{
$data = self::$_data;
self::$_data[$name] = $value;
self::_save_data();
}
public static function get($name)
{
if (isset(self::$_data[$name]))
{
return self::$_data[$name];
}
else
{
return FALSE;
}
}
public static function destroy()
{
$statement = 'DELETE FROM ' . Config::get('session', 'table') . " WHERE id='" . self::$_id . "'";
Database::query($statement);
setcookie('session', '', 1);
}
private static function _save_data()
{
$data = self::_serialize(self::$_data);
$statement = 'UPDATE ' . Config::get('session', 'table') . " SET data='{$data}', last_activity='" . time() . "' WHERE id='" . self::$_id . "'";
Database::query($statement);
}
private static function _get_unique_id()
{
$pool = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
$unique = FALSE;
while ( ! $unique)
{
$id = '';
for($i = 0; $i < 40; $i++)
{
$id .= $pool[rand(0, strlen($pool) -1)];
}
return $id;
$result = Database::query('SELECT * FROM ' . Config::get('session', 'table') . ' WHERE id=' . $id);
if($result)
{
$unique = FALSE;
}
else
{
$unique = TRUE;
}
}
}
public static function _garbage_collection()
{
$chance = rand(1, 100);
$probability = Config::get('session', 'garbage_probability');
if($chance <= $probability)
{
// Clean up
$expiration = time() - Config::get('session', 'expiration');
$statement = 'DELETE FROM ' . Config::get('session', 'table') . ' WHERE last_activity < ' . $expiration;
Database::query($statement);
}
}
public static function get_instance()
{
if (! self::$_instance)
{
self::$_instance = new Session();
}
return self::$_instance;
}
}
/* End of file session.php */
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-18T09:52:15.860",
"Id": "9494",
"Score": "3",
"body": "Matthew there are numerous problems with the code. You do abuse static, you really need to understand the concept before applying it. Every static member or function you have shouldn't have been a static (except for those that participate in making this a singleton). It'd take a lot of time for a proper review, please read up on static and revise the code so it'd be easier to identify other issues."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-18T16:41:09.760",
"Id": "9504",
"Score": "1",
"body": "@YannisRizos, right, I agree. That's actually my main question (how/when to use static). The reason I have troubles is because not static functions can't access the static properties and static function can't access not static properties (which makes more sense)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-18T16:43:53.863",
"Id": "9505",
"Score": "0",
"body": "The how/when to use static is not a good question for Code Review, as it's a conceptual question. You can ask it on [Programmers Stack Exchange](http://programmers.stackexchange.com/), with a reference to your question here to get better answers."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-19T16:02:25.133",
"Id": "39124",
"Score": "0",
"body": "You also *really* don't need methods for serialize / unserialize, when PHP already does this for you."
}
] |
[
{
"body": "<p>The biggest problem you have is this:</p>\n\n<pre><code>self::$_id = $_COOKIE['session'];\n$statement = 'SELECT * FROM ' . Config::get('session', 'table') . \" WHERE id='\" . self::$_id . \"'\";\n</code></pre>\n\n<p>You are <em>blindly</em> trusting user input. This is not only a vector for a <a href=\"http://bobby-tables.com/\" rel=\"nofollow\">SQL Injection attack</a>, it is a gaping hole.</p>\n\n<p><em>Always use parameterized queries.</em></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-18T10:25:48.537",
"Id": "6138",
"ParentId": "6133",
"Score": "3"
}
},
{
"body": "<p>Some generic notes:</p>\n\n<p>1, I agree with @Bobby, the code is vulnerable to SQL injection.</p>\n\n<p>2, I'd invert some condition:</p>\n\n<pre><code>private static function _start() {\n if (!isset($_COOKIE['session'])) {\n self::_new_cookie();\n return;\n }\n\n self::$_id = $_COOKIE['session'];\n $statement = 'SELECT * FROM ' . Config::get('session', 'table') . \" WHERE id='\" \n . self::$_id . \"'\";\n $result = Database::query($statement);\n if ( ! $result)\n {\n self::_new_cookie();\n }\n self::$_data = self::_unserialize($result[0]['data']);\n}\n</code></pre>\n\n\n\n<p>and extract out some functions:</p>\n\n<pre><code>...\n if ($chance <= $probability) {\n doGarbageCollection();\n }\n}\n\nfunction doGarbageCollection() {\n $expiration = time() - Config::get('session', 'expiration');\n $statement = 'DELETE FROM ' . Config::get('session', 'table') \n . ' WHERE last_activity < ' . $expiration;\n Database::query($statement);\n}\n</code></pre>\n\n<p>It makes the code <a href=\"http://www.codinghorror.com/blog/2006/01/flattening-arrow-code.html\" rel=\"nofollow\">flatten</a> which is easier to read. </p>\n\n<p>3, In the <code>_get_unique_id()</code> function there is a <code>return</code> statement in the middle of the <code>while</code> loop. The code after this <code>return</code> is dead code, it never runs:</p>\n\n<pre><code>return $id;\n\n$result = Database::query('SELECT * FROM ' . Config::get('session', 'table') \n . ' WHERE id=' . $id);\n...\n</code></pre>\n\n<p>I think you should remove that <code>return</code>.</p>\n\n<p>4, I'd remove the <code>unique</code> flag and restructure the while loop:</p>\n\n<pre><code>while (true) {\n $id = '';\n for($i = 0; $i < 40; $i++) {\n $id .= $pool[rand(0, strlen($pool) -1)];\n }\n\n $result = Database::query('SELECT * FROM ' . Config::get('session', 'table') \n . ' WHERE id=' . $id);\n if (!$result) {\n return $id;\n }\n}\n</code></pre>\n\n<p>It's easier to read and does the same.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-15T22:24:55.050",
"Id": "6893",
"ParentId": "6133",
"Score": "2"
}
},
{
"body": "<p>You should call that a cookie class. Cookies are stored on the client side, whereas sessions are stored server side. (<a href=\"http://php.net/manual/en/reserved.variables.cookies.php\" rel=\"nofollow noreferrer\">$_COOKIE</a> vs <a href=\"http://php.net/manual/en/reserved.variables.session.php\" rel=\"nofollow noreferrer\">$_SESSION</a>)</p>\n\n<p>As you thought, static is causing you problems. The reasons are:</p>\n\n<p>Your methods are now globally accessible procedures. The benefit of calling them from anywhere is outweighed by the loss of encapsulation that is at the heart of OOP.</p>\n\n<p>The following are virtually equivalent (its only like a namespace with static):</p>\n\n<pre><code>class your\n{\n public static function func() {}\n}\n\nfunction your_func() {}\n</code></pre>\n\n<p>Last, but <strong>most importantly</strong>, check out articles on dependency injection. This post lists quite a few links which are worth reading: <a href=\"https://stackoverflow.com/questions/7676515/should-i-remove-static-function-from-my-code\">Should i remove static function from my code</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-16T02:41:20.587",
"Id": "6906",
"ParentId": "6133",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "6138",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-18T00:20:41.200",
"Id": "6133",
"Score": "2",
"Tags": [
"php",
"design-patterns",
"mvc"
],
"Title": "A simple php Session class, is the layout/design correct?"
}
|
6133
|
<p>I have a WebPostRequest class which looks like this:</p>
<pre><code>public class WebPostRequest
{
public const string Success = "OK";
private WebRequest _webRequest;
private List<string> _paramsList;
public WebPostRequest(string url)
{
try
{
_webRequest = WebRequest.Create(url);
}
catch (Exception)
{
throw;
}
_webRequest.Method = "POST";
_webRequest.ContentType = "application/x-www-form-urlencoded";
_paramsList = new List<string>();
}
public void Add(string key, string value)
{
_paramsList.Add(String.Format("{0}={1}", key, HttpUtility.UrlEncode(value)));
}
public void UploadPdf(string postKey, string name, params UserControl[] userControls)
{
string fileName = FileHelper.GetTimestampedName(name, "pdf");
string filePath = PdfHelper.Save(fileName, userControls);
FtpHelper.UploadFile(filePath);
this.Add(postKey, fileName);
}
public void UploadImage(string postKey, string name, Image image)
{
if (image != null)
{
string fileName = FileHelper.GetTimestampedName(name, "jpg");
FtpHelper.UploadFile(fileName, image.ToByteArray());
this.Add(postKey, fileName);
}
}
public string GetResponse()
{
// Build a string containing all the parameters
string parameters = String.Join("&", _paramsList.ToArray());
_webRequest.ContentLength = parameters.Length;
try
{
// Write the parameters into the request
using (StreamWriter streamWriter = new StreamWriter(_webRequest.GetRequestStream()))
{
streamWriter.Write(parameters);
}
// Execute the query
HttpWebResponse httpWebResponse = (HttpWebResponse)_webRequest.GetResponse();
StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream());
return streamReader.ReadToEnd();
}
catch (Exception)
{
throw;
}
}
}
</code></pre>
<p>The WebPostRequest class uses a WebRequest object to POST to a web server and get the response.</p>
<p>The class is used like this:</p>
<pre><code>bool success = false;
try
{
WebPostRequest webPostRequest = new WebPostRequest(url);
webPostRequest.Add("key_1", "value_1");
webPostRequest.Add("key_2", "value_2");
webPostRequest.UploadPdf("key_3", "pdf_name_1", userControl1);
webPostRequest.UploadPdf("key_4", "pdf_name_2", userControl2);
webPostRequest.UploadImage("key_5", "picture_name_1", image1);
webPostRequest.UploadImage("key_6", "picture_name_1", image2);
string response = webPostRequest.GetResponse();
if (response != WebPostRequest.Success)
{
throw new Exception(response);
}
success = true;
}
catch (Exception ex)
{
//display error messaage
}
if (success)
{
//display success message
}
</code></pre>
<p>What i would like to do is add a window to display a status message and a progress bar (with marquee style). The window needs to be displayed from the WebPostRequest class, because this class is used in multiple locations in the app. The uploading tasks which may take a long time need to be executed on a different thread so that the UI thread remains responsive. Note that all the files need to be uploaded before the POST is made, so the GetResponse method needs to wait for the uploading tasks to finish. Note also that the helper methods can throw errors which are handled outside the WebPostRequest class.</p>
<p>What tips/suggestions can you give me? Any idea is appreciated.</p>
|
[] |
[
{
"body": "<p>I would not show any UI from WebPostRequest. For a fast solution you can just wrap the whole upload part and provide some sort of a listener whose methods will be called to notify about progress.</p>\n\n<p>Thus WebPostRequest will not know nothing about UI layer. UI will not be blocked and be able to track upload progress.</p>\n\n<p>Here's a C#-like pseudo code that illustrates what I mean:</p>\n\n<pre><code>class ProgressListener\n{\n public void OnProgress(OperationContext)\n {\n //notiy UI in the thread-safe way -> use Control.Invoke for Windows Forms\n }\n\n public void OnFinish(OperationContext)\n {\n //show success message in UI\n }\n\n public void OnError(OperationContext)\n {\n //show detailed error message in UI\n }\n}\n\n//on UI class\nvoid PerformUpload()\n{\n\n ProgressListener listener = new ProgressListener(Form f);\n\n Thread thread = new Thread(() =>\n {\n try\n {\n try\n {\n WebPostRequest webPostRequest = new WebPostRequest(url);\n webPostRequest.Add(\"key_1\", \"value_1\");\n webPostRequest.Add(\"key_2\", \"value_2\");\n\n webPostRequest.UploadPdf(\"key_3\", \"pdf_name_1\", userControl1);\n\n listener.OnProgress( /*operaton context*/)\n\n webPostRequest.UploadPdf(\"key_4\", \"pdf_name_2\", userControl2);\n\n listener.OnProgress( /*operaton context*/)\n webPostRequest.UploadImage(\"key_5\", \"picture_name_1\", image1);\n\n listener.OnProgress( /*operaton context*/)\n webPostRequest.UploadImage(\"key_6\", \"picture_name_1\", image2);\n\n listener.OnProgress( /*operaton context*/)\n\n string response = webPostRequest.GetResponse();\n if (response != WebPostRequest.Success)\n {\n listener.OnProgress( /*operaton context*/)\n\n throw new Exception(response);\n }\n success = true;\n\n listener.OnFinish( /*operaton context*/)\n }\n catch (Exception ex)\n {\n listener.OnError( /*operaton context*/)\n //display error messaage\n } \n }\n catch(Exception ex)\n {\n listener.OnError( /*operaton context*/)\n //logging\n }\n });\n\n thread.Name = \"uploader\";\n thread.Start();\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-11T10:53:39.170",
"Id": "6717",
"ParentId": "6134",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "6717",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-18T01:37:27.807",
"Id": "6134",
"Score": "2",
"Tags": [
"c#",
"multithreading"
],
"Title": "How to refactor code to use threads?"
}
|
6134
|
<p>I have the following code which is located within a case, in a switch statement. Its goal is to add a Pupil to a Subject using the Collections in the respective class.</p>
<p>I've tried to make the code as readable as possible, but I'm sure there's a better approach.</p>
<pre><code> System.out.println("Adding a Pupil...");
String AddPupilSubj;
do {
UserInput.prompt("\nEnter the Subject Code to add the Pupil to, or enter 'list' to list all Subjects: ");
AddPupilSubj = UserInput.readString();
if(AddPupilSubj.equals("list"))
school.listSubjects();
} while(AddPupilSubj.isEmpty() || AddPupilSubj.equals("list"));
Boolean found = false;
// Locate the Subject
for(Object obj : school.getSubjects()) {
Subject subj = (Subject) obj;
if(subj.getCode().equals(AddPupilSubj)) {
found = true;
// Get the ID of the Pupil
UserInput.prompt("Enter Pupil ID: ");
int id = UserInput.readInt();
// Get the Pupil's Name
UserInput.prompt("Enter Pupil Name: ");
String name = UserInput.readString();
// Get the Address of the Pupil
UserInput.prompt("Enter Pupil Address: ");
String address = UserInput.readString();
String date; Boolean valid;
do {
// Get the Pupil's Date of Birth
UserInput.prompt("Enter Pupil Date of Birth (dd/mm/yyyy): ");
date = UserInput.readString();
valid = validDOB(date);
} while(!valid);
// Get the Pupil's email address
UserInput.prompt("Enter Pupil Email: ");
String email = UserInput.readString();
DateTime dob = DateTime.forDateOnly(Integer.parseInt(date.substring(6, 10)),
Integer.parseInt(date.substring(3, 5)),
Integer.parseInt(date.substring(0, 2)));
DateTime admitted = DateTime.today(TimeZone.getDefault());
Pupil Pupil = new Pupil(id, name, address, dob, email, admitted);
if(subj.addPupil(Pupil)) {
System.out.println(
String.format("\nPupil, %s, has been added to the %s Subject.",
Pupil.getName(),
subj.getName()));
} else {
System.out.println(
String.format("Pupil #%s is already in the Subject!",
Pupil.getID()));
}
break;
}
}
if(!found) {
System.out.println(
String.format("A Subject with code, %s, doesn't exist!",
AddPupilSubj));
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-21T15:24:53.347",
"Id": "9579",
"Score": "1",
"body": "Just a small one: what benefit are you gaining from using `Boolean` instead of `boolean`?"
}
] |
[
{
"body": "<p>Seems to me like you have a couple functions here that need pulled out:</p>\n\n<ol>\n<li>findSubject</li>\n<li>collect input and validate\n<ul>\n<li>I'd also pull out a function for anything more involved like the date prompts that need validated</li>\n</ul></li>\n<li>create pupil and add</li>\n</ol>\n\n<p>Other questions:</p>\n\n<ul>\n<li>are there other places that a pupil gets input? you should avoid duplicating this code</li>\n<li>why note have validDob return a valid DOB instead of having two different version of this code 1) validates, 2) converts to Date object</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-18T16:07:58.087",
"Id": "6141",
"ParentId": "6139",
"Score": "3"
}
},
{
"body": "<p>I would use a couple helper methods. Most importantly, you really shouldn't have this much within a <code>switch</code> <code>case</code>, put it into a method and call the method from the <code>switch</code>. Then, I would put all the code for inputting the pupil information and creating the pupil (from the ID prompt through the <code>new Pupil(...)</code> into a separate method and return the new pupil; possibly even make it a constructor for <code>Pupil</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-18T16:08:58.653",
"Id": "6142",
"ParentId": "6139",
"Score": "1"
}
},
{
"body": "<p><strong>The function is very long.</strong></p>\n\n<p>Functions should do one thing, do it completely, and do it well. Long functions are difficult to reason about.</p>\n\n<p>Move the subject and pupil data entry into separate functions to isolate the functionality, and streamline the mainline code.</p>\n\n<p>I'm assuming the presence of <code>String getSubjectCode()</code> and <code>Pupil getPupilInformation()</code> methods, each containing the code currently in the mega-function.</p>\n\n<p><strong>Naming conventions</strong></p>\n\n<p>Minor, but you call an instance of the <code>Pupil</code> class <code>Pupil</code>, which is confusing at best, misleading at worst. Non-static-final variables should always begin with lowercase letters.</p>\n\n<p><strong>Use typed collections</strong></p>\n\n<p><code>School.getSubjects()</code> should return a <code>List<Subject></code> (or <code>Collection</code>). (Or at least a properly-typed array; nothing with <code>Object</code>s.)</p>\n\n<p><strong>Reduce the amount of code in conditionals</strong></p>\n\n<p>There's a lot of code in block that loops over the school's subjects, most of which is the block for when the subject is found.</p>\n\n<p>In order to understand what happens if the subject <em>isn't</em> found, I have to scroll down to the end of that block, make sure I'm reading the indentation correctly (assuming the indentation is correct), only to find there's nothing there.</p>\n\n<p>In cases like that, might as well do a negative test and <code>continue</code>, slightly \"flattening\" the loop's guts. (Code turned on its side is not a graph of how awesome it is ;)</p>\n\n<p>That said, this functionality is available in a <code>contains</code> method--looping in the mainline code isn't necessary. See next.</p>\n\n<p><strong>Localize functionality</strong></p>\n\n<p>Deciding if a school has a given subject should be moved into the <code>School</code> class, for example:</p>\n\n<pre><code>public class School {\n // ... existing functionality elided ...\n\n /** Returns subject with given code, or null if not found. */\n public Subject findSubjectByCode(String code) {\n for (Subject s : subjects) {\n if (s.getCode().equals(code)) {\n return s;\n }\n }\n return null;\n }\n}\n</code></pre>\n\n<p><strong>The refactored mainline code</strong></p>\n\n<p>All the above turns the mainline code into the following:</p>\n\n<pre><code>System.out.println(\"Adding a Pupil...\");\n\nString subjectCode = getSubjectCode();\nSubject schoolSubject = school.findSubjectByCode(subjectCode);\nif (schoolSubject == null) {\n System.out.printf(\"A Subject with code, %s, doesn't exist!%n\", subjectCode);\n return;\n}\n\nPupil pupil = getPupilInformation();\nif (schoolSubject.addPupil(pupil)) {\n System.out.printf(\"%nPupil, %s, has been added to the %s Subject.%n\", pupil.getName(), subj.getName());\n} else {\n System.out.printf(\"Pupil #%s is already in the Subject!%n\", pupil.getID());\n}\n</code></pre>\n\n<p>IMO this is more communicative, cleaner, and easier to understand.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-20T19:23:30.360",
"Id": "6171",
"ParentId": "6139",
"Score": "7"
}
},
{
"body": "<p>Lots of work here to do! I'll try to get you started on refactoring this:</p>\n\n<h2>Clarify Your Intent</h2>\n\n<p>I'm not seeing a class or method definition here. Please declare at least one of these so as to give your reader a clue on what this code is attempting to do.</p>\n\n<p>One way to extract your class and method names is to examine your logging or println's.</p>\n\n<blockquote>\n <p>\"Adding a Pupil...\"</p>\n</blockquote>\n\n<p><strong>A-HA!</strong> So your first step is to make a class called \"Pupil\" and a method \"add\" (or \"addPupil\"). Make sure that the method \"add\" adds a pupil to a List of pupil objects.</p>\n\n<p>NOTE: If you're getting a funny feeling about \"adding a pupil to a pupil\" and how it seems strange, make note of it and come back to it later because we're not done yet! (i.e. perhaps there's some more abstractions to find...)</p>\n\n<h2>Extract Classes</h2>\n\n<p>The goal here is to create the appropriate abstractions. One guiding principle you can use is the <a href=\"http://en.wikipedia.org/wiki/Single_responsibility_principle\">Single Responsibility Principle</a>, <em>a class should have a single reason to change</em>. I'm going to continue searching your println's/comments for possible hints.</p>\n\n<ul>\n<li><p>I see \"Enter the Subject Code\" in the prompt. So now you have a Subject class! (already there? great!)</p></li>\n<li><p>Add the following fields to Pupil: int id, String firstName, String lastName, String address*, String* dateOfBirth.</p></li>\n<li><p>I see an operations on a school variable yet one is not defined. Perhaps there is a School object? So now we can move the list of Pupils to School.</p></li>\n</ul>\n\n<p>*Address should be its own class with separate fields for street1, street2, city, state, and zip.</p>\n\n<p>*eventually convert dateOfBirth to a date format; I see you're using DateTime.</p>\n\n<h2>Move Logic Into Classes</h2>\n\n<p>Make methods out of existing conditionals and place in the appropriate class. If you don't have a class that it fits in, make a new class.</p>\n\n<p>For example, this code snippet could be encapsulated in a method:</p>\n\n<p><strong>DateTime createDateOfBirth (String date)</strong></p>\n\n<pre><code>DateTime dob = DateTime.forDateOnly(Integer.parseInt(date.substring(6, 10)), \n Integer.parseInt(date.substring(3, 5)),\n Integer.parseInt(date.substring(0, 2)));\n</code></pre>\n\n<h2>Minor cleanup</h2>\n\n<p>Make small changes like renaming fields, moving field declarations (limiting local variable scope), or make helper functions to improve your code readability. </p>\n\n<ul>\n<li><p>\"String AddPupilSubj\" should be lowercase. Possible that this lives 'too long' as well.</p></li>\n<li><p>Modify \"if(AddPupilSubj.equals(\"list\"))\":</p>\n\n<ol>\n<li>change to \"list\".equals(AddPupilSubject)</li>\n<li>add AddPupilSubject.toLowerCase() since you are comparing it to \"list\".</li>\n<li>possibly call AddPupilSubject.trim() as well to delete any whitespace so that way if someone entered \"list \", your function will work.</li>\n</ol></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-28T17:21:26.163",
"Id": "6366",
"ParentId": "6139",
"Score": "6"
}
},
{
"body": "<p>I would extract out the input/output handling logic to an <code>UserInputOutput</code> interface:</p>\n\n<pre><code>public interface UserInputOutput {\n\n String readCommand();\n\n int readPupilId();\n\n String readPupilName();\n\n String readPupilAddress();\n\n Date readPupilBirthDate();\n\n ...\n}\n</code></pre>\n\n<p>then create a <code>ConsoleUserInputOutput</code> class which implements the interface and pass a reference to the code. </p>\n\n<p>It means looser coupling and if you write some test code you can easily create a mocked class which emulates the user input/output and you can create a <code>TouchScreenUserInputOutput</code> class for touch screens without the need of modification of your class.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-29T09:44:32.533",
"Id": "6377",
"ParentId": "6139",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-18T15:27:44.137",
"Id": "6139",
"Score": "3",
"Tags": [
"java"
],
"Title": "Entering pupil information"
}
|
6139
|
<p>I have two functions, one to convert a datetime to a hex word, and one to convert a word to a datetime. I was just wondering if there was a more efficient way to convert back and forth.</p>
<pre><code>/// <summary>
/// Converts a date time to a hexadecimal word
/// </summary>
/// <param name="date">the date time</param>
/// <returns>returns the Hex value of the date</returns>
private int convertToWordFromDate(DateTime date)
{
int m, d, y;
int month = date.Month;
int day = date.Day;
int year = int.Parse(date.Year.ToString().Substring(2, 2));
int yearShift = 9;
int monthShift = 5;
int word;
y = year << yearShift;
m = month << monthShift;
d = day;
if (year == 0)
word = m + d + (y * 100);
if (year < 10)
word = (m + d + y) * 16;
else
word = m + d + y;
return word;
}
/// <summary>
/// Converts a hexadecimal word to a valid dateTime
/// </summary>
/// <param name="word">the word</param>
/// <returns>the date time</returns>
private DateTime convertToDateFromWord(int word)
{
int month, day, year;
int monthMask = 0x01E0;
int dayMask = 0x001F;
int yearMask = 0xFE00;
int monthShift = 32;
int yearShift = 512;
DateTime date = new DateTime();
try
{
year = (word & yearMask) / yearShift;
month = (word & monthMask) / monthShift;
day = (word & dayMask);
if (year >= 80 && year <= 99)
year += 1900;
else if (year >= 0 && year <= 79)
year += 2000;
else if (year < 0 || month <= 0 || day <= 0)
{
year = 1;
month = 1;
day = 1;
}
else
{
year = 1;
month = 1;
day = 1;
}
date = new DateTime(year, month, day);
}
catch
{
date = new DateTime(1, 1, 1);
}
return date;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-18T17:15:41.110",
"Id": "9507",
"Score": "0",
"body": "Out of curiousity, _why_ are you doing this? And you should really see about getting the shifts and masks defined at the _class_ level, and ideally, have one depend on the other (so changes are automatically propogated)."
}
] |
[
{
"body": "<p>I note that your functions are not doing what they say they're doing. For example, you don't convert a date to a hexadecimal word, you convert to an integer value, a value that also happens to disregard the century and the time component entirely. In getting the date back, you also perform some business rules against the date, by treating certain years as last century, other years as current century.</p>\n\n<p>What I would <em>expect</em> when seeing these functions is that I would certainly get the same date I passed into one function as the output from the other. That is not necessarily going to be the case. </p>\n\n<p>You also have issues with a blanket <code>catch</code> that swallows any exception. If you are going to catch an exception, <em>be specific</em> and catch what you truly can handle, something you might expect. Work towards eliminating those exceptions entirely, so instead of catching them, you are <em>preventing</em> them by validating against their causes beforehand, if possible. </p>\n\n<p>You have an if/else chain where an <code>else if</code> and <code>else</code> have the exact some code in their code blocks. Eliminate the redundancy. </p>\n\n<p>There are issues with <em>shifts</em> and <em>masks</em> not being consistent, in terms of where they are defined and the methodology being used. If you change something in one place, you have to change it in another. More than that, <em>you have to change it in a different way.</em> </p>\n\n<p>To be blunt, it's basically not clear what the code is doing at an initial glance, nor is it necessarily clear <em>why</em> it is doing it. </p>\n\n<p>I don't know what your business case is, but if I was writing a class to convert a date to a \"hexadecimal word\" and then back again, I would probably expect to write something that takes a date and returns a string, and then takes a string and returns a date. The quick, not completely tested version might be something simple like this </p>\n\n<pre><code>public class DateConverter\n{\n public string ConvertToHexString(DateTime date)\n {\n return date.Ticks.ToString(\"X2\");\n }\n\n public DateTime ConvertFromHexString(string hexInput)\n {\n long ticks = Convert.ToInt64(hexInput, 16);\n return new DateTime(ticks);\n }\n}\n</code></pre>\n\n<p>Which you could validate with </p>\n\n<pre><code>DateTime originalDate = new DateTime(1955, 11, 11, 22, 4, 0);\nDateConverter converter = new DateConverter();\n\nstring hexValue = converter.ConvertToHexString(originalDate);\nDateTime returnedDate = converter.ConvertFromHexString(hexValue);\n\nDebug.Assert(originalDate == returnedDate);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-18T18:28:46.777",
"Id": "6146",
"ParentId": "6140",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "6146",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-18T15:54:53.543",
"Id": "6140",
"Score": "2",
"Tags": [
"c#"
],
"Title": "Converting a Date to Hexadecimal Word"
}
|
6140
|
<p>For a project I'm working on, I need to compare version strings where:</p>
<ul>
<li>version strings are composed only of numbers and periods</li>
<li>version strings are made up of an arbitrary number of segments (major.minor, manjor.minor.build, etc)</li>
<li>1.0 is equivalent to 1.0.0, etc.</li>
</ul>
<p><strong>Please provide feedback on performance considerations or style.</strong></p>
<p>Here's my shot at it:</p>
<pre><code>public class VersionStringComparer : IComparer<string>
{
public int Compare(string x, string y)
{
if (x == y) return 0;
var xparts = x.Split('.');
var yparts = y.Split('.');
var length = new[] {xparts.Length, yparts.Length}.Max();
for (var i = 0; i < length; i++)
{
int xint;
int yint;
if (!Int32.TryParse(xparts.ElementAtOrDefault(i), out xint)) xint = 0;
if (!Int32.TryParse(yparts.ElementAtOrDefault(i), out yint)) yint = 0;
if (xint > yint) return 1;
if (yint > xint) return -1;
}
//they're equal value but not equal strings, eg 1 and 1.0
return 0;
}
}
</code></pre>
<p>And two quick unit tests (using the <a href="http://should.codeplex.com/" rel="nofollow">Should.Fluent library</a>:</p>
<pre><code> [TestMethod]
public void VersionStringComparerSortsMajorAndMinorVersionString()
{
var versions = new[]{"1.5","1.0","2.0","1.0"};
var versionStringComparer = new ReleaseGateway.Util.VersionStringComparer();
var sorted = versions.OrderBy(x => x, versionStringComparer).ToArray();
var expected = new[] {"1.0", "1.0", "1.5", "2.0"};
sorted.Should().Equal(expected);
}
[TestMethod]
public void VersionStringComparerSortsArbitraryRadixVersionStrings()
{
var versions = new[] { "1.5.4", "1.7", "1.0", "1","1.4" };
var versionStringComparer = new ReleaseGateway.Util.VersionStringComparer();
var sorted = versions.OrderBy(x => x, versionStringComparer).ToArray();
var expected = new[] { "1.0", "1", "1.4", "1.5.4", "1.7" };
sorted.Should().Equal(expected);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-19T07:55:26.433",
"Id": "9519",
"Score": "10",
"body": "Uhh, what's wrong with using [`Version.Parse`](http://msdn.microsoft.com/en-us/library/system.version.parse.aspx) to parse it and comparing `Version` instances?"
}
] |
[
{
"body": "<p>I adjusted the compare method slightly, making it more readable (IMO) through the use of an Anonymous type with named properties and by extracting two helper methods.</p>\n\n<p>I'm not checking the result of <code>TryParse</code> anymore since the <code>result</code> is <code>0</code> for failed conversions.<br>\nRegarding performance: on my machine, your version runs ten thousand iterations in ~400ms, while mine seems to shave off around one fourth, running the same amount of iterations at ~300ms. </p>\n\n<p>This should be because I moved the parsing of the versions <em>out of the loop</em>.<br>\nI measured this using a System.Diagnostics.Stopwatch. </p>\n\n<p><strong>EDIT:</strong> A note on performance... micro-optimizations such as the ones I've done are <strong>meaningless</strong> unless you have actually identified a real <strong><a href=\"http://en.wikipedia.org/wiki/Bottleneck_%28engineering%29#Engineering\" rel=\"nofollow\">bottleneck</a></strong> in your code. I only ran these simplified benchmarks to make sure I wasn't making your implementation <em>slower</em> while getting it into a more <strong>expressive</strong> form.</p>\n\n<pre><code>public int Compare(string x, string y)\n{\n if (x == y) return 0;\n var version = new { First = GetVersion(x), Second = GetVersion(y) };\n int limit = Math.Max(version.First.Length, version.Second.Length);\n for (int i = 0; i < limit; i++)\n {\n int first = version.First.ElementAtOrDefault(i);\n int second = version.Second.ElementAtOrDefault(i);\n if (first > second) return 1;\n if (second > first) return -1;\n }\n return 0;\n}\n\nprivate int[] GetVersion(string version)\n{\n return (from part in version.Split('.')\n select Parse(part)).ToArray();\n}\n\nprivate int Parse(string version)\n{\n int result;\n int.TryParse(version, out result);\n return result;\n}\n</code></pre>\n\n<p>This adapted converter returns the same test results as your original one - though I haven't tried to test it more thoroughly - maybe someone can spot an edge case? ;-)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-26T19:05:46.847",
"Id": "7174",
"ParentId": "6143",
"Score": "2"
}
},
{
"body": "<p>The performance considerations for your implementation are negligible, and I think it would probably be a waste of time and would sacrifice readability to try to optimize it any further, but for the sake of discussion I'll point out what I think are the things in this code that affect performance the most.</p>\n\n<ol>\n<li><p>You can use <code>Math.Max(xparts.Length, yparts.Length)</code> in order to determine the max length between the two arrays. Your implementation unnecessarily allocates an array so that you can call the <code>Max</code> extension method for <code>IEnumerable<int></code>.</p></li>\n<li><p>For each string (x and y) you are allocating an array in order to store each part of the string when you call <code>x.Split('.')</code> and <code>y.Split('.')</code>. I don't see this as a problem, because it is a very straightforward approach. However, if you felt that you needed to avoid that, then you could write a more complicated implementation using calls to <code>IndexOf</code> and <code>Substring</code>. The only benefit this would give you is that it would avoid allocating the array, but each call to <code>Substring</code> would still allocate a new string object for each part of the string. I suppose a super-performant implementation would involve some kind of <code>Int32.TryParse</code> method that accepts a string parameter along with a startIndex and length parameter; this method would theoretically parse an Int32 value from a substring without having to create an additional string object.</p></li>\n</ol>\n\n<p>An alternative implementation that utilizes the <code>IndexOf</code> and <code>Substring</code> methods is shown below. Although some crude benchmarking indicates that this implementation is faster, I'm not sure that I would use it because it is more complicated.</p>\n\n<pre><code>public static class StringExtensions\n{\n public static bool TryParseSubstringInt32(this string input, int startIndex, int length, out int value)\n {\n // TODO: replace this code with a more efficient version that parses an Int32 value from a substring without allocating a new string\n string s = input.Substring(startIndex, length);\n return int.TryParse(s, out value);\n }\n}\n\npublic class VersionStringComparer : IComparer<string>\n{\n static int GetPart(string version, ref int currentIndex, ref int indexOfDot)\n {\n int part;\n\n if (indexOfDot < 0)\n {\n if (!version.TryParseSubstringInt32(currentIndex, version.Length - currentIndex, out part))\n part = 0;\n\n currentIndex = version.Length;\n }\n else\n {\n if (!version.TryParseSubstringInt32(currentIndex, indexOfDot - currentIndex, out part))\n part = 0;\n\n currentIndex = indexOfDot + 1;\n indexOfDot = version.IndexOf('.', currentIndex);\n }\n\n return part;\n }\n\n public int Compare(string x, string y)\n {\n if (x == y) return 0;\n\n int xCurrentIndex = 0;\n int yCurrentIndex = 0;\n\n int xIndexOfDot = x.IndexOf('.', xCurrentIndex);\n int yIndexOfDot = y.IndexOf('.', yCurrentIndex);\n\n int xPart;\n int yPart;\n\n int xLength = x.Length;\n int yLength = y.Length;\n\n while (xCurrentIndex < x.Length && yCurrentIndex < y.Length)\n {\n xPart = GetPart(x, ref xCurrentIndex, ref xIndexOfDot);\n yPart = GetPart(y, ref yCurrentIndex, ref yIndexOfDot);\n\n if (xPart > yPart) return 1;\n if (xPart < yPart) return -1;\n }\n\n if (xCurrentIndex < x.Length)\n {\n do\n {\n xPart = GetPart(x, ref xCurrentIndex, ref xIndexOfDot);\n\n if (xPart > 0) return 1;\n if (xPart < 0) return -1;\n\n } while (xCurrentIndex < x.Length);\n }\n else if (yCurrentIndex < y.Length)\n {\n do\n {\n yPart = GetPart(y, ref yCurrentIndex, ref yIndexOfDot);\n\n if (yPart > 0) return -1;\n if (yPart < 0) return 1;\n\n } while (yCurrentIndex < y.Length);\n }\n\n return 0;\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-27T20:48:22.090",
"Id": "11233",
"Score": "0",
"body": "I'll stress it here, again. It makes absolutely no sense to do such *optimizations* before you have determined for a fact whether comparing two versions really is the bottleneck in your system (hint: **it isn't.**) It is *seldom* a good idea to sacrifice readability for a *micro-optimization*. Such measures will lead to an utterly [unmaintainable](http://thc.org/root/phun/unmaintain.html) code-base."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-27T22:37:35.390",
"Id": "11240",
"Score": "0",
"body": "Agreed. The first sentence of my answer says that it would probably be a waste of time to optimize this code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-27T22:39:13.607",
"Id": "11241",
"Score": "0",
"body": "Sorry if this sounded as if I hadn't read your answer, of course I have; and I was *very grateful* that you included the warning, but I wanted to but a bit more emphasis on it for other readers."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-28T14:07:01.580",
"Id": "11269",
"Score": "0",
"body": "@codesparkle - my apologies as well for the terseness of my comment; I wanted to clarify my position as well that I am in agreement. Appreciate your comment stressing the importance of addressing performance issues by identifying actual bottlenecks."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-27T17:20:23.823",
"Id": "7185",
"ParentId": "6143",
"Score": "1"
}
},
{
"body": "<p>Two notes about the tests:</p>\n\n<p>1, I'd extract out the following two lines to a method:</p>\n\n<pre><code>var versionStringComparer = \n new ReleaseGateway.Util.VersionStringComparer();\nvar sorted = \n versions.OrderBy(x => x, versionStringComparer).ToArray();\n</code></pre>\n\n<p>They're the same in both tests. An <code>assertSortedEquals(exptectedArray, inputArray)</code> also would be fine. It would made your test methods one-liners which would be easier to read.</p>\n\n<p>2, Having these tests is good, but if you have only these two tests it doesn't help <a href=\"http://xunitpatterns.com/Goals%20of%20Test%20Automation.html#Defect%20Localization\" rel=\"nofollow\">defect localization</a> too much. It would be more effective if you write a few more tests:</p>\n\n<ul>\n<li><code>testDifferentMinorVersion</code>: <code>1.0 < 1.1</code></li>\n<li><code>testDifferentMinorVersionWithZeroBuildNumber</code>: <code>1.0 == 1.0.0</code></li>\n<li><code>testDifferentMinorVersionWithMoreDecimals</code>: <code>1.9 < 1.10</code></li>\n<li><code>testDifferentMajorVersion</code>: <code>1.0 < 2.0</code></li>\n</ul>\n\n<p>I see that some of these are covered by your current tests but if there was a bug in the logic you would not know which part is broken, you just get an error with two different list. Otherwise, you could get a more detailed error message which says, for example, <code>1.9</code> should be less than <code>1.10</code>, but currently it doesn't work. A few custom assertion methods could help a lot for these tests: <code>assertBigger(version1, version2)</code>, assertSameVersion(version1, version2)`.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-27T19:56:34.637",
"Id": "7189",
"ParentId": "6143",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-18T17:11:42.930",
"Id": "6143",
"Score": "4",
"Tags": [
"c#",
"algorithm",
"linq",
"unit-testing"
],
"Title": "VersionString (eg \"1.0.2\") IComparer algorithm"
}
|
6143
|
<p>The last question I have been playing around with is a right rotate. I think it is also called a barrel roll. Please post if you have a better solution please post. I am still learning the art of bit flipping.</p>
<pre><code>/*
* Next write a function rightrot(x,n) that returns the value of the
* integer x rotated to the right by n bit positions
*
* build with:
* gcc -o bit_twiddle -Wall -g -lm ./bit_twiddle.c
*/
#include <stdio.h>
#include <math.h>
#include <limits.h>
size_t size_of_int = sizeof(int) << 3;
void printbits(unsigned x) {
unsigned mask = 1 << (size_of_int - 1);
int i = 0;
for(i = 1; i <= size_of_int; ++i, x <<= 1) {
((x & mask) == 0) ? printf("0") : printf("1");
(((i % 4))==0) ? printf(" ") : printf("%s","");
}
printf("\n");
}
void rightrot(unsigned x, unsigned n) {
printf("%15s =", "rightrot"); printbits((((~(~0 << n)) & x) << (size_of_int - n)) | (x >> n));
}
int main(int argc, char *argv[]) {
unsigned input=4042322167, nbits=4;
printf("%15s =", "x"); printbits(input);
rightrot(input, nbits);
return(0);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-18T19:03:57.983",
"Id": "9513",
"Score": "0",
"body": "What are you trying to do with the `~`? If it's to account for sign extension, the `unsigned` already does that. You should be fine with just `x << (size_of_int - n) | x >> n`."
}
] |
[
{
"body": "<p>What is this supposed to be?</p>\n\n<pre><code>size_t size_of_int = sizeof(int) << 3;\n</code></pre>\n\n<p>The shift left by 3 is very cryptic. Multiply by 8 or explain what you are doing. But a better solution is to multiply the number of bytes by the actual bits in a byte. </p>\n\n<p>If you want the number of bits in an integer:</p>\n\n<pre><code>#include <climits>\nsize_t size_of_int = sizeof(int) * CHAR_BIT;;\n</code></pre>\n\n<h3>PrintBits()</h3>\n\n<p>People are more used to seeing loops from 0:</p>\n\n<pre><code>for(i = 1; i <= size_of_int; ++i, x <<= 1)\n\n// So prefer to loop from zero \n\nfor(i = 0; i < size_of_int; ++i, x <<= 1)\n</code></pre>\n\n<p>This is an ugly way of printing 0/1</p>\n\n<pre><code>((x & mask) == 0) ? printf(\"0\") : printf(\"1\");\n</code></pre>\n\n<p>Only do one print: Then use the expression to decide what to print:<br>\nThe expression <code>(x & mask) == 0</code> is overkill if is zero then it is already false.</p>\n\n<pre><code>printf(\"%d\", (x & mask) ? 1 : 0);\n</code></pre>\n\n<p>Again an ugly way to print a space every four places:</p>\n\n<pre><code>(((i % 4))==0) ? printf(\" \") : printf(\"%s\",\"\");\n\n// Personally I would just use an if\n\nif (i%4==0) { printf(\" \");}\n</code></pre>\n\n<ul>\n<li>Is the result really a void? What happens if any of the printf() statements you use fail. In reality you should be checking the return codes of any function you call and either handling the error or passing the error back to the caller for them to handle.</li>\n<li>Your print function is very limited and only prints to the stdout. You should really make a version that prints to a stream</li>\n</ul>\n\n<p>The function declarations should be:</p>\n\n<pre><code>int printbits(unsigned x) {return fprintbits(stdout, x);}\nint fprintbits(FILE*, unsigned x)\n{\n // Code Here\n}\n</code></pre>\n\n<h3>RightRot()</h3>\n\n<p>Why are you callint printbits() from rightrot()? The function should do one task and that is rotate the bits. If you want to print the result fine. But this function should not be doing the printing.</p>\n\n<ul>\n<li>So you need to change your signature so it can return the result</li>\n</ul>\n\n<p>Refactoring</p>\n\n<pre><code>unsigned rightrot(unsigned x, unsigned n)\n</code></pre>\n\n<ul>\n<li>Doing everything on one line. Just makes the code unreadable. Split it up. One statement per line. Nobody will give you extra marks for writing compressed code (but they will give you marks for writing clear code)</li>\n</ul>\n\n<p>Refactoring:</p>\n\n<pre><code> return ((((~(~0 << n)) & x) << (size_of_int - n)) | (x >> n));\n</code></pre>\n\n<p>Even after removing all the chaff the above line is still unreadable. Split it up into multiple statements and use temporaries. This way you can comment on what is happening. Its not as if a single line is more efficient. The compiler is going to remove any unused temporaries.</p>\n\n<pre><code> // Shift right. Note: We loose bottom n bits (these need to be recovered.\n unsigned base = x >> n;\n\n // Create a mask for the bottom n bits.\n unsigned mask = (~(~0 << n));\n\n // Move the bottom n bits to the top of integer (as if they had wrapped around:\n unsigned wrap = (x & mask) << (size_of_int - n);\n\n return wrap | base;\n</code></pre>\n\n<p>Now that we can read what is happening. We see that creating the mask can be done more clearly.</p>\n\n<pre><code> unsigned mask = (1 << n) - 1;\n</code></pre>\n\n<p>We can also see that the calculation of wrap is overkill. All variables are unsigned and bits that fall of the top are lost.</p>\n\n<pre><code> unsigned wrap = x << (size_of_int - n);\n</code></pre>\n\n<p>Also note: That if n >= size_of_int you are going to be left with zero. So the first thing you should do is make sure that n is in the correct range. Let us assume a value greater will just wrap around multiple times.</p>\n\n<pre><code>// Multiple wraps do not add anything.\nn = n % size_of_int; \n</code></pre>\n\n<h3>Usage (from main)</h3>\n\n<pre><code>fprintbits(stdout, rightrot(input, nbits));\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-19T16:51:48.217",
"Id": "6149",
"ParentId": "6147",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "6149",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-18T18:35:49.220",
"Id": "6147",
"Score": "3",
"Tags": [
"c",
"bitwise"
],
"Title": "Print Bits Part III"
}
|
6147
|
<p>I have a list of sales records sorted by sales date. I need to fill in the gaps (days without a sales record) in this list with 'inferred sales' records. The method in question calculates an average price for the inferred sales records from its closest valid neighbors that have the same <code>SalesType</code>. If there's only one neighbor then no need to average it just returns the sales price of the neighbor. I'd like to improve readability of this method. </p>
<pre><code>public class SalesRecord
{
public DateTime Date { get; set; }
public bool IsValid { get; set; }
public int SalesType { get; set; }
public double UnitPrice { get; set; }
}
public class SalesDataContainter
{
private SortedList<DateTime, SalesRecord> salesData;
private double GetInferredPrice(SalesRecord inferredSalesRecord)
{
SalesRecord closestBefore = null;
SalesRecord closestAfter = null;
foreach (var salesRecord in salesData.Values)
{
//neigbor needs to be valid
if (salesRecord.IsValid)
{
continue;
}
//has to have the same sales type
if (salesRecord.SalesType != inferredSalesRecord.SalesType)
{
continue;
}
//listed is sorted get the last found for before neighbor
if (salesRecord.Date < inferredSalesRecord.Date)
{
closestBefore = salesRecord;
}
//listed is sorted get the first found for after neighbor
if (closestAfter == null && salesRecord.Date > inferredSalesRecord.Date)
{
closestAfter = salesRecord;
}
}
// we have neighbors on both sides
if (closestBefore != null && closestAfter != null)
{
return (closestAfter.UnitPrice + closestBefore.UnitPrice) / 2;
}
// there's only before neighbor
if (closestBefore != null)
{
return closestBefore.UnitPrice;
}
// there's only after neighbor
if (closestAfter != null)
{
return closestAfter.UnitPrice;
}
return 0;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Just a few things I want to point out before tackling this:</p>\n\n<ul>\n<li><p>Based on the comment, your first condition is flipped. You're skipping valid entries instead of invalid entries. It should be:</p>\n\n<pre><code>if (!salesRecord.IsValid)\n</code></pre></li>\n<li><p>Your last condition in the loop could just break at that point. Since it is sorted, every valid item will be a match but you're only interested in the first.</p></li>\n<li><p>You should consider making <code>UnitPrice</code> of type <code>decimal</code>. You're dealing with currency here so you should not be using <code>double</code>.</p></li>\n</ul>\n\n<p>Using a little bit of LINQ here could make this more readable IMHO. It's easier to think of it as \"looping through the list of candidate records\" rather than \"looping through all records and skipping some of them.\"</p>\n\n<p>Personally, I would write the last set of conditions as I have shown using the conditional operator. You may or may not like it this way or this structure so your choice with that part.</p>\n\n<pre><code>public class SalesRecord\n{\n public DateTime Date { get; set; }\n public bool IsValid { get; set; }\n public int SalesType { get; set; }\n public decimal UnitPrice { get; set; }\n}\npublic class SalesDataContainter\n{\n private SortedList<DateTime, SalesRecord> salesData;\n private decimal GetInferredPrice(SalesRecord inferredSalesRecord)\n {\n Func<SalesRecord, bool> isValidRecord = record =>\n record.IsValid //neigbor needs to be valid\n && record.SalesType == inferredSalesRecord.SalesType; //has to have the same sales type\n var candidateRecords = salesData.Values\n .SkipWhile(record => !isValidRecord(record))\n .Where(isValidRecord);\n\n SalesRecord closestBefore = null;\n SalesRecord closestAfter = null;\n foreach (var salesRecord in candidateRecords)\n {\n //get the last found for before neighbor\n if (salesRecord.Date < inferredSalesRecord.Date)\n {\n closestBefore = salesRecord;\n }\n //get the first found for after neighbor\n else if (salesRecord.Date > inferredSalesRecord.Date)\n {\n closestAfter = salesRecord;\n break;\n }\n }\n\n // there's a neighbor before\n if (closestBefore != null)\n {\n return (closestAfter != null)\n // we have neighbors on both sides\n ? (closestBefore.UnitPrice + closestAfter.UnitPrice) / 2M\n : closestBefore.UnitPrice;\n }\n else\n {\n return (closestAfter != null)\n // there's only a neighbor after\n ? closestAfter.UnitPrice\n : 0M;\n }\n }\n}\n</code></pre>\n\n<p>An alternative would be to let LINQ do all the work:</p>\n\n<pre><code>public decimal GetInferredPrice(SalesRecord inferredSalesRecord)\n{\n Func<SalesRecord, bool> isValidRecord = record =>\n record.IsValid //neigbor needs to be valid\n && record.SalesType == inferredSalesRecord.SalesType; //has to have the same sales type\n\n return salesData.Values\n .SkipWhile(record => !isValidRecord(record))\n .Where(isValidRecord)\n .GroupBy(\n record => record.Date.CompareTo(inferredSalesRecord.Date),\n record => record.UnitPrice as decimal?,\n (key, g) => (key < 0) // assumes no records will have equal dates\n ? g.LastOrDefault()\n : g.FirstOrDefault()\n )\n .Average() ?? 0M;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-19T20:52:14.453",
"Id": "6153",
"ParentId": "6150",
"Score": "2"
}
},
{
"body": "<p>I would do something like this:</p>\n\n<pre><code>public class SalesRecord\n{\n public DateTime Date { get; set; }\n public bool IsValid { get; set; }\n public int SalesType { get; set; }\n public decimal UnitPrice { get; set; }\n}\npublic class SalesDataContainter\n{\n private SortedList<DateTime, SalesRecord> salesData;\n private decimal GetInferredPrice(SalesRecord inferredSalesRecord)\n {\n // select valid records of the same type as inferredSalesRecord\n var candidateRecords = salesData.Values.Where(r => r.IsValid && r.SalesType == inferredSalesRecord.SalesType);\n\n SalesRecord closestBefore = candidateRecords.LastOrDefault(r => r.Date < inferredSalesRecord.Date);\n SalesRecord closestAfter = candidateRecords.FirstOrDefault(r => r.Date > inferredSalesRecord.Date);\n\n // we have neighbors on both sides\n if (closestBefore != null && closestAfter != null)\n {\n return (closestAfter.UnitPrice + closestBefore.UnitPrice) / 2m;\n }\n // there's only before neighbor\n if (closestBefore != null)\n {\n return closestBefore.UnitPrice;\n }\n // there's only after neighbor\n if (closestAfter != null)\n {\n return closestAfter.UnitPrice;\n }\n return 0m;\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-19T21:33:09.367",
"Id": "6154",
"ParentId": "6150",
"Score": "2"
}
},
{
"body": "<p>I'm a fail-fast fan, so I'd code <code>GetInferredPrice</code> as such:</p>\n\n<pre><code> private double GetInferredPrice(SalesRecord inferredSalesRecord)\n {\n var candidateRecords = this.salesData.Values.Where(salesRecord => salesRecord.IsValid\n && (salesRecord.SalesType == inferredSalesRecord.SalesType));\n var closestBefore = candidateRecords.LastOrDefault(salesRecord => salesRecord.Date < inferredSalesRecord.Date);\n var closestAfter = candidateRecords.FirstOrDefault(salesRecord => salesRecord.Date > inferredSalesRecord.Date);\n\n // we have no neighbors on either side\n if ((closestBefore == null) && (closestAfter == null))\n {\n return 0;\n }\n\n // only before neighbor, only after neighbor, or both\n return closestAfter == null\n ? closestBefore.UnitPrice\n : (closestBefore == null\n ? closestAfter.UnitPrice\n : (closestAfter.UnitPrice + closestBefore.UnitPrice) / 2);\n }\n</code></pre>\n\n<p>I don't know the full usage of <code>SalesRecord</code>, but despite the lack of good immutable semantics, I still like immutable classes if you can swing it:</p>\n\n<pre><code>public sealed class SalesRecord\n{\n private readonly DateTime date;\n\n private readonly bool isValid;\n\n private readonly int salesType;\n\n private readonly double unitPrice;\n\n public SalesRecord(DateTime date, bool isValid, int salesType, double unitPrice)\n {\n this.date = date;\n this.isValid = isValid;\n this.salesType = salesType;\n this.unitPrice = unitPrice;\n }\n\n public DateTime Date\n {\n get\n {\n return this.date;\n }\n }\n\n public bool IsValid\n {\n get\n {\n return this.isValid;\n }\n }\n\n public int SalesType\n {\n get\n {\n return this.salesType;\n }\n }\n\n public double UnitPrice\n {\n get\n {\n return this.unitPrice;\n }\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-20T01:46:34.160",
"Id": "6159",
"ParentId": "6150",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-19T17:31:20.527",
"Id": "6150",
"Score": "2",
"Tags": [
"c#"
],
"Title": "Finding neighbors and returning average value from neighbors"
}
|
6150
|
<p>I am trying to find a good way of parsing SQL arguments, the way I am accomplishing it now seems like it can use a lot of improvement. I am trying to convert arguments that are split apart by ', & <= =>' from a string into SQL arguments like name = 'ABC' OR name ='John Doe'.</p>
<p>So </p>
<pre><code>parseSQLOperators('dan,john&steven', 'username');
</code></pre>
<p>Will create</p>
<pre><code>WHERE username= 'dan' OR username = 'john' AND username ='steven'
</code></pre>
<p>I have an example how this is being accomplished below but I am wondering if there is a better way for this. I know this code is ugly and I've been trying things like preg_splits but to no avail.</p>
<pre><code>public static function parseSQLOperators($string, $content_term, $encapsulate = TRUE) {
$string = trim($string);
$length = strlen($string);
$ADD_PREFIX = true;
$output = '';
for ($i = 0; $i < $length; $i++) {
if ($string[$i] == '!') {
$output .= ' ' . $content_term . '!=\'';
if ($i == 0) {
$ADD_PREFIX = false;
}
} else if ($string[$i] == '+') {
if (@$string[$i + 1] != '!') {
$output .= ' AND ' . $content_term . '=\'';
} else {
$output .= ' AND ';
}
} else if ($string[$i] == ',') {
if (@$string[$i + 1] != '!') {
$output .= ' OR ' . $content_term . '=\'';
} else {
$output .= ' OR ';
}
}
if ($string[$i] != '!' && $string[$i] != '+' && $string[$i] != ',') {
$output .= $string[$i];
if (@$string[$i + 1] == ',' || @$string[$i + 1] == '+' || @$string[$i + 1] == '!' || $i == $length || $i == $length - 1) {
$output .= '\'';
}
}
}//end for
if ($ADD_PREFIX == true) {
$output = $content_term . '=\'' . $output;
}
if ($encapsulate) {
$output = '(' . $output . ')';
}
return $output;
}//end parseSQLOperator
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-20T06:24:28.577",
"Id": "9535",
"Score": "0",
"body": "Interesting idea. I'll take a look. Give me some time."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-20T06:39:19.500",
"Id": "9537",
"Score": "0",
"body": "How would you feel about changing your grammar up? Namely: `dan,john&steven` becomes `=dan | =john & =steven`? This has LOTS of advantages. First, you are using normal meanings for things. `,` normally means and or union. I've never seen it mean `or`. Secondly, it has a very specific structure: `{comparator}{identifier}({operator}{comparator}{identifier})*` It's VERY easily parsed by a regular expression."
}
] |
[
{
"body": "<p>If this is a whole SQL class of sorts, then I think you can improve your design a bit. What if you want people who aren't archived and names match certain things? <code>'dan,john&steven', 'username'</code> doesn't really work. You need something more like:</p>\n\n<pre><code>$sql\n ->select(...)\n ->from(...)\n ->where('=dan|=john&=steven', 'username')\n ->andWhere('>0', 'archived')\n ->execute();\n</code></pre>\n\n<p>Notice that I didn't use your grammar. I'd recommend the following shorthand grammar notation:</p>\n\n<pre><code>//& means AND\n//| means OR\n//~ means LIKE\n\n//operator means &, |\n//comparator means things like !=, =, <>, <, >, <=, >=, ~\n//identifier means things like dan, john, or jo%\n\n//The pseudo regular expession:\n//{comparator} {identifier} ({operator} {comparator} {identifier})*\n</code></pre>\n\n<p>Doing that, you can turn: <code>'=john | !=jamison & =james | ~%jo_n'</code> into <code>name = 'john' OR name != 'jamison' AND name = 'james' OR name LIKE '%jo_n'</code> quite easily:</p>\n\n<pre><code> function parse($string, $name) {\n //add in quote marks\n $string = preg_replace('/[A-Za-z0-9%_-]+/', \"'$0'\", $string);\n\n //add in name:\n $string = preg_replace('/\\=|\\!\\=|<>|<|<=|>|>=|~/', \"$name $0 \", $string);\n\n //replace ~ with LIKE\n $string = str_replace('~', 'LIKE', $string);\n\n //expand '&' and ',' to ' AND '\n $string = preg_replace('/\\&|\\,/', ' AND ', $string);\n\n //expand '|' to ' OR '\n $string = str_replace('|', ' OR ', $string);\n\n return $string;\n\n }\n</code></pre>\n\n<p>Also note that you should be able to escape things properly. We don't want SQL injection going on 'round here! I'd recommend a syntax like:</p>\n\n<pre><code>where('=? | =? & =?', array('dan', 'john', 'steven'), 'username')\n</code></pre>\n\n<p>The function I provided could easily be modified to do that. You simply use the mysqli or PDO engine to do the replacing. You just have to store the arguments in your structure so you can do it proper. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-17T20:43:30.510",
"Id": "12517",
"Score": "0",
"body": "Very nice solution"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-20T09:20:23.917",
"Id": "6169",
"ParentId": "6151",
"Score": "4"
}
},
{
"body": "<p>Are you sure that you need this custom format (and parsing) at all?</p>\n\n<p>Using some helper functions would be easier to handle, for example:</p>\n\n<pre><code>$sql->select(...)\n ->from(...)\n ->where(\n or(\n eq('dan', 'username'), \n and(eq('john', 'username'), \n eq('steven', 'username')\n )\n )\n )\n ->execute();\n</code></pre>\n\n<p>Some proof of concept implementations:</p>\n\n<pre><code>function eq($value, $col) {\n return \" ('$value' = $col) \";\n}\n\nfunction or($arg1, $arg2) {\n return \" ($arg1 OR $arg2) \";\n}\n\nfunction and($arg1, $arg2) {\n return \" ($arg1 AND $arg2) \";\n}\n</code></pre>\n\n<p>Maybe a framework with similar functionality already exists.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-20T16:28:01.153",
"Id": "7024",
"ParentId": "6151",
"Score": "0"
}
},
{
"body": "<p>Consider this readable solution which enables you to use prepared statements easily:</p>\n\n<pre><code>$condition = array('username = :u and password =:p', array(':u' => $user, ':p' => $pass));\n$result = $database->fetch_row('users', $condition);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-18T21:54:47.893",
"Id": "9122",
"ParentId": "6151",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-19T18:05:37.803",
"Id": "6151",
"Score": "3",
"Tags": [
"php",
"sql",
"parsing"
],
"Title": "Parsing Placeholders as SQL Arguments in PHP"
}
|
6151
|
<p>The problem I am trying to solve can be described as take <code>binarysearch0</code> and rewrite it as <code>binarysearch1</code> such that <code>binarysearch1</code> uses a single test inside the loop instead of two. The code I used to do this is seen below. Please let me know if you think I accomplished the task, and what I can do better.</p>
<pre><code>#include <stdlib.h>
#include <stdio.h>
void printdata(int *v, int n)
{
int i = 0;
for (i = 0; i < n; ++i) {
printf("%3d", v[i]);
}
putchar('\n');
}
int binarysearch0(int x, int *v, int n)
{
int low, high, mid;
low = 0;
high = n - 1;
while (low <= high) {
mid = (low + high) / 2;
if ( x < v[mid])
high = mid -1;
else if (x > v[mid])
low = mid + 1;
else
return mid;
}
return -1;
}
int binarysearch1(int x, int *v, int n)
{
int low, high, mid;
low = 0;
high = n - 1;
while (low <= high && v[(mid = (low + high) / 2)] != x ) {
mid = (low + high) / 2;
if ( x < v[mid])
high = mid -1;
else
low = mid + 1;
}
return (v[mid] == x) ? mid : -1;
}
int main(int argc, char *argv[])
{
int v[10][10] = { { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9},
{10,11,12,13,14,15,16,17,18,19},
{20,21,22,23,24,25,26,27,28,29},
{30,31,32,33,34,35,36,37,38,39},
{40,41,42,43,44,45,46,47,48,49},
{50,51,52,53,54,55,56,57,58,59},
{60,61,62,63,64,65,66,67,68,69},
{70,71,72,73,74,75,76,77,78,79},
{80,81,82,83,84,85,86,87,88,89},
{90,91,92,93,94,95,96,97,97,99}
};
int i = 0;
for (i = 0; i < 10; ++i) {
int search = 0;
(i == 0) ? (search = 1000) : (search = v[i][0] + rand()%10);
if(binarysearch1(search, v[i], 10) > -1) {
printf("%d was found in the data: %14s", search, " ");
printdata(v[i], 10);
} else {
printf("%d was NOT found in the data: %10s", search, " ");
printdata(v[i], 10);
}
putchar('\n');
}
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-19T21:30:33.423",
"Id": "9522",
"Score": "0",
"body": "I find `binarysearch0` clearer than `binarysearch1`, and here's no difference efficiency-wise. If this is a homework question, how exactly was it formulated? If not, what do you hope to gain with `binarysearch1`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-19T21:45:12.123",
"Id": "9523",
"Score": "0",
"body": "This is not homework, but it comes from the C Programming Language book by Kernighan and Ritchie. He asks you to reduce the number of conditionals in the loop and compare run-times."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-19T22:13:08.893",
"Id": "9524",
"Score": "0",
"body": "Then what about `if (v[mid] < x){ low = mid+1; } else { high = mid; }`?"
}
] |
[
{
"body": "<p>In <code>binarysearch1</code>, you've replaced one test in the loop body with one test in the loop condition. That doesn't reduce the number of tests, and I agree with Gilles, <code>binarysearch0</code> is clearer. I would recommend keeping that. However, in both searches, the calculation of <code>mid = (low + high) / 2</code> can overflow if the array you're searching is large. Use an overflow-safe calculation instead. The readable one is <code>mid = low + (high - low) / 2</code> (assuming you can guarantee that <code>low</code> and <code>high</code> are never negative, <code>INT_MAX - INT_MIN</code> for example would overflow).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-19T22:05:46.260",
"Id": "6155",
"ParentId": "6152",
"Score": "3"
}
},
{
"body": "<p>You're not really changing the number of comparisons inside the loop here: all you've done is move it from the loop body to the loop termination condition. Note that in many situations, comparisons on the array elements (which could be strings or more complex objects) are a lot costlier than comparisons on the indices.</p>\n\n<p>You can find several solutions to this exercise on <a href=\"http://clc-wiki.net/wiki/K%26R2_solutions:Chapter_3:Exercise_1\" rel=\"nofollow noreferrer\">the clc-wiki</a>. I think one of them (Paul Griffith's) misses the point (it's pretty much the same as yours); I'm going to show explain the reasoning behind Andrew Tesker and Colin Barker's solutions.</p>\n\n<p>In the original function <code>binsearch</code>, inside the loop, there are three possible situations: <code>x<v[mid]</code>, <code>x==v[mid]</code> and <code>x>v[mid]</code>. Sometimes, a comparison function has three outcomes: less than, equal or greater than; in such cases, the approach in the original function is best. For example, if we were comparing strings with <code>strcmp</code>:</p>\n\n<pre><code> int cmp = strcmp(x, v[mid]);\n if (cmp < 0) high = mid - 1;\n else if (cmp > 0) low = mid + 1;\n else return mid;\n</code></pre>\n\n<p>In other cases, the only primitive you have is a less-than or less-or-equal-to, and to test for equality requires a second comparison. Thus the method presented in K&R requires two calls to the comparison function per iteration through the loop. It is more efficient to require a single comparison. Now we absolutely need to distinguish between the less-than and the greater-than case, so this means we're not going to be able to deal with the equality case inside the loop. So we'll keep going either up or down in the equality case. Since we haven't vetted the value <code>v[mid]</code> in one of the cases, we need to keep it inside the search space.</p>\n\n<pre><code> if (x < v[mid]) high = mid - 1;\n else low = mid;\n</code></pre>\n\n<p>What happens to the loop termination? Now, we can get stuck with <code>low == high</code> and <code>x >= v[low]</code>. However, this is easily resolved by ending the loop when <code>low == high</code>.</p>\n\n<pre><code>while (low < high) {\n mid = (low + high + 1) / 2;\n if (x < v[mid]) high = mid - 1;\n else low = mid;\n}\n</code></pre>\n\n<p>Note that I set <code>mid</code> to <code>low + high + 1</code>. In the case where <code>low + 1 == high</code>, <code>(low + high) / 2</code> is <code>low</code>, and if <code>x</code> is still too small we'd set <code>mid</code> to <code>low</code> and loop forever (thanks to <a href=\"https://codereview.stackexchange.com/users/77713/elyasin\">Elyasin</a> for noticing that my original answer had this bug). Instead in this case we arrange for <code>mid</code> to be set to <code>high</code>. If <code>low <= high</code> we exit the loop anyway, and in other cases we'll continue looping and this change only causes the middle to be rounded up instead of down.</p>\n\n<p>At the exit of the loop, if there is a matching element in the array, then <code>v[low]</code> is equal to it. So we perform a final equality test:</p>\n\n<pre><code>return x == v[low] ? low : -1;\n</code></pre>\n\n<p>The number of element comparisons performed by the original version is anywhere from 1 to 2*ceil(log₂(n)+1) where n is the number of elements in the array. The number of element comparisons in the version with a single comparison within the loop is always ceil(log₂(n))+2. That's a smaller maximum, but not necessarily a gain, because the original version will terminate earlier if it finds the element. The original version is preferable when there is a good chance that the element will be in the array. The modified version is preferable when the element is rarely present.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-08-09T08:21:16.610",
"Id": "183311",
"Score": "0",
"body": "Nice answer. I think there is a bug. I would use the assignment `mid = (low + high) / 2 + 1;`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-08-09T10:30:46.040",
"Id": "183315",
"Score": "0",
"body": "@Elyasin Why? What's the bug?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-08-10T02:41:35.347",
"Id": "183456",
"Score": "0",
"body": "I think it loops infinitely, the reason being that the division by integers is truncated. Try to find the last element in a list."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-08-10T07:32:34.537",
"Id": "183475",
"Score": "0",
"body": "@Elyasin Got it. But (low+high)/2+1 is wrong too: it can cause an access one past the end of the array when low==high."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-08-10T07:42:40.587",
"Id": "183476",
"Score": "0",
"body": "P.S. Beware of bugs in the above code; I have only tried it, not proved it correct."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-08-10T09:43:18.253",
"Id": "183501",
"Score": "0",
"body": "When `low == high` then the loop is not executed. Do you have an example input/output for that case?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-08-10T09:58:34.483",
"Id": "183506",
"Score": "0",
"body": "@Elyasin Sorry, typo in my comment: the access past the end would be when `low + 1 == high == max array index`, then `mid` would be set to one past the end."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-08-11T02:54:56.980",
"Id": "183660",
"Score": "0",
"body": "I am not sure about this. C truncates temporary results while casting to `int`. `(98 + 99) / 2 + 1` would become `98.5 + 1`, which becomes `98 + 1`. That's the last element. So I think it is ok."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-19T22:55:57.377",
"Id": "6156",
"ParentId": "6152",
"Score": "8"
}
},
{
"body": "<p>I would not waste any time at all worrying about factoring away one of the two comparisons, because a good compiler should be able to optimize them into one anyway. (Maybe during Kernighan and Ritchie's time compilers were not smart enough to pull such tricks, so maybe this question was meaningful back then, but believe me, they have gone a very long way since then!)</p>\n\n<p>The compiler knows that <code>x</code> and <code>v[mid]</code> (or the result of calling the comparison function) are not changed by the <code>if</code> statement, so it can emit the code which compares these two operands only once. The results of the comparison will be stored in the <code>Carry</code> (C) and <code>Zero</code> (Z) bits of the <code>Flags</code> register of an x86 CPU, as follows: If Z is set, it means that the two operands of the comparison were equal; otherwise, if C is set, then the second operand was greater than the first; otherwise, (both flags are clear,) the second operand was smaller than the first. So, if the compiler is smart at all, after the comparison instruction it will emit two consecutive conditional jump instructions: one which will branch to the <code>low = mid + 1</code> part if the result of the comparison was 'greater than', (Z=0, C=0,) immediately followed by another which will branch to the <code>high = mid - 1</code> part if the result of the comparison was 'less than'. (Z=0, C=1.) A jump instruction never modifies the <code>Flags</code> register of the CPU, so after the first jump instruction has examined the flags, and decided not to branch, the flags will still be intact for the second jump instruction to also examine them. And if the second jump instruction decides not to branch either, then the CPU will fall through to the code which will handle the last remaining case, where the operands were equal.</p>\n\n<p>I would be willing to bet money that a decent C compiler will do this for you. Even if it turns out that it does not, the whole topic can nonetheless be dismissed as belonging to the general class of problems that compilers should be taking care of for us, so that we can spend our time thinking about more useful things.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-28T11:17:13.023",
"Id": "6353",
"ParentId": "6152",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "6156",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-19T20:18:51.123",
"Id": "6152",
"Score": "3",
"Tags": [
"optimization",
"c",
"binary-search"
],
"Title": "Binary search optimization: Kernighan & Ritchie 3-1"
}
|
6152
|
<p>I want you to review my JavaScript project.</p>
<pre><code>var geocoder;
var map;
var infowindow = new google.maps.InfoWindow();
var marker;
function initialize() {
document.upload.lat.value = geoip_latitude();
document.upload.lng.value = geoip_longitude();
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(geoip_latitude(), geoip_longitude());
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: 'roadmap'
}
map = new google.maps.Map(document.getElementById("gmap"), myOptions);
//var ctaLayer = new google.maps.KmlLayer('http://www.koolbusiness.com/list.kml');
//ctaLayer.setMap(map);
google.maps.event.addListener(map, "click", gAdd);
geocoder.geocode({
'latLng': latlng
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
document.getElementById("message").innerHTML = results[5].formatted_address;
document.upload.place.value = results[5].formatted_address;
} else {
}
});
if (navigator.geolocation) {
browserSupportFlag = true;
navigator.geolocation.getCurrentPosition(function (position) {
initialLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var latlng = initialLocation
geocoder.geocode({
'latLng': latlng
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
marker = new google.maps.Marker({
position: latlng,
map: map
});
infowindow.setContent('<a href="/li?lat=' + latlng.lat() + '&lon=' + latlng.lng() + '">' + results[1].formatted_address + '</a>');
infowindow.open(map, marker);
document.upload.lat.value = latlng.lat();
document.upload.lng.value = latlng.lng();
document.upload.place.value = results[5].formatted_address
} else {
alert("No results found");
}
} else {
alert("Geocoder failed due to: " + status);
}
});
}, function () {
handleNoGeolocation(browserSupportFlag);
});
} else if (google.gears) {
// Try Google Gears Geolocation
browserSupportFlag = true;
var geo = google.gears.factory.create('beta.geolocation');
geo.getCurrentPosition(function (position) {
initialLocation = new google.maps.LatLng(position.latitude, position.longitude);
var latlng = initialLocation
geocoder.geocode({
'latLng': latlng
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
marker = new google.maps.Marker({
position: latlng,
map: map
});
infowindow.setContent('<a href="/li?lat=' + latlng.lat() + '&lon=' + latlng.lng() + '">' + results[1].formatted_address + '</a>');
infowindow.open(map, marker);
document.upload.lat.value = latlng.lat();
document.upload.lng.value = latlng.lng();;
document.upload.place.value = results[5].formatted_address;
} else {
alert("No results found");
}
} else {
alert("Geocoder failed due to: " + status);
}
});
}, function () {
handleNoGeolocation(browserSupportFlag);
});
} else {
// Browser doesn't support Geolocation
browserSupportFlag = false;
handleNoGeolocation(browserSupportFlag);
}
}
function gAdd(ev) {
marker.setMap(null)
var latlng = new google.maps.LatLng(ev.latLng.lat(), ev.latLng.lng());
geocoder.geocode({
'latLng': latlng
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
document.getElementById("message").innerHTML = results[1].formatted_address;
document.upload.place.value = results[5].formatted_address
document.upload.lat.value = latlng.lat();
document.upload.lng.value = latlng.lng();
marker = new google.maps.Marker({
position: latlng,
draggable: true,
animation: google.maps.Animation.DROP,
map: map
});
google.maps.event.addListener(marker, 'click', toggleBounce);
infowindow.setContent('<a href="/li?lat=' + latlng.lat() + '&lon=' + latlng.lng() + '">' + results[1].formatted_address + '</a>');
infowindow.open(map, marker);
} else {
}
});
}
function toggleBounce() {
if (marker.getAnimation() != null) {
alert("test");
marker.setAnimation(null);
} else {
marker.setAnimation(google.maps.Animation.BOUNCE);
}
}
</code></pre>
<p><img src="https://i.stack.imgur.com/6RrLQ.png" alt="enter image description here"></p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-20T00:18:26.303",
"Id": "9525",
"Score": "3",
"body": "Add comments, name your functions, make the code less ugly."
}
] |
[
{
"body": "<p><strong>Comments:</strong></p>\n\n<ul>\n<li><strong>I highly suggest that you document your functions better.</strong> At the beginning of each function, document:\n<ol>\n<li>The overall purpose of the function</li>\n<li>The parameters it takes and their types</li>\n<li>What is returned.</li>\n</ol></li>\n<li><strong>Document each major block of code.</strong>\n<ol>\n<li>Describe the overall procedure for the code piece.</li>\n<li>Document variables that will are already in use that are needed in your code. <em>(I only do this sometimes, it's not as helpful as the rest, but sometimes it's nice)</em></li>\n</ol></li>\n<li><strong>Use semicolons for every code statement.</strong> At least twice when you declared your variables you didn't use a semicolon at the end.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-20T05:35:18.717",
"Id": "6167",
"ParentId": "6157",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "6167",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-19T23:56:47.037",
"Id": "6157",
"Score": "3",
"Tags": [
"google-apps-script",
"google-maps"
],
"Title": "Google Maps project in JavaScript"
}
|
6157
|
<p>I'm trying to conform to the Zend Coding Standard as well.</p>
<pre><code>EDIT 2:
<?php
/**
* Input : Query request
* Output : A row or a list of rows
* Notes :
*
* Provides escaping and binding via PDO library
* Consolidates PDO to use a single calling mechanism
* Consolidates all queries to an associative array
* Mysqli available for those who wish to implement
*/
class Database extends OneDatabase
{
private $dbResource;
public function __construct()
{
$this->dbResource = oneDatabase::_get();
}
public function getResource()
{
return $this->dbResource;
}
protected $_sqlArray = array(
"signin_pass" => "SELECT pass FROM cr WHERE email=?",
"signin_validate" => "SELECT email,pass FROM cr WHERE email=? AND pass=?",
"signin_flname" => "SELECT flname FROM cr WHERE email=?",
"signup_check" => "SELECT * FROM cr WHERE email=?",
"signup_insert" => "INSERT INTO cr VALUES (?,?,?)",
"signup_site1" => "INSERT INTO bo VALUES ('Facebook','http://www.facebook.com','',?)",
"signup_site2" => "INSERT INTO bo VALUES ('Twitter','http://www.twitter.com','',?)",
"bookmark_delete" => "DELETE FROM bo WHERE name=? AND email=? LIMIT 1",
"bookmark_insert" => "INSERT INTO bo VALUES (?, ?,'', ?)",
"bookmark_model" => "SELECT * FROM bo WHERE email=? ORDER BY name ASC",
"tweet_insert" => "INSERT INTO tw VALUES (?,?,?,?)",
"tweet_model" => "SELECT * FROM tw ORDER BY time DESC LIMIT 7",
"create_bookmark" => "CREATE TABLE bookmark(name VARCHAR(64), url VARCHAR(256), tag VARCHAR(256), id INT)",
"create_credentials" => "CREATE TABLE credentials(id INT NOT NULL AUTO_INCREMENT, flname VARCHAR(60), email VARCHAR(32), pass VARCHAR(40), PRIMARY KEY(id))",
"create_tweet" => "CREATE TABLE tweet(id INT NOT NULL AUTO_INCREMENT, flname VARCHAR(60), email VARCHAR(32), pass VARCHAR(40), PRIMARY KEY(id))"
);
public function _pdoQuery($fetchType, $queryType, $parameterArray)
{
$query=$this->_sqlArray[$queryType];
eval("\$query = \"$query\";");
if($parameterArray==0)
{
$results = oneDatabase::$_database->query($query);
return $results;
}
oneDatabase::$_database->quote($query);
$pdoStatement = oneDatabase::$_database->prepare($query);
$pdoStatement->execute($parameterArray);
if($fetchType=='none')
{
$results=NULL;
}
else if($fetchType=='single')
{
$results = $pdoStatement->fetch(PDO::FETCH_ASSOC);
}
else if($fetchType=='multiple')
{
$results = $pdoStatement->fetchAll();
}
return $results;
}
protected function _mysqliQuery($aquery)
{
return oneDatabase::$_database->query($query);
}
}
</code></pre>
|
[] |
[
{
"body": "<p>The good thing about this code is your bracing style which is applied consistently and is visually appealing. Now on to some improvements:</p>\n\n<p>This code does not implement a Database. (You have called the class Database, but it does not resemble something that looks like a database). This class does not really have a good purpose. If you are going to write a database class it should handle database type things. Like transactions or methods for select, insert and delete statements etc.</p>\n\n<p>Some other things:</p>\n\n<ul>\n<li>It is not easy to re-use the code.</li>\n<li>It contains hard coded values.</li>\n<li>It breaks up a logical separation of concerns for your program.</li>\n<li>Don't use eval - it is not good for your application security:\n<code>eval(\"\\$query = \\\"$query\\\";\");</code></li>\n<li>oneDatabase::$_database can be replaced by $this->_database as you\nare extending that class.</li>\n<li>mysqli is mixed in with PDO. Just use PDO.</li>\n<li>databaseCopy is not required</li>\n<li>method access should be specified (public, protected, private)</li>\n</ul>\n\n<p>In summary, I think you should re-think your design.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-20T05:57:13.947",
"Id": "9530",
"Score": "0",
"body": "I can use either one...but I chose oneDatabase::$_database becasue this lets me know that it is static. In general I use $this for objects and class_name:: for classes (i.e. static members), even though it is not required. This is preference, I don't see why it matters either way."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-20T05:58:13.853",
"Id": "9531",
"Score": "0",
"body": "databaseCopy has been removed."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-20T05:59:25.287",
"Id": "9532",
"Score": "0",
"body": "Is PDO standard in all PHP installations? I left mysqli in case it is not in a standard installation and someone needs to revert."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-20T06:00:08.267",
"Id": "9533",
"Score": "0",
"body": "Added in method access"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-20T06:09:25.033",
"Id": "9534",
"Score": "0",
"body": "How should I change the structure...as this seems to be the main issue...what is the reason this does not implement Database? My database class take a query request...and returns with the needed data in the form of an array or an array of arrays. This is my definition of a database class...what is yours?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-20T06:36:00.283",
"Id": "9536",
"Score": "2",
"body": "My idea of a database class is similar to: http://codereview.stackexchange.com/questions/5294/pdo-wrapper-class/ Once you have that Database class defined you would create an instance of it and use it (rather than extending from it). In this way objects are created that do specific things. Likewise when using your database class you should not extend from it, but rather use it as an object. Then you will see how much your object is doing for you. Right now it is an object that provides only one method."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-20T06:41:16.903",
"Id": "9538",
"Score": "0",
"body": "PDO has been enabled by default since 5.1.0 (6 years ago)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-20T07:21:27.260",
"Id": "9539",
"Score": "0",
"body": "I have conceptualized my Database class and OneDatabase class together as a cohesive unit. And I do not extend from them. But once again I do this as a matter of preference."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-20T07:23:29.143",
"Id": "9540",
"Score": "0",
"body": "Even though PDO appears to be best practice...I assume people still use mysqli as it has been improved upon recently from just plain mysql, and b.c. it does no harm I leave it there. Perhaps there are trade-offs I'm unaware of as well."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-21T04:41:53.530",
"Id": "9566",
"Score": "0",
"body": "A query is a Query....if you know mysql..you don't need all of that..you just write the query...insert it in the array....and call it accordingly...much easier...1/5 the code...what is gained by blowing my code up 5X? Why would I put my credentials in xml? Why would I decompose all the mySQL and spread it all over the place?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-21T05:47:35.337",
"Id": "9568",
"Score": "0",
"body": "The reason to spread your SQL all over the place is that the logic will then be with the parts that are doing the work. For example: When you have an object that controls fruit, you would expect it to be able to add fruit, delete them, or modify them. To have that SQL logic split out of the fruit class and put into this database class would make the fruit class unreadable and tightly coupled to this class. So it would need this class in order to be reusable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-03T21:09:55.430",
"Id": "11649",
"Score": "0",
"body": "I have not fruit class or similar...if you want to use the database you need two classes OneDatabase and Database..that is it...if you create additional classes they in fact will be tied to to whatever class initiates the query...your talking about adding another layer of abstraction...a matter of preference...I could do it but I don't gain anything by the extra work and code...however if my list of queries will get absurdly long..then I will need to."
}
],
"meta_data": {
"CommentCount": "12",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-20T05:36:24.197",
"Id": "6168",
"ParentId": "6162",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "6168",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-20T04:41:02.867",
"Id": "6162",
"Score": "0",
"Tags": [
"php"
],
"Title": "class Database extends OneDatabase"
}
|
6162
|
<p>I'm looking for any feedback on this code. If it is too much please pick a random method/group and give me feedback.</p>
<p>This code passes www.jshint.com. I'm trying to shape this collection into a library. The regular expressions have a way to go. Any incremental constructive feedback welcome. Only the objects returned are accessible outside of the file. These will be the API later.</p>
<pre><code>var some_name = (function (global) {
/********************
Structure:
- pragmas
- constants/etc.
- one
- check
- ajax
- interface
- initialize
- api
********************/
/********************
group: pragmas
notes:
********************/
"use strict";
/********************
group: constants/etc.
notes:
********************/
var constant =
{
enter_key: 13,
second : 1000,
minute: 60,
hour: 3600,
day: 43200,
terminate: 0
};
var aml_message =
{
"pass":0,
"fail":1,
"undefined_user":2
};
/********************
group: one
notes:
********************/
var one =
{
fill_id: function(html_id, html_text)
{
return (document.getElementById(html_id).innerHTML=html_text);
},
set_onclick: function(html_id,method_call)
{
return (document.getElementById(html_id).onclick=method_call);
},
set_onkeypress: function(html_id,method_call)
{
return (document.getElementById(html_id).onkeypress=method_call);
},
reload: function()
{
window.location.href=window.location.host.match(/localhost|127.0.0.1/) ? 'http://127.0.0.1' : 'http://www.archemarks.com';
}
};
/********************
group: check
notes:
********************/
/* separeate the view from the model here
var check = {
patterns : {
name: /^[a-zA-Z-\s]{1,20}$/,
email: /^[a-zA-Z0-9._(-)]+@[a-zA-Z0-9.(-)]+\.[a-zA-Z]{1,4}$/,
pass: /.{6,40}/,
url: /^[(-)\w&:\/\.=\?,#+]{1,}$/,
aml: /<(.+)_([a-z]){1}>$/
},
generic: function(reg_ex,text)
{
return (reg_ex.exec(text.value)) ? 0 : 1;
},
empty: function(text_array)
{
for(var a=0;a<text_array.length;a++)
{
if(text_array[a].value==='')
{
return 0;
}
}
return 1;
},
same: function(text1,text2)
{
return ((text1.value)!==(text2.value)) ? 1 : 0;
},
aml: function(regex, text)
{
var aml_response=regex.exec(text);
if(aml_response)
{
if(aml_response[2]==='p')
{
return aml_message.pass;
}
else if (aml_response[2]==='f')
{
return aml_message.fail;
}
}
else
{
return aml_message.undefined_user;
}
}
};
*/
/*prototype only, not for production - will sub real values in later*/
var patterns =
{
name: /^[a-zA-Z-\s]{1,20}$/,
email: /^[a-zA-Z0-9._(-)]+@[a-zA-Z0-9.(-)]+\.[a-zA-Z]{1,4}$/,
pass: /.{6,40}/,
url: /^[(-)\w&:\/\.=\?,#+]{1,}$/,
aml: /<(.+)_([a-z]){1}>$/
};
function check_generic(reg_ex_in,text,html_id,response)
{
if(!reg_ex_in.exec(text.value))
{
one.fill_id(html_id,response);
return 0;
}
return 1;
}
function check_empty(text,html_id,response)
{
for(var a=0;a<text.length;a++)
{
if(text[a].value==='')
{
one.fill_id(html_id,response);
return 0;
}
}
return 1;
}
function check_same(text1,text2,html_id,response)
{
if((text1.value)!==(text2.value))
{
one.fill_id(html_id,response);return 0;
}
one.fill_id(html_id,'');
return 1;
}
function check_aml(text)
{
var aml_response=patterns.aml.exec(text);
if(aml_response)
{
if(aml_response[2]==='p')
{
return aml_message.pass;
}
else if (aml_response[2]==='f')
{
return aml_message.fail;
}
}
else
{
return aml_message.undefined_user;
}
}
/********************
group: ajax
notes: includes call back and related. Create a DOM group
********************/
function Ajax_object()
{
var object;
try
{
object=new XMLHttpRequest();
}
catch(error_1)
{
alert('ajax_object : not instantiated:contact-support@archemarks.com : Error : ' + error_1);
}
return object;
}
function ajax_fix(path,param,ajax_func,html_div)
{
var object=new Ajax_object();
object.open("POST",path,true);
object.setRequestHeader("Content-type","application/x-www-form-urlencoded");
object.setRequestHeader("Content-length",param.length);
object.setRequestHeader("Connection","close");
object.onreadystatechange=function()
{
if(this.readyState===4)
{
if(this.status===200)
{
if(this.responseText!==null || this.responseText!=='')
{
ajax_func(this.responseText,html_div);
}
else
{
alert('Micorosft Ajax Object Failed: responseText is null or empty');
}
}
else if(this.status===12030)
{
return 0;
}
else
{
alert('Micorosft Ajax Object Failed: ' + this.status);
}
}
};
object.send(param);
return 1;
}
function ajax(path,param,ajax_func,html_div)
{
while(!ajax_fix(path,param,ajax_func,html_div))
{
ajax(path,param,ajax_func,html_div);
}
}
function ajax_tryit(server_response_text,html_div)
{
var aml_status=check_aml(server_response_text.slice(0,6));
if(aml_status===aml_message.pass)
{
one.reload();
}
else if(aml_status===aml_message.fail)
{
alert('ajax_tryit(): ' + server_response_text);
}
else
{
alert('php error: ' + server_response_text);
}
}
function ajax_null()
{
}
function ajax_signin(server_response_text,html_div)
{
var aml_status=check_aml(server_response_text.slice(0,6));
if(aml_status===aml_message.pass)
{
one.reload();
}
else if(aml_status===aml_message.fail)
{
one.fill_id(html_div,'');
one.fill_id(html_div,server_response_text);
}
else
{
alert('php error: ' + server_response_text);
}
}
function ajax_signup(server_response_text,html_div)
{
var aml_status=check_aml(server_response_text.slice(0,6));
if(aml_status===aml_message.pass)
{
document.upload_form.submit();
}
else if(aml_status===aml_message.fail)
{
document.getElementById(html_div).innerHTML=server_response_text;
}
else
{
alert('php error: ' + server_response_text);
}
}
function ajax_signout(server_response_text,html_div)
{
var aml_status=check_aml(server_response_text.slice(0,6));
if(aml_status===aml_message.pass)
{
one.reload();
}
else if(aml_status===aml_message.fail)
{
alert('ajax_signout(): ' + server_response_text);
}
else
{
alert('php error: ' + server_response_text);
}
}
function ajax_bookmark(server_response_text,html_div)
{
var aml_status=check_aml(server_response_text.slice(0,6));
if(aml_status===aml_message.pass)
{
ajax_null();
}
else if (aml_status===aml_message.fail)
{
alert('ajax_bookmark(): ' + server_response_text);
}
else
{
alert('php error: ' + server_response_text);
}
}
function ajax_tweet(server_response_text,html_div)
{
var first_split,second_split,tweet_count,return_string='';
var aml_status=check_aml(server_response_text.slice(0,6));
if(aml_status===aml_message.pass)
{
server_response_text=server_response_text.substr(6);
first_split=server_response_text.split(/\|\|/);
for(tweet_count=0;tweet_count<first_split.length;tweet_count++)
{
second_split=first_split[tweet_count].split(/\|/);
return_string=return_string+'<div class="Bb2b"><img class="a" src="pictures/' + second_split[0] + '.jpg" alt=""/><a class="a" href="javascript:void(0)\">' + second_split[1] + ' posted ' + view_date(second_split[2],second_split[3]) + '</a><br/><p class="c">' + second_split[4] + '</p></div>';
}
one.fill_id(html_div,return_string);
}
else if (aml_status===aml_message.fail)
{
alert('ajax_tweet(): ' + server_response_text);
}
else
{
alert('php error: ' + server_response_text);
}
}
function ajax_serialize(form_name)
{
var return_string='',
form_elements=document.forms[form_name].elements,
iterator;
for(iterator=0;iterator<form_elements.length;iterator++)
{
if(form_elements[iterator].name)
{
if(form_elements[iterator].type==='checkbox'&&form_elements[iterator].checked===false)
{
return_string+=form_elements[iterator].name+"=0&";
}
else
{
return_string+=form_elements[iterator].name+"="+form_elements[iterator].value+"&";
}
}
}
return_string=return_string.slice(0,-1);
return return_string;
}
/********************
group: interface
notes:
********************/
var messages =
{
empty: 'Please complete all fields',
empty_bm: 'Please enter both a title and url',
name: 'Only letters or dashes for the name field',
email: 'Please enter a valid email',
same: 'Please make emails equal',
taken: 'Sorry that email is taken',
pass: 'Please enter a valid password, 6-40 characters',
validate: 'Please contact <a class="d" href="mailto:support@archemarks.com">support</a> to reset your password',
url: 'Pleae enter a valid url'
};
function bookmark_error(image_element)
{
image_element.src='http://www.archemarks.com/images/favicon.ico';
}
function bookmark_dom_update()
{
var form_elements=document.bookmark.elements;
var link_element=document.createElement('a');
link_element.innerHTML=form_elements[1].value;
link_element.href=form_elements[2].value;
link_element.name="a1";
link_element.className="b";
link_element.target="_blank";
var image_element=document.createElement('img');
image_element.className="c";
image_element.name="bo_im";
image_element.onerror = function()
{
bookmark_error(image_element);
};
image_element.src=form_elements[2].value+'/favicon.ico';
var list_hold=document.getElementById('Bb1c');
var element_iterator=list_hold.firstChild;
while(!!(element_iterator=element_iterator.nextSibling))
{
if(typeof element_iterator.tagName==='undefined')
{
list_hold.insertBefore(image_element,element_iterator);
list_hold.insertBefore(link_element,element_iterator);
break;
}
else if(element_iterator.tagName.toLowerCase()==='a' && (link_element.innerHTML<element_iterator.innerHTML))
{
element_iterator=element_iterator.previousSibling;
list_hold.insertBefore(image_element,element_iterator);
list_hold.insertBefore(link_element,element_iterator);
break;
}
}
return 1;
}
function interface_tryit()
{
ajax('some_name_1.php','ajax_type=tryit',ajax_tryit,'');
}
function interface_signin()
{
var form_name='signin',
form_elements=document.forms[form_name].elements,
response_div='signin_response',
client_pass=1;
if(some_name.client_validation===1)
{
client_pass=(check_empty(form_elements,response_div,messages.empty)&&check_generic(patterns.email,form_elements[0],response_div,messages.email)&&check_generic(patterns.pass,form_elements[1],response_div,messages.validate));
}
if(client_pass===1){ajax('some_name_1.php',ajax_serialize(form_name)+'&ajax_type=signin',ajax_signin,response_div);}
}
function interface_signup()
{
var form_name='signup',
form_elements=document.forms[form_name].elements,
response_div='signup_response',
client_pass=1;
if(some_name.client_validation===1)
{
client_pass=(check_empty(form_elements,response_div,messages.empty)&&check_generic(patterns.name,form_elements[0],response_div,messages.name)&&check_generic(patterns.email,form_elements[1],response_div,messages.email)&&check_same(form_elements[1],form_elements[2],response_div,messages.same)&&check_generic(patterns.pass,form_elements[3],response_div,messages.pass));
}
if(client_pass===1){ajax('some_name_1.php',ajax_serialize(form_name)+'&ajax_type=signup',ajax_signup,response_div);}
}
function interface_signout()
{
ajax('some_name_1.php','ajax_type=signout',ajax_signout,'NULL');
}
function interface_bookmark_add()
{
var form_name='bookmark',
form_elements=document.forms[form_name].elements,
response_div='bookmark_response';
if(check_empty(form_elements,response_div,messages.empty_bm)&&check_generic(patterns.url,form_elements[2],response_div,messages.url)&&bookmark_dom_update()&&ajax('some_name_1.php',ajax_serialize(form_name)+'&ajax_type=bookmark_add',ajax_bookmark,response_div))
{
one.fill_id('f3aa','');
one.fill_id('bookmark_add_box','');
}
}
function interface_tweet()
{
var form_name='tweet',
form_elements=document.forms[form_name].elements,
response_div='tweet_response';
if(check_empty(form_elements,response_div,'Please share with the community')&&ajax('some_name_1.php',ajax_serialize('tweet')+'&ajax_type=tweet',ajax_tweet,'Bb2b_hold'))
{
document.getElementById('tweet_box').value='';
}
}
function interface_bookmark_delete(event_pull)
{
var delete_elment=this,
send_param=delete_elment.name + "=" + delete_elment.innerHTML;
event_pull.preventDefault();
delete_elment.parentNode.removeChild(delete_elment.previousSibling);
delete_elment.parentNode.removeChild(delete_elment);
ajax('some_name_1.php',send_param+'&ajax_type=bookmark_delete',ajax_bookmark);
}
function interface_bookmark_flip()
{
var button_element=document.getElementById('bookmark_flip_button'),
bookmark_list=document.getElementsByName('a1'),
bookmark_element,
iterator=0;
if(interface_bookmark_flip.p1==='Done')
{
interface_bookmark_flip.p1='Delete';
interface_bookmark_flip.p2='b';
while(!!(bookmark_element=bookmark_list[iterator++]))
{
bookmark_element.removeEventListener("click", interface_bookmark_delete);
bookmark_element.className=interface_bookmark_flip.p2;
}
}
else
{
interface_bookmark_flip.p1='Done';
interface_bookmark_flip.p2='b1';
while(!!(bookmark_element=bookmark_list[iterator++]))
{
bookmark_element.addEventListener("click", interface_bookmark_delete);
bookmark_element.className=interface_bookmark_flip.p2;
}
}
button_element.innerHTML=interface_bookmark_flip.p1;
}
/********************
group: initialize
notes:
********************/
function link_update(link_display)
{
var local_element;
local_element=document.getElementById(some_name.persistent_element);
local_element.style.display='none';
local_element=document.getElementById(link_display);
local_element.style.display='block';
some_name.persistent_element=link_display;
}
function bind_enter_key(event, callback)
{
if(event.keyCode===constant.enter_key)
{
callback();
return false;
}
}
function initialize_page()
{
var signin_found;
signin_found=document.getElementById('signin_button');
if(signin_found)
{
window.some_name =
{
client_validation:0,
persistent_element:'hide_1'
};
signin_found.onclick=interface_signin;
one.set_onclick('signup_button',interface_signup);
one.set_onclick('tryit_button',interface_tryit);
one.set_onkeypress('signup_pass', function(event){return bind_enter_key(event, interface_signup);});
one.set_onkeypress('signin_pass', function(event){return bind_enter_key(event, interface_signin);});
one.set_onkeypress('upload_file', function(event){return false;});
one.set_onclick('l0',function() {return link_update('hide_0');});
one.set_onclick('l1',function() {return link_update('hide_1');});
one.set_onclick('l2',function() {return link_update('hide_2');});
one.set_onclick('l3',function() {return link_update('hide_3');});
one.set_onclick('l4',function() {return link_update('hide_4');});
one.set_onclick('l5',function() {return link_update('hide_5');});
}
else
{
one.set_onclick('signout_button',interface_signout);
one.set_onclick('bookmark_add_button',interface_bookmark_add);
one.set_onclick('bookmark_flip_button',interface_bookmark_flip);
one.set_onclick('tweet_button',interface_tweet);
one.set_onkeypress('tweet_box', function(event){return bind_enter_key(event, interface_tweet);});
one.set_onkeypress('bookmark_add_box', function(event){return bind_enter_key(event, interface_bookmark_add);});
}
}
addEventListener('load', initialize_page);
/********************
group: api related
notes: menu and view
********************/
function view_date(current_time,post_time)
{
var elapsed_time=(current_time-post_time),d,return_string, rounded_time;
if(elapsed_time===0)
{
return_string=' just a second ago';
}
else if((elapsed_time>0) && (elapsed_time<constant.minute))
{
if(elapsed_time===1)
{
return_string='1 second ago';
}
else
{
return_string=elapsed_time+' seconds ago';
}
}
else if((elapsed_time>=constant.minute) && (elapsed_time<constant.hour))
{
rounded_time=Math.floor(elapsed_time/60);
if(rounded_time===1)
{
return_string='1 minute ago';
}
else
{
return_string=rounded_time+' minutes ago';
}
}
else if((elapsed_time>=constant.hour) && (elapsed_time<constant.day))
{
rounded_time=Math.floor(elapsed_time/constant.hour);
if(rounded_time===1)
{
return_string='1 hour ago';
}
else
{
return_string=rounded_time+' hours ago';
}
}
else if((elapsed_time>=constant.day))
{
rounded_time=new Date(post_time*constant.second);
return_string='on '+rounded_time.toLocaleDateString();
}
return return_string;
}
var menu = {
menu_timer:0,
menu_element:0,
top_mouse_over: function (id)
{
menu.bottom_mouse_over();
menu.menu_element=document.getElementById(id);
menu.menu_element.style.visibility='visible';
},
hide_menu: function()
{
if(menu.menu_element)
{
menu.menu_element.style.visibility='hidden';
}
},
bottom_mouse_over: function()
{
if(menu.menu_timer)
{
window.clearTimeout(menu.menu_timer);
}
},
mouse_out: function()
{
menu.menu_timer=window.setTimeout(menu.hide_menu, constant.menu);
}
};
/********************
group: api
notes:
********************/
function api_test()
{
alert("api is up");
}
return {
view_date: view_date,
menu: menu,
bookmark_error: bookmark_error
};
})(window);
</code></pre>
|
[] |
[
{
"body": "<p>Couple of notes from my side:</p>\n\n<ol>\n<li><p><code>var one</code>'s methods perform DOM lookups without caching. Set a field in <code>one</code> object to cache the access to elements. This will increase the performance.</p></li>\n<li><p>Functions <code>check_generic</code>, <code>check_empty</code> etc. return 0 or 1 as a result of check. Booleans make more sense for callers usually; consider use of booleans instead.</p></li>\n<li><p>You're using reserved <code>object</code> keyword in <code>Ajax_object</code> function (and the name of the function is a little different from naming convention you follow in other places). Consider unifications of naming conventions, renaming the <code>object</code> to something else.</p></li>\n<li><p>Also, the <code>Ajax_object</code> function does not support browsers without native support of XMLHttpRequest object. Consider taking a pattern of trying Microsoft specific instantiations of XML HTTP request objects. <code>Ajax_object</code> returns <code>undefined</code> if the XMLHttpRequest is not instantiated. This is usually wrong for external callers. Consider throwing exception further so the callers can deal with it.</p></li>\n<li><p><code>else if(this.status===12030)</code> - could you clarify which special case you're trying to cover here?</p></li>\n<li><p>I would merge all AJAX related functions into namespace/object to group them logically or implement modularity of some sort to have them extended externally.</p></li>\n<li><p>Functions like <em>ajax_signin</em> are clearly way more specific to actual application whereas <em>ajax_tryit</em> are more generic. Consider splitting them into separate objects/namespaces.</p></li>\n<li><p>All the \"specific\" functions follow the same guideline: server response -> slice -> check_aml -> check status of aml -> do stuff. Consider using decorator pattern to amalgamate these calls.</p></li>\n<li><p>I couldn't figure out what <code>ajax_null</code> is for. Could you clarify?</p></li>\n</ol>\n\n<p>That's it for now.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2011-11-21T21:15:34.813",
"Id": "6185",
"ParentId": "6166",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "6185",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2011-11-20T05:31:10.813",
"Id": "6166",
"Score": "1",
"Tags": [
"javascript"
],
"Title": "Shaping collection of methods to MVC pattern"
}
|
6166
|
<pre><code>if (isset($_POST['submit'])) {
if (isset($_SESSION['token']) && $_POST['token'] == $_SESSION['token']) {
$errors = array();
$error = 0;
if (!preg_match('/^[A-Za-z](?=[A-Za-z0-9_.]{3,20}$)[a-zA-Z0-9_]*\.?[a-zA-Z0-9_]*$/i', $_POST['username'])) {
$errors[] = 'Your username must start with a letter (A-Z) and be between 3-20 characters and may only contain alphanumeric characters (A-Z, 0-9 _ ) or a period (1) (".")';
$error = 1;
}
$STH = $DBH->prepare("SELECT username FROM users WHERE username = ?");
$STH->execute(array($_POST['username']));
if ($STH->rowCount() > 0) {
$errors[] = 'The username is already taken!';
$error = 1;
}
if (strlen($_POST['password']) < 3) {
$errors[] = 'Your password must be longer than 3 characters!';
$error = 1;
} else if ($_POST['password'] != $_POST['passconf']) {
$errors[] = 'You didn\'t verify your password correctly!';
$error = 1;
}
if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$errors[] = 'The e-mail is not valid!';
$error = 1;
} else {
$STH = $DBH->prepare("SELECT email FROM users WHERE email = ?");
$STH->execute(array($_POST['email']));
if ($STH->rowCount() > 0) {
$errors[] = 'The email is already taken!';
$error = 1;
}
}
}
}
</code></pre>
<p>This is my current validation for a registration page it works, but I'd like to improve it, give me some tips</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-21T00:05:13.107",
"Id": "9556",
"Score": "0",
"body": "I have some doubt on the username regex"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-21T07:10:06.377",
"Id": "9569",
"Score": "0",
"body": "How could I improve it/change it? Why?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-04T20:58:38.710",
"Id": "60227",
"Score": "0",
"body": "given some explaination in my answer"
}
] |
[
{
"body": "<p>You have two long if blocks:</p>\n\n<pre><code>if (isset($_POST['submit'])) {\n if (isset($_SESSION['token']) && $_POST['token'] == $_SESSION['token']) {\n ...\n }\n}\n</code></pre>\n\n<p>Why not combine them?</p>\n\n<pre><code>if (isset($_POST['submit']) && (isset($_SESSION['token']) && $_POST['token'] == $_SESSION['token'])) {\n ...\n}\n</code></pre>\n\n<p>also the way you've structured this, you don't need <code>$error</code>, to see if there are errors you can simply check <code>empty($errors)</code> (true => ok, false => not ok).</p>\n\n<p>Other than that, your code looks fine.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-21T07:10:46.030",
"Id": "9570",
"Score": "0",
"body": "Thanks, but is really 2 queries needed for my username check and e-mail check? That's what I mainly had thoughts about"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-21T07:18:56.560",
"Id": "9571",
"Score": "0",
"body": "The reason I didn't combine the If statements is because if someone mess with the token / or tries to submit a form from another place, I want to log that someone tried a CSRF attack. If I combine them, I would log everytime I don't submit the form and load the page :P"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-21T11:50:42.327",
"Id": "9575",
"Score": "0",
"body": "@John Well you can get rid of username altogether, and use the email as username. But if you want them both, and they are supposed to be unique then yes you do have to have the two queries..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-21T15:18:54.730",
"Id": "9577",
"Score": "0",
"body": "Shouldn't I be able to query with a OR in the SQL statement, then try fetch the object or something?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-21T15:26:51.397",
"Id": "9580",
"Score": "0",
"body": "@John There are ways to combine the two queries. Easy ways where you won't know which of the two clauses failed (just that one of them did as a simple OR query) and more creative ways where it'd be possible to get all the info you want. But the two queries are extremely low cost, combining in any way won't have any distinguishable performance benefit and there are chances that you actually stress the db a little more. Anyways, if it's the sql you wan't reviewed, I'd suggest you add detailed table structures and their expected size on the question, too little info for a good answer as it is."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-20T22:03:39.810",
"Id": "6174",
"ParentId": "6170",
"Score": "1"
}
},
{
"body": "<p>I think the correct regex for the login should be</p>\n\n<pre><code>if (!preg_match('/^[A-Za-z][A-Za-z0-9_.]{2,19}$/i', $_POST['username'])) {\n $errors[] = 'Your username must start with a letter (A-Z) and be between 3-20 characters and may only contain alphanumeric characters (A-Z, 0-9 _ ) or a period (1) (\".\")';\n $error = 1;\n }\n</code></pre>\n\n<p><strong>EDIT</strong>\nI think that the current regexp allows more thant 30 letters</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-22T13:22:30.373",
"Id": "6200",
"ParentId": "6170",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "6174",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-20T11:27:39.267",
"Id": "6170",
"Score": "2",
"Tags": [
"php"
],
"Title": "Validation code tips"
}
|
6170
|
<p>I'm trying to transpose the following data from:</p>
<pre><code>1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
</code></pre>
<p>to:</p>
<pre><code>1 1 1 1 1 1 1 1 1 1
2 2 2 2 2 2 2 2 2 2
3 3 3 3 3 3 3 3 3 3
4 4 4 4 4 4 4 4 4 4
5 5 5 5 5 5 5 5 5 5
6 6 6 6 6 6 6 6 6 6
7 7 7 7 7 7 7 7 7 7
8 8 8 8 8 8 8 8 8 8
9 9 9 9 9 9 9 9 9 9
10 10 10 10 10 10 10 10 10 10
</code></pre>
<p>using <code>sed</code> only please.</p>
<p>I have a working solution but I'm sure it can be improved:</p>
<pre><code>sed -rn 'H;${x;s/\n/ &/g;s/$/@/;:a;s/\n([^ ]+ ?)(.*@.*)/%\2\1/;ta;s/ %+@//p;t;s/ *$/\n/;y/%/\n/;ta}'
</code></pre>
<p>It uses <code>%</code> and <code>@</code> for newline and end-of-string delimiters which may be problematic.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-14T01:18:01.683",
"Id": "9545",
"Score": "0",
"body": "Any reason you are limiting the solution to `sed`? What about `awk`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-14T01:22:50.527",
"Id": "9546",
"Score": "0",
"body": "Thanks for the link @Kristian I was unaware of the site."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-14T01:26:55.210",
"Id": "9547",
"Score": "0",
"body": "@Yzmir I'm sure there are many published solutions in other languages but I am trying to improve my understanding of `sed`. BTW @Dave this is not homework per se just personal curiosity."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-14T01:34:08.837",
"Id": "9548",
"Score": "0",
"body": "Will the columns for each line be the same? Will the row count always match the column count? Will a single space be the delimiter?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-14T01:45:57.637",
"Id": "9549",
"Score": "0",
"body": "@Yzmir for the moment lets go with the input data provided above. That is 10x10 square matix each value delimited by a single space. But of course is should work for bigger or smaller matrices and 4x3 or 7x9 should work to. Tabs can be catered for by pre and post formating using `tr` or `sed`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-14T08:24:52.050",
"Id": "9550",
"Score": "4",
"body": "This is a better fit back on SO than here on cg"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-14T19:18:59.327",
"Id": "9551",
"Score": "0",
"body": "Or actually, even better on codereview."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-24T04:30:13.220",
"Id": "9693",
"Score": "4",
"body": "Dubious as a code review question, here we like code you can read."
}
] |
[
{
"body": "<p>This yet another way to do it:</p>\n\n<pre><code>sed -r '1{s/$/ /;s/ / \\n/g};:a;$!N;s/$/ /;:b;s/\\n(.*\\n+)(\\S+\\s)/\\2@!@\\1/;tb;s/@!@/\\n/g;${s/ \\n/\\n/g;s/\\n+$//;q};ba'\n</code></pre>\n\n<p>This method is somewhat faster and only uses single delimiter which may be crafted to be unique. i.e. <code>@!@</code> in this example</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-24T00:17:24.103",
"Id": "6242",
"ParentId": "6175",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-14T01:14:19.583",
"Id": "6175",
"Score": "4",
"Tags": [
"matrix",
"shell",
"sed"
],
"Title": "Transpose a matrix using sed"
}
|
6175
|
<p><strong>Are there any security flaws in what I plan to do?</strong></p>
<p>I need to store the following in my DB:</p>
<ol>
<li>a random string to act as a salt for encrypting a password</li>
<li>the encrypted password that used the salt in #1</li>
</ol>
<p>Here's the PHP code I have to accomplish the above tasks:</p>
<pre><code><?php
function decrypt($string, $encryption_key = '')
{
$initialization_vector = get_initialization_vector();
// Convert hexadecimal data into binary representation
$string = hex2bin($string);
// See: http://php.net/manual/en/mcrypt.ciphers.php
return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $encryption_key, $string, MCRYPT_MODE_ECB, $initialization_vector));
}
function encrypt($string, $encryption_key = '')
{
$initialization_vector = get_initialization_vector();
// See: http://php.net/manual/en/mcrypt.ciphers.php
$string = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $encryption_key, $string, MCRYPT_MODE_ECB, $initialization_vector);
// Convert binary data into hexadecimal representation
$string = bin2hex($string);
return $string;
}
function get_initialization_vector()
{
// See: http://php.net/manual/en/mcrypt.ciphers.php
// MCRYPT_BLOWFISH selected as it appears to be one of the "universally"
// supported ciphers supported by the mcrypt extension
$initialization_vector_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB);
// See: http://php.net/manual/en/function.mcrypt-create-iv.php
// The source can be MCRYPT_RAND (system random number generator), MCRYPT_DEV_RANDOM
// (read data from /dev/random) and MCRYPT_DEV_URANDOM (read data from /dev/urandom).
// Prior to 5.3.0, MCRYPT_RAND was the only one supported on Windows.
$initialization_vector = mcrypt_create_iv($initialization_vector_size, MCRYPT_RAND);
return $initialization_vector;
}
function get_random_string($character_set = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz', $minimum_length = 8, $maximum_length = 12)
{
if ($minimum_length > $maximum_length)
{
$length = mt_rand($maximum_length, $minimum_length);
}
else
{
$length = mt_rand($minimum_length, $maximum_length);
}
$random_string = '';
for ($i = 0; $i < $length; $i++)
{
$random_string .= $character_set[(mt_rand(0, (strlen($character_set) - 1)))];
}
return $random_string;
}
function hex2bin($hexadecimal_data)
{
$binary_representation = '';
for ($i = 0; $i < strlen($hexadecimal_data); $i += 2)
{
$binary_representation .= chr(hexdec($hexadecimal_data{$i} . $hexadecimal_data{($i + 1)}));
}
return $binary_representation;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-20T17:41:26.737",
"Id": "9552",
"Score": "0",
"body": "I don't think “critique my code” is appropriate on this site. “Critique my protocol” could be, although a precise description of your security objectives would be preferable. There's a site for code critique in the Stack Exchange network: [codereview.se]. Do not repost there for the time being; I've flagged a moderator, and if the moderators agree your question is fine for Code Review, they will migrate it there."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-20T18:14:25.447",
"Id": "9553",
"Score": "0",
"body": "How do you encrypt something with a salt? That doesn't make much sense. Typically you encrypt something with a key. Now, if instead of salt you meant to say key, then your scheme is very insecure. Think about it. You are storing the key and the ciphertext in the same place. If the attacker can access the database, she has both and can decrypt the ciphertext."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-20T22:54:20.147",
"Id": "9554",
"Score": "0",
"body": "Gilles - points 1 and 2 need critiquing, not the code. The code is just there to elaborate on my idea."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-21T15:08:22.520",
"Id": "9576",
"Score": "0",
"body": "@mikeazo I believe he is salting like one should do in a hash. It's not a problem with his terminology, just that there's no reason to salt an encryption."
}
] |
[
{
"body": "<p>To summarize what you are doing here:</p>\n\n<p>You use AES in ECB-mode, with some unknown key, to encrypt a password.</p>\n\n<p>You also try to use a random initialization vector as a salt for this encryption.</p>\n\n<p>I see these problems:</p>\n\n<ul>\n<li><p>Usually, <strong>you don't want to encrypt a password, but hash it instead.</strong> See the recent <a href=\"http://security.blogoverflow.com/2011/11/why-passwords-should-be-hashed/\">blog article about this topic</a>, which links to relevant questions.</p>\n\n<p>If this password is for login verification only, there is no need to\nstore it encrypted, instead hash it. Only store the password itself\nif you need it for login somewhere else. (But this can open another\ncan of worms, so think about using something else here.)</p></li>\n<li><p>ECB-mode, which you are using, <em>doesn't have an initialization vector</em>. So your code will actually generate a zero-length random string (or a longer one, which will not be used).</p>\n\n<p>Encrypting the same password twice will result in the same ciphertext both times. <strong>Don't ever use ECB-mode</strong> (if you are not sure it is the right thing to use for some reason), use CBC-mode or CTR instead. Then your initialization vector generation actually will do something (see next point).</p></li>\n<li><p><em>You generate a random initialization vector on decryption</em>. This doesn't\nhit you now, as it isn't actually used (see previous point), but if you\nare using it, you actually have to store it together with the encrypted\ndata and retrieve it before decrypting, otherwise the first block (16 bytes)\nof the decrypted plaintext (for CBC) will be garbage.</p></li>\n</ul>\n\n<p>And a non-security-relevant remark:</p>\n\n<ul>\n<li>You don't need the hexadecimal encoding, if you define your database\ncolumn with a binary type (<code>BINARY</code> or <code>VARBINARY</code>) instead of a text type.\nThis will safe some storage space (and a tiny bit of processing time).</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-20T22:56:44.870",
"Id": "9555",
"Score": "0",
"body": "Doh! Hashing is what I want. I knew that! Was working at 4am; wasn't thinking particularly straight. Will review your link. Thanks."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-20T18:45:57.423",
"Id": "6177",
"ParentId": "6176",
"Score": "4"
}
},
{
"body": "<h2>Why Encryption Doesn't Fit the Goal of Password Storage</h2>\n\n<p>Cryptographic hashing and encryption have two different purposes. Hashing is not reversible -- given a hash, you can't determine what made it except by testing to see if a source input matches the hash output. When used for passwords, this becomes a validation only question: \"does this password (mixed with this salt) match?\" With passwords, the goal is to prevent somebody with full access to the database from recovering passwords.</p>\n\n<p>Encrypting passwords handles that goal poorly. To verify a password, one must have the encryption key. That means one is also able to determine the source password from looking at the encrypted version of the password. In the event of a compromise, having those encrypted fields and the key will result in the disclosure of all passwords regardless of how strong they were.</p>\n\n<h2>Good Resources</h2>\n\n<p><a href=\"https://security.stackexchange.com/questions/211/how-to-securely-hash-passwords\">https://security.stackexchange.com/questions/211/how-to-securely-hash-passwords</a></p>\n\n<h2>The Rules of Crypto</h2>\n\n<p>You'll hear it a lot around here: don't roll your own. The problem is that the field has changed too much for \"common sense\" to really be something that's working on our favor. Encryption and password issues have evolved relatively fast on a human-life scale of time. Where not everybody is following that, a lot of varying ideas exist about how to solve these problems and many of them have been proven wrong.</p>\n\n<p>If you're not current, the proper approach is to research the issue you're trying to solve rather than the method you're trying to solve it with.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-20T19:08:44.030",
"Id": "6178",
"ParentId": "6176",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-20T17:17:23.053",
"Id": "6176",
"Score": "4",
"Tags": [
"php",
"strings",
"security",
"random"
],
"Title": "Random string + encrypt/decrypt"
}
|
6176
|
<p>Alright, well the title doesn't really explain anything, so I'll show a pared down version of my code:</p>
<pre><code>class Handler {
Dictionary<object, Leaf> AllItems = new Dictionary<object, Leaf>(); //This list
Leaf RootLeaf = new Leaf();
public void Add (object obj)
{
Leaf AddedTo = RootLeaf.Add(obj); //Adds to a leaf, then returns the leaf it was added to
AllItems.Add(obj, AddedTo); //adds references to the obj and the leaf it's in.
}
}
class Leaf {
private Leaf _Parent;
public Leaf SubLeaf;
public List<object> Children = new List<object>();
public Leaf (Leaf parent)
{
this._Parent = parent;
}
public void Add (object obj)
{
if (Children.Count > 5)
{
SubLeaf = new Leaf();
return SubLeaf.Add(obj); //recursively return the reference to the end leaf
}
Children.Add(obj);
return this; //start the recursive return
}
public Leaf Parent { get { return this._Parent; } }
}
</code></pre>
<p><em>Note: The above isn't real code, just an example of what I plan to do.</em></p>
<p>So the idea of the above is to organize all the items into leaves, but I need a quick way to loop through every object, and its leaf. Would doing the above (storing a reference of every object & its parent in a list in the Handler class) cause a drop in performance? Or would there be a better way to do this?</p>
<p>I hope this was clear enough, if not, please ask any questions.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-21T18:28:56.520",
"Id": "9585",
"Score": "0",
"body": "Are you really going to allow any object to be a key to the `Dictionary<object, Leaf>`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-21T22:45:39.167",
"Id": "9593",
"Score": "0",
"body": "It is actually a interface that others inherit from, but for the basic example, an object would suffice just as well"
}
] |
[
{
"body": "<p>Well, it's not a tree, it's a linked list, and it won't work properly for more than seven items. After that you will overwrite the <code>SubLeaf</code> variable in the first node, and previously added items will be removed from the list, and <code>AllItems</code> will contain lost items with disowned nodes.</p>\n\n<p>To make the list work you have to check if the node has a next node before creating a new one.</p>\n\n<pre><code>public class Node {\n\n private Node _next;\n private List<object> _items;\n\n public Node Previous { get; private set; }\n\n public Leaf (Leaf previous) {\n _previous = previous;\n _next = null;\n _items = new List<object>(6);\n }\n\n public void Add(object obj) {\n if (_items.Count == 6) {\n if (_next == null) {\n _next = new Leaf(this);\n }\n return _next.Add(obj);\n }\n _items.Add(obj);\n return this;\n }\n\n}\n</code></pre>\n\n<p>Note: Consider using an array in the node instead of a list. Creating a list that uses lists seems redundant...</p>\n\n<p>Also, keeping a reference to the last node in the handler would help when you want to add nodes, so that you don't have to loop through all nodes each time.</p>\n\n<p>Putting the objects and their nodes in a list is not needed for looping through them, as you already have all the nodes and the objects. Adding the list would roughly tripple the memory usage and the time to add an item. You would only need another list if you need two completely different ways of accessing the items, for example both predictable enumerating and hash lookup.</p>\n\n<p>To enumerate the list as pairs of objects and nodes, you can put an enumerator in the <code>Node</code> class which gets all objects and their nodes from the current node and forward, so you just use it on the first node to get all objects:</p>\n\n<pre><code>public IEnumerable<KeyValuePair<object,Node>> GetAll() {\n Node node = this;\n while (node != null() {\n foreach (object obj in node._items) {\n yield return new KeyValuePair<object,Node>(obj, node);\n }\n node = node._next;\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-21T09:12:11.503",
"Id": "9573",
"Score": "0",
"body": "I'm sorry, I mis-wrote the example code above (and you are correct). My question was more along the lines of \"Does using a list (in this case called `AllItems`) in the Handler class that stores references to all of the items I have hurt performance?\"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-21T11:35:41.183",
"Id": "9574",
"Score": "0",
"body": "I added some notes on performanc above."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-21T18:51:09.537",
"Id": "9586",
"Score": "0",
"body": "Thanks for the feedback, so holding a List of every item added to sub nodes (and their sub nodes, etc) would greatly damage performance, though would it hurt it to the point that looping through every node and retrieving every item would be a better alternative? And this is an implementation for a video game, so performance is (in this case) more important then memory, though memory could still be a problem with many items."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-21T18:53:23.633",
"Id": "9587",
"Score": "0",
"body": "And FYI, the IEnumerable is a gorgeous piece of code, but what if there are multiple sub-nodes per node? Sorry for dragging this on, but hopefully you can help me iron out the performance issues in this bit of code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-21T20:01:06.260",
"Id": "9589",
"Score": "0",
"body": "@mazzzzz: Looping the nodes would be rougly as fast as looping the items in a dictionary, and at no memory cost. You should define what you really need to do with your collection, so that you can pick one that does that fast."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-21T20:07:49.787",
"Id": "9590",
"Score": "0",
"body": "I suppose paring down the code didn't help as much as hurt. I am working on an implementation of a quad-tree. Each node can have 4 child nodes, or none. Each node can also have any amount of children. Could you help write an IEnumerable for that? It is very nice to see a more skilled developer's perspective on this, I've already learned a lot :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-22T06:36:07.837",
"Id": "9610",
"Score": "0",
"body": "Thanks for the help you were able to provide. You did answer the asked question, and I won't ask that you also answer my rephrased question to get your answer accepted."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-21T08:11:44.613",
"Id": "6180",
"ParentId": "6179",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "6180",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-21T06:13:38.207",
"Id": "6179",
"Score": "2",
"Tags": [
"c#"
],
"Title": "Hold a list of items stored in recursive class?"
}
|
6179
|
<p>I am working a project which uses a function to show a modal dialog. The dialog can be hidden by calling the hideModal() function. This function is triggered by:</p>
<ul>
<li>Pressing the ESC key</li>
<li>Clicking on the modal background</li>
<li>Clicking on the close button</li>
</ul>
<p>My current code is:</p>
<pre><code> $("#modal").click(function() {
hideModal();
});
$("#modal-object-container > a").click(function(e) {
hideModal();
e.preventDefault();
});
$(document).keydown(function (e) {
if (e.keyCode == '27') {
hideModal();
}
});
</code></pre>
<p>I have the feeling there should be a faster way to bind all these events at once.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-21T21:18:38.863",
"Id": "9592",
"Score": "2",
"body": "Since your event sources (elements, document etc) are different and there are custom actions you have to implement each time, there is no better way of doing this, unfortunately."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-22T09:08:28.853",
"Id": "9613",
"Score": "0",
"body": "I thought the same thing but was hoping for a clever trick :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-24T01:21:20.077",
"Id": "9681",
"Score": "0",
"body": "for `click` events you can use event delegation , but that's about it"
}
] |
[
{
"body": "<p>Your code isn't all that bad. However because you are binding key events on the document, you need to allow room, for other key events to be bound, for other tasks, so your code doesn't interfere with other ESC functions.</p>\n\n<p>The concept is that you bind on click, and unbind upon hiding your modal. This way the key events are only applicable when your code is run.</p>\n\n<pre><code>// save your doc once, it's faster\nvar doc = $(document);\n // bind a function, which you can unbind later, so esc can be used in other cases as well, without triggering your function\n doc.bind('keydown', _processKey);\n\n// on click binding for as many elements as you like. \n// The preventDefault shouldn't influence other elements in this case.\n$(\"#modal, #modal-object-container > a\").click(function(ev) {\n ev.preventDefault();\n hideModal();\n});\n\n// when you hide your modal, you unbind the event, so the document is free for other events and functions\nfunction hideModal() {\n doc.unbind('keydown', _processKey);\n}\n\n// have a 'private' function to do what you want. This way you can unbind it anytime you like\nfunction _processKey(ev) {\n if (ev.keyCode == '27') {\n hideModal();\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-22T12:17:36.860",
"Id": "9619",
"Score": "0",
"body": "Really good arguments, I will change this in my code. Instead of bind() I will use on() and off() as described in http://www.andismith.com/blog/2011/11/on-and-off/ Thanks!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-22T12:10:57.677",
"Id": "6198",
"ParentId": "6181",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "6198",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-21T13:00:40.453",
"Id": "6181",
"Score": "2",
"Tags": [
"javascript",
"jquery"
],
"Title": "jQuery multiple events execute same function refactoring"
}
|
6181
|
<p>I've learned MVVM for a week or so, and I've seen the <a href="http://blog.lab49.com/archives/2650" rel="noreferrer">Jason Dolinger video</a> many times. Step by step, following the Jason Dolinger video, I've created my own application which is almost the same to the one presented by Jason Dolinger. I'm completely satisfied with my current application, however, because the recorded video is several years old I think that something can probably be improved or some things are obsolete.</p>
<pre><code>namespace TerminatorConsole.Model
{
public interface IWcfModel
{
List<ConsoleData> DataList { get; set; }
event Action<List<ConsoleData>> DataArrived;
}
}
namespace TerminatorConsole.Model
{
class WcfModel : IWcfModel
{
private List<ConsoleData> _dataList;
public List<ConsoleData> DataList
{
get { return _dataList; }
set { _dataList = value;
var dataDel = DataArrived;
if (dataDel != null)
{
DataArrived(_dataList);
}
}
}
public event Action<List<ConsoleData>> DataArrived;
}
}
namespace TerminatorConsole.Utils
{
class DispatchingWcfModel : IWcfModel
{
private readonly IWcfModel _underlying;
private readonly Dispatcher _currentDispatcher;
public DispatchingWcfModel(IWcfModel model)
{
_currentDispatcher = Dispatcher.CurrentDispatcher;
_underlying = model;
_underlying.DataArrived += new Action<List<ConsoleData>>(_underlying_DataArrived);
}
private void _underlying_DataArrived(List<ConsoleData> obj)
{
Action dispatchAction = () =>
{
if (DataArrived != null)
{
DataArrived(obj);
}
};
_currentDispatcher.BeginInvoke(DispatcherPriority.DataBind, dispatchAction);
}
public List<ConsoleData> DataList
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
public event Action<List<ConsoleData>> DataArrived;
}
}
namespace TerminatorConsole.ViewModel
{
public class OverviewViewModel
{
private IWcfModel model;
public ObservableCollection<ConsoleData> DataList { get; set; }
public OverviewViewModel(IWcfModel model)
{
this.model = model;
this.DataList = new ObservableCollection<ConsoleData>();
model.DataArrived += new Action<List<ConsoleData>>(model_DataArrived);
}
private void model_DataArrived(List<ConsoleData> dataList)
{
DataList.Clear();
dataList.ForEach(x => DataList.Add(x));
}
private static ObservableCollection<T> ToObservableCollection<T>(IEnumerable<T> coll)
{
var c = new ObservableCollection<T>();
foreach (var e in coll) c.Add(e);
return c;
}
}
}
namespace TerminatorConsole
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
private WcfLoader loader;
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
IUnityContainer container = new UnityContainer();
WcfModel model = new WcfModel();
DispatchingWcfModel dispatching = new DispatchingWcfModel(model);
loader = new WcfLoader(model);
container.RegisterInstance<IWcfModel>(dispatching);
MainWindow window = container.Resolve<MainWindow>();
window.Show();
}
}
}
namespace TerminatorConsole
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private OverviewViewModel _vm;
[Dependency]
public OverviewViewModel VM
{
set
{
_vm = value;
this.DataContext = _vm;
}
}
public MainWindow()
{
InitializeComponent();
}
}
}
namespace TerminatorConsole.Utils
{
class WcfLoader
{
private IManagementConsole pipeProxy;
Timer refresh_timer;
private int interval = 1000;
private WcfModel model;
public WcfLoader(WcfModel model)
{
this.model = model;
ChannelFactory<IManagementConsole> pipeFactory =
new ChannelFactory<IManagementConsole>(
new NetNamedPipeBinding(),
new EndpointAddress("net.pipe://localhost/PipeMBClientManagementConsole"));
pipeProxy = pipeFactory.CreateChannel();
refresh_timer = new System.Timers.Timer(interval);
refresh_timer.AutoReset = false;
refresh_timer.Elapsed += OnRefreshTimedEvent;
refresh_timer.Start();
}
void OnRefreshTimedEvent(object source, ElapsedEventArgs args)
{
try
{
LoadModel(model);
}
finally
{
refresh_timer.Start();
}
}
public void LoadModel(WcfModel model)
{
var dataList = new List<ConsoleData>();
foreach (StrategyDescriptor sd in pipeProxy.GetStrategies())
{
dataList.Add(pipeProxy.GetData(sd.Id));
}
model.DataList = dataList;
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>There are a few things you can improve here. Unless all your classes are in separate files, you do not need to do <code>namespace NamespaceName</code> around each class.</p>\n\n<p>This is most unnecessary:</p>\n\n\n\n<pre class=\"lang-cs prettyprint-override\"><code>public List<ConsoleData> DataList\n{\n get { throw new NotImplementedException(); }\n set { throw new NotImplementedException(); }\n}\n</code></pre>\n\n<p>Why define something just to make it throw an exception every time it is used? This is being abstracted from <code>IWcfModel</code>, so if you don't do this, it will use the <code>DataList</code> defined in <code>IWcfModel</code>. If that <code>DataList</code> is not correct for this instance, you should either not abstract from <code>IWcfModel</code>, or you should implement the correct version of this.</p>\n\n<p>If you use a <code>try</code> block, there should usually be a <code>catch</code> block too:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>try\n{\n LoadModel(model);\n}\nfinally\n{\n refresh_timer.Start();\n}\n</code></pre>\n\n<p>If there is no <code>catch</code> block and the <code>try</code> block throws, the <code>finally</code> does not run until the exception is caught. It can be caught anywhere up the call stack, but it must be caught or the application will probably crash. If <code>LoadModel(model)</code> does not throw, the <code>finally</code> will be guaranteed to run, and if it does throw and the exception is not caught, your application will probably crash. Because of this, you should either place a catch in there or the <code>try-finally</code> block is not needed because both statements will run in order.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-01-28T22:17:33.413",
"Id": "78921",
"ParentId": "6183",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-21T18:30:11.747",
"Id": "6183",
"Score": "8",
"Tags": [
"c#",
"mvvm"
],
"Title": "MVVM implementation based on Jason Dolinger's video"
}
|
6183
|
<p>How can this solution be improved?</p>
<pre><code>#include <limits.h>
void itoa(int n, char s[])
{
int min_int = 0;
int i, sign;
if (INT_MIN == n) {
min_int = 1;
n++;
}
if ((sign = n) < 0)
n = -n;
i = 0;
do {
s[i++] = n % 10 + '0';
} while ((n /= 10) > 0);
if (sign < 0)
s[i++] = '-';
s[i] = '\0';
if (min_int)
s[0]++;
reverse(s);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-21T21:12:19.813",
"Id": "9591",
"Score": "1",
"body": "How about just use `snprintf()`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-22T10:34:05.603",
"Id": "9615",
"Score": "0",
"body": "@JeffMercado: The only thing that's better with snprintf is that it's standard. Apart from that, it is a horrible slow function that can't be used in application with high real time demands."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-07-24T19:48:45.907",
"Id": "254416",
"Score": "0",
"body": "Funny part. This code is almost exactly Kernighan & Ritchie solution. So it is K&R code review! (source https://en.wikibooks.org/wiki/C_Programming/C_Reference/stdlib.h/itoa)"
}
] |
[
{
"body": "<p>Just some general idea about the code (without any effort to create a better algorithm).</p>\n\n<p>First of all, I agree with @Jeff, if there is a library for that use it. You don't have to maintain it and everybody will know what the code does.</p>\n\n<p>So, code. I would use longer variable names:</p>\n\n<pre><code>void itoa(int number, char result[])\n</code></pre>\n\n\n\n<pre><code>int i, sign;\n</code></pre>\n\n<p>I prefer one declaration per line because it's easier to read and find the type of variables.</p>\n\n<pre><code>if ((sign = n) < 0)\n</code></pre>\n\n<p>It looks cool but hard to maintain. Just some questions:</p>\n\n<ul>\n<li>Why is it here? </li>\n<li>Is it intentionally <code>=</code> (and not <code>==</code>)?</li>\n<li>Why isn't it in a line before?</li>\n</ul>\n\n<p>If you have to maintain this code these kind of question could be hurt. So, I would write</p>\n\n<pre><code>sign = number;\nif (number < 0) ...\n</code></pre>\n\n<p>The questions are the in the while loop:</p>\n\n<pre><code>do { \n ...\n} while ((n /= 10) > 0);\n</code></pre>\n\n<p>I'd write:</p>\n\n<pre><code>do { \n ...\n n /= 10;\n} while (n > 0);\n</code></pre>\n\n<p>Finally, I guess there is a potential buffer overflow if the caller pass too small char array to the function.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-22T10:39:15.100",
"Id": "9616",
"Score": "2",
"body": "Good comments. There is nothing gained by merging several rows into one, that's just obfuscation and makes the code less readable."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-21T22:44:10.807",
"Id": "6186",
"ParentId": "6184",
"Score": "5"
}
},
{
"body": "<p>I think I'd break this up into a few separate routines, each with a single more specific intent. I think the easiest way to do this is <em>probably</em> to start by taking the absolute value of the input (represented as an unsigned type), something like this:</p>\n\n<pre><code>unsigned iabs(int input) { \n if (input >= 0)\n return (unsigned)input;\n return (UINT_MAX - (unsigned)input)+1U;\n}\n</code></pre>\n\n<p>I believe C's requirements for converting a signed to unsigned ensure that this produce correct results for all inputs (including INT_MIN).</p>\n\n<p>With that, nearly everything else can deal with an unsigned number. Personally, I also prefer to generate the result in order instead of generating in reverse, then reversing it. One fairly simple way to do that is with recursion, with each step first generating previous numerals (if any), then adding its own numeral to the end of the string. I'd have the recursive function deal only with an unsigned type (as produced above). Of course, like nearly everything that manipulates data in a buffer in C, you should also pass the maximum buffer length for it to use, to prevent buffer overruns. For the sake of generality, I've also made it accept the base for the conversion as a parameter instead of always assuming base 10.</p>\n\n<pre><code>char *itoa_internal(char *buffer, size_t len, unsigned input, int base) { \n static const char digits[] = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n char *pos = buffer;\n if (input >= base)\n pos = itoa_internal(buffer, len, input/base, base);\n\n if (pos-buffer < len-1)\n *pos++ = digits[input % base];\n return pos;\n}\n</code></pre>\n\n<p>Then I'd have a small wrapper function that puts in a <code>-</code> if the input is negative, invokes the function above with the absolute value of the input, and terminates the string after the internal function returns.</p>\n\n<pre><code>char *itoa(char *buffer, size_t len, int input, int base) {\n char *pos = buffer;\n\n if (base < 2 || base > 36 || len < 1)\n return NULL;\n\n if (input < 0)\n *pos++ = '-';\n\n pos = itoa_internal(pos, len, iabs(input), base);\n *pos = '\\0';\n return buffer;\n}\n</code></pre>\n\n<p>This should also make it pretty trivial to write a <code>utoa</code> that handles unsigned inputs -- it would be like <code>itoa</code> without the code to deal with negative numbers. As a minor refinement, I'd probably also make <code>iabs</code> and <code>itoa_internal</code> static functions to minimize the chances of them interfering with other names.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-22T10:57:50.770",
"Id": "9617",
"Score": "0",
"body": "It is probably bad practice to use `unsigned` to implicitly refer to `unsigned int`. If I remember correctly, this is one of the things the C committee will make obsolete in future language standards. The best is of course to use the C99 int types from stdint.h (uint8_t, uint16_t etc) if C99 is available. Also, I don't see why you would use recursion for this, a plain for loop will both be faster and easier to read."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-22T11:57:27.467",
"Id": "9618",
"Score": "0",
"body": "@Lundin: Why would it be bad practice? Do you think somebody might think it referred to a nonexistent unsigned float type? I can't imagine the committee changing this -- it would gain nothing, and break huge amounts of code. In this case, the types for `stdint.h` would be detrimental. I used recursion because I've yet to see an iterative version that was nearly as clean. \"Recursion => slow\" has been obsolete for a decade or more."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-22T12:26:34.863",
"Id": "9620",
"Score": "0",
"body": "I'm not sure from where I heard that it may become obsolete, but anyway, there's no reason why you can't type out 3 more letters just in case, it isn't that big an effort and makes the code clearer. stdint.h could actually improve the code further - if you know the size of an int, then you can tell whether the [len] parameter is valid or not, if you know that int is 16 bits, then len shouldn't be longer than 5 letters + 1 null."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-22T12:42:15.120",
"Id": "9621",
"Score": "0",
"body": "I don't see how recursion could be optimized by the compiler and still C standard-compliant? A function call is a sequence point and all side effects must be complete before the function is called. With all the side effects in place, I don't see how the compiler could unroll the recursion on its own? Also, if it _is_ standard-compliant, mustn't it be tail recursion if the compiler should have any chance at all of optimizing it? I suspect whether the compiler is allowed/able to do this is highly language-dependent."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-22T15:43:38.690",
"Id": "9623",
"Score": "0",
"body": "IMO, it does not make the code any clearer. Do you also think there's some improvement from replacing `int x;` with `auto signed int x;`? If so, why? If not, why should one use defaults but not the other? Faster recursion is a result of hardware improvements (branch prediction, on-chip return stack, on-chip stack)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-22T16:00:35.007",
"Id": "9624",
"Score": "0",
"body": "As far as the types go, I see two obvious problems: first, it would be silly to reject a call just because the type *could* hold a value too large for the buffer. Second, these allow the user to specify the base, so (to use your example) that 16-bit integer *could* require up to 17 characters."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-03-15T02:42:01.823",
"Id": "151323",
"Score": "0",
"body": "Or you can use the mathematical definition of `abs()`; `sqrt(pow(val, 2))`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-03-15T04:23:25.000",
"Id": "151327",
"Score": "0",
"body": "@MotokoKusanagi: I suppose you could, but I doubt you'd want to--it's likely to be slower and less accurate than most others."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-22T05:19:32.297",
"Id": "6192",
"ParentId": "6184",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "6192",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-21T20:56:05.990",
"Id": "6184",
"Score": "7",
"Tags": [
"c",
"reinventing-the-wheel",
"integer"
],
"Title": "Implementation of itoa()"
}
|
6184
|
<p>I'm somewhat curious on peoples opinion about such a method. I Actually didn't find anything similar in librarys I use on regular bases so far.</p>
<p>This is my implementation:</p>
<pre><code>Object.map = function _map( obj, transform ) {
if( typeof obj === 'object' && typeof transform === 'function' ) {
Object.keys( obj ).forEach(function _forEach( key ) {
(function _mapping( oldkey, transmuted ) {
if( transmuted && transmuted.length ) {
obj[ transmuted[ 0 ] || oldkey ] = transmuted[ 1 ];
if( transmuted[ 0 ] && oldkey !== transmuted[ 0 ] ) {
delete obj[ oldkey ];
}
}
}( key, transform.apply( obj, [ key, obj[ key ]] ) ));
});
}
};
</code></pre>
<p>I normally put it on the Object object and not the prototype. However, usage is like this</p>
<pre><code>var foo = {
someProp: 5,
bar: 10,
moar: 20
};
Object.map( foo, function(key, value) {
return [ key.toUpperCase(), value*2 ];
});
</code></pre>
<p>result:</p>
<pre><code>Object { SOMEPROP=10, BAR=20, MOAR=40}
</code></pre>
<p>I most often use it to translate CSS properties (to vendor prefixes). But I don't see people use an approach like this often in ECMAscript. Any thoughts?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-22T01:15:34.917",
"Id": "9596",
"Score": "0",
"body": "[I would implement it as such](http://jsfiddle.net/VP2H8/1). I'd also avoid the word \"map\". And probably use word \"transform\". It's also a rare operation and simple to do without a utility function so most people probably do this by hand"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-21T18:45:28.077",
"Id": "66688",
"Score": "0",
"body": "As for other libraries, `jQuery.each()` does exactly that."
}
] |
[
{
"body": "<p>First comment, there is no need for the closure inside _forEach which makes the code unnecessarily difficult to read. More importantly I would argue that the function would be much more useful if did not transform the original object and instead returned a new object.</p>\n\n<pre><code>Object.map = function (obj, mapping) {\n var mapped = {};\n\n if (typeof obj !== 'object') {\n return mapped;\n }\n\n if (typeof mapping !== 'function') {\n // We could just return obj but that wouldn't be\n // consistent with the rest of the interface which always returns\n // a new object.\n mapping = function (key, val) {\n return [ key, val ];\n };\n }\n\n Object.keys( obj ).forEach(function (key) {\n var transmuted = mapping.apply(obj, [ key, value ]);\n\n if (transmuted && transmuted.length) {\n mapped[ transmuted[0] || key ] = kv[ 1 ];\n }\n });\n\n return mapped;\n};\n</code></pre>\n\n<p>This is not only less dangerous for widely available object but it also makes the function more flexible by allowing it to be chained or used within an expression:</p>\n\n<pre><code>Object.map(oldCss, function (key, value) {\n // ...\n}).doSomethingElse();\n</code></pre>\n\n<p>At the very least I would have your original function return the passed in object to allow for chaining or use within an expression.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-24T18:50:56.640",
"Id": "6261",
"ParentId": "6189",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-22T00:57:12.660",
"Id": "6189",
"Score": "3",
"Tags": [
"javascript"
],
"Title": "Object map() / transmute() method"
}
|
6189
|
<pre><code>/**
* View_message
* Object Model
*/
var View_message = function(div)
{
this.div = document.getElementById(div);
};
View_message.prototype.messages =
{
empty: 'Please complete all fields',
empty_bm: 'Please enter both a title and url',
name: 'Only letters or dashes for the name field',
email: 'Please enter a valid email',
same: 'Please make emails equal',
taken: 'Sorry that email is taken',
pass: 'Please enter a valid password, 6-40 characters',
validate: 'Please contact <a class="d" href="mailto:support@host.com">support</a> to reset your password',
url: 'Pleae enter a valid url'
};
View_message.prototype.display = function(type)
{
this.div.innerHTML = this.messages[type];
};
</code></pre>
<p><strong>And the Call</strong></p>
<pre><code>obj_view = new View_message('test_id');
obj_view.display('empty');
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-22T02:11:48.250",
"Id": "9605",
"Score": "0",
"body": "Your using `.innerHTML` instead of `.textContent`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-22T04:23:53.050",
"Id": "9609",
"Score": "0",
"body": "What's the question?"
}
] |
[
{
"body": "<p>I believe you are overcomplicating things. Declaring a prototype, will not make your code any more robust or even faster. I'm sure you know, but actually something like the code below will be easier to read, more effective and also faster.</p>\n\n<pre><code>/**\n * View_message\n * Object Model\n */ \nvar ViewMessage = function(div) {\n this.div = document.getElementById(div); \n\n this.messages = { \n empty: 'Please complete all fields',\n empty_bm: 'Please enter both a title and url',\n name: 'Only letters or dashes for the name field',\n email: 'Please enter a valid email',\n same: 'Please make emails equal',\n taken: 'Sorry that email is taken',\n pass: 'Please enter a valid password, 6-40 characters',\n validate: 'Please contact <a class=\"d\" href=\"mailto:support@host.com\">support</a> to reset your password',\n url: 'Pleae enter a valid url'\n };\n\n this.display = function(type) {\n this.div.innerHTML = this.messages[type];\n\n return this;\n };\n\n return this;\n};\n</code></pre>\n\n<p>Then two ways of doing this:</p>\n\n<pre><code>var view = new ViewMessage('divID');\n view.display('email');\n</code></pre>\n\n<p>OR</p>\n\n<pre><code>var view = new ViewMessage('divID').display('email');\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-22T18:33:03.070",
"Id": "9629",
"Score": "0",
"body": "Do I even need to set it to a variable? Could I just do new ViewMessage('divID').display('email')"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-24T10:43:07.840",
"Id": "9712",
"Score": "0",
"body": "No need to set it in a variable, no. But if you want to add more functions later, or anything, well you might need it.. Otherwise, initialise and fire it up! (without the new)\nViewMessage('divID').display('email');"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-25T08:21:50.220",
"Id": "9751",
"Score": "0",
"body": "@lcampanis When instantiating multiple instances, adding methods to the prototype is much faster: http://jsperf.com/instance-vs-prototype-methods"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-25T11:41:53.877",
"Id": "9762",
"Score": "0",
"body": "No doubt it is, but in this case I'm afraid it isn't the case. One instance seems to be needed alone. And sure it might be faster to use the prototype, but on one instance, the delay (if any) we are talking about is almost nothing. \nNo doubt it is though, if many are needed, and you intend to loop an enormous amount of time to get things done :)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-22T11:14:44.047",
"Id": "6197",
"ParentId": "6190",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "6197",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-22T01:55:08.253",
"Id": "6190",
"Score": "0",
"Tags": [
"javascript"
],
"Title": "View_messages \"class\""
}
|
6190
|
<p>I used to use static or singleton for my DAL class. However, I read some articles saying that singleton is evil and should be avoided. Therefore I try to rewrite my code like this:</p>
<pre><code>public class CustomerBLL
{
private CustomerHelper helper = new CustomerHelper();
private CustomerDAL dal = new CustomerDAL();
public void Method1(string param)
{
dal.Method1(param);
}
public void Method2(string param)
{
dal.Method2(param);
}
public void MethodA(int param)
{
helper.MethodA(param);
}
}
</code></pre>
<p>How do I improve this code? It just doesn't look right.</p>
|
[] |
[
{
"body": "<p>I believe that some generalizations are to be made lightly. i.e. stating that Singletons are evil in general is not accurate, as there are some cases where Singleton is a proper (and maybe the only) solution. And yes I do believe that it is one of the overly abused patterns out there. Having gotten that out of the way, I move to answer your question.</p>\n\n<p>From the code sample you submitted, it is very clear that your <code>CustomerBLL</code> has no business logic and merely acts as a <code>Façade</code> on top of the data access and other helper classes. Facades should be stateless by nature.</p>\n\n<p>Having said that, I will offer two choices based on testability and decoupling requirements.</p>\n\n<p>If you want to make you <code>CustomerBLL</code> testable and decouple it from the <code>CustomerHelper</code> and <code>CustomerDAL</code> concretions and substitute them with abstractions, then one good design enhancement would be to inject the <code>CustomerHelper</code> and <code>CustomerDAL</code> dependencies into the <code>CustomerBLL</code> class, which allows you to mock and stub the data access and helper classes and focus on testing other code modules that consume the <code>CustomerBLL</code> class. You acheive that through extraxcting interfaces of course.</p>\n\n<p>Here is an example of how the code would look if we inject the dependencies through a constructor, note that your CustomerBLL Façade will be an instance class i.e. no static methods will be exposed.</p>\n\n<pre><code>public class CustomerBLL\n{\n private readonly ICustomerHelper _helper;\n private readonly ICustomerDAL _dal;\n\n // default constructor initializes the concrete dependencies\n public CustomerBLL()\n :this(new CustomerHelper(), new CustomerDAL())\n {}\n\n // constructor to inject stubbed dependencies for testing purposes\n public CustomerBLL(ICustomerHelper customerHelper, ICustomerDAL customerDal)\n {\n _helper = customerHelper;\n _dal = customerDal;\n }\n\n public void Method1(string param)\n {\n _dal.Method1(param);\n }\n\n public void Method2(string param)\n {\n _dal.Method2(param);\n }\n\n public void MethodA(int param)\n {\n _helper.MethodA(param);\n }\n}\n\npublic interface ICustomerDAL\n{\n void Method1(string s);\n void Method2(string s);\n}\n\npublic interface ICustomerHelper\n{\n void MethodA(int i);\n}\n\ninternal class CustomerDAL : ICustomerDAL\n{\n public void Method1(string s)\n {\n }\n\n public void Method2(string s)\n {\n }\n}\n\ninternal class CustomerHelper : ICustomerHelper\n{\n public void MethodA(int i)\n {\n }\n}\n</code></pre>\n\n<p>If on the other hand, testability is not a concern at all, then you can proceed by consuming the CustomerBLL as a Façade in a procedural way through static methods (although I much prefer the testability approach, but it’s not every one’s cup of tea). </p>\n\n<p>Here you notice I removed the private fields that hold references to the Helper and DAL classes, because we want to promote that the CustomerBLL Façade is stateless.</p>\n\n<pre><code>public class CustomerFacade\n{\n public static void Method1(string param)\n {\n new CustomerDAL().Method1(param);\n }\n\n public static void Method2(string param)\n {\n new CustomerDAL().Method2(param);\n }\n\n public static void MethodA(int param)\n {\n new CustomerHelper().MethodA(param);\n }\n}\n</code></pre>\n\n<p>I have seen and used both approaches, in my humble opinion they both are valid depending on the usage scenario. In general I am in favor of testable design and decoupled modules and that’s why I proposed the first approach.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-23T02:55:41.943",
"Id": "9642",
"Score": "0",
"body": "In the 2nd approach, does that mean CustomerFacade will create an instance for CustomerDAL/CustomerHelper everytime I call a method?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-23T05:17:04.527",
"Id": "9644",
"Score": "0",
"body": "@WalterHuang, yes you instantiate a helper or a DAL class only when needed. This should be fine as long as your Helpers and DALs do not create costly resources in their constructors or keep references (state) to those resources without Disposing them."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-24T02:15:21.177",
"Id": "9683",
"Score": "0",
"body": "@AnasKarkoukli Could I also make Helper and DAL static? Just like CustomerFacade, they act as containers of methods. Thank you :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-24T04:22:54.103",
"Id": "9692",
"Score": "0",
"body": "@WalterHuang Man you break my heart :-) can you at least consider the testability approach. Over use of static methods is a symptom of procedural programming and lack of object orientation. Nothing prevents you from using static methods across the board. I just encourage you to explore other ways."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-24T08:48:33.180",
"Id": "9703",
"Score": "0",
"body": "@AnasKarkoukli I admit that I am a \"staticaholic\" :P OK, I will try the 1st approach :) thx"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-22T05:21:45.147",
"Id": "6193",
"ParentId": "6191",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "6193",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-22T02:38:22.110",
"Id": "6191",
"Score": "2",
"Tags": [
"c#",
"singleton",
"static"
],
"Title": "How can I improve this code without using static or singleton?"
}
|
6191
|
<p>I'm combining 2 UISliders made from scratch -- one horizontal and one vertical -- to make a single slider that controls 2 parameters. They are set up so that the vertical slider is perpendicular to the horizontal one. (Like a cross) The thumb knob can move both horizontally and vertically, and if it's moved horizontally, the vertical tracker will move left and right to follow the thumb.</p>
<p>I'm having trouble setting the boundaries of the thumb. Its leftmost limit is supposed to be reached when the left edge of the v. slider touches the left edge of the horizontal slider, and the rightmost limit is when the right edges of the sliders intersect. For the sake of consistency, I took whatever code I needed to obtain the previous conditions and used a similar structure for the top and bottom limits -- even though there is no actual intersection.</p>
<p>This is what I came up with. (This is in a custom UIView which holds both sliders. Also, the size of the UIView is 100 x 100, and the sliders are each 90 points long.) </p>
<pre><code>- (BOOL)continueTrackingWithTouch:(UITouch *)touch withEvent:(UIEvent *)event {
CGPoint touchPoint = [touch locationInView:self];
CGFloat hLimitLeft = horizontalSliderFrame.origin.x + .5* ksliderThickness;
CGFloat hLimitRight = horizontalSliderFrame.origin.x + horizontalSliderFrame.size.width - .5* ksliderThickness;
CGFloat vLimitTop = verticalSliderFrame.origin.y + .5* ksliderThickness;
CGFloat vLimitBottom = verticalSliderFrame.origin.y + verticalSliderFrame.size.height - .5* ksliderThickness;
CGRect thumbBoundaries = CGRectMake(hLimitLeft, vLimitTop, hLimitRight - hLimitLeft, vLimitBottom - vLimitTop) ;
if (CGRectContainsPoint(thumbBoundaries, touchPoint)) {
self.thumb.center = CGPointMake(touchPoint.x, touchPoint.y);
[self setNeedsDisplay];
[self updateValues];
}
return YES;
}
</code></pre>
<p>Generally, it works fine. However, it doesn't move at the edges because the touch usually lies outside the boundaries even when it's holding on to the thumb knob. </p>
<p>I'm wondering if there's a better way to design this code.</p>
|
[] |
[
{
"body": "<p>Once your control is active, just keep tracking until the touch ends, even if the touch moves outside of the view:</p>\n\n<pre><code>- (BOOL)continueTrackingWithTouch:(UITouch *)touch withEvent:(UIEvent *)event {\n CGPoint touchPoint = [touch locationInView:self];\n\n CGFloat hLimitLeft = horizontalSliderFrame.origin.x + .5* ksliderThickness;\n CGFloat hLimitRight = hLimitLeft + horizontalSliderFrame.size.width - ksliderThickness;\n CGFloat vLimitTop = verticalSliderFrame.origin.y + .5* ksliderThickness;\n CGFloat vLimitBottom = vLimitTop + verticalSliderFrame.size.height - ksliderThickness;\n\n self.thumb.center.x = MAX(hLimitLeft, MIN(hLimitRight, touchPoint.x));\n self.thumb.center.y = MAX(vLimitTop, MIN(vLimitBottom, touchPoint.y));\n\n [self setNeedsDisplay];\n [self updateValues];\n\n return YES;\n}\n</code></pre>\n\n<p>Note also that I changed the calculation of <code>hLimitLeft</code> and <code>vLimitTop</code>. I think this approach is clearer (in particular I missed the different signs on the <code>.5 * ksliderThickness</code> term the first couple of times through).</p>\n\n<p>It's been a while since I've done iOS development, so there might be some minor mistakes, but this should get you going in the right direction.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-27T15:28:20.787",
"Id": "8363",
"ParentId": "6195",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-22T08:47:35.093",
"Id": "6195",
"Score": "3",
"Tags": [
"objective-c"
],
"Title": "Combining horizontal and vertical sliders into one"
}
|
6195
|
<p>For the time being, I am not interested in any recursive solution. The code is not modularized; the whole body is inside the main function.</p>
<pre><code>#include<iostream.h>
#include<stdlib.h>
/*This code is written by NF between any time of 120711 and 210711;modified at 231211*/
int main()
{
int length=0,min_heapified=0,start_length=0,index=0;
cout<<"Enter Array Length:";
cin>>length;
int array[length];
for(int i=0;i<length;i++)
{
array[i]=rand()%100;
}
cout<<"Array is filled now with random elements";
cout<<"\nSorted Array:"<<endl;
do
{
do
{
min_heapified=0;
for(int root=0;root<length/2;root++)/*As the leaf nodes have no child they should not be in a consideration while swapping so looping upto length/2 is enough*/
{
int left=((2*root)+1);
int right=((2*root)+2);
if(left<length)
{
if(array[left]<array[root])
{
int swap=array[left];
array[left]=array[root];
array[root]=swap;
min_heapified=1;
}
}
if(right<length)
{
if(array[right]<array[root])
{
int swap=array[right];
array[right]=array[root];
array[root]=swap;
min_heapified=1;
}
}
}
}while(min_heapified>0);
int swap=array[0];
array[0]=array[--length];/*modification done at this point to avoid keeping the sorted elements into another array;and swapping done between the 0th and last element*/
array[length]=swap;
cout<<array[length]<<" ";
}while(length>0);
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-22T10:15:09.263",
"Id": "9614",
"Score": "2",
"body": "Are those the original whitespaces? If yes...those should be changed first."
}
] |
[
{
"body": "<pre><code>int length=0,min_heapified=0,start_length=0,index=0;\n</code></pre>\n\n<p>I prefer one declaration per line because it's easier to read and find the type of variables. Furthermore, <code>min_heapified</code> is only used inside the <code>do-while</code> loop, so declare it there:</p>\n\n<pre><code>do { \n int min_heapified = 0;\n do {\n...\n</code></pre>\n\n<hr>\n\n<p>Change </p>\n\n<pre><code>if(x<=(length-1))\n</code></pre>\n\n<p>to</p>\n\n<pre><code>if (x < length)\n</code></pre>\n\n<p>It's more common and simple.</p>\n\n<hr>\n\n<p>Instead of</p>\n\n<pre><code>int swap=array[left];\narray[left]=array[root];\narray[root]=swap;\n</code></pre>\n\n<p>you should create a <code>swap</code> function. Maybe it already exists in a library.</p>\n\n<pre><code>int swap(array, index, rootIndex) {\n int swap = array[index];\n array[index] = array[rootIndex];\n array[root] = swap;\n}\n</code></pre>\n\n<hr>\n\n<p>If I'm right you could extract the following to a new function:</p>\n\n<pre><code>if(array[left]<array[root])\n{\n int swap=array[left];\n array[left]=array[root];\n array[root]=swap;\n min_heapified=1; \n}\n</code></pre>\n\n<p>It looks for me that the other <code>if</code> do the same. The only difference is the used index, so I'd write something like this:</p>\n\n<pre><code>int swapIfLess(array, index, rootIndex) {\n if (array[index] < array[rootIndex]) {\n swap(array, index, rootIndex)\n return 1; \n }\n return 0;\n}\n</code></pre>\n\n\n\n<pre><code>if (left < length) {\n if (swapIfLess(array, left, root)) {\n min_heapified=1; \n }\n}\nif (right < length) {\n if (swapIfLess(array, right, root)) {\n min_heapified=1; \n }\n}\n</code></pre>\n\n<hr>\n\n<p>The <code>i</code> variable looks unnecessary:</p>\n\n<pre><code>int root=i;\n</code></pre>\n\n<p>Use the <code>root</code> variable in the for loop:</p>\n\n<pre><code>for (int root = 0; root < length; root++)\n</code></pre>\n\n<p>Maybe you should rename it to <code>rootIndex</code>.</p>\n\n<hr>\n\n<p>Extract more functions. The <code>for</code> loop (inside the <code>do-while</code> loops) looks as a good candidate for this. Additionally, you should have a <code>readInputArray</code> function and a <code>printResults</code> function too.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-22T16:42:20.797",
"Id": "9625",
"Score": "3",
"body": "Since this is C++ there is already a std::swap"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-22T12:31:17.457",
"Id": "6199",
"ParentId": "6196",
"Score": "7"
}
},
{
"body": "<p>Lets declare one variable per line.<br>\nAlso don't declare all you variables at the top. Declare them as close to the use point as possible.</p>\n\n<pre><code> int length=0,min_heapified=0,start_length=0,index=0;\n</code></pre>\n\n<p>Declaring arrays like this is not valid. It is C functionality. your compiler is letting you get away with it but not all compiler will. The size of the array must be static and known at compile time. If you need to dynamical size arrays then use std::vector</p>\n\n<pre><code> int array[length],sorted_array[length];\n</code></pre>\n\n<p>C++ already has a std::swap() use that rather than doing it manually.</p>\n\n<p>use < rather than <= (it looks more natural for most C/C++ programmers). In your case it is especially a god thing as you are subtracting one anyway.</p>\n\n<pre><code>if(root <= (length-1))\n// Prefer the following\nif(root < length)\n</code></pre>\n\n<p>This is an un-needed test:</p>\n\n<pre><code>if(root < length)\n</code></pre>\n\n<p><code>root</code> is <code>i</code> and <code>i</code> is the loop variable constrained to be less then length. While we are here you should not use <code>i</code> as a variable name. It conveys no meaning (this is not fortran). Name your variables. Also think about the maintainer searching for all uses of i is a real pain as the letter i is used everywhere. Name your variables so it can be easily found.</p>\n\n<p>Prefer to use pre-increment.</p>\n\n<pre><code>for(int root=0;root<length;root++)\n// prefer\nfor(int root=0;root<length;++root)\n</code></pre>\n\n<p>In this case it makes no difference. But when using class types (like a lot of iterators) the standard way to implement post increment is to do a copy (as the return value) then call pre-increment. Thus it can be slightly less efficient to use post increment when loop variable is a class type. The problem with post increment comes not when you write the code but when you maintain it. If sombody converts the container to a standard container and then converts the loop to iteratos etc you need to spot and change the increment. By being consistent and always using pre-increment changes to the types have less affect on changes to the code (ie it help when types are changed (especially when the type change is a long way from the type being used).</p>\n\n<p>You are using <code>min_heapified</code> as a boolean. Declare it as such and use appropriately.</p>\n\n<pre><code>min_heapified=0;\n</code></pre>\n\n<p>While you are at it. Declare it here and not at the top.</p>\n\n<pre><code>bool min_heapified = false;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-22T17:05:00.087",
"Id": "6206",
"ParentId": "6196",
"Score": "2"
}
},
{
"body": "<p>The other answers cover the stylistic concerns of your code pretty well already. However, there is still one major issue with your code that warrants another (albeit late)answer: it's <strong>incorrectly</strong> implemented!</p>\n\n<p>The \"heapsort\" algorithm that you implemented has a run-time complexity of O(N<sup>2</sup>). Judging from your comment, you probably realized something was wrong too since the run-time sky-rocketed as you tried to sort more items.</p>\n\n<p>Here are the problem areas I see that's causing the abysmal performance:</p>\n\n<ul>\n<li>You are re-heapifying the <em>entire</em> array on each iteration. This is of course completely wrong and it's the biggest reason why your code is performing so poorly. You're only suppose to heapify the array <em>once</em>, at the beginning when you start the sort. </li>\n<li>Shifting all the elements down by one after removing the smallest. This is an O(N) operation that can be avoided altogether with a redesign.</li>\n<li>Use of a temp array -- this is also unnecessary. Like quicksort, one of heapsort's advantages is that it's capable of sorting in-place without the need to allocate a temporary buffer.</li>\n<li>Heapifying 'leaf' elements needlessly. By definition, leaf elements don't have any child nodes below them so there's nothing to push down. Therefore, it doesn't make sense to heapify pass the <em>last</em> parent element. In other words, you should be going from <code>root = 0</code> to <code>root < (length / 2)</code>. Going pass <code>length / 2</code> will just result in unnecessary comparisons: <code>left < length</code> and <code>right < length</code> will <strong>always</strong> be false.</li>\n</ul>\n\n<p>It's typical to write 2 helper functions when implementing heapsort: <code>heapify</code> that turns the array into a heap, and a <code>push_down</code> or <code>filter_down</code> function to enforce the heap property for the element passed in. You usually implement <code>heapify</code> with the help of the filter function.</p>\n\n<p>Note that the stl has heap functions that does exactly those tasks: <code>push_heap</code>, <code>pop_heap</code> and <code>make_heap</code>.</p>\n\n<p>I'll leave the utility functions for you to figure out but here's how the top view of heapsort should look:</p>\n\n<pre><code>void heapsort(int *begin, int *end)\n{\n // assume end is one pass the last element. eg. arry + length;\n heapify(begin, end);\n\n while(begin != --end)\n {\n swap(*begin, *end); // invariant: the next item to order will be at the top\n // after the swap, the next biggest/smallest item may not be\n // at the top. use push_down to fix this and preserve the heap property.\n push_down(begin, end); \n }\n}\n</code></pre>\n\n<p>Note that you do not call heapify inside the loop. After the swap, <em>only the top</em> element might violate the heap property -- the rest of the remaining elements are still in a heap. To fix the top you just need to <code>push_down</code> that element until it reaches the right level. This can be done in O(log n) since that's how deep the tree can ever be.</p>\n\n<p><strong>Edit</strong>: Added more explanation and example.</p>\n\n<p>An analogy might help clear up the idea behind heapsort. You can think of heapsort as hosting an elimination tournament where in each match-up bracket 3 contenders duke it out. The winner will move up the bracket to the next match-up and the 2 losers stay where they are. The tournament starts out by doing all the match-ups at the bottom bracket first, progressively moving up -- this is basically the heapifying phrase.</p>\n\n<p>After you heapify, that's finishing one entire tournament -- the champion is at array[0] and the runner-ups will be either array[1] or array[2]. To find the runner-up you host another match-up between them plus a 3rd contender from the bottom bracket.</p>\n\n<p>Now if you think of 'push_down' as a sort of scorekeeper, his job is to keep track of the winners and move them up the bracket + what match-ups need to take place. Each match-up has 1 'defender'(the guy one bracket up) and 2 'challengers'. If the defender loses, he swaps places with the challenger that defeated him. If there are more challengers below the defender's new spot, another match-up is between them. The defender will get pushed further and further down the match-up bracket until he can successfully defend his spot or there are no more opponents to defend against.</p>\n\n<p>The 'push_down' function is probably the most important helper since that's where the reordering actually happens. It's almost analogous to partition in qsort or merge in mergesort.</p>\n\n<p>Here's basically what the push_down function would look like: (note, it's not thoroughly tested)</p>\n\n<pre><code>void push_down(int *begin, int *end, size_t defender = 0)\n{\n // at the very bottom?\n if(defender >= std::distance(begin, end) / 2) return;\n\n size_t challenger = defender * 2 + 1;\n // is there a right-child?\n // Note that in even# arrays, last parent doesn't have a right child\n if(begin + challenger + 1 != end) \n if(begin[challenger + 1] < begin[challenger])\n ++challenger;\n\n // defended successfully?\n if( !(begin[challenger] < begin[defender]) ) return;\n\n // challenger wins\n std::swap(begin[challenger], begin[defender]);\n push_down(begin, end, challenger);\n}\n</code></pre>\n\n<p>Note that the array will be sorted in descending order if smallest is at the top. But this is trivial to fix once sorting is working -- just flip the comparison being done.</p>\n\n<p>You should heed the advice from the other answers and extract out those functions. It will make your code easier to reason about.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-20T00:47:36.293",
"Id": "10937",
"Score": "0",
"body": "@MiNdFrEaK no problem, I only just posted this recently. I do feel bad for stealing someone else's accepted answer :p"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-22T23:29:02.337",
"Id": "11078",
"Score": "0",
"body": "From the algorithms I have read(so far) I found they almost did the same thing I did.But still I am missing something I guess as the code havent speeded up.It would be better if you can give an expample of the actual heapsort algorithm if you can,if its not the actual one.What I did is: I took an array,heapified it,swapped the array[0] with array[length](as array[0] has the minimum value here),decreased length,then repeated the whole process until length=0.I then flushed the final sorted array."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-23T02:02:33.053",
"Id": "11083",
"Score": "0",
"body": "@MiNdFrEaK I've added more detail. Hope it clears some things up."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-24T01:39:34.720",
"Id": "11108",
"Score": "0",
"body": "It speeded up,but still runs behind my bubble sort.:(The main flaws were: (1)I was saving all the sorted elements to other array;and also I am moving the tree a step down all using extra loops. (2)I used one extra loop to print. So I just removed this,and it takes now some micro seconds may be to print out sorted elements.:)))"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-24T01:53:56.247",
"Id": "11109",
"Score": "0",
"body": "@MiNdFrEaK if your revised code still looks like your question, you haven't fixed the first bullet point issue -- which as I indicate is the primary reason for lack of performance."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-24T03:38:53.137",
"Id": "11113",
"Score": "0",
"body": "somehow I cant get your first point,everytime I heap,I get the lowest value at array[0],then I swap it with the last array element that is array[length],so I need to heapify again because that swapping breaks the heaps property,next time I am heaping the array having 1 less element than the last array...whats wrong with it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-24T03:44:50.147",
"Id": "11115",
"Score": "0",
"body": "The problem is you're potentially touching every single element for every iteration if you use heapify like that. The question is, is this really necessary because this will become a very expensive operation? If you have to do that why not just pick the smallest element every iteration and do a selection sort? You're not taking full advantage of the heap property to speed sorting."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-24T03:52:54.423",
"Id": "11116",
"Score": "0",
"body": "Take a look at my `push_down` helper function and see if you can figure out how it can help."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-24T05:13:40.367",
"Id": "11117",
"Score": "0",
"body": "We can take this to [code review chat](http://chat.stackexchange.com/rooms/2066/heapsort-discussion) if you have more questions."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-24T18:59:59.133",
"Id": "11128",
"Score": "0",
"body": "ok victor,finally I have done with it(and the confusion between building max heap and max heapify is cleared),I went through the cormens algorithm and implemented it.Now it seems the real fast heap sort.It takes only 0.08 unit,whether in previous it took 37.7 unit time.I have posted this after my code.Would you please edit it so that it can be displayed as a totally different code block?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-24T19:11:28.193",
"Id": "11129",
"Score": "0",
"body": "let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/2069/discussion-between-mindfreak-and-victor-t)"
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-19T15:08:18.470",
"Id": "6987",
"ParentId": "6196",
"Score": "4"
}
},
{
"body": "<p>This is an improved version of the previous code:</p>\n\n<ol>\n<li>The max heapify logic was flawed, which is now fixed. </li>\n<li>This one is modularized, more readable as a recursive function is used.</li>\n</ol>\n\n<p></p>\n\n<pre><code> #include <iostream.h>\n #include <stdlib.h>\n #include <time.h>\n #include <stdlib.h>\n/*This code is written by NF at 241211,algorithm taken from cormens intro to algorithm,This algorithm has clear distinction in between the the max_heapify and build_max_heap function;The previous version had used only a naive approach of build_max_heap at each iteration and was explotingexploiting all the nodes of the heap tree,so it was very slow,having O(n^2)complexity,this code sorts 8483876 reversed elements within 4.4 secs(worst case) */\n\n int swap(int *a, int l, int r)\n { \n int swap_variable=a[l];\n a[l]=a[r];\n a[r]=swap_variable;\n\n return 0;\n }\n\nint left(int i)\n{\n return (2*i)+1; \n}\nint right(int i)\n{\n return (2*i)+2; \n}\n\n int max_heapify(int *array,int i,int length)\n { \n int l=left(i);\n int r=right(i);\n int largest=0;\n\n if((l<length) && (array[l]>array[i]))\n {\n largest=l;\n }\n else\n {\n largest=i;\n }\n if((r<length) && (array[r]>array[largest]))\n {\n largest=r;\n }\n\n if(largest!=i)\n {\n swap(array,i,largest);\n max_heapify(array,largest,length); \n }\n return 0; \n}\n\nint build_max_heap(int *a,int length)\n{\n for(int i=(length/2);i>=0;i--)\n {\n max_heapify(a,i,length);\n }\n return 0; \n }\n\n int heap_sort(int *a,int length)\n { \n build_max_heap(a,length);\n\n for(int i=length-1;i>=1;i--)\n {\n swap(a,0,i);\n length--;\n max_heapify(a,0,length); \n }\n}\n\n\nint main()\n{\n int length = 0;\n cout<<\"Enter Array Length:\";\n cin>>length;\n\n int array[length];\nint count=0;\n\n for(int i=0;i<length;i++)\n {\n array[i]=rand()%100;\n }\n cout<<\"Array filled with random elements..sorting started...:\"<<endl;\n //cout<<\"Before sort:\"<<endl;\n //for(int i=0;i<length;i++)cout<<array[i]<<\" \";\n\n clock_t start = clock();\n heap_sort(array, length);\n cout<<\"Sorting done!..Time elapsed:\"<<((double)clock()-start)/CLOCKS_PER_SEC; \n\n //for(int i=0;i<length;i++)cout<<array[i]<<\" \"; \n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-05-04T18:30:10.617",
"Id": "88801",
"ParentId": "6196",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "6987",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-22T09:33:20.833",
"Id": "6196",
"Score": "7",
"Tags": [
"c++",
"algorithm",
"sorting"
],
"Title": "Heapsort is not modular"
}
|
6196
|
<p>I am trying to validate time entry. <code>ArrTime</code> is the time entered by the user from the UI. I am trying to make it so that when a user attempts to add a time, it must be between 8:45 and 17:30. Is there any thing wrong with my code? I am not very good at JavaScript so I have a feeling it is that, but if you can help me at all I will be very grateful.</p>
<p>Here are all the parts of code that are involved in validation:</p>
<p><strong>JavaScript</strong></p>
<pre><code> timeValid: function () {
var s = $(this).val();
if ($(this).required()) {
var arrTime = new ArrTime(s);
var startTime = new Date(0001, 01, 01, 08, 46, 00, 00);
var endTime = new Date(9999, 12, 366, 17, 30, 00, 00);
if (arrTime > startTime) {
$(this).removeClass("error");
return true;
}
else {
validation.showError("Invalid", $(this).attr("name"));
$(this).addClass("error");
}
if (!isNaN(arrTime)) {
if (arrTime >= ArrTime.parse(new ArrTime().toTimeString())) {
$(this).removeClass("error");
return true;
}
else {
validation.showError("Invalid", $(this).attr("name"));
$(this).addClass("error");
return false;
}
}
else {
validation.showError("Required", $(this).attr("name"));
$(this).addClass("error");
return false;
}
}
else return false;
},
</code></pre>
<p><strong>JavaScript</strong></p>
<pre><code>var deferrend = $.Deferred();
if (new Date(dateTo) > new Date()) {
deferrend = confirmation.ask("Are you sure you want to add a future absence?");
} else {
deferrend.resolveWith(true);
}
if (new Date(arrTime) > new Date()) {
deferrend = confirmation.ask("Are you sure this is the correct time for being late?");
}
else {
deferrend.resolveWith(true);
}
</code></pre>
<p><strong>C#</strong></p>
<pre><code>public static bool IsValidTime(this string s, out string error)
{
error = String.Empty;
if (s.Required())
{
TimeSpan outTime;
TimeSpan startTime = new TimeSpan(8, 46, 0);
TimeSpan endTime = new TimeSpan(17, 30, 0);
if (TimeSpan.TryParse(s, out outTime))
if (outTime >= startTime && outTime <= endTime)
return true;
else
{
error = "Invalid";
return false;
}
}
else
{
error = "Required";
return false;
}
return false;
}
}
</code></pre>
<p><strong>JavaScript</strong></p>
<pre><code> if (new Date(arrTime) > new Date()) {
deferrend = confirmation.ask("Are you sure this is the correct time for being late?");
}
else {
deferrend.resolveWith(true);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-23T12:28:12.520",
"Id": "9649",
"Score": "0",
"body": "You can remove every 'return false;' and only put it at the end of each method. You could also extract the error message operations to one single method, with the message as parameter."
}
] |
[
{
"body": "<p>I would refactor conceptually and introduce a reusable <code>TimeRange</code> object with methods to check for inclusion:</p>\n\n<pre><code>class TimeRange : Range<DateTime>{\n\n bool Includes(DateTime other){...}\n bool Includes(TimeRange other){...}\n bool Includes(string other){...}\n\n}\n</code></pre>\n\n<p>In this case, if <code>Includes</code> returns false, you have a validation error.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-24T13:55:55.327",
"Id": "6253",
"ParentId": "6202",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-22T15:26:13.360",
"Id": "6202",
"Score": "2",
"Tags": [
"c#",
"javascript",
"datetime",
"validation"
],
"Title": "Validation of Time"
}
|
6202
|
<p>Fiddle: <a href="http://jsfiddle.net/fhBd5/" rel="nofollow">http://jsfiddle.net/fhBd5/</a></p>
<p>So the above is working but I'm having trouble trying to come up with a clean and concise way to do some type of loop on the if or statements. </p>
<p>Any help is very much appreciated! </p>
<pre><code>var checkPositionOnLoad = function (e) {
var currentPos = 0;
var listItem = document.getElement('li.current');
var currentSelected = $('list').getChildren('li').indexOf(listItem) + 1;
if (currentSelected <= 3) {
return false;
}
if(currentSelected==4||currentSelected==5||currentSelected==6){
currentPos = -300 * 1;
$('list').setStyle('left', currentPos);
}
else if(currentSelected== 7||currentSelected==8||currentSelected==9){
currentPos = -300 * 2;
$('list').setStyle('left', currentPos);
}
else if(currentSelected==10||currentSelected==11||currentSelected==12){
currentPos = -300 * 3;
$('list').setStyle('left', currentPos);
}
else if(currentSelected==13||currentSelected==14||currentSelected==15){
currentPos = -300 * 4;
$('list').setStyle('left', currentPos);
};
};
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-22T17:07:48.300",
"Id": "9626",
"Score": "0",
"body": "Please post code into question. We can grantee that http://jsfiddle.net will be available in the future and thus the question may becomes meaningless for other people when reading it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-22T18:10:22.637",
"Id": "9627",
"Score": "0",
"body": "@LokiAstari not a problem!"
}
] |
[
{
"body": "<p>Here is my slightly \"mathematical\" version of the function you have posted:</p>\n\n<pre><code>var checkPositionOnLoad = function (e) {\n var currentPos = 0;\n var listItem = document.getElement('li.current');\n var currentSelected = $('list').getChildren('li').indexOf(listItem) + 1;\n\n currentPos = -300 * (Math.floor((currentSelected + 2) / 3) - 1);\n\n $('list').setStyle('left', currentPos);\n};\n</code></pre>\n\n<p>I will try to explain how I got to that succinct version.</p>\n\n<p>I removed the duplication and wrote the function as follows:</p>\n\n<pre><code>var checkPositionOnLoad = function (e) {\n var currentPos = 0;\n var listItem = document.getElement('li.current');\n var currentSelected = $('list').getChildren('li').indexOf(listItem) + 1;\n\n if (currentSelected <= 3) {\n currentPos = -300 * 0;\n }\n if (currentSelected == 4 || currentSelected == 5 || currentSelected == 6) {\n currentPos = -300 * 1;\n }\n else if (currentSelected == 7 || currentSelected == 8 || currentSelected == 9) {\n currentPos = -300 * 2;\n }\n else if (currentSelected == 10 || currentSelected == 11 || currentSelected == 12) {\n currentPos = -300 * 3;\n }\n else if (currentSelected == 13 || currentSelected == 14 || currentSelected == 15) {\n currentPos = -300 * 4;\n };\n\n $('list').setStyle('left', currentPos);\n};\n</code></pre>\n\n<p>Then I realized you want to figure where a given selected element falls (in which group of triplets that is {1, 2, 3} {4, 5, 6}, etc..). I played around and came up with a mathematical formula:</p>\n\n<pre><code>Math.floor((i + 2) / 3) \n</code></pre>\n\n<p>This basically tells you that for i = 7, the selected element falls in the third group <code>{7, 8, 9}</code> which is the third triplet after <code>{1, 2, 3}</code> and <code>{4, 5, 6}</code></p>\n\n<p>And the <code>left</code> property can be set using:</p>\n\n<pre><code>var currentPos = -300 * (Math.floor((i + 2) / 3) - 1); // (-1 to make it zero-based index)\n</code></pre>\n\n<p>And that's it.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-22T18:24:17.850",
"Id": "6209",
"ParentId": "6205",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "6209",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-22T16:29:15.663",
"Id": "6205",
"Score": "1",
"Tags": [
"javascript",
"jquery",
"mootools"
],
"Title": "Clean up If or syntax in JavaScript"
}
|
6205
|
<p>I am a Scala newbie and attempting to improve my skills. I have decided to be playful about it and work to do a conversion of the spaceinvaders game supplied with the LWJGL. It consists of 10 Java classes of which I have loaded, compiled and successfully ran from Eclipse.</p>
<p>My first Scala step is to replace the Sprite.java class with a SpriteNew.scala class. I have completed the first pass (see below). However, I have several questions:</p>
<ol>
<li>How do I make class SpriteNew only have instances created by Object
SpriteNew.create? In Java, I would just make the constructor
private. Since I cannot do that, I am wondering if I am missing how
I must approach a problem like this different than how I do so with Java. </li>
<li>In Object SpriteNew, I don't
like how I used a var to temporarily define a field so that I can
reference/return it in the final line of the load method. Are there
any better ways to write this method keeping the intention of
isolating the Java/null-ness/Exception-ness?</li>
</ol>
<p>Any feedback, coaching, guidance, suggestions you can give me on this would be greatly appreciated.</p>
<p>For brevity, I have stripped the comments out of the original Sprite.java class (go <a href="http://lwjgl.org/wiki/index.php?title=Examples%3aSpaceInvaders_Sprite" rel="nofollow">here</a> if you would like to see the original unmodified source for Sprite.java):</p>
<pre><code>package org.lwjgl.examples.spaceinvaders;
import java.io.IOException;
import static org.lwjgl.opengl.GL11.*;
public class Sprite {
private Texture texture;
private int width;
private int height;
public Sprite(TextureLoader loader, String ref) {
try {
texture = loader.getTexture(ref);
width = texture.getImageWidth();
height = texture.getImageHeight();
} catch (IOException ioe) {
ioe.printStackTrace();
System.exit(-1);
}
}
public int getWidth() {
return texture.getImageWidth();
}
public int getHeight() {
return texture.getImageHeight();
}
public void draw(int x, int y) {
glPushMatrix();
texture.bind();
glTranslatef(x, y, 0);
glBegin(GL_QUADS);
{
glTexCoord2f(0, 0);
glVertex2f(0, 0);
glTexCoord2f(0, texture.getHeight());
glVertex2f(0, height);
glTexCoord2f(texture.getWidth(), texture.getHeight());
glVertex2f(width, height);
glTexCoord2f(texture.getWidth(), 0);
glVertex2f(width, 0);
}
glEnd();
glPopMatrix();
}
}
</code></pre>
<p>And here is my first pass at the Scala version as a Factory (using both object and class):</p>
<pre><code>package org.lwjgl.examples.spaceinvaders
import java.io.IOException
import org.lwjgl.opengl.GL11._
object SpriteNew {
def create (textureLoader: TextureLoader, resourceName: String): SpriteNew = {
def load: Texture = {
var texture: Texture = null
try {
texture = textureLoader.getTexture(resourceName)
}
catch
{
case ioe: IOException => {
println(ioe.getStackTraceString)
System.exit(-1)
}
}
texture
}
val texture = load
new SpriteNew(texture)
}
}
class SpriteNew (val texture: Texture) {
val width = texture.getImageWidth()
val height = texture.getImageHeight()
def draw(x: Int, y: Int) {
glPushMatrix
texture.bind()
glTranslatef(x, y, 0)
glBegin(GL_QUADS)
glTexCoord2f(0, 0)
glVertex2f(0, 0)
glTexCoord2f(0, texture.getHeight())
glVertex2f(0, height)
glTexCoord2f(texture.getWidth(), texture.getHeight())
glVertex2f(width, height);
glTexCoord2f(texture.getWidth(), 0)
glVertex2f(width, 0)
glEnd
glPopMatrix
}
}
</code></pre>
<p><strong>Update (2011/Nov/22 - 15:00 CDT):</strong></p>
<p>I am incorrect in question 1 about not being able to make the constructor private. Placing the keyword "private" after the Scala class name and before the constructor parameter list allows the class to remain public while the constructor become private. In other words, snippet above "class SpriteNew (val texture: Texture) {" would be altered to become "class SpriteNew <strong>private</strong> (val texture: Texture) {"</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-07-28T17:42:10.660",
"Id": "180248",
"Score": "0",
"body": "I have made huge progress with Scala since I initially posted this. To see an even more effective way to isolate the new operator and to easily implement case class instance caching, have a look at this answer I posted: http://codereview.stackexchange.com/a/98367/4758"
}
] |
[
{
"body": "<p>Question 1: You answered it yourself.</p>\n\n<p>Question 2: <code>try</code> / <code>catch</code> in Scala is an expression. Also, <code>sys.exit</code> is of type <code>Nothing</code>, which is the bottom type, a sub-type of every other type, hence it will not throw off the type inference. So your <code>create</code> method can be</p>\n\n<pre><code> def create (textureLoader: TextureLoader, resourceName: String) = new SpriteNew (\n try textureLoader.getTexture(resourceName)\n catch { case ioe: IOException => \n println(ioe.getStackTraceString)\n sys.exit(-1)\n } \n )\n</code></pre>\n\n<p>It would also be more usual to use <code>apply</code> for the creation method name (instead of <code>create</code>), so that you can make a new instance with <code>SpriteNew(a, b)</code>.</p>\n\n<p>I like to avoid wasted vertical space in my layout. It's not great if you're paid by lines of code written, but IMO it's much easier to see what's going on if the code isn't all spread out, and you can fit more on the page so you don't have scroll back and forth.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-27T01:22:03.660",
"Id": "9813",
"Score": "0",
"body": "Awesome! Tysvm for your response. It's so obvious, now that you have written it. And I so didn't see it when I was working with the problem."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-27T04:10:47.807",
"Id": "9820",
"Score": "1",
"body": "@chaotic3quilibrium You're welcome. Re-throwing the exception looked a bit strange so I thought \"wouldn't it be good if `System.exit` were of type `Nothing`\". A quick look at the documentation reveals that indeed the Scala version, `sys.exit` is! So I've updated the answer."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-24T04:12:21.393",
"Id": "6245",
"ParentId": "6208",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "6245",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-22T18:20:56.303",
"Id": "6208",
"Score": "1",
"Tags": [
"scala",
"exception"
],
"Title": "Simple factory pattern in scala (attempting to restrict use of new)"
}
|
6208
|
<p>I was hoping someone could provide some feedback with regards to this:</p>
<pre><code>import java.util.InputMismatchException;
import java.util.Scanner;
public class Bank {
protected double myBalance = 10.40;
protected double bankBalance = 1000000;
protected double creditRating = 0.1;
private static final int PIN = 1234;
boolean access = false;
protected Scanner s = new Scanner(System.in);
public Bank() {
int pin = 0000;
int option;
System.out.print("Please enter your 4 digit pin code: ");
try {
pin = s.nextInt();
} catch (InputMismatchException e) {
System.out.print("Invalid character entered, bye bye...");
}
if (pin != PIN) {
System.err.println("Incorrect PIN entered, please try again later.");
System.exit(0);
}
access = true;
System.out.println("Welcome to JCBank please choose from the following options");
System.out.println();
System.out.println("Withdraw (1)\tDeposit (2)\tCheck Balance (3)\tApply for Loan(4) \tQuit (5)");
System.out.println();
do {
option = s.nextInt();
} while(!selectOption(option));
}
public boolean selectOption(int option) {
switch (option) {
case 1:
System.out.println("You would like to withdraw");
System.out.println();
break;
case 2:
System.out.println("You would like to Deposit");
System.out.println();
break;
case 3:
System.out.println("Your account balance is £" + myBalance);
System.out.println();
break;
case 4:
System.out.println("Please wait whilst we perform a credit check.");
try {
checkCreditRating();
} catch (InterruptedException e) {
System.out.println("How embarrassing, the system is currently unavailable. Try again later.");
}
System.out.println();
break;
case 5:
System.out.println("Successfully logged out, see you soon!");
System.out.println();
return true;
default:
System.out.println("Invalid option, please choose another option.");
System.out.println();
return false;
}
System.out.println("Please choose another option.");
return false;
}
public void deposit(double amount) {
myBalance += amount;
}
public void withdraw(double amount) {
if (myBalance > amount) {
System.out.println("Your funds have been successfully withdrawn.");
} else {
System.out.println("You don't have the funds to complete this transaction");
}
}
public void checkCreditRating() throws InterruptedException {
Thread.sleep(1000);
if (creditRating <= 0.0) {
System.err.println("Sorry, we can't lend you any money at this time.");
return;
}
System.out.print("Please enter your loan amount: ");
double amount = s.nextDouble();
if (amount > bankBalance) {
System.err.println("We are unable to loan you such an amount.");
}
double amountToPayBack = (20/100)*amount;
System.out.println("The amount to payback is " + amountToPayBack);
}
public double checkAccountBalance() {
return myBalance;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-22T19:48:01.940",
"Id": "9632",
"Score": "0",
"body": "BTW, you can format stuff as source code by adding four spaces of indentation."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-22T20:00:16.893",
"Id": "9633",
"Score": "0",
"body": "First your stackexchange code formatting is a little messed up as the first part of the code is not formatted. There's room for a ton of improvement. A couple things: Your code is tightly coupled to the UI, ideally you want to decouple it so you could easily switch between a console app, a windowed GUI, or a GUI-less app used in scripting. 2. Don't do work in the constructor like that, make a separate method. 3. Don't try to put everything into one class like you are here. I know this is just a test but a \"real\" java class would have way more classes."
}
] |
[
{
"body": "<p>A number of points:</p>\n\n<ul>\n<li>Do not use floating-point data types (<code>float</code> or <code>double</code>) for amounts of money. Floating-point data types have limited precision, they cannot represent all decimal values exactly, and you're going to get roundoff errors sooner or later. Use integers instead (<code>int</code> or <code>long</code>) and store cents instead (for example, 1040 cents) or use <code>BigDecimal</code>.</li>\n<li>Make member variables <code>private</code> by default; only make them <code>protected</code> (or another access level) if there is a good reason to do so.</li>\n<li>Prefer local variables above member variables. Is there a good reason why <code>s</code> is a member variable instead of a local variable?</li>\n<li>Don't write the main part of a program in the constructor of a class. You have the main part of your program in the constructor of the <code>Bank</code> class. The constructor is meant to initialize the state of a new object, so the only thing that the constructor should do is initialize member variables.</li>\n<li>In your constructor, you catch an <code>InputMismatchException</code> and print an error message (\"bye bye...\") but you are not actually returning from the constructor. So execution will continue and print \"Incorrect PIN entered ...\" which is not what you meant.</li>\n<li>The program doesn't actually do what you'd expect it to do; withdrawal, deposit etc. functionality never gets called anywhere.</li>\n<li>You need a <code>public static void main(String[] args)</code> method to be able to run this as a stand-alone program.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-22T20:11:15.170",
"Id": "9634",
"Score": "0",
"body": "Thank you both very much some good feedback, really appreciated !!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-23T00:32:17.547",
"Id": "9639",
"Score": "1",
"body": "In vein about floating point precision (or lack thereof), the amount `.1` cannot be accurately represented. In other words, you can't add _exactly_ one dime (say, of interest) to an account. It might be _close_ (especially with doubles), but it _will_ add up over time."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-22T19:56:00.223",
"Id": "6211",
"ParentId": "6210",
"Score": "16"
}
},
{
"body": "<p>I would say instead of:</p>\n\n<pre><code>if (pin != PIN) {\n System.err.println(\"Incorrect PIN entered, please try again later.\");\n System.exit(0);\n }\n access = true;\n</code></pre>\n\n<p>use :</p>\n\n<pre><code>if(pin == PIN){\n access = true;\n System.out.println(\"Welcome to JCBank please choose from the following options\");\n System.out.println();\n System.out.println(\"Withdraw (1)\\tDeposit (2)\\tCheck Balance (3)\\tApply for Loan(4) \\tQuit (5)\");\n System.out.println();\n}\nelse{\n System.err.println(\"Incorrect PIN entered, please try again later.\");\n System.exit(0);\n}\n</code></pre>\n\n<p>its much more readable I guess.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-23T07:39:32.557",
"Id": "9647",
"Score": "0",
"body": "That's not good. You have an unneccessary conditional in your code. Why not just `access |= pin == PIN; if (access) ...`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-23T10:18:39.350",
"Id": "9648",
"Score": "3",
"body": "Why not just `pin == PIN`...it's not like `access` is used somewhere else anymore."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-23T21:08:18.747",
"Id": "9678",
"Score": "0",
"body": "I assumed he would use `access` later in the development of his code. If not,you could also delete the variable access."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-23T01:22:52.707",
"Id": "6216",
"ParentId": "6210",
"Score": "3"
}
},
{
"body": "<p>Jesper has already made comments on the code itself, so I will address your organization. You only have one big class that does everything, and it does things in many areas. For instance, your class handles customers, accounts, and security. You should split these out into separate classes. Perhaps <code>Bank</code> would be your top level class, with the <code>main</code> method. Then you would have an <code>Account</code> class, with the <code>withdraw</code>, <code>deposit</code>, and <code>checkBalance</code> methods, a <code>Customer</code> class with a list of accounts that customer has as well as methods for checking their credit rating, etc.</p>\n\n<p>Security - your model is weak, but obviously this is an exercise so let's keep it simple (and I'm no security expert either!). I'd create a file with the credentials for each customer, and have a class used for authenticating the user before you do anything, say <code>Authenticator</code>.</p>\n\n<pre><code>Authenticator auth = new Authenticator();\nCustomer cust = null;\n\nwhile (cust == null) {\n System.out.println(\"Username: \");\n String username = s.nextLine();\n System.out.println(\"PIN: \");\n int pin = s.nextInt();\n\n cust = auth.authenticateCredentials(username, pin);\n}\n</code></pre>\n\n<p>The <code>authenticateCredentials()</code> method would return null if the credentials provided did not match any on record. If a match was found, it would return the customer records that match the login credentials. </p>\n\n<p>Obviously I'm leaving a lot out, like how to save the customer and login information, and organizing the relationship between customers and accounts. I'd recommend that you take a peek at the <code>ArrayList</code> class for keeping lists of accounts. You've got a good start here, with a lot you can do to improve and add new features. Have fun on the new project!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-23T20:08:53.453",
"Id": "6238",
"ParentId": "6210",
"Score": "10"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-22T19:29:35.800",
"Id": "6210",
"Score": "12",
"Tags": [
"java",
"beginner",
"finance"
],
"Title": "Bank transaction system"
}
|
6210
|
<p>Should I be using <code>this</code> more, instead of <code>slider</code>? Am I making any serious no-no's here, and is there a better design I should implement? I'm up for any pointers :)</p>
<pre><code>slider = {
selector : '#slider',
init : function() {
$('#slider').hover(function(e){
slider.toggle();
});
$(document).bind('click', function(e){
slider.lock.unlock();
slider.state.collapse();
});
$('#slider').bind('click', function(e){
e.stopPropagation();
slider.lock.lock();
})
},
toggle : function() {
if (!this.lock.isLocked) {
this.state.toggle();
}
},
lock : {
isLocked : false,
lock : function() {
this.isLocked = true;
},
unlock : function() {
this.isLocked = false;
}
},
state : {
isExtended : false,
toggle : function() {
if (this.isExtended===true) {
this.collapse();
} else {
this.extend();
}
},
extend : function() {
this.isExtended = true;
$('#slider').stop().animate({'left':'-5px'}, 'slow');
},
collapse : function() {
this.isExtended = false;
$('#slider').stop().animate({'left':'-210px'}, 'slow');
}
}
};
</code></pre>
|
[] |
[
{
"body": "<ol>\n<li><p><strong>You never use <code>slider.selector</code></strong>, so what's the point?</p></li>\n<li><p><strong>jQuery instances should be \"cached\"</strong>, otherwise you are creating new jQuery object each time you call <code>$()</code> function.</p></li>\n<li><p><strong>This code permits only one slider per page</strong>. What if you need more? Will you copy-paste the whole thing?</p></li>\n<li><p><strong>This is not configurable</strong> at all. You have to change the objects source, just to change the way animation works.</p></li>\n<li><p><strong>jQuery is not really necessary here</strong>. You actually need it only for animations, which is not jQuery's strong point.</p></li>\n<li><strong>Slider object ends up in global scope.</strong></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-22T21:16:35.067",
"Id": "6214",
"ParentId": "6213",
"Score": "7"
}
},
{
"body": "<p>All your <code>slider</code> calls are inside the jQuery callbacks, so they use their own context. For example, in this callback:</p>\n\n<pre><code>$('#slider').hover(function(e){\n slider.toggle();\n});\n</code></pre>\n\n<p><code>this</code> would refer to the #slider DOM element, not your slider object. </p>\n\n<p>At the jQuery help page they suggest a <a href=\"http://learn.jquery.com/code-organization/concepts/#the-module-pattern\" rel=\"nofollow\">basic Module pattern</a> that would help you a lot designing your plugin slider.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-22T14:29:50.740",
"Id": "57684",
"ParentId": "6213",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "6214",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-22T20:52:08.333",
"Id": "6213",
"Score": "5",
"Tags": [
"javascript",
"jquery"
],
"Title": "Quality of custom slider"
}
|
6213
|
<p>I wrote a small class that demonstrates my problem:</p>
<pre><code>class Root
{
private Leaf RootLeaf;
private Dictionary<object, Leaf> AllItems = new Dictionary<object, Leaf>(); //dictionary contains a reference to each item, and the leaf it is assigned to (its parent)
public Root()
{
RootLeaf = new Leaf();
}
public List<object> GetAllChildren
{
get { return RootLeaf.getAllChildren; }
}
public void Add(object o)
{
Leaf AddedTo = RootLeaf.Add(o);
AllItems.Add(o, AddedTo); //Add object reference to AllItems dictionary
}
private IEnumerable<object> GetNeighbors(object obj)
{
foreach (object o in this.AllItems[obj].getAllChildren)
{
if (obj != o)
yield return o;
}
}
public void Update()
{
foreach (KeyValuePair<object, Leaf> i in AllItems)
{
foreach (object b in this.GetNeighbors(i.Key))
{
//Would do collision checks here
}
}
}
}
class Leaf
{
private const int MaxChildCount = 1;
private List<object> Children = new List<object>();
private Leaf[] ChildLeaves = null;
private bool _LeavesGenerated = false; //Have the leaves been created? (Low Level, do not touch)
private bool HasLeaves = false; //Should we use the leaves?
protected void CreateLeaves()
{
if (!_LeavesGenerated)
{
//create each of the four leaves
for (int i = 0; i < 4; i++)
ChildLeaves[i] = new Leaf();
_LeavesGenerated = true;
}
HasLeaves = true;
}
protected void RemoveLeaves()
{
HasLeaves = false;
}
/// <summary>
/// Returns children of this leaf, and all of its subleaves
/// </summary>
public List<object> getAllChildren
{
get
{
List<object> outp = Children.ToList();
if (HasLeaves)
{
foreach (Leaf l in ChildLeaves)
outp.AddRange(l.getAllChildren);
}
return outp;
}
}
/// <summary>
/// Get count of all children in this leaf, and its subleaves
/// </summary>
public int getChildCount
{
get
{
int outp = Children.Count;
if (HasLeaves)
{
foreach (Leaf l in ChildLeaves)
outp += l.getChildCount;
}
return outp;
}
}
static Random rand = new Random();
/// <summary>
///
/// </summary>
/// <param name="o">The object to be added</param>
/// <returns>The leaf the object was added to</returns>
public Leaf Add(object o)
{
if (Children.Count >= MaxChildCount)
{
//Pick random subleaf, I know this isn't correct for a quadtree, but it will simplify this explanation code
if (!HasLeaves)
CreateLeaves();
return ChildLeaves[rand.Next(0, 3)].Add(o);
}
else
{
Children.Add(o);
return this;
}
}
}
</code></pre>
<p>I ran this through the ANTS profiler, and it not surprisingly pulled the <code>Leaf.getAllChildren</code> and <code>Leaf.getChildCount</code> as the two most expensive operations. I'm ok with how everything thing else is laid out. My question is: how could I optimize the two aforementioned properties? </p>
<p>The properties are called when the <code>Root.Update()</code> function is run.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-23T03:00:09.023",
"Id": "9643",
"Score": "0",
"body": "What is your test program that uses these classes that you're using to profile?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-23T05:19:11.980",
"Id": "9645",
"Score": "0",
"body": "I can post it if you feel it's relevent, but it's some 300+ lines, and after optimizing most of it, the profiler pointed out the lines that called the above properties (and the call count can't be reduced) as taking up 30% of the execution time. I'll see if I can trim it down to the important bits."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-23T05:25:21.047",
"Id": "9646",
"Score": "0",
"body": "Update, I've added what I think you were referring to, was that what you were talking about?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-23T14:47:37.490",
"Id": "9650",
"Score": "0",
"body": "I don't think so? I'm looking for perhaps a `Main()` method which creates these objects and calls their methods."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-23T20:36:58.150",
"Id": "9673",
"Score": "0",
"body": "Oh, they are very simple functions, the first is on form.load and adds new objects, and the second runs on a every 1000/60 millisecs. I can also add that if you wish"
}
] |
[
{
"body": "<p>What I saw when quickly looking at it:</p>\n\n<p>Naming convetion: Some of your Properties and variables are lowerCamelCase, some are UpperCamelCase, some of your variables have a leading underscore, some don't. Some <code>objects</code> are called <code>o</code>, some <code>obj</code>.</p>\n\n<p>Here are <a href=\"http://msdn.microsoft.com/en-us/library/x2dbyw72%28v=vs.71%29.aspx\" rel=\"nofollow\">the basic naming conventions proposed for C#</a>:</p>\n\n<ul>\n<li>Variables are lowerCamelCase: <code>myVariable</code></li>\n<li>Properties are UpperCamelCase: <code>MyProperty</code></li>\n<li>Methods and Functions are UpperCamelCase: <code>MyFunction</code></li>\n</ul>\n\n<p>Stick to those, and don't confuse them with the Java conventions, they're quite different.</p>\n\n<hr>\n\n<pre><code>private Dictionary<object, Leaf> AllItems = new Dictionary<object, Leaf>(); //dictionary contains a reference... ... ...\n</code></pre>\n\n<p>We've got some cool documentation features available, make that information easily accessible:</p>\n\n<pre><code>/// <summary>\n/// Contains a reference to each item, and the leaf it is assigned to (its parent).\n/// </summary>\nprivate Dictionary<object, Leaf> AllItems = new Dictionary<object, Leaf>();\n</code></pre>\n\n<hr>\n\n<p>Organize your classes better, what does that lone static Random do there between the <code>Add</code> and <code>getChildCount</code> functions?</p>\n\n<pre><code>static Random rand = new Random();\n</code></pre>\n\n<hr>\n\n<p>You never initialize the <code>ChildLeaves</code> variable as far as I can see.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-23T20:34:50.457",
"Id": "9672",
"Score": "0",
"body": "Thanks for the case information, I do need to follow that more closely. As for the underscore, I use it when I feel it is a low level type of function/variable, and it should never be called straight out, though that probably isn't the best way todo it..."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-23T11:31:05.713",
"Id": "6218",
"ParentId": "6217",
"Score": "1"
}
},
{
"body": "<p>All right, I've done a bit of work here (a good most of it stylistic, to be sure). Do note I replaced <code>object</code> with a generic implementation to help avoid boxing of value types. It does also employ LINQ in a couple instances to remove some complexity. When I run it and generate 1,000,000 integer leaves, I find that the bulk of the time is taken in the class constructors and the methods themselves are close enough to 0 time to be considered 0. Hope this helps:</p>\n\n<pre><code>internal sealed class Root<T>\n{\n private readonly Leaf<T> rootLeaf = new Leaf<T>();\n\n // dictionary contains a reference to each item, and the leaf it is assigned to (its parent)\n private readonly IDictionary<T, Leaf<T>> allItems = new Dictionary<T, Leaf<T>>();\n\n /// <summary>\n /// Gets GetAllChildren.\n /// </summary>\n public IList<T> GetAllChildren\n {\n get\n {\n return this.rootLeaf.GetAllChildren;\n }\n }\n\n public void Add(T o)\n {\n var addedTo = this.rootLeaf.Add(o);\n\n this.allItems.Add(o, addedTo); // Add object reference to AllItems dictionary\n }\n\n public void Update()\n {\n foreach (var i in from i in this.allItems from b in this.GetNeighbors(i.Key) select i)\n {\n // Would do collision checks here\n }\n }\n\n private IEnumerable<T> GetNeighbors(T obj)\n {\n return this.allItems[obj].GetAllChildren.Where(o => ReferenceEquals(obj, o));\n }\n}\n\ninternal class Leaf<T>\n{\n private const int MaxChildCount = 1;\n\n private static readonly Random rand = new Random();\n\n private readonly IList<T> children = new List<T>();\n\n private List<Leaf<T>> childLeaves;\n\n private bool hasLeaves; // Should we use the leaves?\n\n private bool leavesGenerated; // Have the leaves been created? (Low Level, do not touch)\n\n /// <summary>\n /// Returns children of this leaf, and all of its subleaves\n /// </summary>\n public IList<T> GetAllChildren\n {\n get\n {\n var allChildren = this.children.ToList();\n\n if (this.hasLeaves)\n {\n this.childLeaves.ToList().ForEach(l => allChildren.AddRange(l.GetAllChildren));\n }\n\n return allChildren;\n }\n }\n\n /// <summary>\n /// Get count of all children in this leaf, and its subleaves\n /// </summary>\n public int GetChildCount\n {\n get\n {\n var allChildrenCount = this.children.Count;\n\n if (this.hasLeaves)\n {\n allChildrenCount += this.childLeaves.Sum(l => l.GetChildCount);\n }\n\n return allChildrenCount;\n }\n }\n\n /// <summary>\n /// \n /// </summary>\n /// <param name=\"o\">The object to be added</param>\n /// <returns>The leaf the object was added to</returns>\n public Leaf<T> Add(T o)\n {\n if (this.children.Count < MaxChildCount)\n {\n this.children.Add(o);\n return this;\n }\n\n // Pick random subleaf, I know this isn't correct for a quadtree, but it will simplify this explanation code\n if (!this.hasLeaves)\n {\n this.CreateLeaves();\n }\n\n return this.childLeaves[rand.Next(0, 3)].Add(o);\n }\n\n protected void CreateLeaves()\n {\n if (!this.leavesGenerated)\n {\n // create each of the four leaves\n this.childLeaves = new List<Leaf<T>> { new Leaf<T>(), new Leaf<T>(), new Leaf<T>(), new Leaf<T>() };\n\n this.leavesGenerated = true;\n }\n\n this.hasLeaves = true;\n }\n\n protected void RemoveLeaves()\n {\n this.hasLeaves = false;\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-23T16:20:35.497",
"Id": "9659",
"Score": "0",
"body": "Nice work. Only one thing, can `outp` get a better name?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-23T16:30:17.537",
"Id": "9661",
"Score": "2",
"body": "I don't see why not."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-23T21:27:00.297",
"Id": "9679",
"Score": "0",
"body": "One question I can't seem to figure out: How would I select both items in the collision foreach loop? If I wanted to do something like : `if (Rect1.Intersects(Rect2))` where Rect1 was the first object, and Rect2 was its neighbor? With the nested foreach loops it was simple, take the outer variable, and the inner variable; I'm not sure how to do it with your LINQ though"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-23T21:40:28.320",
"Id": "9680",
"Score": "0",
"body": "Also, would it be better to loop through each child every time I need that information, or should I store it in each leaf (like I do in the Root class), and just update it whenever a child changes leaves?"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-23T15:11:00.773",
"Id": "6220",
"ParentId": "6217",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "6220",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-23T02:00:42.160",
"Id": "6217",
"Score": "5",
"Tags": [
"c#",
"recursion"
],
"Title": "Optimize Recursive Fetching of information?"
}
|
6217
|
<p>This is a pattern in SQL queries that I've found myself repeating recently:</p>
<pre><code>SELECT
w,
x,
y,
(w + x) / y as z
FROM
(SELECT
<some gigantic and complicated query> as w,
a + b as x,
a - b as y
FROM
basetable) somealias;
</code></pre>
<hr>
<p>The issue is:</p>
<ul>
<li>a select query that does some complex operations, resulting in a column with a new name</li>
<li>directly reusing the "new" column doesn't work in MySQL (unsure about other RDBMS's)</li>
</ul>
<p>This code fails:</p>
<pre><code>SELECT
<some gigantic and complicated query> as w,
a + b as x,
a - b as y,
(w + x) / y as z
FROM
basetable;
</code></pre>
<p>Because MySQL doesn't allow column aliases (<code>x</code> and <code>y</code>) to be re-used in the same select query.</p>
<hr>
<p>The solution I'm using:</p>
<ul>
<li>wrap the select in a subquery</li>
<li>this renames the columns</li>
<li>use the new column names from the outer query</li>
</ul>
<p>I'm unsure whether it's a best practice, or a common practice, and thus easily understandable for other programmers.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-23T15:29:57.363",
"Id": "9652",
"Score": "0",
"body": "Why not just `SELECT (a+b) / (a-b) AS z FROM basetable`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-23T15:36:26.517",
"Id": "9653",
"Score": "0",
"body": "@Kevin -- I've updated the question to also select `x` and `y` in the outer query. Hopefully that clarifies the problem."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-23T15:40:00.167",
"Id": "9654",
"Score": "0",
"body": "Ok. So am I reading your problem correctly, that you have to alias `x`, `y`, and `z`? That you can't add, say, `ORDER BY z`? (or `ORDER BY x` if you don't use the subquery?) I believe you can `ORDER BY a+b`, if that's what you want."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-23T15:47:21.597",
"Id": "9655",
"Score": "0",
"body": "@Kevin -- I've added the \"desired\" code, which fails."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-23T15:59:48.597",
"Id": "9656",
"Score": "0",
"body": "Change `x / y` to `(a+b)/(a-b)` in the column spec. The alias can't be used there, but (from the [MySQL docs](http://dev.mysql.com/doc/refman/5.5/en/select.html)) it \"can be used in GROUP BY, ORDER BY, or HAVING clauses.\" Is the problem that `a+b` are actually more long/complex? In that case you could [define a function](http://dev.mysql.com/doc/refman/5.1/en/create-function.html)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-23T16:04:43.727",
"Id": "9658",
"Score": "0",
"body": "@Kevin -- yes, the problem is that the expressions for `x` and `y` could be arbitrarily complex, or even be subqueries. I know there are other ways to solve this problem, I'm just trying to get a feel for how much of an anti-pattern this is."
}
] |
[
{
"body": "<p>As long as the variables are well-named, I think your way (subquery) will be clear and therefore quite acceptable, though I'm not quite sure whether it will affect performance or to what extent (try benchmarking).</p>\n\n<p>That said, I'd still urge you to use a <a href=\"http://dev.mysql.com/doc/refman/4.1/en/sql-syntax-prepared-statements.html\" rel=\"nofollow\">prepared query</a> or <a href=\"http://dev.mysql.com/doc/refman/5.5/en/stored-routines-syntax.html\" rel=\"nofollow\">stored procedure or function</a>, I think that would make it even more clear, and potentially faster.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-23T16:26:56.863",
"Id": "6226",
"ParentId": "6221",
"Score": "3"
}
},
{
"body": "<p>I think your practice is fine. Here are the two queries and their explain results:</p>\n\n<pre><code>explain extended SELECT\n w,\n x,\n y,\n (w + x) / y as z\nFROM\n (SELECT \n (SELECT SUM(s) FROM test2) as w,\n a + b as x,\n a - b as y\n FROM\n test) somealias;\n</code></pre>\n\n\n\n<pre><code>+----+-------------+------------+------+---------------+------+---------+------+------+----------+-------+\n| id | select_type | table | type | possible_keys | key | key_len | ref | rows | filtered | Extra |\n+----+-------------+------------+------+---------------+------+---------+------+------+----------+-------+\n| 1 | PRIMARY | <derived2> | ALL | NULL | NULL | NULL | NULL | 3 | 100.00 | |\n| 2 | DERIVED | test | ALL | NULL | NULL | NULL | NULL | 3 | 100.00 | |\n| 3 | SUBQUERY | test2 | ALL | NULL | NULL | NULL | NULL | 3 | 100.00 | |\n+----+-------------+------------+------+---------------+------+---------+------+------+----------+-------+\n</code></pre>\n\n\n\n<pre><code>explain extended SELECT \n (SELECT SUM(s) FROM test2) as w,\n a + b as x,\n a - b as y,\n ((SELECT SUM(s) FROM test2) + (a + b)) / (a -b) as z\n FROM\n test\n</code></pre>\n\n\n\n<pre><code>+----+-------------+-------+------+---------------+------+---------+------+------+----------+-------+\n| id | select_type | table | type | possible_keys | key | key_len | ref | rows | filtered | Extra |\n+----+-------------+-------+------+---------------+------+---------+------+------+----------+-------+\n| 1 | PRIMARY | test | ALL | NULL | NULL | NULL | NULL | 3 | 100.00 | |\n| 3 | SUBQUERY | test2 | ALL | NULL | NULL | NULL | NULL | 3 | 100.00 | |\n| 2 | SUBQUERY | test2 | ALL | NULL | NULL | NULL | NULL | 3 | 100.00 | |\n+----+-------------+-------+------+---------------+------+---------+------+------+----------+-------+\n</code></pre>\n\n<p>If I'm right the second version runs the complex (maybe bottleneck) subquery on table <code>test2</code> <em>twice</em>, so it should be slower than the first query which runs the complex subquery only once. Furthermore, the first one is much easier to read. So, I prefer the first one. (I'm not a MySQL guru, feel free to correct me.)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-23T16:53:52.613",
"Id": "6227",
"ParentId": "6221",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "6227",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-23T15:12:47.073",
"Id": "6221",
"Score": "5",
"Tags": [
"mysql",
"sql"
],
"Title": "Using a subquery to rename columns"
}
|
6221
|
<p>I have a class which updates an object. The class takes a <code>String id</code> in its constructor and returns the appropriate class based on the <code>id</code>. I think these two methods should be separated into their own classes as returning an object based on a String <code>id</code> will probably have uses elsewhere in the code base.</p>
<p>I've considered adding the functionality which returns the object to update into its own static method:</p>
<pre><code>ObjectToUpdate = Utils.getObjectToUpdate(id)
</code></pre>
<p>Is there a better way or a design pattern?</p>
<pre><code>UpdateContestantObj c = new UpdateContestantObj(childWithParentRatingsObject.getCoupleId());
c.getContestantObj().setSortVal(singleScoringFM.getScore());
c.persistContestant();
public class UpdateContestantObj {
private String id;
private ContestantObj contestantToSave = null;
public ContestantObj getContestantObj(){
return this.contestantToSave;
}
public UpdateContestantObj(String id){
this.id = id;
SimpleSortingVector simpleSortingVector = (SimpleSortingVector)FutureContent.future.getContent(Constants.CONTESTANTS_DATA);
Enumeration contestantsEnumeration = simpleSortingVector.elements();
while(contestantsEnumeration.hasMoreElements()){
final ContestantButtonField contestantButtonField = (ContestantButtonField)contestantsEnumeration.nextElement();
if(contestantButtonField.getContestant().getId().equalsIgnoreCase(this.id)){
contestantToSave = contestantButtonField.getContestant();
}
}
}
public void persistContestant(){
contestantsStore.setContents(contestantToSave);
contestantsStore.commit();
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-23T12:57:58.083",
"Id": "9651",
"Score": "0",
"body": "In one sense if you've thought about asking then the answer is \"yes\"."
}
] |
[
{
"body": "<p>There's no super-design-pattern that would be beneficial here, but you could definitely benefit from some basic OO concepts like encapsulation and single responsibility.</p>\n\n<p>For starters, rather than making a bunch of utility methods, it's better design to allow each class a static method like:</p>\n\n<pre><code>// inside the ContestantObj class\npublic static ContestantObj fromID(string ID) {\n // code to retrieve ContestantObj \n}\n</code></pre>\n\n<p>This way, each class is responsible for creating itself, which it should be (outside of cases where a builder or abstract factory is required).</p>\n\n<p>Your <code>UpdateContestantObj</code> constructor should take in a <code>ContestantObj</code>. It shouldn't care about how the <code>ContestantObj</code> is created. A \"Contestant Updater\" should be a machine that takes in Contestants and outputs Contestants that have been updated.</p>\n\n<p>Also, the naming convention of <code>ContestantObj</code> should simply be <code>Contestant</code>. We know it's an object.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-18T13:45:41.023",
"Id": "6223",
"ParentId": "6222",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "6223",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-18T12:37:59.503",
"Id": "6222",
"Score": "1",
"Tags": [
"java",
"design-patterns"
],
"Title": "Class which updates an object"
}
|
6222
|
<p>The exercise was to take a file such as this:</p>
<blockquote>
<pre class="lang-none prettyprint-override"><code>You say yes
I say no
You say stop
And I say go go go
CHORUS:
Oh no
You say Goodbye
And I say hello
Hello hello
I don't know why
You say Goodbye
I say hello
#repeat 9 12
Why
#repeat 11 13
I say high
You say low
You say why
And I say I don't know
#repeat 5 19
</code></pre>
</blockquote>
<p>And parse the repeats so they actually repeat the lines. Nested repeats have to work and I had to use my own stack class.</p>
<p><strong>main.cpp</strong></p>
<pre class="lang-cpp prettyprint-override"><code>#include "Stack.h"
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
void parseLines(const std::vector<std::string> text, const int begin, const int end);
void parseRepeat(const std::string repeatLine, int &begin, int &end);
int main() {
int fileLines = 0;
std::string in;
std::string fileName = "lyrics";
std::ifstream inFile(fileName.c_str());
std::vector<std::string> text;
while(!inFile.eof()) {
getline(inFile, in);
text.push_back(in);
fileLines++;
}
parseLines(text, 0, fileLines);
}
void parseLines(const std::vector<std::string> text, const int begin, const int end) {
Stack<int> lyricStack;
int fromLine = begin;
int toLine = end;
while(fromLine <= toLine && (unsigned int)fromLine < text.size()) {
if(text.at(fromLine).substr(0, 7) == "#repeat") {
lyricStack.push(fromLine);
lyricStack.push(toLine);
parseRepeat(text.at(fromLine), fromLine, toLine);
} else {
std::cout << text.at(fromLine) << std::endl;
fromLine++;
}
}
while(!lyricStack.isEmpty()) {
toLine = lyricStack.pop();
fromLine = lyricStack.pop();
fromLine++;
parseLines(text, fromLine, toLine);
}
}
void parseRepeat(const std::string repeatLine, int &begin, int &end) {
std::string numbers = repeatLine.substr(repeatLine.find(" ") + 1);
begin = atoi((numbers.substr(0, numbers.find(" "))).c_str()) - 1;
end = atoi((numbers.substr(numbers.find(" "))).c_str()) - 1;
}
</code></pre>
<p><strong>Stack.h</strong></p>
<pre class="lang-cpp prettyprint-override"><code>#ifndef STACK_H_
#define STACK_H_
#include <string>
template <class A>
struct NODE {
A data;
NODE* next;
};
template <class B>
class Stack {
private:
NODE<B>* head;
public:
Stack();
virtual ~Stack();
void push(const B item);
B pop();
bool isEmpty();
};
#endif /* STACK_H_ */
</code></pre>
<p><strong>Stack.cpp</strong></p>
<pre class="lang-cpp prettyprint-override"><code>#include "Stack.h"
#include <string>
template <class B>
Stack<B>::Stack() {
head = NULL;
}
template <class B>
Stack<B>::~Stack() {
NODE<B>* current = head;
NODE<B>* previous;
while(current) {
previous = current;
current = current->next;
delete previous;
}
}
template <class B>
void Stack<B>::push(const B item) {
NODE<B>* newNode = new NODE<B>;
newNode->data = item;
if(!head) {
newNode->next = NULL;
head = newNode;
} else {
newNode->next = head;
head = newNode;
}
}
template <class B>
B Stack<B>::pop() {
NODE<B>* next = head->next;
B data = head->data;
delete head;
head = next;
return data;
}
template <class B>
bool Stack<B>::isEmpty() {
if(!head) {
return true;
}
return false;
}
</code></pre>
|
[] |
[
{
"body": "<p>First main problem is the code does not compile:</p>\n\n<p>When you implement template classes. The compiler instantiates the templates on use. This means the compilation unit that is instantiating the class must have already seen the source for the template (if it has not then it marks it as unresolved) and then tries to resolve them at link time. In your case this does not happen.</p>\n\n<pre><code>main.cpp: Uses Stack<int> thus needs the constructor and destructor.\n But does not have them at this point. So waits for the linker to find one.\n\nStack.cpp: Contains only template definition and thus does **NOT** generate any code.\n Templates only become real code when there is an instantiation\n (implicit as done by the compiler in main.cpp or explicit when you do it).\n Since there is no instantiation there is no code.\n</code></pre>\n\n<p>This all means that main fill fail to link.</p>\n\n<p>The easiest way to solve this:</p>\n\n<ol>\n<li>Rename Stack.cpp to Stack.tpp</li>\n<li>#include \"Stack.tpp\" from inside \"Stack.h\"</li>\n</ol>\n\n<p>The reason to rename to Stack.tpp is that some build systems will try to build all source and since this is included by a header this can cause problems with some build systems. So it is best to change the name just to avoid any future problems. <code>tpp</code> is often used to hold template definitions.</p>\n\n<p>Never do this:</p>\n\n<pre><code>while(!inFile.eof()) {\n getline(inFile, in);\n text.push_back(in);\n fileLines++;\n}\n</code></pre>\n\n<p>Several problems:</p>\n\n<ol>\n<li>If getline() fails with a real error (not EOF) you end up with an infinite loop.</li>\n<li>The last line read reads up to (but not past the EOF).<br>\nSo you have read the last line but EOF is not set. You then re-enter the loop try to get another line, this fails and sets EOF but nothing is done with <code>in</code> yet you still push in onto <code>text</code>. So you end up pushing the last line twice.</li>\n</ol>\n\n<p>The correct way to read from a file is:</p>\n\n<pre><code>while(getline(inFile, in))\n{\n // The loop is only entered if getline() successfully reads a line.\n // Thus it solves the two problems above.\n\n text.push_back(in);\n fileLines++;\n}\n</code></pre>\n\n<p>This works because getline() returns a reference to a stream. When a stream is used in a boolean context it is converted to a type that can be used as a boolean (type unspecified in C++03 but bool in C++11). It is converted by checking the fail() flag. If this is true the conversion returns an object equivalent to false otherwise an object equivalent to true.</p>\n\n<p>When passing big objects as parameters consider passing them by reference. If they are never modified pass by const reference. If you don't the compiler is going to generate a copy.</p>\n\n<pre><code>void parseLines(const std::vector<std::string> text, const int begin, const int end) {\n</code></pre>\n\n<p>Here you should probably pass text by const reference.</p>\n\n<pre><code>void parseLines(const std::vector<std::string> const& text, const int begin, const int end) {\n// ^^^^^^^^\n</code></pre>\n\n<p>Same thing here:</p>\n\n<pre><code>void parseRepeat(const std::string repeatLine, int &begin, int &end) {\n// Should probably be\nvoid parseRepeat(const std::string& repeatLine, int &begin, int &end) {\n// ^^^\n</code></pre>\n\n<p>Casting is nearly always a sign that something is wrong with your design:</p>\n\n<pre><code>(unsigned int)fromLine\n</code></pre>\n\n<p>This should be a hint that fromLine is the wrong type. Since it is measuring a size and will never by less than 0 this is an indication that the correct type for the type is unsigned int (or probably size_t).</p>\n\n<pre><code>void parseLines(const std::vector<std::string> text, std::size_t const begin, std::size_t const end) {\n Stack<int> lyricStack;\n\n std::size_t fromLine = begin;\n std::size_t toLine = end;\n\n while(fromLine <= toLine && fromLine < text.size()) {\n</code></pre>\n\n<p>atoi() is fast but non standard and not always available. An easier way is to just use the stream operators. This will always work and 99% of the time will be sufficiently fast. Only optimize out when you know it makes a difference.</p>\n\n<p>Also this code is so dense it is nearly unreadable. White space is your friend.</p>\n\n<pre><code>void parseRepeat(const std::string repeatLine, int &begin, int &end)\n{\n std::string numbers = repeatLine.substr(repeatLine.find(\" \") + 1);\n begin = atoi((numbers.substr(0, numbers.find(\" \"))).c_str()) - 1;\n end = atoi((numbers.substr(numbers.find(\" \"))).c_str()) - 1;\n}\n</code></pre>\n\n<p>Much easier to write with streams:</p>\n\n<pre><code>void parseRepeat(const std::string repeatLine, int &begin, int &end)\n{\n // This line always has the form \n // #repeat <number> <number>\n std::stringstream linestream(repeatLine);\n std::string repeat;\n\n linestream >> repeat >> begin >> end;\n}\n</code></pre>\n\n<p>Both NODE and Stack contain RAW pointers. Yet they do not obey the rule of three. This is very dangerous. The simple rule is your classes should never contain RAW pointers (all pointers should be wrapped in smart pointers) unless you are writing a smart pointer or container.</p>\n\n<p>In this situation NODE would be easy to implement using smart pointer. </p>\n\n<p>Also you do a work handling node inside stack. It simplifies the design if you move this work to the constructor of NODE. This makes the code in Stack much easier to read as it just handles the stack and the NODE can handle itself.</p>\n\n<p>The Stack is arguably a container so it can have a pointer but you must implement the rule of three. This means you need to implement the Copy Constructor/Assignment operator/Destructor or make these methods private. The reason is that if you do not then the compiler will automatically generate these methods. And the compiler generated version does not plat well with \"OWNED RAW pointers\".</p>\n\n<pre><code>{\n Stack<int> a;\n a.push(4);\n\n Stack<int> b(a); // Copy made of a\n\n DO STUFF\n} // Here B is destroyed. \n // But because you did not define a copy constructor b is a shallow copy of a\n // This means they both contain the same pointer. So b deletes it first.\n // Now A is destroyed.\n // This also deletes its pointer (the same as b) but it has already been deleted. \n // Your program is now free to produce nasal daemons (undefined behavior).\n</code></pre>\n\n<p>The simplest solution is to disable copy construction and the assignment operator.</p>\n\n<p>You have over complicated push:</p>\n\n<pre><code>if(!head) {\n newNode->next = NULL;\n head = newNode;\n} else {\n newNode->next = head;\n head = newNode;\n}\n</code></pre>\n\n<p>Would this not be easier to write as:</p>\n\n<pre><code>newNode->next = head;\nhead = newNode;\n</code></pre>\n\n<p>Also isEmpty() is over complicated:</p>\n\n<pre><code>if(!head) {\n return true;\n}\n\nreturn false;\n</code></pre>\n\n<p>Could be written as:</p>\n\n<pre><code>return head == NULL;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-23T20:43:11.050",
"Id": "9674",
"Score": "0",
"body": "What a great reply"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-24T03:38:04.483",
"Id": "9685",
"Score": "0",
"body": "Is there any compelling reason not to use a smart pointer for my Stack class?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-24T14:34:36.443",
"Id": "9718",
"Score": "0",
"body": "Personally I would (just use a smart pointer)."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-23T16:03:33.340",
"Id": "6225",
"ParentId": "6224",
"Score": "12"
}
}
] |
{
"AcceptedAnswerId": "6225",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-23T15:39:37.840",
"Id": "6224",
"Score": "7",
"Tags": [
"c++",
"parsing",
"stack"
],
"Title": "Song repetition manager with Stack"
}
|
6224
|
<p>I'm working on a piece of code in my MVC3 application and I'm struggling to decide if what I plan to do is a bad idea or not.</p>
<p>I have a snippet of JavaScript that calls an MVC action that in turn returns an HTML partial that I then insert into a <code>div</code> element on my page. Nothing complicated there.</p>
<p>However, things have changed and I now need to pass back a possible error message as well. I propose to send this back with the HTML partial as part of a JSON object.</p>
<p>It would look something like this:</p>
<pre><code>{
errorMessage: "things have gone wrong!",
partial : "<tr><td><a href='#'>Test</a></td><td>0MB</td></tr><tr><td><a href='#'>Test2</a></td><td>1MB</td></tr>"
}
</code></pre>
<p>This seems pragmatic but maybe a little dirty to me, so I'd like the thoughts of the community, please.</p>
<p>Now the obvious alternative would be to pass the table data back as JSON as well, and parse it client-side. But this will be a pain, even with something like jQuery templates (the example I've put up is simplified).</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-23T17:44:20.300",
"Id": "9662",
"Score": "0",
"body": "Would you please clarify the reason why you want to post back the partial html to the server side (if I understand correctly)? Also, what would possibly cause the erros on the client side? What kind of processing is happening there? Just trying to get a clearer picture."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-23T19:12:22.027",
"Id": "9670",
"Score": "0",
"body": "A misunderstanding. The json object is being passed to the client side. Am literally just passingly a HTML table and an error message back to the client"
}
] |
[
{
"body": "<p>I would consider returning with a more detailed JSON object:</p>\n\n<pre><code>{\n errorMessage: \"things have gone wrong!\",\n data: [\n {\n link: #,\n linkText: Test,\n size: 0MB\n },\n {\n link: #,\n linkText: Test2,\n size: 1MB\n }\n}\n</code></pre>\n\n<p>It moves some processing from the server to the clients but it's more reusable. For example you need a second type of table later with the same data but with an extra column. With this JSON format you don't have to touch the server side code nor to parse and modify the returned HTML on the client side.</p>\n\n<p>Finally, if there is an error maybe you want to omit the whole data part:</p>\n\n<pre><code>{\n errorMessage: \"things have gone wrong!\",\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-24T08:08:41.423",
"Id": "9702",
"Score": "0",
"body": "i suggest to come back with an additional template, eg:\n{ errorMessage: \"..\", data: [ ... ], template: '<div>... </div>' }\n\nIt allows default decorating the data"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-23T22:17:44.110",
"Id": "6241",
"ParentId": "6228",
"Score": "1"
}
},
{
"body": "<p>Passing the HTML is a bad idea because it will cause a tight coupling. It will be difficult for you to port it to a mobile application. Pass the data as JSON as suggested by palacsint, the consumer should know the format so that it can parse it</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-24T09:08:51.517",
"Id": "9704",
"Score": "0",
"body": "I think one only asks for advice when they already know the answer. They just don't like it :D"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-24T10:38:09.510",
"Id": "9709",
"Score": "0",
"body": "or when one is really confused"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-24T06:51:09.987",
"Id": "6249",
"ParentId": "6228",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-23T17:29:11.483",
"Id": "6228",
"Score": "3",
"Tags": [
"c#",
"json",
"mvc"
],
"Title": "Passing HTML back inside a JSON object"
}
|
6228
|
<p>The below is a class designed to implement <a href="https://www.rememberthemilk.com" rel="nofollow">Rememember the Milk</a>'s task priorities. I'm using it partly as an exercise in "Pythonic" programming, so it's fairly simple already, but advice on how to make it simpler or more Pythonic would be particularly appreciated.</p>
<p>I'm using Python 2.6.5 in case it makes any difference.</p>
<pre><code>class Pri(int): # Subclass int to get handy comparison functions etc.
'''Task priority'''
public_from_internal = {1: 1, 2: 2, 3: 3, 4: 'N'}
internal_from_public_str = {'N': 4, '1': 1, '2': 2, '3': 3}
_dict = dict()
def __new__(cls, level):
try:
level = Pri.internal_from_public_str[str(level)]
except KeyError:
raise ValueError, "Pri must be 'N', '1', '2', or '3'"
# If there's already an instance of this priority, don't create a new one.
if level in Pri._dict: return Pri._dict[level]
else: return super(Pri, cls).__new__(cls, level)
def __init__(self, level):
super(Pri, self).__init__()
Pri._dict[self] = self
def __repr__(self): return "Pri('" + str(Pri.public_from_internal[self]) + "')"
# Priority 1 is clearly greater than priority 3, so invert cmp
def __cmp__(self, other): return (-cmp(int(self), int(other)))
</code></pre>
<p>Some selected output, for the curious:</p>
<pre><code>>>> Pri(1)
Pri('1')
>>> Pri('N')
Pri('N')
>>> Pri(4)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "rtm.py", line 10, in __new__
raise ValueError, "Pri must be 'N', '1', '2', or '3'"
ValueError: Pri must be 'N', '1', '2', or '3'
>>> Pri._dict
{Pri('1'): Pri('1'), Pri('N'): Pri('N')}
>>> Pri(1) > Pri(2)
True
>>> bool(Pri('N'))
True
>>> repr(Pri("2"))
"Pri('2')"
>>> print repr(Pri('N'))
Pri('N')
>>> Pri(1)._dict
{Pri('1'): Pri('1'), Pri('2'): Pri('2'), Pri('N'): Pri('N')}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-23T19:22:13.417",
"Id": "9671",
"Score": "1",
"body": "I'm curious as to why you're extending `int` -- I don't see any benefit from it here. Maybe I missed something?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-24T10:31:25.427",
"Id": "9707",
"Score": "0",
"body": "@Matt: No. It made sense in my mind at the time, but looking again it's entirely redundant now."
}
] |
[
{
"body": "<pre><code>class Pri(int): # Subclass int to get handy comparison functions etc.\n</code></pre>\n\n<p>Abbreviating words in class names makes it harder to follow. Just call it <code>Priority</code></p>\n\n<pre><code> '''Task priority'''\n\n public_from_internal = {1: 1, 2: 2, 3: 3, 4: 'N'}\n internal_from_public_str = {'N': 4, '1': 1, '2': 2, '3': 3}\n _dict = dict()\n</code></pre>\n\n<p>Naming this <code>_dict</code> doesn't give me a hint about what its used for</p>\n\n<pre><code> def __new__(cls, level):\n try:\n level = Pri.internal_from_public_str[str(level)]\n</code></pre>\n\n<p>I don't like stringifying anything that gets passed in here. You really only want to support strings and ints not things that happen to stringify into the correct types. </p>\n\n<pre><code> except KeyError:\n raise ValueError, \"Pri must be 'N', '1', '2', or '3'\"\n\n # If there's already an instance of this priority, don't create a new one.\n if level in Pri._dict: return Pri._dict[level]\n else: return super(Pri, cls).__new__(cls, level)\n</code></pre>\n\n<p>Use the following construct instead:</p>\n\n<pre><code>try:\n return Pri._dict[level] \nexcept KeyError:\n return super(Pri,cls).__new__(cls, level)\n</code></pre>\n\n<p>I think its clearer, and it will be slightly faster.</p>\n\n<pre><code> def __init__(self, level):\n super(Pri, self).__init__()\n Pri._dict[self] = self\n</code></pre>\n\n<p>I do this is <code>__new__</code> and not have an <code>__init__</code> function.</p>\n\n<pre><code> def __repr__(self): return \"Pri('\" + str(Pri.public_from_internal[self]) + \"')\"\n</code></pre>\n\n<p>I don't like putting the method name and implementation on the same line. I think it makes it look clutered. I'd also recommend using <code>return \"Pri(%s)\" % Pri.public_from_internal[self]</code> as I think its clearer as to the result. </p>\n\n<pre><code> # Priority 1 is clearly greater than priority 3, so invert cmp\n def __cmp__(self, other): return (-cmp(int(self), int(other)))\n</code></pre>\n\n<p>You inherited from int to get comparisons. But then you have to reimplement the comparisons anyways. Now you also have all the other stuff like adding/multipyling/subtracting/etc which don't make sense to apply to priorities. Basically, there is no reason to inherit from int here, and many reasons not to.</p>\n\n<p>How I'd do this</p>\n\n<pre><code>class Priority(object):\n priorities_by_name = {}\n @classmethod\n def from_string(cls, name):\n return cls.priorities_by_name[name]\n\n priorities_by_number = {}\n @classmethod\n def from_number(cls, number):\n return cls.priorities_by_number[number]\n\n def __init__(self, name, number):\n self.priorities_by_name[name] = self\n self.priorities_by_number[number] = self\n self.name = name\n self.number = number\n\n def __repr__(self):\n return \"Priority<%d>\" % self.number\n\n def __cmp__(self, other):\n return -cmp(self.number, other.number)\n\n\nPriority.First = Priority('1', 1)\nPriority.Second = Priority('2', 2)\nPriority.Third = Priority('3', 3)\nPriority.None = Priority('N', 4)\n\nPriority.__init__ = None # Prevent any future creations\n</code></pre>\n\n<ol>\n<li>I explicitly call class method to get a priority from either the string or number. I dislike overloading the one constructor to take either. </li>\n<li>For a small number of items, I prefer to create them all upfront. It makes the construction simpler</li>\n<li>I can access Priority objects at Priority.First (etc) </li>\n</ol>\n\n<p>Truth be told I probably wouldn't implement a Priority class, instead I'd keep track of the priority as an int. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-24T09:22:38.437",
"Id": "9705",
"Score": "0",
"body": "Truth be told, *I* probably wouldn't implement a Priority class if this were for \"normal\" development. As I mentioned in the question, I'm writing it partly as an exercise in using some of the bits of Python's class model that I'm less familiar with."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-24T10:32:11.510",
"Id": "9708",
"Score": "0",
"body": "Why're you subclassing `object` here? I'm not sure what benefit that provides…"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-24T10:42:19.787",
"Id": "9711",
"Score": "0",
"body": "Also, why that definition of `__repr__`? The docs suggest `repr` should result in a string that will return the same value if pushed through `eval`, or something of the form `<...>` otherwise, and that seems to match neither."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-24T10:43:35.933",
"Id": "9713",
"Score": "0",
"body": "Ack. I'm worried those questions sound like I'm being overly defensive. I'm very grateful for the comments, thank you! The suggestion to use `@classmethod` in particular is useful; I hadn't really understood what that did without those examples."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-24T12:28:40.753",
"Id": "9715",
"Score": "0",
"body": "Ah. A little Googling answered my own question about subclassing `object`: it's a new-style/old-style class thing. For future readers: if you don't subclass anything or only subclass old-style classes, you get an old-style class. If you subclass a new-style class, where `object` is the simplest such, you get a new-style class. More info at the [Python Wiki](http://wiki.python.org/moin/NewClassVsClassicClass \"New class vs classic class\")."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-24T13:25:56.053",
"Id": "9717",
"Score": "0",
"body": "@me_and, I think this style of `__repr__` is easier to read when output. But that's pretty subjective. It looks like you found the answer to your other question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-08-12T14:18:47.027",
"Id": "258919",
"Score": "0",
"body": "I agree with @me_and regarding `__repr__`. All other classes, it's ether `eval`able, or `<...>`. Pretty output should be the done using `__str__`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-08-12T22:33:15.580",
"Id": "259081",
"Score": "0",
"body": "@RoadieRich, and five years after writing this answer, I'd agree with you."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-24T00:39:47.833",
"Id": "6243",
"ParentId": "6229",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "6243",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-23T18:05:03.127",
"Id": "6229",
"Score": "3",
"Tags": [
"python"
],
"Title": "Python simple int subclass"
}
|
6229
|
<p>I came across this code in our project today. Where possible I'm trying to leave the code base in a better shape than I found it, as I go along, and this method jumped out at me for a number of reasons, mainly the sql string and the try/catch block. I feel there's a less expensive way to do it.</p>
<p>Original Code:</p>
<pre><code>public bool CheckSomething(string paramA, int paramB)
{
using (var conn = new SqlConnection(Connection))
{
conn.Open();
string sqlCommand = "SELECT ColumnA FROM OurTable WHERE ColumnB = '" + paramA +
"' AND ColumnC = " + paramB;
using (var dbCommand = new SqlCommand(sqlCommand, conn))
{
int noOfRecords = -1;
try
{
noOfRecords = (int)dbCommand.ExecuteScalar();
}
catch (Exception ex)
{
}
finally
{
dbCommand.Dispose();
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
return noOfRecords > 0;
}
}
}
}
</code></pre>
<p>I was thinking of re-writing it as this, but I still think it could be improved further, one of which would be to create an procedure for the sql, but that's unlikely. Was aiming to improve it purely from the code point of view. I'd appreciate thoughts.</p>
<p>Rewritten version:</p>
<pre><code>public bool CheckSomething(string paramA, int paramB)
{
using (var conn = new SqlConnection(Connection))
{
conn.Open();
string sqlCommand = string.Format("SELECT ColumnA FROM OurTable WHERE ColumnB = '{0}' and ColumnB = {1}", paramA, paramB);
using (var dbCommand = new SqlCommand(sqlCommand, conn))
{
object noOfRecords = dbCommand.ExecuteScalar();
dbCommand.Dispose();
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
return noOfRecords != null;
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-22T16:34:50.133",
"Id": "9663",
"Score": "0",
"body": "Why in the world would you change noOfRecords (horrible name) to an object and check for null? How is that the same?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-22T16:38:04.457",
"Id": "9664",
"Score": "0",
"body": "Yeah, I noticed that after I posted. The variable name there wasn't changed, that's an oversight. what that check for null is supposed to do, and I may be wrong, is to simply check if a result was returned. The method essentially boils down to, if a result is returned, then true, else false."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-22T16:40:55.243",
"Id": "9665",
"Score": "0",
"body": "Which is fundamentally different than what was there. Are you trying to... save the cost of a cast or something?..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-22T16:48:13.640",
"Id": "9666",
"Score": "0",
"body": "I'm simply trying to rewrite the method to return the result it needs as efficiently as possible. The original attempts to get a result, then cast it an int, and then return a comparison on whether that int value is more than 0. The reality is that if a result is returned from that query then the method should return true. To me that is much more simpler to understand, and I'm assuming more efficient, even by a very small margin."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-22T17:53:50.863",
"Id": "9667",
"Score": "0",
"body": "Is the intent to check \"ColumnA\" to see if it has a value > 0, or did the original developer have the misguided idea that ExecuteScalar returns the number of rows? If the first, you're changing the functionality, if the second, you should fix it. If you don't know... you shouldn't change it. That being said, the amount of time you're \"saving\" is so miniscule compared to the cost of the DB call that it simply doesn't matter. If you think it's easier to understand (and the functionality isn't changing), then by all means go ahead. But don't do it for \"speed\"."
}
] |
[
{
"body": "<pre><code>public bool CheckSomething(string paramA, int paramB)\n{ \n using (var conn = new SqlConnection(\"..\"))\n using (var comm = new SqlCommand(\"\", conn))\n {\n conn.Open();\n object noOfRecords = comm.ExecuteScalar();\n return noOfRecords != null;\n }\n}\n</code></pre>\n\n<p>There is no need to close or dispose, the <code>using</code> handles that part. This removes the need for a manual try catch or closing logic, leaving a much compressed chunk of code that is functionally equivalent and just as safe.</p>\n\n<p>As for the select statement itself, either use parameterized SQL or a stored procedure as opposed to string concatenation. Parameterized SQL:</p>\n\n<pre><code>string sql = \"SELECT ColumnA FROM OurTable WHERE ColumnB = @param1 AND ColumnC = @param2\";\n\nusing (var comm = new SqlCommand(sql, conn))\n{\n comm.Parameters.AddWithValue(\"@param1\", param1);\n comm.Parameters.AddWithValue(\"@param2\", param2);\n\n conn.Open();\n // etc...\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-22T16:17:27.410",
"Id": "6231",
"ParentId": "6230",
"Score": "16"
}
},
{
"body": "<p>As Adam said, there is no real need to call the <code>Dispose</code> methods because the <code>using</code> clauses are there for that.</p>\n\n<p>However, what I'd really want to change about your code is how the SQL query is built. You should <strong>never</strong> concatenate strings to create your SQL queries, unless you're willing to invite SQL injections into your code.</p>\n\n<p>You should check out how to use <a href=\"http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.parameters.aspx\" rel=\"nofollow\">Parameters</a> instead.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-22T16:20:40.547",
"Id": "6232",
"ParentId": "6230",
"Score": "4"
}
},
{
"body": "<p>I agree that your rewritten version looks much cleaner. My only change would be to make use of SQL parameters.</p>\n\n<pre><code> string sqlCommand = \"SELECT ColumnA FROM OurTable WHERE ColumnB = @paramA and ColumnC = @paramB\";\n\n using (var dbCommand = new SqlCommand(sqlCommand, conn))\n {\n dbCommand.Parameters.Clear();\n dbCommand.Parameters.AddWithValue(\"paramA\",paramA);\n dbCommand.Parameters.AddWithValue(\"paramB\",paramB);\n object noOfRecords = dbCommand.ExecuteScalar();\n dbCommand.Dispose();\n</code></pre>\n\n<p>SQL parameters are good to use any time you're dealing with user input.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-22T16:44:20.413",
"Id": "9668",
"Score": "0",
"body": "Yes, good approach here, which was an improvement on mine. Thankfully I don't think we have too many examples in our code base of Sql commands written like the example I provided, but if I do come across any more, I will probably replace the existing code with parameters as you suggest."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-22T16:24:35.690",
"Id": "6233",
"ParentId": "6230",
"Score": "0"
}
},
{
"body": "<p>This is terrible:</p>\n\n<pre><code> catch (Exception ex)\n {\n }\n</code></pre>\n\n<p>It will hide problems. It's like putting black tape over the idiot lights on your car's dashboard.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-22T16:42:50.837",
"Id": "9669",
"Score": "0",
"body": "I agree, though siding with the author of the original example, he was probably just using a common (but derided) way of handling casting to an int. If the cast fails, assume a default value. The alternative way to write the original would to make this logic clearer have been to declare int noOfRecords, and then specifically put noOfRecords = -1 in the catch. It still masks a range of issues as to why it caused an exception, but my assumption is that original writer didn't care about why it failed, just to assume that the method will return false in any case where a result isn't returned."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-22T16:31:59.903",
"Id": "6234",
"ParentId": "6230",
"Score": "1"
}
},
{
"body": "<p>Here's how I'd code it up. It more or less resembles <a href=\"https://codereview.stackexchange.com/users/8556/adam-houldsworth\">Adam Houldsworth</a>'s <a href=\"https://codereview.stackexchange.com/q/6231/6172\">answer</a>, but does actually check the <code>int</code> value that the <code>ExecuteScalar()</code> is expected to return from the O.P.</p>\n\n<pre><code>public bool CheckSomething(string paramA, int paramB)\n{\n using (var conn = new SqlConnection(Connection))\n using (var command = new SqlCommand(\"SELECT ColumnA FROM OurTable WHERE ColumnB = @paramA AND ColumnC = @paramB\", conn))\n {\n command.Parameters.Add(new SqlParameter(\"@paramA\", SqlDbType.VarChar)).Value = paramA;\n command.Parameters.Add(new SqlParameter(\"@paramB\", SqlDbType.Int)).Value = paramB;\n conn.Open();\n return (int)command.ExecuteScalar() > 0;\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-23T19:23:03.633",
"Id": "6235",
"ParentId": "6230",
"Score": "0"
}
},
{
"body": "<p>Addionally avoid using <code>AddWithValue</code>.</p>\n\n<p>An implicit conversion for the parameter value for the sql is done, it can result in bad performance.</p>\n\n<p>If parameter of the command are different SqlServer is not able to cache the execution plan and has to compile the statement again and again.\nYou can see it if you trace/watch that in the sqlprofiler.</p>\n\n<p>Use the \"long\" version instead and specify the datatype and length of the paramter.</p>\n\n<pre><code> var parameter = new SqlParameter(\"@p1\", SqlDbType.VarChar, 5);\n parameter.Value = \"value\";\n</code></pre>\n\n<p>I recommend to read the accepted answer from <a href=\"https://stackoverflow.com/questions/1374804/addwithvalue-difficulty\">AddWithValue difficulty</a> from stack.</p>\n\n<p><a href=\"https://stackoverflow.com/users/105929/remus-rusanu\">Remus Rusanu</a> explained it a bit deeper.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-23T21:13:02.520",
"Id": "6240",
"ParentId": "6230",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "6231",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-22T16:15:37.620",
"Id": "6230",
"Score": "7",
"Tags": [
"c#",
"exception-handling"
],
"Title": "Could this ExecuteScalar call be written better?"
}
|
6230
|
<pre><code><?php
include_once('../dbInfo.php');
function getReport($user_table) {
$tables = array(
"day" => "p_day",
"month" => "p_month"
... etc. .....
);
$table = $tables[$user_table];
if(!$table) {
die(json_encode(array("error" => "bad table name")));
}
$con = getConnection(); // getConnection is in '../dbInfo.php'
$query = "select * from " . $table;
$res = mysql_query($query, $con);
if(!$res) {
die(json_encode(array("error" => "no results from table")));
}
$fields_num = mysql_num_fields($res);
$fields = array();
for($i=0; $i < $fields_num; $i++) {
$field = mysql_fetch_field($res);
$fields[$i] = $field->name;
}
$i = 0;
while($row = mysql_fetch_array($res)) {
$rows[$i] = $row;
$i++;
}
$json = array("rows" => $rows, "headers" => $fields);
$jsontext = json_encode($json);
return $jsontext;
}
?>
</code></pre>
<p>What this code is doing:</p>
<ul>
<li>access the database, selecting rows from a table, and returning them as a serialized json object</li>
<li>a table name is looked up in <code>$tables</code> -- the keys are acceptable user input, the values are actual table/view names in the database</li>
<li>data is selected from the table</li>
<li>the data is put into a big hash</li>
<li>the hash is serialized as a json string and returned</li>
</ul>
<hr>
<p>Specific issues I'm concerned about:</p>
<ol>
<li>security -- is my DB connection info safe? This file is in the root directory of public content, so <code>dbiInfo.php</code>, with the database connection information, is not publicly accessible (I think)</li>
<li>security -- am I open to SQL injection attacks? I build a SQL query with string concatenation</li>
<li>security -- <code>$user_table</code> is untrusted input; is it safe? It's only used as a key to look up trusted input ...</li>
<li>error handling -- have I dealt with all error conditions</li>
<li>there are lots of versions of PHP functions -- am I using the right ones?</li>
</ol>
<p>General issues:</p>
<ul>
<li>following conventions</li>
<li>quality/readability/comments</li>
</ul>
<hr>
<p><strong>Edit:</strong> the data is publicly available -- I'm worried about somebody getting more than read access to one of the listed tables, or any access to any other table in the DB.</p>
|
[] |
[
{
"body": "<p>If the output is json you may want to set the content type:</p>\n\n<p>This is what I nievely do:</p>\n\n<pre><code>$type =\"text/json\";\nif ($_GET{\"test\"})\n{\n $type = \"text/plain\";\n}\nheader(\"Content-type: $type\");\n</code></pre>\n\n<p>I also use mysql_query() but that is because my PHP is not good (and I have not done it for a while). But apparently this DB module is deprecated in favour of \"mysqli(mproved)\" module. <a href=\"http://us.php.net/manual/en/book.mysqli.php\" rel=\"nofollow\">http://us.php.net/manual/en/book.mysqli.php</a></p>\n\n<blockquote>\n <p>security -- is my DB connection info safe? This file is in the root directory of public content, so dbiInfo.php, with the database connection information, is not publicly accessible (I think)</p>\n</blockquote>\n\n<p>Don't think it makes a difference.<br>\nIf your Web server is set up correctly it will never deliver php files (only execute them).</p>\n\n<blockquote>\n <p>security -- am I open to SQL injection attacks? I build a SQL query with string concatenation</p>\n</blockquote>\n\n<p>Potentially. All input from insecure location must be escaped.</p>\n\n<ul>\n<li><a href=\"http://us.php.net/manual/en/function.mysql-real-escape-string.php\" rel=\"nofollow\">http://us.php.net/manual/en/function.mysql-real-escape-string.php</a> </li>\n<li><a href=\"http://us.php.net/manual/en/mysqli.real-escape-string.php\" rel=\"nofollow\">http://us.php.net/manual/en/mysqli.real-escape-string.php</a> </li>\n</ul>\n\n<p>Also you print error message that contain information about your tables into the response. This is definitely a security problem. The only response to the user should be a failed message (not why it failed), potentially with an ID so you can use this to look it up.</p>\n\n<p>All the error should be put into the log file (with the query that generated them). You can then use the ID provided in the error message to look up the query and the error message it produced.</p>\n\n<blockquote>\n <p>security -- $user_table is untrusted input; is it safe? It's only used as a key to look up trusted input ...</p>\n</blockquote>\n\n<p>And data from this table must be escaped before use.</p>\n\n<blockquote>\n <p>error handling -- have I dealt with all error conditions\n there are lots of versions of PHP functions -- am I using the right ones?</p>\n</blockquote>\n\n<p>OK. Not an expert here so others may know better but I like to put the error checking and command on the same line.</p>\n\n<pre><code>$res = mysql_query($query, $con);\n\nif(!$res) {\n die(json_encode(array(\"error\" => \"no results from table\")));\n}\n\n// For me this would be\n$res = mysql_query($query, $con) or LogErrorAndDie(array(\"error\" => \"no results from table\"));\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-23T20:50:07.243",
"Id": "9676",
"Score": "0",
"body": "Thanks for the advice. I'm not sure that I need to escape the user input, though -- I don't use the user input to build the SQL query, I use it to look up a *trusted* string in a table, which then goes into the query. Is data from the database untrusted -- it needs to be escaped too? I also don't understand how the error messages are a security problem -- could you clarify? Thanks again for the help!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-23T21:02:56.153",
"Id": "9677",
"Score": "0",
"body": "The problem with security is you can never know what can potentially be usefull to an attacker. Thus you should never give away anything. On the other hand a normal user usually does not care why it went wrong (they are not in a position to fix it) so providing this information is redundant. So both cases are best handled with non specific data. So best is just to apologize and provide a reference (GUID) the user can use when complaining. You can use the reference to look up the problem in the log files."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-23T20:17:57.040",
"Id": "6239",
"ParentId": "6237",
"Score": "4"
}
},
{
"body": "<p>This: </p>\n\n<pre><code>$tables = array(\n \"day\" => \"p_day\", \n \"month\" => \"p_month\"\n ... etc. .....\n);\n\n$table = $tables[$user_table];\n\nif(!$table) {\n die(json_encode(array(\"error\" => \"bad table name\")));\n}\n</code></pre>\n\n<p>will throw a notice if <code>$user_table</code> is not a valid array key, something you should have already tested. Rewrite as:</p>\n\n<pre><code>$tables = array(\n \"day\" => \"p_day\", \n \"month\" => \"p_month\"\n ... etc. .....\n);\n\nif(!array_key_exists($user_table, $tables)) {\n die(json_encode(array(\"error\" => \"bad table name\")));\n}\n\n$table = $tables[$user_table];\n</code></pre>\n\n<p>I really hate it when functions <code>die()</code>, and in your case there's no point in that. You could simply do: </p>\n\n<pre><code>if(!$table) {\n return json_encode(array(\"error\" => \"bad table name\"));\n}\n</code></pre>\n\n<p>since the function is expected to return a json formatted string. If you really want to <code>die()</code> you should do that where you call the function and the returned string is an error. Or you could just return <code>false</code> when an error occurs and the raw array when everything works, and when calling the function do something like: </p>\n\n<pre><code>$result = json_encode(getReport(\"some_table\"));\n</code></pre>\n\n<p>That way <code>getReport()</code> will be useful even when you don't need json encoded output. But that's up to you and how you actually use it.</p>\n\n<p>As @LokiAstari <a href=\"https://codereview.stackexchange.com/q/6239/4673\">mentions</a> <code>mysql_*</code> functions are deprecated and should be avoided. I would skip <code>mysqli_*</code> functions too and use <a href=\"http://php.net/manual/en/book.pdo.php\" rel=\"nofollow noreferrer\">PDO</a> which will give you the extra bonus of switching to another database engine if you ever need to and it has a nice OO interface.</p>\n\n<p>For everything else, I'm with @LokiAstari.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-24T15:48:35.557",
"Id": "6256",
"ParentId": "6237",
"Score": "6"
}
},
{
"body": "<pre><code><?php\n\ninclude_once('../dbInfo.php');\n\nfunction resolve_table($user_table) {\n $tables = array(\n \"day\" => \"p_day\",\n \"month\" => \"p_month\"\n ... etc. .....\n );\n\n // check table exists or return null\n return isset($tables[$user_table]) ? $tables[$user_table] : null;\n}\n\n\nfunction getReport($user_table) {\n\n $output = array();\n\n try {\n // move resolve table into separate function so can be reused\n $table = resolve_table($user_table);\n\n if(!$table) {\n // don't die here, throw and exception instead\n throw new Exception(\"bad table name\");\n }\n\n $con = getConnection(); // getConnection is in '../dbInfo.php'\n\n // this is safe as $table is a trusted source,\n // have added backticks around table name incase it is a reserved word in mysql\n // $query = \"select * from \" . $table\n $query = \"select * from `$table`\";\n\n $res = mysql_query($query, $con);\n\n if(!$res) {\n // don't return error here, throw exception\n throw new Exception(\"no results from table\");\n }\n\n // do you want to handle the case of no results?\n if (mysql_num_rows($res) == 0) {\n throw new Exception(\"no results from table\");\n }\n\n // as others have said, mysqli_ or pdo not mysql_ functions\n // see nicer way of doing this below\n// $fields_num = mysql_num_fields($res);\n// $fields = array();\n// for($i=0; $i < $fields_num; $i++) {\n// $field = mysql_fetch_field($res);\n// $fields[$i] = $field->name;\n// }\n\n // declare the array before using\n $rows = array();\n\n // not needed\n // $i = 0;\n\n // use fetch assoc instead to get an associative array\n // while($row = mysql_fetch_array($res)) {\n while($row = mysql_fetch_assoc($res)) {\n // $rows[$i] = $row;\n // $i++;\n\n // [] automatically adds next element to array\n $rows[] = $row;\n }\n\n // assuming there is at least 1 row in result set (we have tested for 0 rows above)\n // we can just get the array_keys of the last $row\n $fields = array_keys($row);\n\n // if exceptions have been thrown we will never reach this line\n $output = array(\"rows\" => $rows, \"headers\" => $fields);\n\n } catch (Exception $ex) {\n $output['error'] = $ex->getMessage();\n }\n\n // not necessary\n // $jsontext = json_encode($output);\n\n return json_encode($output);\n}\n\n// remove closing php tag (unless something follows), otherwise you may have unwanted whitespace after it, which can cause header or cookie issues\n// ? >\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-26T18:25:53.917",
"Id": "30270",
"ParentId": "6237",
"Score": "-1"
}
}
] |
{
"AcceptedAnswerId": "6256",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-23T20:03:36.877",
"Id": "6237",
"Score": "4",
"Tags": [
"php",
"security"
],
"Title": "PHP function to access a database and return json"
}
|
6237
|
<p><strong>First Implementation</strong></p>
<pre><code>public enum ReviewFlowExample {
Draft {
@Override
public ReviewFlowExample getNext() {
return Review;
}
@Override
public ReviewFlowExample getPrevious() {
return null;
}
},
Review {
@Override
public ReviewFlowExample getNext() {
return Final;
}
@Override
public ReviewFlowExample getPrevious() {
return Draft;
}
},
Final {
@Override
public ReviewFlowExample getNext() {
return null;
}
@Override
public ReviewFlowExample getPrevious() {
return Review;
}
};
public abstract ReviewFlowExample getNext();
public abstract ReviewFlowExample getPrevious();
public boolean isDraft() {
return this.equals(Draft);
}
}
</code></pre>
<hr>
<p><strong>Second Implemenation</strong></p>
<pre><code>public enum ReviewFlowExample {
Draft,
Review,
Final;
private ReviewFlowExample next;
private ReviewFlowExample previous;
static{
Draft.setNext(Review);
Review.setNext(Final);
Review.setPrevious(Draft);
Final.setPrevious(Review);
}
private ReviewFlowExample(){
}
public ReviewFlowExample getNext(){
return next;
}
public ReviewFlowExample getPrevious(){
return previous;
}
private void setNext(ReviewFlowExample next){
this.next = next;
}
private void setPrevious(ReviewFlowExample previous){
this.previous = previous;
}
public boolean isDraft(){
return this == Draft;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-24T03:39:48.093",
"Id": "9686",
"Score": "1",
"body": "The first one. No need to set up boilerplate getters and setters when you don't need any dynamic wiring. The first one is much more concise and clearer. You should trim it down even more: What is the need for the wrappers (`getNextState()` and so on)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-24T03:57:53.377",
"Id": "9689",
"Score": "0",
"body": "@Thilo What would that be did not get you ? please elaborate."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-24T04:12:57.957",
"Id": "9690",
"Score": "0",
"body": "Why do you need getNextState, getPreviousState when you already have getNext and getPrevious?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-24T04:17:48.497",
"Id": "9691",
"Score": "0",
"body": "@Thilo yes that's wrong I agree with that, I meant to ask about dynamic wiring what would that be . Asking just make sure I have covered all grounds.Thanks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-24T07:20:39.430",
"Id": "9701",
"Score": "1",
"body": "I would say the state before Draft and after Final is `null` as it is in the second example."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-24T23:20:05.603",
"Id": "9737",
"Score": "0",
"body": "@PeterLawrey please post an answer with little more explanation and your opinion about which one is better- Thanks a lot."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-25T08:04:28.900",
"Id": "9750",
"Score": "3",
"body": "Personally, I wouldn't do either. Instead I would use a state machine approach which is involves integrating how this as used as well. i.e. you introduce code as well as data in to your enums. http://vanillajava.blogspot.com/2011/06/java-secret-using-enum-as-state-machine.html"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-26T00:15:44.957",
"Id": "9776",
"Score": "1",
"body": "@PeterLawrey while the link you have posted is brilliant and they way to go forward. I however need to break the tie between two approaches . So if you post your comment as an answer along with tie breaking between the two approaches in terms of better implementation. I will accept your answer.First of these implementations is mine and second one is from a colleague who thinks I am wrong and the other one is better :( I think otherwise. But yes I will go with state machine that's exactly what I needed but please help is break the tie for now :) cheers..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-26T05:56:44.747",
"Id": "9786",
"Score": "0",
"body": "The second version is terser, however the first form is easier to translate into a state machine. So I would stick with what you have for now."
}
] |
[
{
"body": "<p>Just to spice up the discussion, you could also do something like this:</p>\n\n<pre><code> public ReviewFlowExample getNext() {\n ReviewFlowExample[] values = values();\n int next = ordinal() + 1 == values.length ? ordinal() : ordinal() + 1;\n return values[next];\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-24T04:45:40.937",
"Id": "9696",
"Score": "0",
"body": "is this dependent on the order of appearance."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-24T04:48:49.317",
"Id": "9697",
"Score": "0",
"body": "You bet :) Luckily tests can confirm order!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-24T04:50:59.910",
"Id": "9698",
"Score": "1",
"body": "Saw your comment below (I don't have general comment privileges yet). Please tell me your employer doesn't enforce alphabetical order of members!? We use IDEs for a reason!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-26T03:25:24.430",
"Id": "9783",
"Score": "1",
"body": "@Muel Two jobs ago they had Jalopy set up to alphabetize properties and methods as a CVS checkin hook. It drove me insane--it essentially randomized the class. It took quite awhile before I was allowed to remove the hook :("
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-24T04:27:48.033",
"Id": "6247",
"ParentId": "6246",
"Score": "2"
}
},
{
"body": "<p>Why not use the order you are setting up in the enum declaration? I played with this a while ago and came up with something like this (modified to fit your implementation above):</p>\n\n<pre><code>private enum Planet { MERCURY, VENUS, EARTH, MARS, JUPITER, SATURN, URANUS, NEPTUNE;\n public Planet getNext() {\n return this.ordinal() < Planet.values().length - 1\n ? Planet.values()[this.ordinal() + 1]\n : this;\n }\n public Planet getPrevious() {\n return this.ordinal() > 0\n ? Planet.values()[this.ordinal() - 1]\n : this;\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-24T04:33:06.647",
"Id": "9694",
"Score": "0",
"body": "You can find the original in my blog post at http://digitaljoel.nerd-herders.com/2011/04/05/get-the-next-value-in-a-java-enum/ but there's not much more info there than you'll find here."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-24T04:32:11.750",
"Id": "6248",
"ParentId": "6246",
"Score": "5"
}
},
{
"body": "<p>Although the other answers are correct, their readability suffers and they work only for linear workflows (and I don't like solutions which rely on declaration). I would go for readability, which is better in the second implementation. But it could be shortend:</p>\n\n<pre><code>public enum ReviewFlowExample {\n Draft,\n Review,\n Final;\n\n private ReviewFlowExample next = null;\n private ReviewFlowExample previous = null;\n\n static{\n Draft.next = Review;\n\n Review.previous = Draft;\n Review.next = Final;\n\n Final.previous = Review;\n }\n\n public ReviewFlowExample getNext(){\n return next;\n }\n\n public ReviewFlowExample getPrevious(){\n return previous;\n }\n\n public boolean isDraft(){\n return this == Draft;\n }\n}\n</code></pre>\n\n<hr>\n\n<p><a href=\"https://codereview.stackexchange.com/questions/6246/which-one-of-the-two-enum-implementation-is-better#comment9750_6246\">Peter suggested using a state machine instead.</a> I think the first solution is already a state machine, there is no need to add extra interfaces. You just have to move your workflow logic into the enum. But it's hard to tell, if a state machine is worth it, without knowing the other code.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T08:52:40.610",
"Id": "29430",
"ParentId": "6246",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "6248",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-24T03:34:55.590",
"Id": "6246",
"Score": "5",
"Tags": [
"java"
],
"Title": "Which one of the two enum implementation is better?"
}
|
6246
|
<p>I wanted to try experimenting with <a href="http://en.wikipedia.org/wiki/Fluent_interface">fluent interface</a> design in the C programming language. That's why I wanted to ask you, Dear Code Review users, comments on the way I have implement this simple employee record interface.</p>
<p>Please note that for maximum simplicity I am resorting to as simple data structures as possible.</p>
<pre><code>#include <stdio.h>
#include <assert.h>
/* if this weren't just an example I'd make a linked list */
#define MAX_EMPLOYEE_COUNT 10
/* global this pointer, there is no way around this */
void* this;
typedef struct Employee {
struct Employee* (*set_salary)(int);
struct Employee* (*set_employee_id)(int);
char* name;
int salary;
int employee_id;
} Employee;
Employee* do_set_salary(int s)
{
((Employee*)this)->salary = s;
return this;
}
Employee* do_set_employee_id(int id)
{
((Employee*)this)->employee_id = id;
return this;
}
typedef struct Record {
Employee* (*add_employee)(char*);
Employee employees[MAX_EMPLOYEE_COUNT];
int cnt;
} Record;
Employee* do_add_employee(char *n)
{
Record* this_record = (Record*)this;
assert(this_record->cnt < MAX_EMPLOYEE_COUNT);
this_record->employees[this_record->cnt].set_salary = do_set_salary;
this_record->employees[this_record->cnt].set_employee_id =
do_set_employee_id;
this_record->employees[this_record->cnt].name = n;
this = &this_record->employees[this_record->cnt];
this_record->cnt++;
return this;
}
void init_record(Record* r)
{
r->cnt = 0;
r->add_employee = do_add_employee;
}
Record* edit(Record* r)
{
this = r;
return r;
}
void print_record(Record* r)
{
int i;
for (i = 0; i < r->cnt; i++) {
printf("%s, salary %d, id %d\n",
r->employees[i].name,
r->employees[i].salary,
r->employees[i].employee_id);
}
}
int main(void)
{
Record record;
init_record(&record);
/* behold, fluent interface design! */
edit(&record)->
add_employee("Alice")->
set_salary(1500)->
set_employee_id(10201);
edit(&record)->
add_employee("Bob")->
set_salary(2000)->
set_employee_id(10202);
print_record(&record);
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-24T14:46:02.073",
"Id": "9719",
"Score": "3",
"body": "The point of fluent is to make the code more readable. This fails on that account. It would be more readable just to use normal methods in this situation (rather than chaining)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-24T16:26:50.060",
"Id": "9720",
"Score": "2",
"body": "I'd also add that fluency often drops the verb (`add`, `set`, etc.) , or turns it into something more \"human\" (`with`, `having`, etc.) One of the points is to make it *sound* \"right\"."
}
] |
[
{
"body": "<p>I would drop the <code>edit</code> function and make <code>add_employee</code> the entry point to the API. I've written a number of fluent APIs in C++ and found that placing the required arguments (e.g., employee name) in the API entry point invaluable. From the usage point of view, something like:</p>\n\n<pre><code>int main(void) {\n Record db;\n init_record(&db);\n add_employee_to(&db, \"Bob\")\n ->having_salary(2000)\n ->with_id(10202);\n return 0;\n}\n</code></pre>\n\n<p>The goal of the API is to create a new employee and append them, so make that the entry point. If you can't have a valid employee record with a name, then this becomes a first-class parameter of the entry point. Not sure about the requirements, so it may make sense for ID to be a required parameter as well. I also changed the names to make them <em>More Fluent™</em>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-25T14:48:15.733",
"Id": "6291",
"ParentId": "6254",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "6291",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-24T14:07:17.440",
"Id": "6254",
"Score": "8",
"Tags": [
"c",
"database",
"fluent-interface"
],
"Title": "Fluent interface for manipulating employee records"
}
|
6254
|
<p>I have a piece of code that takes a couple of integers and check if performing an addition on the inputs would result in an overflow.</p>
<p>I was wondering if this code is SOLID:</p>
<pre><code>public static boolean CanAdd(int me, int... args) {
int total = me;
for (int arg : args) {
if (total >= 0) {
if (java.lang.Integer.MAX_VALUE - total >= arg) { // since total is positive, (MaxValue - total) will never overflow
total += arg;
} else {
return false;
}
} else {
if (java.lang.Integer.MIN_VALUE- total <= arg) { // same logic as above
total += arg;
} else {
return false;
}
}
}
return true;
}
</code></pre>
<p>Does anyone have a better (faster) way to achieve the same thing?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-24T19:08:54.340",
"Id": "9728",
"Score": "1",
"body": "Have you done any profiling which showed that this method is a bottleneck in your application?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-24T20:30:34.560",
"Id": "9731",
"Score": "1",
"body": "@palacsint no this isn't a bottleneck in my application.. just that I'm interested in algorithms related to range checking and was wondering if there's a better solution (besides the casting one) =)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-24T22:18:34.017",
"Id": "9734",
"Score": "0",
"body": "I have seen some (usually C/C++) questions and answers on SO with nice bitwise code, maybe you want to check them :-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-28T23:56:17.963",
"Id": "13148",
"Score": "0",
"body": "I don't know your ultimate purpose, but depending on what you are trying to accomplish, perhaps, you might find Guava's checked arithmetic useful. Note this is not actually a direct response to your query. http://code.google.com/p/guava-libraries/wiki/MathExplained"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-19T03:14:26.367",
"Id": "401533",
"Score": "0",
"body": "Speaking of checked arithmetic - Java8+ now has that in its Math class (you can see my other answer here about Java8+)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T16:05:24.347",
"Id": "520916",
"Score": "0",
"body": "SOLID principles generally apply to classes (generally: types) and their interactions, not to a single function like this."
}
] |
[
{
"body": "<p>I haven't found any input which isn't handled well by your code. Here are some tests:</p>\n\n<pre><code>assertTrue(CanAdd(0, Integer.MAX_VALUE));\nassertTrue(CanAdd(0, Integer.MIN_VALUE));\nassertTrue(CanAdd(Integer.MIN_VALUE, 0));\nassertTrue(CanAdd(-1, Integer.MAX_VALUE));\nassertFalse(CanAdd(1, Integer.MAX_VALUE));\nassertFalse(CanAdd(-1, Integer.MIN_VALUE));\n</code></pre>\n\n<p>So, it works but it isn't an easy task to read it. If this isn't a bottleneck in an application I would use a <code>long</code>:</p>\n\n<pre><code>public static boolean canAdd(int... values) {\n long sum = 0;\n for (final int value: values) {\n sum += value;\n if (sum > Integer.MAX_VALUE) {\n return false;\n }\n if (sum < Integer.MIN_VALUE) {\n return false;\n }\n }\n return true;\n}\n</code></pre>\n\n<p>I think it's easier to read and maintain.</p>\n\n<p>Finally, a note: according to <a href=\"http://www.oracle.com/technetwork/java/codeconventions-135099.html#367\" rel=\"noreferrer\">Code Conventions for the Java Programming Language</a> the name of your method should be <code>canAdd</code> (with lowercase first letter).</p>\n\n<blockquote>\n <p>Methods should be verbs, in mixed case with the first letter\n lowercase, with the first letter of each internal word capitalized.</p>\n</blockquote>\n\n<p><strong>Edit:</strong></p>\n\n<p><a href=\"http://commons.apache.org/proper/commons-math/\" rel=\"noreferrer\">Apache Commons Math</a> also uses <a href=\"http://svn.apache.org/viewvc/commons/proper/math/trunk/src/main/java/org/apache/commons/math3/util/ArithmeticUtils.java?view=markup#l40\" rel=\"noreferrer\">long conversion</a>:</p>\n\n<pre><code>public static int addAndCheck(int x, int y)\n throws MathArithmeticException {\n long s = (long)x + (long)y;\n if (s < Integer.MIN_VALUE || s > Integer.MAX_VALUE) {\n throw new MathArithmeticException(LocalizedFormats.OVERFLOW_IN_ADDITION, x, y);\n }\n return (int)s;\n} \n</code></pre>\n\n<p>As well as <a href=\"https://code.google.com/p/guava-libraries/source/browse/guava/src/com/google/common/math/IntMath.java#409\" rel=\"noreferrer\">Guava</a>:</p>\n\n<pre><code>public static int checkedAdd(int a, int b) {\n long result = (long) a + b;\n checkNoOverflow(result == (int) result);\n return (int) result;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-11T20:30:06.307",
"Id": "400435",
"Score": "0",
"body": "This Answer is valid, but fwiw, other Answer by Todd Lehman seems to be even less lines of code. But this is still a good Answer :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-13T21:56:11.347",
"Id": "400708",
"Score": "1",
"body": "Thank you for including the illuminating examples of how Apache & Guava also use long-conversion. I think its helpful to not that they accept *exactly 2 int params*, which I think precludes any possibility of *long-overflow* - attempting to sum more than 2 params starts down the path pf possibly reaching long-overflow... However I believe Answers like this implicitly account for long-overflow, by them having an \"early out\" loop/method exit of the Integer-size check (within each loop iteration)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-14T01:18:50.150",
"Id": "400724",
"Score": "1",
"body": "@cellepo: Thanks! Yeah, an explicit `values.length` check would help reasoning here. Just for fun, you need an array with at least `(Long.MAX_VALUE / Integer.MAX_VALUE) = (2^63−1) / (2^31−1) = 4294967298` int elements to overflow the `long sum` variable. This 4294967298 is the double of the possible maximal array length in Java :-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-19T03:02:59.860",
"Id": "401531",
"Score": "0",
"body": "@ palacsint ah good point with that math analysis (thanks!) - I think it infers that the long-overflow I mentioned is actually not possible, because even an array of max size completely-filled with `MAX_VALUE` instances would not be enough to long-overflow the sum."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-19T03:09:49.977",
"Id": "401532",
"Score": "1",
"body": "So maybe I was getting too theoretical :) At least for arrays on a JVM - I think long-overflow could still happen with a Collection that can hold sufficiently-more (if such a Collection exists), a custom Object (like a manual/custom linked list data structure), or in math analysis involving max-sizes for number types. But again, getting a bit theoretical (especially with the last Math analysis I just mentioned) ... :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-19T03:24:48.433",
"Id": "401535",
"Score": "0",
"body": "Sorry if this ended up being a trivial rabbit hole."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-19T14:49:19.003",
"Id": "401590",
"Score": "0",
"body": "It was fun for me :-)"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-24T19:13:11.627",
"Id": "6262",
"ParentId": "6255",
"Score": "21"
}
},
{
"body": "<p>Your logic looks solid to me. It's subtle, though.</p>\n\n<p>Here is another version using <code>long</code>, but with much simpler logic:</p>\n\n<pre><code>public static boolean canAdd(int... values) {\n long longSum = 0;\n int intSum = 0;\n for (final int value: values) {\n intSum += value;\n longSum += value;\n }\n return intSum == longSum;\n}\n</code></pre>\n\n<p>That's the most straightforward way I can think to write it. Note that there is no \"early out\" in this loop, meaning it will always run to the end of the list. However, not having any conditionals, it's likely to be faster in many cases, if that matters.</p>\n\n<p>(6 years later) Here is an updated version inspired by user 'cellepo' that stops as soon as it detects overflow, in order to avoid false positives (possible in the earlier version if the list of values was in the billions):</p>\n\n<pre><code>public static boolean canAdd(int... values) {\n long longSum = 0;\n int intSum = 0;\n for (final int value: values) {\n intSum += value;\n longSum += value;\n if (intSum != longSum)\n return false;\n }\n return true;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-13T21:22:15.563",
"Id": "400701",
"Score": "1",
"body": "It is possible that longSum could ALSO overflow (at least eventually, when therefore after intSum had to also overflow prior). However, I'm not sure if it is possible (in a case of both overflowing) if it could end up that `intSum == longSum` ends up returning a false positive (of `true`)? In other words, could `intSum` overflow & `longSum` _overflow_ values (within the same `canAdd` call) ever end up being equal (therefore invalidly returning `true`)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-13T22:09:31.697",
"Id": "400712",
"Score": "1",
"body": "If my above comment is accurate about the false-positive possibility, then I think that is then an [invalidating] consequence of there being no \"early out\" as mentioned in this Answer. (Some other Answers here do have an \"early out\" btw)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-13T22:18:09.917",
"Id": "400713",
"Score": "1",
"body": "fwiw, my comments on this Answer are not intended as personal criticism, but rather as constructive critique (and I might be wrong about my skepticism). This was otherwise my favorite Answer a few days prior [when I upvoted this!], and led me to my other Answer here (containing \"food-for-thought\") - however if my skepticism is correct, then that other Answer of mine also suffers from the same long-overflow without \"early out\" (and is noted there as such). Regardless of if my skepticism is correct, I still appreciate this Answer for its other illuminating qualities :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-14T18:33:20.373",
"Id": "400881",
"Score": "1",
"body": "@cellepo — Thanks! Your skepticism is correct! If the length of the list is in the billions (2^32 or more, I believe) then some combination of input *could* provide false positives if the 31-bit positive `int` values sum to a value large enough to exceed the 63-bit positive value of a `long`. I've added a second version that avoids this shortcoming by exiting immediately upon detecting any `int` overflow."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-19T03:24:17.610",
"Id": "401534",
"Score": "1",
"body": "Yep, 2nd version's simple check would account for long-overflow! However maybe I should apologize for getting too theoretical: I think I recently realized, with insight from @ palacsint on comments in their Answer, that an array's max-capacity would actually preclude ever reaching long-overflow (at least on a JVM) - see comment discussion on that other Answer for more details. (Sorry if this ended up being a trivial rabbit hole)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-19T17:52:07.080",
"Id": "401619",
"Score": "1",
"body": "@cellepo — I think it's an important question! Thanks for asking it. Even if the capacity is the limiting factor, at least the second version can early-out of the loop if the values cause overflow early in the sequence...whereas the first version always loops over all the values unconditionally."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2012-01-30T00:11:29.987",
"Id": "8439",
"ParentId": "6255",
"Score": "4"
}
},
{
"body": "<p>About the current code:</p>\n\n<ul>\n<li>I'd rename <code>CanAdd</code> to <code>canAdd</code> (according to the coding conventions).</li>\n<li>Rename <code>me</code> to <code>value</code> (it's more descriptive), and <code>args</code> to <code>values</code> and <code>arg</code> to <code>currentValue</code>.</li>\n<li>Remove the unnecessary <code>java.lang</code> package prefix.</li>\n</ul>\n\n \n\n<pre><code>public static boolean canAdd(int value, int... values) {\n int total = value;\n for (int currentValue: values) {\n if (total >= 0) {\n // since total is positive, (MaxValue - total) will never\n // overflow\n if (Integer.MAX_VALUE - total >= currentValue) {\n total += currentValue;\n } else {\n return false;\n }\n } else {\n // same logic as above\n if (Integer.MIN_VALUE - total <= currentValue) {\n total += currentValue;\n } else {\n return false;\n }\n }\n }\n return true;\n}\n</code></pre>\n\n<p>I have also moved the comments a line up to avoid horizontal scrolling.</p>\n\n<p>I don't really like the <code>value</code> and <code>values</code> here so I've changed the first two lines a little bit:</p>\n\n<pre><code>public static boolean canAdd(int... values) {\n int total = 0;\n ...\n}\n</code></pre>\n\n<p>If you invert the inner <code>if</code> statements you could eliminate the <code>else</code> keywords:</p>\n\n<pre><code>if (total >= 0) {\n if (Integer.MAX_VALUE - total < currentValue) {\n return false;\n }\n total += currentValue;\n} else {\n if (Integer.MIN_VALUE - total > currentValue) {\n return false;\n }\n total += currentValue;\n}\n</code></pre>\n\n<p>The <code>+=</code> is the same in both branches therefore it could be moved after the <code>if</code>:</p>\n\n<pre><code>if (total >= 0) {\n if (Integer.MAX_VALUE - total < currentValue) {\n return false;\n }\n} else {\n if (Integer.MIN_VALUE - total > currentValue) {\n return false;\n }\n}\ntotal += currentValue;\n</code></pre>\n\n<p>Introducing a explanatory <code>boolean</code> variable could make it shorter and save an indentation level:</p>\n\n<pre><code> public static boolean canAdd(int... values) {\n int total = 0;\n for (int currentValue: values) {\n final boolean positiveTotal = total >= 0;\n if (positiveTotal && (Integer.MAX_VALUE - total < currentValue)) {\n return false;\n }\n if (!positiveTotal && (Integer.MIN_VALUE - total > currentValue)) {\n return false;\n }\n total += currentValue;\n }\n return true;\n}\n</code></pre>\n\n<p>But I think it's still hard to understand. I'd go with <code>long</code> conversion.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T19:57:10.837",
"Id": "42803",
"ParentId": "6255",
"Score": "5"
}
},
{
"body": "<p>[<strong>note</strong>: This is more of a \"food-for-thought\" Answer, since I ended up realizing it could actually be invalid when called with enough <code>args</code> to cause <code>long</code>-overflow... but I thought this might still be worth posting to show other possibilities with <code>long</code>...]</p>\n\n<p>This is not <em>asymptotically</em> faster (still linear O(|args|) like in the Question), but is many less lines of body code (3), and is <em>trivially</em> faster due to only 1 logic/if-check:</p>\n\n<pre><code>public static boolean canSumToInt(long... args){\n long sum = 0;\n for(long curLong: args) sum += curLong;\n return Integer.MIN_VALUE <= sum && sum <= Integer.MAX_VALUE;\n}\n</code></pre>\n\n<ul>\n<li>Can even still call this with <code>int</code>-type args, because of numeric promotion of [smaller data type] <code>int</code> -> [larger data type] <code>long</code> (actual numeric value ends ups the same)</li>\n<li>I don't see why you would need a separate/additional/distinct <code>me</code> parameter - you can just make <code>me</code> the first value in <code>args</code></li>\n<li>The technically possible invalidity I mentioned however, is that the loop-summing could reach a point where there is <code>long</code>-overflow (which would go \"undetected\") with sufficiently-large-magnitude individual <code>args</code> or sufficiently-many <code>args</code> - and that overflowed sum could end up being <code>int</code>-type-magnitude, which would return a false-positive [of <code>true</code>]</li>\n</ul>\n\n<p>However you could even save 1 more line of code by re-introducing additional <code>me</code> parameter:</p>\n\n<pre><code>public static boolean canSumToInt(long me, long... args){\n for(long curLong: args) me += curLong;\n return Integer.MIN_VALUE <= me && me <= Integer.MAX_VALUE;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-12T02:38:39.457",
"Id": "400449",
"Score": "0",
"body": "If Java 8, you should see my other Answer on this page."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-13T22:03:04.593",
"Id": "400710",
"Score": "0",
"body": "If not Java8+, and you want/need to account for long-overflow, improving this Answer as such would essentially arrive at other Answers here that use an \"early out\" loop/method exit of an Integer-size check (within each loop iteration) - so use one of those Answers :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-19T03:33:57.960",
"Id": "401536",
"Score": "0",
"body": "fwiw - if `args` were `int` (instead of `long`), the long-overflow possibility would then be precluded (on a JVM at least, due to max-capacity of an array) - see comments on other Answer here by @ palacsint for more discussion."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-11T21:18:31.830",
"Id": "207444",
"ParentId": "6255",
"Score": "2"
}
},
{
"body": "<p>All other Answers here (as of this writing) are valid.\nBut if you are <strong>Java 8+</strong>, you probably would want to be even more precise with Java 8+'s <a href=\"https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#addExact-int-int-\" rel=\"nofollow noreferrer\"><code>Math.addExact(int, int)</code></a>:</p>\n\n<pre><code>public static boolean canSumToInt(int me, int... args){\n for(int curArg: args){\n try{\n me = Math.addExact(me, curArg);\n }catch(ArithmeticException ae){\n return false;\n }\n }\n return true;\n}\n</code></pre>\n\n<p><strong>Overflow would throw</strong> <code>ArithmeticException</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-12T18:33:54.853",
"Id": "400553",
"Score": "0",
"body": "It might be more readable (and exactly equivalent in speed) to have the `try`/`catch` outside the loop. I.e. `try { for (int curArg: args) me = Math.addExact(me, curArg); return true; } catch(ArithmeticException ae) { return false; }`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-13T20:26:35.017",
"Id": "400689",
"Score": "0",
"body": "Yes that's a valid alternative. I personally like mine better, as I prefer a try block to be as close/limited to the actual line(s)/call(s) that could be the source of Exception - rather than the try encompassing the loop/guard itself also, where the loop/guard would never throw the Exception. Limiting the try block as I prefer, to me, is more readable as the limiting makes it more clear/specific where the Exception source could be (helps de-bugging too). Toby Speight alternative is also valid & I'm not criticizing it (just clarifying my personal preference in the context of alternative)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-11-12T02:37:39.273",
"Id": "207458",
"ParentId": "6255",
"Score": "6"
}
},
{
"body": "<p>The code is correct from a realistic point of view but implements a stricter criterion than actually stated. Consider e.g.:</p>\n<p>2147483647 + 2147483647 + (-2147483648) + (-2147483648)</p>\n<p>Here, the result could be a "solid" -2 but CanAdd rejects it nevertheless. As such, the code does not satisfy its requirements (but, in this case, I'd almost certainly adjust the requirements instead of the code ;-).</p>\n<p>On a more practical note: simply performing each addition (regardless of overflows), followed by a check if the sign of the result is as expected could marginally improve performance (it suffices to check that at least one argument has the same sign as that of the result, which can be done using trivial bit-wise operations - e.g. <code>(a ^ c) & (b ^ c) >= 0</code>, where <code>a</code> and <code>b</code> are the arguments and <code>c</code> is the result).</p>\n<p>PS: if (and that's a big if) the code may not yield false negatives even in cases such as in the "-2" example, it'd be better to keep track of the difference <code>d</code> between the number of overflows (positive → negative) and the number of underflows (negative → positive), e.g. by <code>if ((a ^ c) & (b ^ c) < 0) d += c < 0 ? -1 : 1;</code>. CanAdd should then <code>return d == 0</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T15:36:08.000",
"Id": "520907",
"Score": "0",
"body": "Actually, if the arguments have different sign, no check is needed, so we possibly get a faster path there."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T15:42:05.953",
"Id": "520908",
"Score": "0",
"body": "Re-ordering addition for the example you show is not prohibitively difficult. At every step, if we can find value of opposite sign to the running total, add that value next. Otherwise add and check the same-sign values available. Some impact on speed, though that could be mitigated with a bit of thought."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T15:43:52.900",
"Id": "520909",
"Score": "0",
"body": "If the arguments have different signs, the result will be indeed be valid and no check needs to be done afterwards. But the only way to know if that's the case is to check for different signs at the start, which defeats the purpose of micro-optimization (since the scenario of equals signs still needs to be checked afterwards in the other case)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T15:49:18.237",
"Id": "520912",
"Score": "0",
"body": "I agree that the reordering is easy, but it's still O(number of arguments). I'm guessing that that's not within the scope of the unstated requirements (i.e. that CanAdd should be as fast as possible)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T15:50:57.367",
"Id": "520913",
"Score": "0",
"body": "I was thinking that my observation simplifies \"_at least one argument has the same sign as that of the result_\" down to \"_either the arguments have different signs or the first argument has the same sign as the result_\". Unless you know a different way to test the two arguments simultaneously with the result?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T15:53:59.260",
"Id": "520915",
"Score": "1",
"body": "Still should probably become a chat, but FYI here's the simultaneous check : (a ^ c) & (b ^ c) < 0, where a and b are the arguments and c is the result."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T15:32:53.437",
"Id": "263811",
"ParentId": "6255",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-24T15:41:56.477",
"Id": "6255",
"Score": "33",
"Tags": [
"java",
"performance",
"integer"
],
"Title": "Int overflow check in Java"
}
|
6255
|
<p>I wrote a quicksort program in C++.</p>
<ol>
<li>Is it okay to implement it this way?</li>
<li>Am I using pointers correctly?</li>
<li>Is my style okay?</li>
<li>Any ideas to speed it up or save memory?</li>
</ol>
<p> </p>
<pre><code>void change(int *i, int *j)
{
int temp = *j;
*j = *i;
*i = temp;
}
int *toplace(int *start, int *end)
{
int *i = start+1, *j= end;
while(i<=j)
{
for(; *i<=*start && i<=end; i++);
for(; *j>=*start && start+1<=j; j--);
if (i<j) change(i++,j--);
}
change(start,i-1);
return i-1;
}
void quicksort(int *start, int *end)
{
if (start >= end) return;
for(int *debug = start;debug<=end;debug++) std::cout<<*debug <<" ";
std::cout<<std::endl; //this and...
int *temp = start;
temp = toplace(start,end);
for(int *debug = start;debug<=end;debug++) std::cout<<*debug <<" ";
std::cout<<std::endl; //...this are only to "see under the hood"
std::cout<<std::endl;
quicksort(start,temp-1);
quicksort(temp+1,end);
}
</code></pre>
<p>An example usage:</p>
<pre><code>int main(int argc, char* argv[])
{
int A[] = {5,14,8,12,1,2,11,15,6,9,7,3,13,4,10};
int n = sizeof (A) / sizeof(A[0]);
quicksort(A, &A[n-1]);
for (int i =0; i<n; i++) std::cout<<A[i] <<" ";
getchar();
return 0;
}
</code></pre>
<p>produces the output:</p>
<pre><code>5 14 8 12 1 2 11 15 6 9 7 3 13 4 10
1 4 3 2 5 12 11 15 6 9 7 8 13 14 10
1 4 3 2
1 4 3 2
4 3 2
2 3 4
2 3
2 3
12 11 15 6 9 7 8 13 14 10
8 11 10 6 9 7 12 13 14 15
8 11 10 6 9 7
6 7 8 10 9 11
6 7
6 7
10 9 11
9 10 11
13 14 15
13 14 15
14 15
14 15
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-24T16:06:46.363",
"Id": "9721",
"Score": "0",
"body": "I don't see any pointer issues. Nice work!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-24T16:10:48.407",
"Id": "9722",
"Score": "0",
"body": "Or you have wrong copy-paste or 2nd test from the top is failed."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-24T16:10:53.960",
"Id": "9723",
"Score": "1",
"body": "@Caleb - me too. Except I could not find that site on the list which appeared, so I just flagged it as offtopic. Can you somehow get it on that list?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-24T16:27:28.383",
"Id": "9724",
"Score": "0",
"body": "@Vilx, when you flag you can use the 'needs moderator attention' option and type a comment in the box suggesting migration to a different site."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-24T17:15:57.480",
"Id": "9726",
"Score": "2",
"body": "Not really C++ is it!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-24T20:12:21.297",
"Id": "9729",
"Score": "0",
"body": "@Loki Astari: hey, there's `cout`!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-25T00:41:40.667",
"Id": "9740",
"Score": "0",
"body": "@VioletGiraffe: Writing C and compiling with a C++ compiler does not make it C++. The style of the two languages is completely different. This is indicative of C style not C++."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-25T06:01:13.950",
"Id": "9744",
"Score": "0",
"body": "@Loki Astari: I understand what you're saying, but, on the other hand, if your program manipulates pointers and doesn't use classes, what can you do to make it more C++-style?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-25T19:27:20.203",
"Id": "9771",
"Score": "0",
"body": "@VioletGiraffe: But this problem is not about manipulating pointers. Its about sorting. The fact that he is using pointers (not iterators) for the sorting. He is using pointers (not references) for swapping."
}
] |
[
{
"body": "<p>The interface to quicksort:</p>\n\n<pre><code>quicksort(A, &A[n-1]);\n</code></pre>\n\n<p>In C I would expect to see a pointer and a size.<br>\nIn C++ I would expect to see two iterators (like above), but generally the end point is usually one past the end (if you want to be consistent with C++ idioms and the STL way of doing things).</p>\n\n<pre><code>quicksort(A, A+n); // This is what I would expect to see.\n</code></pre>\n\n<p>Change!<br>\nI would normally call this swap()</p>\n\n<pre><code>void change(int *i, int *j)\n{\n int temp = *j;\n *j = *i;\n *i = temp;\n}\n</code></pre>\n\n<p>Also in C++ I would pass the values to be swapped by reference. And there is already a std::swap() that works perfectly well.</p>\n\n<p>Your for() loops that do nothing in the body.</p>\n\n<pre><code>for(; *i<=*start && i<=end; i++);\n</code></pre>\n\n<p>These are hard to read when doing maintenance. At first glance it looks like you accidentally did not indent the code correctly you need to study the code to understand it is correct. I find it best to put an empty body (maybe even with a comment /* Deliberately Empty */</p>\n\n<pre><code>for(; *i<=*start && i<=end; i++) { /* Empty */ }\n</code></pre>\n\n<p>In your loops you are testing the loop variable against start and end. Should they not be tested against each other?</p>\n\n<pre><code>while(i<=j)\n{\nfor(; *i<=*start && i<=end; i++);\nfor(; *j>=*start && start+1<=j; j--); \n\n// Should be:\n\nfor(; *i<=*start && i <= j; i++) { /* Empty */ }\nfor(; *j>=*start && i <= j; j--) { /* Empty */ }\n</code></pre>\n\n<p>Your quick sort seems to work but is slightly non traditional in a couple of features.</p>\n\n<p>The pivot point <code>*start</code>. Values that are equal seem to go into both sub buckets. Traditionally they would go into a specific bucket.</p>\n\n<p>You always use the first element as the pivot point. This case leads to worst case behavior of quicksort when the list is already sorted. Either choose a random element or the one in the middle of the partition.</p>\n\n<p>Currently your code works with pointers to integers. But really you are using pointers as iterators. So you should templatize it so the inputs are not pointers but are generic iterators this then allows you to use the algorithm on any container type (with the side affect that it works with any type that implements the <= operator.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-25T02:04:22.177",
"Id": "9741",
"Score": "1",
"body": "I'd refactor these for loops to `while(*i<=*start && i<=end) i++;` and `while(*j>=*start && start+1<=j) j--;`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-25T09:20:03.193",
"Id": "9756",
"Score": "0",
"body": "Thank you @Loki Astari! Really appreciated. That was what I expected."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-24T17:50:46.827",
"Id": "6259",
"ParentId": "6257",
"Score": "10"
}
},
{
"body": "<p>First of all there's already a <code>std::sort</code> function in the standard library. If you're aware of this and just wrote this as a learning exercise that's fine, but if you actually want to use this code in production, there's no reason not to use <code>std::sort</code> instead. That being said, here's a review of your code:</p>\n\n<hr>\n\n<h3>Efficiency</h3>\n\n<p>One important thing to note about your algorithm is that you're using the first element of the array as the pivot element. This is quite inefficient if you're sorting an array that is already partially sorted (leading to a quadratic runtime). You should use a random element instead.</p>\n\n<p>Other than that I don't see any inefficiencies in your code.</p>\n\n<hr>\n\n<h3>Genericity</h3>\n\n<p>Currently your code only works on arrays of ints. This is bad because there's no reason you shouldn't be able to use a) anything that is comparable using <code><</code>,<code>></code> etc. instead of ints and b) other collections like for example <code>vector</code>s instead of arrays. If you turn your functions into template functions, you can easily achieve this simply by replacing all occurrences of <code>int*</code> with a template argument.</p>\n\n<p>You could further generalize your sorting function by using an optional comparator argument like <code>std::sort</code> does.</p>\n\n<hr>\n\n<h3>Code readability and general good practices</h3>\n\n<p>I'd rename your <code>change</code> function to <code>swap</code> because that's what this function is usually called and the name <code>change</code> doesn't really give a good idea of what the function does. I'd also change it to use references instead of pointers because it's good practice to avoid using pointers if you don't need them. And again: if you didn't just re-implement this as a learning exercise, use <code>std::swap</code> instead of building your own (which does the same thing).</p>\n\n<p>In your sort function you should rename <code>temp</code> to something more descriptive because the name contains absolutely no information.</p>\n\n<p>Also all the print statements makes your code hard to follow. I'd remove them and use a debugger when I need to debug the code instead.</p>\n\n<p>A couple of comments couldn't hurt either.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-25T10:08:10.883",
"Id": "9758",
"Score": "0",
"body": "Thank you! I will take a look on std::sort(). I actually created this to learn c++. I already new the algorithm from school (class: algorithm design and analysis). Now I changed using the first element as pivot element to use the one in the middle. Thank you for good comment."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-24T17:53:54.963",
"Id": "6260",
"ParentId": "6257",
"Score": "10"
}
}
] |
{
"AcceptedAnswerId": "6259",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-24T16:04:39.063",
"Id": "6257",
"Score": "15",
"Tags": [
"c++",
"homework",
"sorting",
"quick-sort"
],
"Title": "Is this C++ quicksort program okay?"
}
|
6257
|
<p>I did not get the job after submitting this piece of work in an interview, but I have no feedback to know what "BAD" things are inside this block of code.</p>
<p>The requirements are:</p>
<blockquote>
<ul>
<li>Connect to the server on a known port and IP </li>
<li>Asynchronously send a message to the server in your choice of format </li>
<li>Calculate and display the round trip time for each message and the average round trip time for all messages sent</li>
</ul>
</blockquote>
<p>The solution should not be so hard. But I just don't know what's wrong? Bad design? Bad naming? Bad practise?</p>
<pre><code>import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.UnknownHostException;
public class EchoClient {
private String hostname;
private int port;
private Socket clientSocket;
private BufferedReader inFromUser, inFromServer;
private DataOutputStream outToServer;
private double averageTime = 0;
private int count = 0;
public EchoClient(String hostname, int port){
this.hostname = hostname;
this.port = port;
try {
this.clientSocket = new Socket(this.hostname, this.port);
} catch (UnknownHostException e) {
System.out.println("Connection Error: unknown host");
System.exit(1);
} catch (IOException e) {
System.out.println("Connection Error: connection refused");
System.exit(1);
}
try{
this.inFromUser = new BufferedReader( new InputStreamReader(System.in));
this.outToServer = new DataOutputStream(this.clientSocket.getOutputStream());
this.inFromServer = new BufferedReader(
new InputStreamReader(this.clientSocket.getInputStream()));
} catch (IOException e) {
System.out.println("Error on Initializing echoclient");
System.exit(1);
}
}
public void start(){
System.out.println("Connecting to " + hostname + " with port No " + port);
String msgSend;
try {
while ((msgSend = inFromUser.readLine()) != null){
// sendMessage asynchronous
sendMessage(msgSend, new Callback(){
// callback function and calculate the average time
public void callback(long timeUsed, String msgReceived){
averageTime = (count * averageTime + (timeUsed)) / (count + 1);
++count;
System.out.println(msgReceived +
" rtt=" + (double)Math.round(timeUsed * 100)/100 + " ms" +
" artt=" + (double)Math.round(averageTime * 100)/100 + " ms");
}
});
}
} catch (IOException e) {
System.out.println("Error on reading message from user");
}
}
private void sendMessage(String message, Callback cb){
Thread sendMessageThread = new Thread(new SendMessageRequest(message, cb));
sendMessageThread.start();
}
interface Callback {
public void callback(long time, String msg);
}
class SendMessageRequest implements Runnable{
private String message;
private Callback cb;
SendMessageRequest(String message, Callback cb){
this.message = message;
this.cb = cb;
}
@Override
public void run() {
String msgReceived;
long timeStart, timeEnd, timeUsed;
try {
timeStart = System.nanoTime();
outToServer.writeBytes(this.message + '\n');
msgReceived = inFromServer.readLine();
timeEnd = System.nanoTime();
// Calculate the time and get the output
timeUsed = (timeEnd - timeStart) / 1000000;
cb.callback(timeUsed, msgReceived);
} catch (IOException e) {
System.out.println("Error on sending message to server");
}
}
}
public static void showUsage(){
System.out.println("Usage: java EchoClient [hostname] [portNo]");
}
/**
* Entry of the program
*/
public static void main(String[] args) {
String hostname = "";
int port = 0;
if (args.length < 2){
showUsage();
System.exit(0);
}
else{
hostname = args[0];
port = Integer.parseInt(args[1]);
}
EchoClient client = new EchoClient(hostname, port);
client.start();
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-24T21:53:10.880",
"Id": "9732",
"Score": "9",
"body": "Any company that doesn't provide feedback on a candidate's assignment is a company that wouldn't be worth working for."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-25T02:23:45.303",
"Id": "9742",
"Score": "10",
"body": "@Rontologist I disagree. First of all, a company would never send a résumé back with feedback, so why should they do it for a code review? It would require the reviewer to spend time annotating reviews for what may be several candidates, and ultimately his decision may come down to preferring someone's code style over another's. Making such a statement on paper would be confrontational at best."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-25T18:19:28.067",
"Id": "9770",
"Score": "2",
"body": "@kojiro A resume is not solicited work and does not belong in the same category. I am of the opinion that if I ask a candidate to do any work (and to create a good source package that is polished with unit tests, etc) than I as an interviewer should be prepared to contact that person and let him know the results, even it if is just high level notes. If there are so many samples that doing that takes too long than you didn't shortlist good enough. Also a code review need not be confrontational (Most people I've phoned with rejections were happy to be given feedback) but can be constructive."
}
] |
[
{
"body": "<p>I think the biggest problem is the lack of synchronization. You modify the <code>averageTime</code> and <code>count</code> variables in the callback which runs concurrently. You should synchronize the access of this variables. There is a good book on this topic: <a href=\"http://jcip.net/\">Read the Java Concurrency in Practice</a>, if you have time read it, it's very useful.</p>\n\n<p>Some other things:</p>\n\n<ol>\n<li><p>I don't like inner classes. Reference: <em>Effective Java Second Edition, Item 22: Favor static member classes over.</em>\nI would also create an <code>EchoClientMain</code> class which contains the <code>main</code> method and parse the command line parameters. Furthermore, I'd move out to a new file the <code>Callback</code> anonymous inner class and I'd create a <code>Statistics</code> class which would be responsible to calculate and maintain the stats. (Check <a href=\"http://en.wikipedia.org/wiki/Single_responsibility_principle\">Single responsibility principle on Wikipedia</a>.)</p></li>\n<li><p>Instead of <code>System.exit()</code> you should rethrow the exceptions. This class is not reusable since a simple error stops the whole application. Just create a custom exception class and throw it:</p>\n\n<pre><code>try {\n this.clientSocket = new Socket(this.hostname, this.port);\n} catch (final UnknownHostException uhe) {\n throw new EchoClientException(\"Connection Error: unknown host\", uhe);\n}\n</code></pre>\n\n<p>Let the caller to handle them. In this case the <code>main</code> method should catch the <code>EchoClientException</code> and print its message to the console.</p>\n\n<pre><code>try {\n EchoClient client = new EchoClient(hostname, port);\n client.start();\n} catch (final EchoClientException ece) {\n System.err.println(ece.getMessage());\n}\n</code></pre></li>\n<li><p>You should <em>NOT</em> connect to the server in the constructor. I'd do it in the <code>start()</code> method.</p></li>\n<li><p>Close the resources. Create a <code>stop()</code> method which close the opened streams.</p></li>\n<li><p>Check at least for <code>null</code> input parameters: <em>Effective Java, Item 38: Check parameters for validity</em></p></li>\n</ol>\n\n<p><em>Clean Code by Robert C. Martin</em> is also worth reading.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-24T19:50:59.663",
"Id": "6263",
"ParentId": "6258",
"Score": "22"
}
},
{
"body": "<p>I wonder if when they asked for you to send the message asynchronously, they did not want you to launch a second thread. Your second thread does its processing synchronously. Yes its off on another thread, but that may or may not be what they meant by asynchronous. Something like the library here does: <a href=\"https://github.com/sonatype/async-http-client\">https://github.com/sonatype/async-http-client</a>.</p>\n\n<p>As palacsint points out, you haven't synchronized the variables. That my have made it look like you didn't know what you were doing.</p>\n\n<p>The other thing I don't like is that way you handle errors. I'd shut down the application if an error occours, not write it to standard error and try to keep going. I'd also want to display more information about the error, not the simple fact that it happened.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-24T20:25:10.603",
"Id": "6265",
"ParentId": "6258",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "6263",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-24T17:21:42.457",
"Id": "6258",
"Score": "36",
"Tags": [
"java",
"multithreading",
"interview-questions",
"asynchronous",
"callback"
],
"Title": "Asynchronous network callback code"
}
|
6258
|
<p>I am just trying to use ASP.NET MVC using repository pattern. Am I doing something wrong here?</p>
<p><strong>Model</strong> - Contains the model</p>
<pre><code>public class Contact
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string EmailAddress { get; set; }
}
</code></pre>
<p><strong>Repository interface</strong> - Interface</p>
<pre><code>public interface IContactRepository
{
void Create(Contact contact);
void Delete(int contactId);
void Save(Contact contact);
Contact Retrieve(int contactId);
IEnumerable<Contact> Select();
}
</code></pre>
<p><strong>Repository class</strong></p>
<pre><code>public class ContactRepository : IContactRepository
{
private AddressBookDb addressBookdb = new AddressBookDb();
public void Create(Contact contact)
{
addressBookdb.Contacts.Add(contact);
addressBookdb.SaveChanges();
}
public void Save(Contact contact)
{
Delete(contact.Id);
Create(contact);
}
public void Delete(int contactId)
{
Contact contact = Retrieve(contactId);
if (contact != null)
{
addressBookdb.Contacts.Remove(contact);
addressBookdb.SaveChanges();
}
}
public Contact Retrieve(int contactId)
{
return addressBookdb.Contacts.FirstOrDefault<Contact>(c => c.Id == contactId);
}
public IEnumerable<Models.Contact> Select()
{
return addressBookdb.Contacts.ToList<Contact>();
}
}
</code></pre>
<p><strong>Controller class</strong></p>
<pre><code>public class ContactController : Controller
{
IContactRepository contactRepository = null;
public ContactController() : this (new ContactRepository())
{
}
public ContactController(IContactRepository contactRepository)
{
this.contactRepository = contactRepository;
}
[HttpPost]
public ActionResult Edit(Contact contact)
{
if (ModelState.IsValid)
{
contactRepository.Save(contact);
return RedirectToAction("Index");
}
return View(contact);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-25T06:43:09.450",
"Id": "9745",
"Score": "2",
"body": "What about moving IContactRepository to a IRepository<T> interface. That way you will not have to implement an interface for every model type you want a repository for?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-05T13:27:23.233",
"Id": "10191",
"Score": "0",
"body": "I believe that the Get() is more conventional than Retrieve()"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-25T01:08:50.770",
"Id": "38349",
"Score": "1",
"body": "I dont understand your save method. Why do you delete it before saving??? If youre saving its not even supposed for you to have any ID! And if saving means updating why do you exclude it from db then reinsert? Isnt it messing up with any relationship that might already exists???"
}
] |
[
{
"body": "<p>Couple of things I'd change:</p>\n\n<ol>\n<li><p>Make save work out whether it needs to create or modify itself.</p></li>\n<li><p>Don't delete and re-create in the same. It will mess with relational data as Renato said.</p></li>\n<li><p>In the Retrieve method return <code>SingleOrDefault</code> - Only one contact record should have a unique id. Then let the controller check for null instead of a try/catch which you'd need around a <code>Single</code> call as this would throw an exception if no record was returned. <code>FirstOrDefault</code> makes it look like you're not confident there will be only one record; also depending on ordering it <em>could</em> return a different record depending on conditions.</p></li>\n<li><p>You could make you save method return a bool value to stop the db side of things throwing an error and crashing the site. You could then do the following:</p>\n\n<pre><code>[HttpPost]\npublic ActionResult Edit(Contact contact)\n{\n if ((ModelState.IsValid) && (contactRepository.Save(contact)))\n {\n return RedirectToAction(\"Index\");\n }\n return View(contact);\n}\n</code></pre></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-05T09:04:47.237",
"Id": "6548",
"ParentId": "6266",
"Score": "1"
}
},
{
"body": "<p>I have a very good solution for you. See the below two blog posts:</p>\n\n<blockquote>\n <p><a href=\"http://www.tugberkugurlu.com/archive/generic-repository-pattern-entity-framework-asp-net-mvc-and-unit-testing-triangle\" rel=\"nofollow\">Generic Repository Pattern - Entity Framework, ASP.NET MVC and Unit\n Testing Triangle</a></p>\n \n <p><a href=\"http://www.tugberkugurlu.com/archive/how-to-work-with-generic-repositories-on-asp-net-mvc-and-unit-testing-them-by-mocking\" rel=\"nofollow\">How to Work With Generic Repositories on ASP.NET MVC and Unit Testing\n Them By Mocking</a></p>\n</blockquote>\n\n<p>What I can suggest more is this:</p>\n\n<p><strong>Implementing <code>IDisposable</code>:</strong></p>\n\n<p>Implement IDisposable on your repository and dispose them on your controller by overriding the Controller.Dispose method. Sample:</p>\n\n<p><strong>IContactRepository:</strong></p>\n\n<pre><code>public interface IContactRepository : IDisposable {\n\n //same as above\n}\n</code></pre>\n\n<p>Add the below code to your <code>ContactRepository</code> class:</p>\n\n<pre><code>private bool disposed = false;\n\nprotected virtual void Dispose(bool disposing) {\n\n if (!this.disposed)\n if (disposing)\n addressBookdb.Dispose();\n\n this.disposed = true;\n}\n\npublic void Dispose() {\n\n Dispose(true);\n GC.SuppressFinalize(this);\n}\n</code></pre>\n\n<p>On your controller, add this code:</p>\n\n<pre><code>protected override void Dispose(bool disposing) {\n\n contactRepository.Dispose();\n\n base.Dispose(disposing);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-02T13:38:40.753",
"Id": "7382",
"ParentId": "6266",
"Score": "3"
}
},
{
"body": "<p>I may come back and fill this answer out more, time permitting. But I would do as others here suggest re a Generic repository... As a starting point on this take a look at <a href=\"https://www.youtube.com/watch?v=SExnyXhX3gk\" rel=\"nofollow\">this 6 min video</a>.</p>\n\n<p>A little difficult to understand his accent but the code speaks for itself and for such a short example it really does get through a lot.</p>\n\n<p>The reason I recommend a generic repository with the repo pattern is because you can do so much with it. Usually it acts almost as a clear line which defines what should be done directly in the database (meaning a SQL Query) vs. anywhere in code.</p>\n\n<p>The argument against the generic repo is that it cant handle multiple tables via joins. Some say it requires convoluted Linq (which is technically correct). My answer to this is that this is the line I was speaking of earlier. If you find yourself writing long winded Linq queries, or manual queries in C# anywhere the repo pattern is used (specifically the generic version of it), then really this belongs in the DB. So its a clear sign to me that a proper query should be written in SQL, and made into a view which can be properly optimised. Then this view can be brought into the system via EF as a single table and the generic pattern used on it. Hence the generic repo pattern now acts as a clear separation of concerns and serves to highlight where things should be.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-02-27T13:00:27.230",
"Id": "82738",
"ParentId": "6266",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-24T22:53:36.507",
"Id": "6266",
"Score": "5",
"Tags": [
"c#",
"design-patterns",
"asp.net-mvc-3"
],
"Title": "ASP.NET MVC using Repository pattern"
}
|
6266
|
<p>I have two small structs (might change to classes later) that get loaded into Generic lists. The loading of the lists is what I'm asking about. Can it be done better or more object-oriented?</p>
<p>You'll notice I'm using MS Enterprise library for data access to a SqlCe database.</p>
<p>I'm just looking for some opinions on this code. Is there a more efficient way to do what I've written so far? My goal is to make the code as efficient and small as possible while still being maintainable and expandable.</p>
<pre><code> public class ConversionUtility
{
private List<ComicBook> _books;
private List<ComicPublisher> _publishers;
private void Load()
{
try
{
_books = GetBooks();
_publishers = GetPublishers();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
public void PerformConversion()
{
Load();
//still working on this
}
private List<ComicPublisher> GetPublishers()
{
List<ComicPublisher> tmp = new List<ComicPublisher>();
Database db = EnterpriseLibraryContainer.Current.GetInstance<Database>("CeConnectionString");
IDataReader rdr = db.ExecuteReader(CommandType.Text, "SELECT * FROM Publisher");
while (rdr.Read())
{
tmp.Add(new ComicPublisher { Id = (int)rdr["PublisherId"], Name = rdr["PublisherName"].ToString() });
}
return tmp;
}
private List<ComicBook> GetBooks()
{
List<ComicBook> tmp = new List<ComicBook>();
Database db = EnterpriseLibraryContainer.Current.GetInstance<Database>("CeConnectionString");
IDataReader rdr = db.ExecuteReader(CommandType.Text, "SELECT * FROM Book");
while (rdr.Read())
{
tmp.Add(new ComicBook { Id = (int)rdr["BookId"], Title = rdr["Title"].ToString(), Company = rdr["Company"].ToString() });
}
return tmp;
}
}
public struct ComicPublisher
{
public int Id { get; set; }
public string Name { get; set; }
}
public struct ComicBook
{
public int Id { get; set; }
public string Title { get; set; }
public string Company { get; set; }
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-25T03:06:20.327",
"Id": "9743",
"Score": "0",
"body": "`Dispose()` of your `IDisposable` type (`IDataReader`) with a `using` block."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-25T03:16:12.917",
"Id": "13411",
"Score": "0",
"body": "Thanks guys! Yes, this is small but it's not truly a project. This is just something I'm trying to put into habit. I'd like to have a consistent style in my coding :) The interface idea is excellent. I'm going to play with that some. Good call about closing the reader! I had it wrapped in a using statement but the runtime yelled at me. It was saying something about the Enterprise Library not liking it but I didn't pay a whole lot of attention at the time unfortunately. Overall, using a reader and creating the new instances of the classes for each record found looks good up there? Thanks so muc"
}
] |
[
{
"body": "<p>Firstly:</p>\n\n<h2>Close your DataReaders!!!</h2>\n\n<p><br></p>\n\n<p>Secondly:</p>\n\n<p>You may want to consider abstracting boilerplate code like this:</p>\n\n<pre><code> Database db = EnterpriseLibraryContainer.Current.GetInstance<Database>(\"CeConnectionString\");\n IDataReader rdr = db.ExecuteReader(CommandType.Text, \"SELECT * FROM Book\");\n</code></pre>\n\n<p>Into some helper methods.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-24T23:24:20.160",
"Id": "6268",
"ParentId": "6267",
"Score": "4"
}
},
{
"body": "<p>You could make this into a generic method. If you wanted to change your tables & classes to a consistent format then it would be very simple:</p>\n\n<pre><code>interface IThing\n{\n int Id {get;set;}\n string Name {get;set;}\n string DatabaseTableName {get;}\n}\n\nclass GetThings<T> where T : IThing, new()\n{\n private List<T> GetItems()\n {\n var t = new T();\n\n List<T> tmp = new List<T>();\n Database db = EnterpriseLibraryContainer.Current.GetInstance<Database>(\"CeConnectionString\");\n string query = String.Format(\"SELECT * FROM {0}\", t.DatabaseTableName);\n IDataReader rdr = db.ExecuteReader(CommandType.Text, query);\n\n while (rdr.Read())\n {\n tmp.Add(new T { Id = (int)rdr[\"Id\"], Name = rdr[\"Name\"].ToString() });\n }\n return tmp;\n }\n}\n</code></pre>\n\n<p>and your classes need to implement the IThing interface. If you don't want to use an interface then things will get messier, and reflection and property matching will be required.</p>\n\n<p>Having said that, I don't believe it's worth writing generic classes to handle two structs.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-03-31T01:07:09.593",
"Id": "231723",
"Score": "0",
"body": "And what effect would Little Bobby Tables have on this code? https://xkcd.com/327/"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-25T01:36:53.463",
"Id": "6272",
"ParentId": "6267",
"Score": "0"
}
},
{
"body": "<p>I prefer <code>struct</code>s to be immutable and to use <code>interface</code> types when available, so I have this (incorporating my comment to the question) to present:</p>\n\n<pre><code>public sealed class ConversionUtility\n{\n private IList<ComicBook> _books;\n private IList<ComicPublisher> _publishers;\n\n public void PerformConversion()\n {\n this.Load();\n\n // still working on this\n }\n\n private void Load()\n {\n try\n {\n this._books = this.GetBooks();\n this._publishers = this.GetPublishers();\n }\n catch (Exception ex)\n {\n Console.WriteLine(ex.Message);\n }\n }\n\n private IList<ComicPublisher> GetPublishers()\n {\n IList<ComicPublisher> tmp = new List<ComicPublisher>();\n\n Database db = EnterpriseLibraryContainer.Current.GetInstance<Database>(\"CeConnectionString\");\n\n using (IDataReader rdr = db.ExecuteReader(CommandType.Text, \"SELECT * FROM Publisher\"))\n {\n while (rdr.Read())\n {\n tmp.Add(new ComicPublisher((int)rdr[\"PublisherId\"], rdr[\"PublisherName\"].ToString()));\n }\n }\n\n return tmp;\n }\n\n private IList<ComicBook> GetBooks()\n {\n IList<ComicBook> tmp = new List<ComicBook>();\n\n Database db = EnterpriseLibraryContainer.Current.GetInstance<Database>(\"CeConnectionString\");\n\n using (IDataReader rdr = db.ExecuteReader(CommandType.Text, \"SELECT * FROM Book\"))\n {\n while (rdr.Read())\n {\n tmp.Add(new ComicBook((int)rdr[\"BookId\"], rdr[\"Title\"].ToString(), rdr[\"Company\"].ToString()));\n }\n }\n\n return tmp;\n }\n}\n\npublic struct ComicPublisher\n{\n private readonly int id;\n private readonly string name;\n\n public ComicPublisher(int id, string name)\n {\n this.id = id;\n this.name = name;\n }\n\n public int Id { get { return this.id; } }\n public string Name { get { return this.name; } }\n}\n\npublic struct ComicBook\n{\n private readonly int id;\n private readonly string title;\n private readonly string company;\n\n public ComicBook(int id, string title, string company)\n {\n this.id = id;\n this.title = title;\n this.company = company;\n }\n\n public int Id { get { return this.id; } }\n public string Title { get { return this.title; } }\n public string Company { get { return this.company; } }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-25T03:23:28.983",
"Id": "6274",
"ParentId": "6267",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-24T23:20:52.967",
"Id": "6267",
"Score": "4",
"Tags": [
"c#",
"object-oriented"
],
"Title": "Comic book conversion"
}
|
6267
|
<p>In his <a href="http://blog.stevensanderson.com/2011/08/31/knockout-1-3-0-beta-available/" rel="nofollow">KnockoutJs 1.3 beta</a> post, Steve Sanderson has an example of using Binding providers ("5. Binding providers (and hence external bindings)") where he makes a comment in the JSFiddle JavaScript tab that says "// This syntax would be way more succinct with CoffeeScript".</p>
<p>How would this actually be accomplished? </p>
<pre><code>// This syntax would be way more succinct with CoffeeScript
ko.bindingConventions.conventions(".person-editor", {
".person-editor" : { 'with': myViewModel.person },
".first-name" : function(person) { return { value: person.firstName } },
".last-name" : function(person) { return { value: person.lastName } }
});
ko.bindingConventions.conventions("#weather-list", {
"#weather-list" : { 'with': myViewModel.weather },
".cities-list" : function(weather) { return { foreach: weather.cities } },
".city" : function(item) { return { text: item.city } },
".temp" : function(item) { return { text: item.temperature } },
".add-city" : { click: function() { this.addItem() } }
});
</code></pre>
|
[] |
[
{
"body": "<pre><code> ko.bindingConvenrions.conventions \".person-editor\"\n \".person-editor\" : \n 'with' : myViewModel.person\n \".first-name\" : ( person ) ->\n value : person.firstName\n \".last-name\" : ( person ) ->\n value : person.lastName\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-26T11:04:34.187",
"Id": "6308",
"ParentId": "6269",
"Score": "1"
}
},
{
"body": "<p>This would be even better with simpler spacing and single quotes where\ninterpolation is not being used (a hint to the reader that these strings are\nliteral). Grouping related functions can add clarity, too, if you end up with\nan unruly number of properties.</p>\n\n\n\n<pre class=\"lang-coffee prettyprint-override\"><code>ko.bindingConventions.conventions '.person-editor',\n '.person-editor':\n with: myViewModel.person\n '.first-name': (person) ->\n value: person.firstName\n '.last-name': (person) ->\n value: person.lastName\n\nko.bindingConventions.conventions '#weather-list',\n '#weather-list':\n with: myViewModel.weather\n '.add-city':\n click: ->\n @addItem()\n '.cities-list': (weather) ->\n foreach: weather.cities\n '.city': (item) ->\n text: item.city\n '.temp': (item) ->\n text: item.temperature\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-22T21:58:49.590",
"Id": "51456",
"ParentId": "6269",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "6308",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-25T00:26:48.800",
"Id": "6269",
"Score": "2",
"Tags": [
"coffeescript"
],
"Title": "Writing binding providers in CoffeeScript?"
}
|
6269
|
<p>I have been tasked with implementing a secure account login system for a website's content management system. I have built a solution around an access masterpage that handles all account access functions. Here is the Page_Load</p>
<pre><code>Protected Sub Page_Load() Handles Me.Load
If Not Request.IsSecureConnection Then
Response.Redirect(Request.Url.ToString.Replace("http://", "https://"))
End If
UpdateSecurity()
End Sub
</code></pre>
<p>And the definition of UpdateSecurity()</p>
<pre><code>Private Sub UpdateSecurity()
PageContentPanel.Visible = Session("access")
PleaseLogInPanel.Visible = Not Session("access")
End Sub
</code></pre>
<p>As you can probably infer from the snippet, having "access" set in the Session makes an asp:Panel containing the content of whatever child page the user requested visible, otherwise, the PageContentPanel is hidden, and the PleaseLogInPanel with a username and password prompt is made visible. In the handler for the login button (also on the login Panel), the posted credentials are verified and if correct, Session values are added. </p>
<p>I was wondering if this implementation is fundamentally sound or not. Page requests from not logged in users still execute (I think), but the results are hidden inside an invisible asp:Panel. I'm not familiar enough with the ASP.NET security model to know if this poses risks or not from wayward POSTs. If a child page utilizes this masterpage, what access do not logged in users have to resources on the page?</p>
|
[] |
[
{
"body": "<p>What you are doing right now is not fundamentally correct. This link <a href=\"http://learn.iis.net/page.aspx/170/developing-a-module-using-net/\" rel=\"nofollow\">http://learn.iis.net/page.aspx/170/developing-a-module-using-net/</a> explains developing a custom authentication module. </p>\n\n<p>Also you should read about page life cycle while working asp webforms. <a href=\"http://msdn.microsoft.com/en-us/library/ms178472.aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/ms178472.aspx</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-05T00:40:07.293",
"Id": "10171",
"Score": "0",
"body": "why is what I'm doing not fundamentally correct? Where is the hole?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-25T06:47:32.647",
"Id": "6275",
"ParentId": "6271",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-25T01:18:03.790",
"Id": "6271",
"Score": "2",
"Tags": [
"asp.net",
"security",
"vb.net"
],
"Title": "ASP.NET account login system implemented via Masterpage and Panels"
}
|
6271
|
<p>I just made this sort method. It runs fine and the code looks okay in my eyes.</p>
<p>Is is possible to optimize it so it runs faster? If it's \$O(n^3)\$ now, it would be interesting changing it to \$O(n^2)\$ or something like that.</p>
<p>Side question: This is \$O(n^3)\$, right (I only like \$O(n^2)\$ and below)?</p>
<pre><code>List<Log> errors = _logHandler.GetErrors(daysBack);
List<Log> errorsSorted = new List<Log>();
for (int i = 0; i < errors.Count; i++)
{
bool inserted = false;
for (int j = 0; j < errorsSorted.Count; j++)
{
if (errors[i].Date < errorsSorted[j].Date)
{
List<Log> tempList = new List<Log>();
tempList.AddRange(errorsSorted.GetRange(j,
errorsSorted.Count - j));
errorsSorted[j] = errors[i]; // replace at bigger date index
inserted = true;
errorsSorted.RemoveRange(j+1, errorsSorted.Count - (j+1));
// move all bigger dates one place to the right..
foreach (Log log in tempList)
{
errorsSorted.Add(log);
}
break;
}
}
if (!inserted)
{
errorsSorted.Add(errors[i]); // No date is bigger, add at the end
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-25T08:58:10.640",
"Id": "9752",
"Score": "6",
"body": "Why aren't you using any of the built-in sorting methods?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-25T09:02:23.190",
"Id": "9753",
"Score": "1",
"body": "Just make `Log` Comparable and then use the inbuilt method."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-25T09:07:07.343",
"Id": "9754",
"Score": "0",
"body": "I did what was intuitive for me. I guess it's my skill cap."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-25T09:10:40.117",
"Id": "9755",
"Score": "0",
"body": "I don't know if I can make it comparable, since the Log class is located in Log.designer.cs as a partial class. Maybe I should mention that I have a Log.dbml"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-25T11:23:48.140",
"Id": "9759",
"Score": "0",
"body": "I think for sort algorithms, you should rarely if ever accept anything with worse than O(n log n) runtime =)"
}
] |
[
{
"body": "<p>You are just sorting by date, correct? I'd use</p>\n\n<pre><code>using System.Linq;\n// ....\nList<Log> errors = _logHandler.GetErrors(daysBack);\nList<Log> errorsSorted = errors.OrderBy(l => l.Date).ToList();\n</code></pre>\n\n<p>According to <a href=\"https://stackoverflow.com/questions/2792074/what-sorting-algorithm-is-used-by-linq-orderby\">this stackoverflow question</a>, <code>OrderBy</code> uses QuickSort in this case, which usually has a run time of O(n log n).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-25T12:27:23.423",
"Id": "9763",
"Score": "0",
"body": "Looks cool, I while check it out later to day when I get some spare time :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-02T08:21:03.197",
"Id": "10056",
"Score": "0",
"body": "Works very good and reduce the number of lines with 27 thanks :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-25T11:13:52.277",
"Id": "6281",
"ParentId": "6279",
"Score": "4"
}
},
{
"body": "<p>Well, the obvious would be to use a better algorithm, i.e the built in:</p>\n\n<pre><code>errors.Sort((x,y) => x.Date.CompareTo(y.Date));\n</code></pre>\n\n<p>What you can do with your code is to use a more effective way to move the elements around. Right now you are moving items from one list to another to instert an item, but the <code>List<T></code> class is itself capable of inserting an item. It will be a bit faster because you will only be copying the items once instead of twice for each insert.</p>\n\n<p>Much better would be to use a linked list instead. It will be a lot faster because inserting an item will be O(1) instead of O(n) (where n is the number of items that needs to be moved). Something like this (not tested):</p>\n\n<pre><code>List<Log> errors = _logHandler.GetErrors(daysBack);\nLinkedList<Log> errorsSorted = new LinkedList<Log>();\nforeach (Log error in errors) {\n LinkedListNode<Log> node = errorsSorted.Last;\n while (node != null && error.Date < node.Value.Date) {\n node = node.Previous;\n }\n if (node != null) {\n errorsSorted.AddAfter(node, error);\n } else {\n errorsSorted.AddFirst(error);\n }\n}\n</code></pre>\n\n<p>This is the <a href=\"http://en.wikipedia.org/wiki/Insertion_sort\" rel=\"nofollow\">insertion sort</a>, which has a worst case performance of O(n^2) and a best case performance of O(n). Note that it starts looking through the sorted list from the end instead of the beginning, which gives it the O(n) performance if the list is already sorted.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-25T15:21:26.063",
"Id": "6292",
"ParentId": "6279",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "6281",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-25T08:56:44.830",
"Id": "6279",
"Score": "4",
"Tags": [
"c#",
"performance",
"algorithm",
"sorting",
"reinventing-the-wheel"
],
"Title": "Optimizing error-sorting method"
}
|
6279
|
<p>I would like some advice to shorten down this snippet, give it more efficient flow and look. Review should focus on keeping it as a compact single method (except the two public props). The <code>DataType</code> and <code>MeasureStatus</code> is an <code>enum</code>. Readability is of course more important than compactness.</p>
<pre><code>....
/// <summary>
/// Helper that hold methods for evaluate and calculate data
/// that will be serialized/deserialized in Serializer/SerializerBase.
/// Please don't put serializing routines in here and also understand
/// that some decisions here are based on protocol specifikations.
/// </summary>
....
public Unit MeasureType { get; set; }
public ModeType Aggregate { get; set; }
.....
public Tuple<DataType, byte> EvaluateDataType(double value, MeasureStatus? status = null)
{
int quantityOfDecimals = 0;
DataType dataType = DataType.MISSING_LONG;
byte nibbled = 0;
bool statusIsMissing = false;
if (status != null)
if (status == MeasureStatus.Missing)
statusIsMissing = true;
quantityOfDecimals =
(this.MeasureType == Unit.kWh || this.MeasureType == Unit.ºC) ? 1 : 2;
// Qty decimals affect limit size of 'value'
if (quantityOfDecimals == 1)
{
if (value < 3276 && value > -3276)
if (!statusIsMissing)
dataType = DataType.SHORT_1DEC;
else
dataType = DataType.MISSING_SHORT;
else
if (!statusIsMissing)
dataType = DataType.LONG_1DEC;
else
dataType = DataType.MISSING_LONG;
}
// Qty decimals affect limit size of 'value'
if (quantityOfDecimals == 2)
{
if (value < 327 && value > -327)
if (!statusIsMissing)
dataType = DataType.SHORT_2DEC;
else
dataType = DataType.MISSING_SHORT;
else
if (!statusIsMissing)
dataType = DataType.LONG_2DEC;
else
dataType = DataType.MISSING_LONG;
}
nibbled = (byte)(Aggregate | dataType);
return new Tuple<DataType, byte>(dataType, nibbled);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-28T16:37:52.183",
"Id": "9871",
"Score": "0",
"body": "If there are design decisions that are driving this, then they need to be referenced in comments, probably more than just a 'look here for why' (unless you have a good referencing system with tool...). Magic numbers are still bad, perhaps _especially_ if specified externally - you only want to have to change **ONE** value if the specification changes, not look for a million hard-coded values (and in your case, they aren't written as the same value anyways!). And never rely on a developer reading documentation before looking at isolated code..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-29T07:41:37.123",
"Id": "9892",
"Score": "0",
"body": "Thank's. I think this fell outside of the scoop of question. Also we came to goal of the question already,"
}
] |
[
{
"body": "<p>There are some (potentially bizarre to me) things going on here. A slightly larger view of the system may be helpful in further refining this method. In any case, here's how I'd restructure this. I've also included notes about some things I found odd...</p>\n\n<pre><code>public Tuple<DataType, byte> EvaluateDataType(double value, MeasureStatus? status = null) \n{ \n\n // As much as possible, initialize a local variable to the proper value\n // when you declare it (as if it had Java's *final* attatched).\n // This isn't always possible, of course\n DataType dataType;\n // Really, these are the only two datatypes that use 1 decimal place?\n int decimalPlaces = (MeasureType == Unit.kWh || MeasureType == Unit.ºC) ? 1 : 2;\n // Structure your code so that it's values and executions give the -reasons-\n // or the -why-. The code itself says -what- is happening, but it's usually -why-\n // that's actually important. \n // Among other things, this means you should (usually) avoid magic numbers. \n bool valueOutOfRange = Math.Abs(value) >= (Int16.MaxValue / (10 * decimalPlaces)); \n\n // status == null is considered -present-?\n if (status != null && status == MeasureStatus.Missing) \n {\n // Note, never leave off brackets - {} - you run a nasty risk of\n // someone writing indented code that isn't actually part of the block. \n // Also, as much as possible, test for -affirmative- results, not negative ones.\n // Although, multiple negatives should still be avoided. \n if (valueOutOfRange) \n {\n dataType = DataType.MISSING_LONG;\n } \n else\n {\n dataType = DataType.MISSING_SHORT;\n }\n }\n else\n {\n if (valueOutOfRange) \n {\n if (decimalPlaces == 1) \n {\n dataType = DataType.LONG_1DEC;\n }\n else\n {\n dataType = DataType.LONG_2DEC;\n }\n }\n else\n {\n if (decimalPlaces == 1)\n {\n dataType = DataType.SHORT_1DEC;\n }\n else \n }\n dataType = DataType.SHORT_2DEC;\n }\n }\n }\n\n // Are you sure you don't mean \"byte nibbled = (byte) (Aggregate & dataType);\"?\n // I'm assuming you're attempting to mask Aggregate for the cast, and that \n // you haven't done anything -too- out there in the operator override.\n byte nibbled = (byte) (Aggregate | dataType);\n return new Tuple<DataType, byte>(dataType, nibbled);\n}\n</code></pre>\n\n<p>Although, I'm a little suspicious of anything that's moving some sort of <code>DataType</code> around like this (especially because you're only storing a <code>byte</code>). Normally it's best to prefer some sort of implemented generic, so you can get <em>compile time</em> checking of your datatypes. Nothing like mismatches at runtime to crash your probe into Mars (granted, that was a mismatch in the measure type, which you're attempting to cover here. However, you still need to deal with value mis-matches...).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-25T20:37:50.620",
"Id": "9773",
"Score": "0",
"body": "ermm \"never leave off brackets\". I think your missing a bracket after the else statement just after this comment :) Otherwise good feedback. To some degree I think your use of spacing helps the readability more than the changes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-25T21:41:09.347",
"Id": "9774",
"Score": "0",
"body": "@dreza - Thanks. This is another reason why - your compile can catch that you've put something in the wrong place. I don't have a C# compiler here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-28T13:31:44.270",
"Id": "9854",
"Score": "0",
"body": "Updated! I hope the edits are clear enough, at last."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-28T15:06:48.743",
"Id": "9869",
"Score": "0",
"body": "One super-minor-pity comment, `decimalPlaces` = number of `,`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-28T16:41:09.183",
"Id": "9872",
"Score": "0",
"body": "@Jonas - `decimalPlaces` is equivalent to your `quantityOfDecimals`, which is a somewhat counter-intuitive name. Usually, 'decimal places' is used to refer to how many `places` (digits) are present to the _right_ of the decimal-point - tenths, hundreths, thousandths, and so on."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-29T07:45:58.990",
"Id": "9893",
"Score": "0",
"body": "@X-Zero There can be some funny translations between languages. I got a hard lesson ones, regarding the word \"decimalPlaces\" which refer to `0.000,000,000,000,009` = 4 if we talk i.e. number formatting. In this case though, the code says that at isn't the kind of use. `3.444` <-- three decimals. Your probably right, just the word Decimals would fit perfectly!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-29T16:34:44.173",
"Id": "9913",
"Score": "0",
"body": "@jonas - (American) english speakers would most likely expect a variable named `quantityOfDecimals` or similar to be an array of decimals, each (probably) different. The wikipedia page on [arithmetic precision](http://en.wikipedia.org/wiki/Arithmetic_precision) details how most would expect it to be used."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-25T19:01:52.663",
"Id": "6293",
"ParentId": "6282",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "6293",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-25T11:37:02.607",
"Id": "6282",
"Score": "2",
"Tags": [
"c#",
"floating-point"
],
"Title": "Helper that hold methods for evaluate and calculate data"
}
|
6282
|
<p>As part of our sprints, we do peer review each others code. </p>
<p>Here is the code that I am reviewing. </p>
<pre><code>public void SendEmail()
{
string emailAddress = string.Empty;
string managerEmailAddress = string.Empty;
if (//condition)
{
//do something
//Retrieve emailAddress and managerEmailAddress
EmailMessage.To = emailAddress;
EmailMessage.CC = managerEmailAddress;
}
}
</code></pre>
<p>The suggestion from Resharper was to have the string declarations closer to the usage. However, my colleague suggest that it is not a good idea to have them closer to the usage and have them declared right at the beginning. And, I sort of agree with him because for methods where the variables are used in multiple places with different values being assigned depending upon conditions...it would make sense to have them all grouped right at the top but for smaller methods, where there is just one if condition, stick them along with the usage (for instance the above mentioned code). </p>
<p>What do you think?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-25T19:38:40.530",
"Id": "9772",
"Score": "2",
"body": "More of a standards holy-war which belongs on Programmers SE."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T13:19:19.100",
"Id": "62463",
"Score": "5",
"body": "This question appears to be off-topic because it is about reviewing code written by [someone other than the OP](http://meta.codereview.stackexchange.com/questions/1294/why-is-only-my-own-written-code-on-topic)."
}
] |
[
{
"body": "<p>Read <em>Effective Java, Second Edition, Item 45: Minimize the scope of local variables</em>. It has a good overview on the topic. (Google for \"minimize the scope of local variables\", it's on Google Books too.)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-25T12:41:36.780",
"Id": "6287",
"ParentId": "6283",
"Score": "3"
}
},
{
"body": "<p>In C# the variables have the scope of their code block, compared to Javascript for example where variables have the scope of the entire function. In Javascript it makes sense to declare all variable at the top of the function, because that is their actual scope.</p>\n\n<p>You should minise the scope of variables, so that you can't use them in the wrong part of the code by accident.</p>\n\n<p>Example:</p>\n\n<pre><code>void DoSomething(bool write) {\n\n string source = String.Empty;\n string destination = String.Empty;\n string data = String.Empty;\n\n if (write) {\n destination = \"some other thing\";\n WriteTo(destination, data);\n } else {\n source = \"something\";\n data = ReadFrom(destination); // oops, used the wrong variable\n }\n\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-25T14:45:58.100",
"Id": "6290",
"ParentId": "6283",
"Score": "3"
}
},
{
"body": "<p>I think it sort of depends on the context. Like you said, for smaller methods where there is only a few lines then declaring at the top of the method will be neither here nor there as the reader can easily see what the entire method is doing.</p>\n\n<p>However my preference is to declare the variables as close to their first usage as possible. A few reasons.</p>\n\n<ol>\n<li>I believe a variable should be used for one thing only. By declaring them close to their usage then you are implicitly stating this is where the variable is being use.</li>\n<li>Easier to see when that variable is used in the code. If you method is a few lines long then you can easily see where a variable is first used.</li>\n<li>It might help with identifying refactoring of code. For example by adding the variables inside the scope of the condition above you might come to decide that actually the condition could be done elsewhere.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-25T19:17:44.167",
"Id": "6294",
"ParentId": "6283",
"Score": "4"
}
},
{
"body": "<p>I agree with Guffa and dreza, variables should only be declared at an outer scope if it is really really necessary as doing so is confusing and error prone. Also, if a method is long enough that having the variable declaration at the top means it isn't close to it's use then it could probably benefit from refactoring into separate methods. Doing this will also help readability because you'll have method names explaining what's happening.</p>\n\n<p>Some examples (quotes as this is only my opinion):</p>\n\n<p><strong>1: \"Bad\" example</strong></p>\n\n<p>As an outside coder, if I saw this I would wonder why the variables are declared at the outer scope and would waste time worrying there was a special reason for it.</p>\n\n<pre><code>string emailAddress = string.Empty;\nstring managerEmailAddress = string.Empty;\n\nif (//condition)\n{\n emailAddress = Foo();\n EmailMessage.To = emailAddress;\n}\nelse\n{\n emailAddress = Bar();\n // Do something different with emailAddress;\n}\n\n// No more usages of emailAddress\n</code></pre>\n\n<p><strong>2: \"Improved\" example:</strong></p>\n\n<p>This is better because the variables are defined where they are used so there is no need to go looking around for other usages.</p>\n\n<pre><code>if (//condition)\n{\n var emailAddress = Foo();\n EmailMessage.To = emailAddress;\n}\nelse\n{\n var emailAddress = Bar();\n // Do something different with emailAddress;\n}\n</code></pre>\n\n<p><strong>3: \"Even better\" example:</strong></p>\n\n<p>I think this is the best it can get because the method names will help with understanding the code.</p>\n\n<pre><code>if (//condition)\n{\n ExplanatoryName1(//pass anything in that is required);\n}\nelse\n{\n ExplanatoryName2(//pass anything in that is required);\n}\n</code></pre>\n\n<p><strong>4: If you need a return from the methods:</strong></p>\n\n<pre><code>var methodReturn = condition ? ExplanatoryName1(args) : ExplanatoryName2(args);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-25T20:50:33.580",
"Id": "6296",
"ParentId": "6283",
"Score": "5"
}
},
{
"body": "<p>The scope of local variables should always be as minimal as possible. So, I would declare the variable precisely there where it is used even if I have to re-declare it in multiple places within the same method. As a matter of fact, I would declare it precisely where it is used even if there was no <code>if</code> condition. Many people do not know it, but you can start a new scope with curly brackets anywhere you want within a method, even if you do not have a control statement to put it under. For example:</p>\n\n<pre><code>//some code\n\n//comment explaining what the following does:\n{\n string emailAddress = Foo();\n EmailMessage.To = emailAddress;\n}\n\n//more code\n\n//comment explaining what the following does:\n{\n string emailAddress = Boo();\n SomeOtherEmailMessage.From = emailAddress;\n}\n\n//yet more code\n</code></pre>\n\n<p>One more note: I see that when your colleague declared the email address variable he assigned <code>string.Empty</code> to it, and then further down he re-assigned a meaningful value to it prior to using it. Some people believe that when declaring a local variable you should always initialize it with some initial value, and they follow this rule in an almost superstitious fashion. This is wrong. It may have been advisable back in the times when all we had was some primitive and crude C compilers, but not anymore. Modern compilers of C, C++, C# and Java are quite good at warning you if a variable might be read before it has been initialized. So, by pre-initializing the variable at declaration time with a value which is by definition meaningless, (since a meaningful value is not yet known at that time,) you are circumventing the safety checks of your compiler, and you are actually opening up the possibility of error: if you forget to assign a proper value to your variable further down before you actually make use of it, the compiler will not warn you, because as far as the compiler knows, the variable has already been initialized at declaration time.</p>\n\n<p>Furthermore, even if the compiler was incapable of warning about uninitialized values, you would still have to wonder which outcome is better for a program with an uninitialized variable bug: to fail with a null pointer exception the first time it is used, or to <em>appear</em> to work but never send any messages to anyone.</p>\n\n<p>In any case, you should not really have to worry about the above note, because if you follow the rule which says that the scope of local variables should always be as minimal as possible, you will always be initializing your local variables with meaningful values precisely at the moment that you are declaring them.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-05-19T21:11:26.553",
"Id": "19114",
"Score": "3",
"body": "Avoid declaring an inner scope in curly brackets. It is an indication that you should refactor that code into a separate method."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-27T09:39:50.390",
"Id": "6329",
"ParentId": "6283",
"Score": "5"
}
},
{
"body": "<p>Before I read <a href=\"http://rads.stackoverflow.com/amzn/click/0132350882\" rel=\"nofollow\">Clean Code by Robert C. Martin</a>, I would've said that you should go with your colleague's option (group all the variables at the top) because it looks better/cleaner and it makes more sense (the last reason comes, without a doubt, from a couple of years of C/C++). Nowadays, I pay attention to variable scope and clean code practices; so the version which I would use is:</p>\n\n<pre><code>public void SendEmail()\n{\n if (//condition)\n {\n string emailAddress = GetEmailAddress(); \n EmailMessage.To = emailAddress;\n\n string managerEmailAddress = GetManagerEmailAddress();\n EmailMessage.CC = managerEmailAddress;\n }\n}\n</code></pre>\n\n<p>which, depending on the rest of the code, can be further improved (\"extract 'till you drop\").</p>\n\n<p>Still, I can think of a possible problem on this subject, when you apply refactoring before seeing all the usages. Consider the original code:</p>\n\n<pre><code>public void SendEmail()\n{\n string emailAddress = string.Empty;\n string managerEmailAddress = string.Empty;\n\n if (//condition)\n {\n //do something\n //Retrieve emailAddress and managerEmailAddress\n EmailMessage.To = emailAddress;\n EmailMessage.CC = managerEmailAddress;\n }\n\n EmailMessage.BCC = emailAddress;\n}\n</code></pre>\n\n<p>...and the refactored one:</p>\n\n<pre><code>public void SendEmail()\n {\n if (//condition)\n {\n string emailAddress = GetEmailAddress(); \n EmailMessage.To = emailAddress;\n\n string managerEmailAddress = GetManagerEmailAddress();\n EmailMessage.CC = managerEmailAddress;\n }\n\n EmailMessage.BCC = emailAddress; //now what?\n }\n</code></pre>\n\n<p>So, when you refactor the code, you need to keep an eye to the scope.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T11:20:17.183",
"Id": "37667",
"ParentId": "6283",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "6296",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-25T11:57:14.373",
"Id": "6283",
"Score": "8",
"Tags": [
"c#"
],
"Title": "Variable declaration closer to usage Vs Declaring at the top of Method"
}
|
6283
|
<p>I'm currently looking at <a href="http://www.boost.org/doc/libs/1_48_0/libs/crc/crc_example.cpp" rel="nofollow">this Boost::CRC example code</a> which I have also inserted below.</p>
<p>I always try to look for suggestions for improving my own coding style when I encounter well-written and well-formatted code.</p>
<p>This code definitely looks like good code, but two things puzzle me about this:</p>
<ul>
<li><p>is it good practice to copy <code>#define</code>d constants to local <code>const</code> variables before using them? Why would this be a good idea?</p></li>
<li><p>is it actually acceptable to just omit the parenthesis around a function body if the body is a <code>try</code>-<code>catch</code>-block?</p></li>
</ul>
<p></p>
<pre><code>// Boost CRC example program file ------------------------------------------//
// Copyright 2003 Daryle Walker. Use, modification, and distribution are
// subject to the Boost Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or a copy at <http://www.boost.org/LICENSE_1_0.txt>.)
// See <http://www.boost.org/libs/crc/> for the library's home page.
// Revision History
// 17 Jun 2003 Initial version (Daryle Walker)
#include <boost/crc.hpp> // for boost::crc_32_type
#include <cstdlib> // for EXIT_SUCCESS, EXIT_FAILURE
#include <exception> // for std::exception
#include <fstream> // for std::ifstream
#include <ios> // for std::ios_base, etc.
#include <iostream> // for std::cerr, std::cout
#include <ostream> // for std::endl
// Redefine this to change to processing buffer size
#ifndef PRIVATE_BUFFER_SIZE
#define PRIVATE_BUFFER_SIZE 1024
#endif
// Global objects
std::streamsize const buffer_size = PRIVATE_BUFFER_SIZE;
// Main program
int
main
(
int argc,
char const * argv[]
)
try
{
boost::crc_32_type result;
for ( int i = 1 ; i < argc ; ++i )
{
std::ifstream ifs( argv[i], std::ios_base::binary );
if ( ifs )
{
do
{
char buffer[ buffer_size ];
ifs.read( buffer, buffer_size );
result.process_bytes( buffer, ifs.gcount() );
} while ( ifs );
}
else
{
std::cerr << "Failed to open file '" << argv[i] << "'."
<< std::endl;
}
}
std::cout << std::hex << std::uppercase << result.checksum() << std::endl;
return EXIT_SUCCESS;
}
catch ( std::exception &e )
{
std::cerr << "Found an exception with '" << e.what() << "'." << std::endl;
return EXIT_FAILURE;
}
catch ( ... )
{
std::cerr << "Found an unknown exception." << std::endl;
return EXIT_FAILURE;
}
</code></pre>
|
[] |
[
{
"body": "<p>I'd invert the condition and use a <code>continue</code> if there is an error with the stream:</p>\n\n<pre><code>for (int i = 1; i < argc; ++i) {\n std::ifstream ifs(argv[i], std::ios_base::binary);\n if (!ifs) {\n std::cerr << \"Failed to open file '\" << argv[i] << \"'.\" << std::endl;\n continue; // or return EXIT_FAILURE;\n }\n\n do {\n char buffer[buffer_size];\n\n ifs.read(buffer, buffer_size);\n result.process_bytes(buffer, ifs.gcount());\n } while (ifs);\n}\n</code></pre>\n\n<p><a href=\"http://www.codinghorror.com/blog/2006/01/flattening-arrow-code.html\" rel=\"nofollow\">http://www.codinghorror.com/blog/2006/01/flattening-arrow-code.html</a></p>\n\n<p>I'm not a C++ master, but maybe the streams should be closed somewhere.</p>\n\n<p>(I know that this isn't an answer to your questions but maybe you find it useful.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-26T01:59:33.087",
"Id": "9777",
"Score": "0",
"body": "Strictly speaking yes, ifstream ifs should be closed. Practically speaking, in an application of this size it doesn't matter. The streams will be destroyed when the application terminates."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-26T02:32:22.540",
"Id": "9778",
"Score": "3",
"body": "@Nathanael, eh? This is C++, the file will be closed when the ifs object is destructed at the end of the loop body. Each file will be closed before the next one is opened."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-26T02:49:01.877",
"Id": "9781",
"Score": "1",
"body": "@Winston Ewert: You're correct. Too much time spent in other languages for me."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-25T21:10:00.957",
"Id": "6297",
"ParentId": "6295",
"Score": "0"
}
},
{
"body": "<blockquote>\n <p>is it good practice to copy #defined constants to local const\n variables before using them? Why would this be a good idea?</p>\n</blockquote>\n\n<p>It's not good or bad, but it's definitely weird. In general I prefer constant values to #defines because they have an explicit type that can be checked at compile time. The only benefit (and I hesitate to call it that) of this code is that you could define PRIVATE_BUFFER_SIZE in another header file and it would override the definition here.</p>\n\n<blockquote>\n <p>is it actually acceptable to just omit the parenthesis around a\n function body if the body is a try-catch-block?</p>\n</blockquote>\n\n<p>It might compile, but it's a terrible practice. Don't do it! ;)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-26T02:33:28.937",
"Id": "9779",
"Score": "0",
"body": "The missing braces around main irks me, but I can't express a reason why it seems like a bad idea. I suspect the define trick is used in order to allow it to be specified as a compile time constant on the command line."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-26T04:28:02.793",
"Id": "9785",
"Score": "2",
"body": "This is called a \"function-try-block\". It's a somewhat unusual feature (and generally only aimed at constructors), so some people object to it. It has to follow certain special rules, so perhaps it's less confusion to avoid those."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-26T01:55:46.447",
"Id": "6301",
"ParentId": "6295",
"Score": "2"
}
},
{
"body": "<p>With the manifest constant being assigned to a const variable, you now have two ways of referring to the same value. In principle, this is superfluous, and should therefore be avoided. In practice, with manifest constants always being globally visible in C++, this is a rather moot point, but it can still be used for making a decision in lack of any other point. So, if there are any other considerations not immediately evident in the code, such as the need to be able to redefine the manifest constant AND at the same time the need to have the constant strongly typed, then by all means, it should be kept, and preferably documented.</p>\n\n<p>The try statement used as a function body looks mighty weird, which means that the average C++ programmer looking at it will go \"WTF?\". At the same time it does not accomplish any mighty feat that will make one add \"--oh, I see why it is done that way, cool!\". It is okay for a coding technique to have a certain WTF factor to it, as long as it accomplishes something neat, the neatness of which is proportional to its WTFness, so as to justify it. All that the try-statement-used-as-a-function-body accomplishes is to spare us from having to type an additional --but expected-- pair of curly brackets. Therefore, it should definitely be avoided.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-26T20:25:16.413",
"Id": "9800",
"Score": "0",
"body": "I think the intention for the `try` block as function body was that it's immediately evident that no code can be put somewhere else than in the `try` block, meaning that there can be no unhandled exceptions. But, of course, the `catch` block could, in theory, still throw …"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-26T21:14:18.343",
"Id": "9804",
"Score": "0",
"body": "Right, it could still throw. Also, it could fail to catch some exceptions; you don't know unless you scroll down to the catch statements and make sure that one of them is indeed a catch-all."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-26T09:17:31.530",
"Id": "6307",
"ParentId": "6295",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "6307",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-25T20:13:13.157",
"Id": "6295",
"Score": "8",
"Tags": [
"c++",
"boost"
],
"Title": "Boost CRC example program file"
}
|
6295
|
<p>Here it is the best I can do (I am a noob using Haskell):</p>
<pre><code>map (\(y, z) -> y + z) (zip x (tail x))
</code></pre>
<p>I'm looking for a point-free solution.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-26T19:57:20.337",
"Id": "9794",
"Score": "0",
"body": "\"Each element is the sum of itself with the next element of a List\", so in other words, `repeat 0`? :)"
}
] |
[
{
"body": "<p>Pointfree, eh? Let's ask lambdabot.</p>\n\n<pre><code><DanBurton> @pl map (\\(y, z) -> y + z) (zip x (tail x))\n<lambdabot> zipWith (+) x (tail x)\n</code></pre>\n\n<p>Assuming that <code>x</code> is simply the input to this \"function\"</p>\n\n<pre><code><DanBurton> @pl \\x -> map (\\(y, z) -> y + z) (zip x (tail x))\n<lambdabot> map (uncurry (+)) . ap zip tail\n</code></pre>\n\n<p>Personally I'd go with the former; I'm not a fan of Lambdabot's gratuitous use of <code>uncurry</code> and <code>ap</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-10T04:50:40.267",
"Id": "10410",
"Score": "3",
"body": "The fact that Haskell has an IRC bot that can refactor Haskell code blows my mind. Well played sir."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-02T12:07:01.350",
"Id": "16814",
"Score": "0",
"body": "The usage of lambdabot here is amazing. I would give you 10 ups, if I could!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-26T19:55:06.747",
"Id": "6316",
"ParentId": "6299",
"Score": "7"
}
},
{
"body": "<p>You could use <code>&&&</code> from <code>Control.Arrow</code> (along with the <code>zipWith</code> trick from Dan's solution):</p>\n\n<pre><code>foo = uncurry (zipWith (+)) . (tail &&& id)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-27T02:27:46.700",
"Id": "6322",
"ParentId": "6299",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-26T00:50:58.017",
"Id": "6299",
"Score": "8",
"Tags": [
"haskell"
],
"Title": "Each element is the sum of itself with the next element of a List: now do this point-free in Haskell"
}
|
6299
|
<p>After checking some incoming coding competitions, I feel I may want to develop a little bit more on my coding skills and style using some basic algorithms/data structures.</p>
<p>The following two pieces of Java code are about some <code>LinkedList</code> operation. Can you take a quick look and give me some feedback about the accuracy, efficiency, better solution, or code style?</p>
<p>The Java code includes some simple comments, test cases, and it is tested at Java 6 and reviewed by myself.</p>
<pre><code>/*
* purpose of program - for a singly linkedList, switch the elements at odd number positions with
* the ones at even number positions
*
input sample : 1>2>3>4>5; expecting output: 2>1>4>3>5;
input sample : 1>2>3>4; expecting output: 2>1>4>3;
*/
</code></pre>
<hr>
<p>ListTwister.java</p>
<pre><code>package com.algo;
/*
* purpose of program - for a singly linkedList, switch the elements at odd number positions with
* the ones at even number positions
*
input sample : 1>2>3>4>5; expecting output: 2>1>4>3>5;
input sample : 1>2>3>4; expecting output: 2>1>4>3;
*/
public class ListTwister {
/* for odd sequence element (array index = 0, 2, etc), store a "branch head", store prev node, and move to next;
for even sequence element (array index = 1, 3, etc), store the "nextNode", twist current and prev node, link the "branch head" to the currentNode, and link the "prev node" to cached "nextNode"
*/
public static Node twist(Node head) {
Node current = head, newHead = null, branchHead = null, tempNext = null, prev = null ;
int index = 0;
if (head!=null & head.next!=null ) {
newHead = head.next;
}
else {
newHead = head;
}
while (current != null) {
//odd sequence
if (index % 2 == 0) {
branchHead = prev;
prev = current;
current = current.next;
}
//even sequence
else {
tempNext = current.next;
current.next = prev;
if (branchHead != null ) {
branchHead.next = current;
}
prev.next = tempNext;
current = tempNext;
}
index ++;
} // end of while
return newHead;
} // end of twist()
public static void main (String args[]) {
Node head_list1 = new Node(1, null);
Node node2_list1 = new Node(2, null);
Node node3_list1 = new Node(3, null);
Node node4_list1 = new Node(4, null);
Node node5_list1 = new Node(5, null);
head_list1.add(node2_list1 );
node2_list1.add(node3_list1 );
node3_list1.add(node4_list1 );
node4_list1.add(node5_list1 );
Node head_list2 = new Node(1, null);
Node node2_list2 = new Node(2, null);
Node node3_list2 = new Node(3, null);
Node node4_list2 = new Node(4, null);
head_list2.add(node2_list2 );
node2_list2.add(node3_list2 );
node3_list2.add(node4_list2 );
head_list1.print();
//expect to output : 2->1->4->3->5->END.
twist(head_list1).print();
head_list2.print();
//expect to output : 2->1->4->3->END.
twist(head_list2).print();
} // end of main()
} // end of class
</code></pre>
<hr>
<p>Node.java</p>
<pre><code>package com.algo;
/*
Node for singly LinkedList;
*/
public class Node {
public int value;
public Node next;
public Node (int value, Node next) {
this.value = value;
this.next = next;
}
public void add(Node node) {
this.next = node;
}
public void print() {
Node current = this;
while (current!=null ) {
System.out.print(current.value + "->");
current = current.next;
}
if (current==null) {
System.out.println("END.");
}
}
} // end of class
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-26T02:50:12.243",
"Id": "9782",
"Score": "0",
"body": "You missed a `&`. `if (head!=null & head.next!=null )` should be `&&`. I assume that was just a copy-paste thing because it wouldn't compile otherwise."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-26T04:00:19.337",
"Id": "9784",
"Score": "0",
"body": "If you're going to use Javadoc comments, make them real Javadocs :) In `Node.print` is there a way that loop can terminate w/o `current == null`? If no, what's the check for?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-26T17:06:37.513",
"Id": "9789",
"Score": "0",
"body": "@Kevin: thx. I changed \"&\" to \"&&\". it was bug due to typo, although \"&\" is totally compilable. \"&\" is not a short-circuit logical operator, which will cause NPR exception in some case."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-26T17:07:27.387",
"Id": "9790",
"Score": "0",
"body": "@DaveNewton: thx. yr suggestion makes sense. I removed the unnecessary check."
}
] |
[
{
"body": "<p>Rename <code>Node.add</code> to <code>setNext</code>, since its a setter method:</p>\n\n<pre><code>public void setNext(final Node node) {\n this.next = node;\n}\n</code></pre>\n\n<hr>\n\n<p>Create a constructor with only the <code>value</code> parameter:</p>\n\n<pre><code>public Node(final int value) {\n this.value = value;\n}\n</code></pre>\n\n<p>and call this in your <code>main</code> method instead of passing <code>null</code>s:</p>\n\n<pre><code>final Node head_list1 = new Node(1);\n</code></pre>\n\n<hr>\n\n<p>Do not use <code>public</code> fields:</p>\n\n<pre><code>public int value;\npublic Node next;\n</code></pre>\n\n<p>Make them <code>private</code> and provide getters and setters.</p>\n\n<hr>\n\n<p>The <code>value</code> field could be <code>final</code>:</p>\n\n<pre><code>public class Node {\n private final int value;\n ...\n}\n</code></pre>\n\n<p>It should not change, so protect it with <code>final</code>.</p>\n\n<hr>\n\n<p>Instead of the main method write self-checking unit tests. The posted <code>main</code> should be separated to two test.</p>\n\n<hr>\n\n<p>The <code>Node</code> class shouldn't be responsible for printing. It should return a <code>String</code> instead of <code>System.out.print()</code> calls. Maybe another client wants to write it to a file or a socket, but <code>System.out.print()</code> made it impossible.</p>\n\n<hr>\n\n<p>Declare only one variable per line.</p>\n\n<hr>\n\n<pre><code> while (current != null) {\n System.out.print(current.value + \"->\");\n current = current.next;\n }\n if (current == null) {\n System.out.println(\"END.\");\n }\n</code></pre>\n\n<p>The <code>current == null</code> condition seems always true, so it's unnecessary:</p>\n\n<pre><code> while (current != null) {\n System.out.print(current.value + \"->\");\n current = current.next;\n }\n System.out.println(\"END.\");\n</code></pre>\n\n<hr>\n\n<p>Check input:</p>\n\n<pre><code>public static Node twist(final Node head) {\n if (head == null) {\n throw new NullPointerException(\"head cannot be null\");\n }\n ...\n}\n</code></pre>\n\n<hr>\n\n<p>It's unnecessary to set default value for all variables to <code>null</code>:</p>\n\n<pre><code>Node newHead = null;\n</code></pre>\n\n<p>Furthermore, it could be <code>final</code> since it get its value before it will be used:</p>\n\n<pre><code>final Node newHead;\n</code></pre>\n\n<hr>\n\n<p>Read Effective Java, Second Edition, Item 45: Minimize the scope of local variables. (Google for \"minimize the scope of local variables\", it's on Google Books too.)</p>\n\n<p>For example, <code>tempNext</code> should be declared inside the else branch:</p>\n\n<pre><code>else {\n final Node tempNext = current.next;\n current.next = prev;\n if (branchHead != null) {\n branchHead.next = current;\n }\n prev.next = tempNext;\n current = tempNext;\n}\n</code></pre>\n\n<hr>\n\n<p>Use camelCase variable names: <code>head_list1</code> -> <code>headList1</code>. (Effective Java, Second Edition, Item 56: Adhere to generally accepted naming conventions)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-26T17:09:48.880",
"Id": "9791",
"Score": "0",
"body": "thanks a lot for your detailed feedbacks. majority of them make sense to me. I shall take some time to absorb the suggestions."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-26T08:33:54.633",
"Id": "6305",
"ParentId": "6302",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "6305",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-26T02:23:55.370",
"Id": "6302",
"Score": "2",
"Tags": [
"java",
"algorithm",
"linked-list"
],
"Title": "Linked list operations for a competition"
}
|
6302
|
<p>I'm trying to convert from random bytes to integers within a range. Basically converting as such:</p>
<pre><code>byte[] GetRandomBytes(int count) -> int NextInteger(int min, int max)
</code></pre>
<p>Another way to think about it would be: I have a <a href="http://msdn.microsoft.com/en-us/library/system.security.cryptography.rngcryptoserviceprovider.aspx" rel="nofollow noreferrer"><code>RNGCryptoServiceProvider</code></a> but would rather have the interface to <a href="http://msdn.microsoft.com/en-us/library/system.random.aspx" rel="nofollow noreferrer"><code>Random</code></a>.</p>
<p>My current algorithm works out how many bits it needs based on <code>min</code> and <code>max</code>, gets a random int (after masking off any bits it doesn't need), then loops until it gets a number less than <code>max - min</code>.</p>
<p>Question 1: Is my algorithm sound? </p>
<p>Question 1a: Is the below implementation sound (c#) (specifically: <code>RandomSourceBase.Next(int, int)</code>)?</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Security.Cryptography;
namespace ConsoleApplication1
{
public abstract class RandomSourceBase
{
public abstract byte[] GetRandomBytes(int numberOfBytes);
public int Next()
{
return Next(0, Int32.MaxValue);
}
public int Next(int maxValue)
{
return Next(0, maxValue);
}
public int Next(int minValue, int maxValue)
{
if (minValue < 0)
throw new ArgumentOutOfRangeException("minValue", minValue, "MinValue must be greater than or equal to zero.");
if (maxValue <= minValue)
throw new ArgumentOutOfRangeException("maxValue", maxValue, "MaxValue must be greater than minValue.");
int range = maxValue - minValue;
if (range == 1) // Trivial case.
return minValue;
// Determine how many bits are required for the range requested.
int bitsRequired = (int)Math.Ceiling(Math.Log(range, 2) + 1);
int bitmask = (1 << bitsRequired) - 1;
// Loop until we get a number within the range.
int result = -1;
while (result < 0 || result > range - 1)
{
var bytes = this.GetRandomBytes(4);
result = (Math.Abs(BitConverter.ToInt32(bytes, 0)) & bitmask) - 1;
}
return result + minValue;
}
}
public class CryptoRandomSource : RandomSourceBase
{
private RNGCryptoServiceProvider _RandomProvider;
public CryptoRandomSource()
{
this._RandomProvider = new RNGCryptoServiceProvider();
}
public override byte[] GetRandomBytes(int numberOfBytes)
{
var result = new byte[numberOfBytes];
this._RandomProvider.GetBytes(result);
return result;
}
}
class Program
{
static void Main(string[] args)
{
TestNextInt32(new CryptoRandomSource(), 50);
TestNextInt32(new CryptoRandomSource(), 64);
Console.ReadLine();
}
private static void TestNextInt32(RandomSourceBase randomness, int max)
{
var distributionTable = new Dictionary<int, int>();
for (int i = 0; i < max; i++)
distributionTable.Add(i, 0);
Console.WriteLine("Testing CryptoRandomStream.Next({0})...", max);
int trials = max * 50000;
for (int i = 0; i < trials; i++)
{
var choice = randomness.Next(max);
distributionTable[choice] = distributionTable[choice] + 1;
}
for (int i = 0; i < max; i++)
Console.WriteLine("{0}, {1}", i, distributionTable[i]);
Console.WriteLine();
}
}
}
</code></pre>
<p>Question 2: Assuming <code>GetRandomBytes</code> is actually random, will my algorithm / implementation also be random (specifically a uniform distribution?).</p>
<p>I've done a few test runs and graphed the distribution in Excel. They look random-ish to me. But, well, I'm no security expert, and the stats course I did was in 2003 and my memory isn't very good! Specifically, I don't know if the variation of up to 800 or ~1.6% (point #3 on the 50 graph) is acceptable or if I've done something horribly wrong.</p>
<p><img src="https://i.stack.imgur.com/LiRna.png" alt="0..49">
<img src="https://i.stack.imgur.com/pioRO.png" alt="0..63"></p>
<p>(Note, the Y axis isn't zeroed. 50,000 is the desired number).</p>
<p>Context: I'm building a plugin for <a href="http://keepass.info/" rel="nofollow noreferrer">KeePass</a> and its RNG returns a <code>byte[]</code> but most of my logic is tied up in choosing indexes from a collection, hence my need to convert random bytes to random <code>int</code>s within a range. </p>
<p><sub>
Actual real life code (for those who are interested):
</sub>
<sub>
<a href="http://readablepassphrase.codeplex.com/SourceControl/changeset/changes/aa085616bc23" rel="nofollow noreferrer">http://readablepassphrase.codeplex.com/SourceControl/changeset/changes/aa085616bc23</a>
</sub>
<sub>
Relevant code located in: trunk/ReadablePassphrase/Random
</sub></p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-26T06:41:15.020",
"Id": "9787",
"Score": "0",
"body": "Fun part about real randomness: it's entirely possible (though \"unlikely\" is a severe understatement) for you to legitimately get the same number a million times in a row. I'd be a bit more skeptical of a flat line than one with spikes in it, unless the spikes always occurred in the same places."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-26T09:11:01.027",
"Id": "9788",
"Score": "0",
"body": "@cHao - Just to point out how unlikely that scenario is, `Int32.MaxVal ^ 1000000` gives an error in windows calculator and returns `Double.Infinity` in .NET. Even 64^10 (10 of the same number in a row) is 1.15E+18 (an order of magnitude less than 2^64). I'd be highly suspicious of that generator! http://dilbert.com/strips/comic/2001-10-25/"
}
] |
[
{
"body": "<p>I think that looping until a number within range pops up is a very weird idea. The first potential problem that comes to mind is the possibility that under certain circumstances (say, max = min + 2) you might be looping for a long time. A closer examination of your code shows that such a possibility is taken care of, but at the expense of significant added complexity. Why not just apply the modulus operator between the generated random 32-bit integer and the desired range? This would simplify your code and greatly reduce its length. It is a lot easier to tell whether a short and simple piece of code is sound, than a long and complicated one.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-27T03:44:22.997",
"Id": "9819",
"Score": "0",
"body": "Ahhh, modulus! Why didn't I think of that. I'm accepting Peter's answer because he supplied code I could test though."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-19T14:25:46.237",
"Id": "29975",
"Score": "1",
"body": "Modulus wouldn't work because the lower numbers would appear more frequently. Consider generating a number in the range 0..200 from a 8 bit random number: x = random(256) % 200. P(x == 0) = 2/256 and P(x == 199) = 1/256"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-22T23:09:23.520",
"Id": "30171",
"Score": "0",
"body": "@Phil Not that it matters much now that the question has an accepted answer, but I think that modulus will yield a skewed distribution favoring smaller numbers only if the desired range represents a significant portion of the original range. In other words, if you have random byte values and you need indexes between 0 and 200, then modulus is probably not a very good idea. But if you group every four random bytes into a random 32-bit integer, as I suggested, and then apply modulus, then you should be fine for any reasonable range of indexes. No?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-23T13:53:56.613",
"Id": "30197",
"Score": "1",
"body": "In the end it will depend how much bias is acceptable for the application. If you assume that the OP is using RNGCryptoServiceProvider because it is security sensitive, then it is likely easier to have no bias than to work out how much is acceptable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-04-29T00:58:29.747",
"Id": "307679",
"Score": "0",
"body": "Need to reject values greater than the last modus to remove bias. Easy enough."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-26T11:55:28.120",
"Id": "6310",
"ParentId": "6304",
"Score": "1"
}
},
{
"body": "<p>Yes, the algorithm as described is sound, although not the most efficient use of the random number source. However, there are a few surprises in the code. Making the default <code>Next()</code> capable of returning 2^31 - 1 distinct values is a bit unexpected, and slightly skews the distribution of the lower bits. It might be worth changing the names, too, in case you want to add more output types later. I would adjust as follows:</p>\n\n<pre><code> public int NextInt32()\n {\n byte[] bytes = GetRandomBytes(4);\n int i = BitConverter.ToInt32(bytes);\n return i & Int32.MaxValue;\n }\n\n public int NextInt32(int maxExcl)\n {\n if (maxExcl <= 0) throw new ArgumentOutOfRangeException(\"maxExcl\", maxExcl, \"maxExcl must be positive\");\n\n // Let k = (Int32.MaxValue + 1) % maxExcl\n // Then we want to exclude the top k values in order to get a uniform distribution\n // You can do the calculations using uints if you prefer to only have one %\n int k = ((Int32.MaxValue % maxExcl) + 1) % maxExcl;\n while (true)\n {\n int rnd = NextInt32();\n if (rnd <= Int32.MaxValue - k)\n return rnd % maxExcl;\n }\n }\n\n public int NextInt32(int minIncl, int maxExcl)\n {\n if (minIncl < 0)\n throw new ArgumentOutOfRangeException(\"minIncl\", minIncl, \"minValue must be non-negative\");\n if (maxExcl <= minIncl)\n throw new ArgumentOutOfRangeException(\"maxExcl\", maxExcl, \"maxExcl must be greater than minIncl\");\n\n return minIncl + NextInt32(maxExcl - minIncl);\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-26T18:26:10.007",
"Id": "6314",
"ParentId": "6304",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "6314",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-26T04:17:11.553",
"Id": "6304",
"Score": "4",
"Tags": [
"c#",
"random"
],
"Title": "Algorithm to convert random bytes to integers"
}
|
6304
|
<p>I've written a simple class that somewhat simulates multiple inheritance using mixins. It allows you to extend the functionality of multiple classes and manage any conflicts between them, should they arise.</p>
<p><strong><code>Mixer</code> class</strong></p>
<pre><code>abstract class Vm_Mixer {
protected $methods = array();
protected $mixins = array();
protected $priorities = array();
/**
* @description By adding a mixin, the class will automatically adopt all of a mixin's methods.
* @param object $mixin - The instantiated object that's methods should be adopted by the extending class.
*/
public function addMixin($mixin){
$name = get_class($mixin);
$this->mixins[$name] = $mixin;
$methods = get_class_methods($name);
$this->methods[$name] = $methods;
}
/**
* @description Gets the class's current mixins by name
* @return An array of mixin names
*/
public function getMixins(){
return array_keys($this->methods);
}
/**
* @description Manages conflicts for the mixins.
* @param array $priorities - The method name as the key, the class name that has priority in a conflict as the value.
*/
public function setPriorities(array $priorities){
$this->priorities = $priorities;
}
/**
* @description Magic method that calls the mixin methods automatically
* @param string $methodName - The name of the mixin method
* @param array $arguments - The arguments for the method
*/
public function __call($methodName, $arguments){
foreach ($this->methods as $className=>$methods){
if (in_array($methodName, $methods)){
if ((in_array($methodName, array_keys($this->priorities)))&&($className == $this->priorities[$methodName])){
call_user_func_array(array($className, $methodName), $arguments);
break;
} else if (!in_array($methodName, array_keys($this->priorities))){
call_user_func_array(array($className, $methodName), $arguments);
break;
}
}
}
}
}
</code></pre>
<p><strong>Example</strong></p>
<p>Here is a quick example of how this could be used:</p>
<p><strong>Mixin 1</strong></p>
<pre><code>class Weapons {
public function laser(){
echo 'Firing laser!<br/>';
}
public function catapult(){
echo 'Launching catapult! MEEEOOOWWW!<br/>';
}
public function explode(){
echo 'Boom!<br/>';
}
public function greet(){
echo 'Prepare for your doom!<br/>';
}
}
</code></pre>
<p><strong>Mixin 2</strong></p>
<pre><code>class Defense {
public function shield(){
echo 'Enabling shield!<br/>';
}
public function invisibility(){
echo 'Activating invisibility cloak!<br/>';
}
public function explode(){
echo 'Self destruct sequence activated!<br/>';
}
public function serve(array $foodItems){
echo '#Sets table with '.implode(', ', $foodItems).'#<br/>';
}
}
</code></pre>
<p><strong><code>Robot</code> class</strong></p>
<pre><code>class Robot extends Vm_Mixer {
protected $name;
public function __construct($name){
$this->name = $name;
$this->addMixin(new Weapons());
$this->addMixin(new Defense());
//The explode method has a conflict as it exists in both Weapons and Defense, so let's give precedence to Defense
$this->setPriorities(array('explode'=>'Defense'));
}
//Pre-empts the Weapons::greet method
public function greet(){
echo "Hi, my name is $this->name.</br>";
}
}
</code></pre>
<p><strong>Usage</strong></p>
<pre><code>$robot = new Robot('Robby');
$robot->greet();
$robot->shield();
$robot->laser();
$robot->explode();
$robot->serve(array('Pizza', 'Cheeseburgers', 'Egg Nog', 'Vanilla Pudding'));
</code></pre>
<p>The above will return:</p>
<blockquote>
<pre class="lang-none prettyprint-override"><code>Hi, my name is Robby.
Enabling shield!
Firing laser!
Self destruct sequence activated!
#Sets table with Pizza, Cheeseburgers, Egg Nog, Vanilla Pudding#
</code></pre>
</blockquote>
<p>What I'm looking for in a review is as follows:</p>
<ul>
<li>How much will performance be an issue with this implementation (I'm mainly talking about method overloading here)?</li>
<li>Are there any other issues that I might run into that could cause conflicts or problems?</li>
<li>How can I improve the existing code?</li>
<li>What are some ways that this could be used? I know a few, but other ideas would be nice as well.</li>
<li>When should and shouldn't something like this be used?</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-12T19:11:01.550",
"Id": "137431",
"Score": "0",
"body": "> How can I improve the existing code? Your missing an implementation for `Vm_Mixer_Exception()`. Why were you using a custom `Exception` class? Was there more information than a regular `Exception` would give you?"
}
] |
[
{
"body": "<p>It's an interesting approach and it works as expected. My first reaction when reading the code was that you are trying to solve a problem that's commonly solved with the <a href=\"http://en.wikipedia.org/wiki/Composite_pattern\" rel=\"nofollow\">Composite pattern</a>, but then I realised you aren't actually trying to solve a problem but present an idea.</p>\n\n<p>Now as for the specifics: </p>\n\n<blockquote>\n <p>How much will performance be an issue with this implementation (I'm mainly talking about method overloading here)?</p>\n</blockquote>\n\n<p>Unless you find a realistic scenario, you can't discuss performance. Commonly method overloading and the <a href=\"http://php.net/manual/en/book.reflection.php\" rel=\"nofollow\">Reflection API</a> are considered to be very slow, but performance is not about being slow, it's about comparing solutions. Unless we find a realistic use of your architecture and at least one alternative, performance doesn't matter. </p>\n\n<blockquote>\n <p>Are there any other issues that I might run into that could cause conflicts or problems?</p>\n</blockquote>\n\n<p>You are dealing with the <a href=\"http://en.wikipedia.org/wiki/Diamond_problem\" rel=\"nofollow\">Diamond Problem</a> with the priorities scheme but you don't do anything for cases of equal priority. These might be outside of your scope, but the following snippet shows that relying on a priority list is extremely vulnerable: </p>\n\n<pre><code>$robot->setPriorities(array('explode'=>'Defense'));\n$robot->setPriorities(array('explode'=>'Weapons'));\n$robot->setPriorities(array('explode'=>'Defense'));\n$robot->setPriorities(array('explode'=>'Weapons'));\n</code></pre>\n\n<p>At any point the priority list can be changed, and the last one will be the actual one. This kind of dynamic behaviour can lead to myriads of extremely hard to find bugs, you should consider throwing an exception if a priority was already set. </p>\n\n<p>Furthermore you don't check for priority validity and you could do something like: </p>\n\n<pre><code>$robot->setPriorities(array('explode'=>'aaaa'));\n</code></pre>\n\n<p>since you don't check if the priority class actually exists and set the priority anyway, which will render <code>explode()</code> uncallable. And of course you could do something evil like:</p>\n\n<pre><code>$robot->setPriorities(array('explode'=>'Robot'));\n</code></pre>\n\n<p>which would throw your robot into an infinite loop. So you haven't actually dealt with every aspect of the Diamond Problem. You should also check if the class exists in <code>addMixin()</code>.</p>\n\n<blockquote>\n <p>How can I improve the existing code?</p>\n</blockquote>\n\n<p>Here: </p>\n\n<pre><code>public function __call($methodName, $arguments){\n foreach ($this->methods as $className=>$methods){\n if (in_array($methodName, $methods)){\n if ((in_array($methodName, array_keys($this->priorities)))&&($className == $this->priorities[$methodName])){\n call_user_func_array(array($className, $methodName), $arguments);\n break;\n } else if (!in_array($methodName, array_keys($this->priorities))){\n call_user_func_array(array($className, $methodName), $arguments);\n break; \n }\n } \n }\n}\n</code></pre>\n\n<ul>\n<li>it would be a lot nicer if you returned the value of the \"Mixin\" class instead of just calling it and breaking,</li>\n<li>you should deal with the case of a non existing function,</li>\n<li>the block is kind of unreadable. </li>\n</ul>\n\n<p>I'd refactor like: </p>\n\n<pre><code>public function __call($methodName, $arguments){\n foreach ($this->methods as $className => $methods) { \n if(!in_array($methodName, $methods)) {\n continue;\n }\n\n if(\n in_array($methodName, array_keys($this->priorities))\n && $className == $this->priorities[$methodName]\n ) {\n return call_user_func_array(array($className, $methodName), $arguments);\n } else if (!in_array($methodName, array_keys($this->priorities))) {\n return call_user_func_array(array($className, $methodName), $arguments); \n } \n }\n\n throw new Exception(\"Function not found\"); // or something like that\n}\n</code></pre>\n\n<p>And probably you should somehow deal with Exceptions thrown from the called functions.</p>\n\n<blockquote>\n <p>What are some ways that this could be used? I know a few, but other ideas would be nice as well.</p>\n \n <p>When should and shouldn't something like this be used?</p>\n</blockquote>\n\n<p>I have absolutely no clue. I've trained myself to forget all about multiple inheritance, since my programming roots were in C++. It would be nice if you tell us about your ideas that made you come up with the approach.</p>\n\n<p>PHP 5.4 will support <a href=\"http://php.net/manual/en/language.oop5.traits.php\" rel=\"nofollow\">traits</a>, a concept very similar to mixins. So, unfortunately your approach will soon become obsolete.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-26T20:31:48.803",
"Id": "9801",
"Score": "0",
"body": "Thanks, Yannis, very useful. I had done some reading on component based programming and so I wanted to experiment with it a little. Take a look at [Evolve Your Hierarchy](http://cowboyprogramming.com/2007/01/05/evolve-your-heirachy/) and [Component based game engine design](http://stackoverflow.com/questions/1901251/component-based-game-engine-design) for an introduction. The primary use case that I had in mind is game programming, similar to the first article I linked to. Can you expand a little on cases of equal priority? I can't think of an example of where that would come up."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-26T21:08:34.513",
"Id": "9803",
"Score": "0",
"body": "@VirtuosiMedia I've updated the answer. Just finished reading \"Evolve Your Hierarchy\" and I think it strongly hints towards the Composite pattern. Here's a [PHP oriented introduction](http://devzone.zend.com/364/php-patterns_the-composite-pattern/). Another pattern you could use in conjunction with composite and it might prove useful performance-wise is [flyweight](http://en.wikipedia.org/wiki/Flyweight_pattern). BTW what you're doing is somewhere between mixins and composite, as they are very closely related."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-27T02:35:44.963",
"Id": "9816",
"Score": "0",
"body": "Thanks again, Yannis. You're right on needing to have exceptions. I've updated the class to reflect your suggestions. Regarding the __call method, I think that I need both of those checks because a class could contain the called method but not be the one given the priority. The second check prevents those types of methods from being executed. Otherwise, the first class with the called method would automatically be executed."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-27T02:39:30.260",
"Id": "9817",
"Score": "0",
"body": "Regarding the composite pattern, I might be misunderstanding it, but wouldn't it require each of the mixins to share an interface? If so, that seems a little different than my implementation, where no restrictions are put on the mixins."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-27T03:27:22.300",
"Id": "9818",
"Score": "0",
"body": "@VirtuosiMedia Yes of course it would be a different implementation, and I'm not suggesting it be a better implementation. But why would it be bad if your mixins shared an interface? I've noticed why you need both checks when I last updated the question to expand the \"equal priority\" section and rollbacked the code to include both checks as it did originally."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-27T05:59:49.467",
"Id": "9824",
"Score": "0",
"body": "I don't think a shared interface would be bad either, just different. It takes a while to grasp certain design patterns sometimes, so I just wanted to make sure I understood what you were suggesting as it related to my class. I appreciate all the time and your insights, it definitely helped."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-26T20:05:09.427",
"Id": "6317",
"ParentId": "6306",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "6317",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-26T09:14:24.053",
"Id": "6306",
"Score": "5",
"Tags": [
"php",
"mixins"
],
"Title": "Multiple inheritance Mixin class"
}
|
6306
|
<p>I am writing this Monte Carlo simulation and I am facing this issue when running the code at 10,000,000 iterations. here is the code:</p>
<pre><code>import random as rnd
from time import time
#get user input on number of iterations
numOfIterations = raw_input('Enter the number of iterations: ')
numOfIterations = int(numOfIterations)
start = time()
#initialize bag (44 green, 20 blue, 15 yellow, 11 red, 2 white, 1 black
#a counter
#and question counter
bag = 44*'g'+ 20*'b' + 15*'y' + 11*'r' + 2*'w' + 'k'
counter = {'g':0, 'b':0,'y':0 ,'r':0,'w':0,'k':0}
question = {'one':0,'two':0,'three':0,'four':0,'five':0}
for i in range(0,numOfIterations):
for j in xrange(0,5):
draw = rnd.sample(bag,5)
for x in draw: counter[x]+=1
if counter['w'] >0 and counter['k'] >0: question['one']+=1
if counter['b'] > counter['r']: question['two']+=1
if counter['b'] > counter['y']: question['three']+=1
if counter['y'] > counter['r']: question['four']+=1
if counter['g'] < (counter['b']+counter['y']+counter['r']+counter['w']+counter['k']): question['five']+=1
for k in counter: counter[k] = 0
p1 = float(question['one'])/float(numOfIterations)
p2 = float(question['two'])/float(numOfIterations)
p3 = float(question['three'])/float(numOfIterations)
p4 = float(question['four'])/float(numOfIterations)
p5 = float(question['five'])/float(numOfIterations)
print 'Q1 \t Q2 \t Q3 \t Q4 \t Q5'
print str(p1)+'\t'+str(p2)+'\t'+str(p3)+'\t'+str(p4)+'\t'+str(p5)
end = time()
print 'it took ' +str(end-start)+ ' seconds'
</code></pre>
<p>any suggestions/criticism would be appreciated.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-28T16:26:05.633",
"Id": "9870",
"Score": "1",
"body": "Maybe switching to a compiled language might help. Not sure how well Python can JIT."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-28T08:18:43.970",
"Id": "30519",
"Score": "0",
"body": "you might want to try an run it in pypy. http://pypy.org/"
}
] |
[
{
"body": "<pre><code>import random as rnd\n</code></pre>\n\n<p>I dislike abbreviation like this, they make the code harder to read</p>\n\n<pre><code>from time import time\n\n#get user input on number of iterations\nnumOfIterations = raw_input('Enter the number of iterations: ')\nnumOfIterations = int(numOfIterations)\n</code></pre>\n\n<p>Any reason you didn't combine these two lines?</p>\n\n<pre><code>start = time()\n\n#initialize bag (44 green, 20 blue, 15 yellow, 11 red, 2 white, 1 black\n#a counter\n#and question counter\nbag = 44*'g'+ 20*'b' + 15*'y' + 11*'r' + 2*'w' + 'k'\ncounter = {'g':0, 'b':0,'y':0 ,'r':0,'w':0,'k':0}\nquestion = {'one':0,'two':0,'three':0,'four':0,'five':0}\n</code></pre>\n\n<p>Looking up your data by strings all the time is going to be somewhat slower. Instead, I'd suggest you keep lists and store the data that way. </p>\n\n<pre><code>for i in range(0,numOfIterations):\n</code></pre>\n\n<p>Given that numOfIterations will be very large, its probably a good idea to use xrange here. </p>\n\n<pre><code> for j in xrange(0,5):\n</code></pre>\n\n<p>You should generally put logic inside a function. That is especially true for any sort of loop as it will run faster in a function.</p>\n\n<pre><code> draw = rnd.sample(bag,5)\n for x in draw: counter[x]+=1\n</code></pre>\n\n<p>I dislike putting the contents of the loop on the same line. I think it makes it harder to read.</p>\n\n<pre><code> if counter['w'] >0 and counter['k'] >0: question['one']+=1\n if counter['b'] > counter['r']: question['two']+=1\n if counter['b'] > counter['y']: question['three']+=1\n if counter['y'] > counter['r']: question['four']+=1\n if counter['g'] < (counter['b']+counter['y']+counter['r']+counter['w']+counter['k']): question['five']+=1\n for k in counter: counter[k] = 0\n\np1 = float(question['one'])/float(numOfIterations)\np2 = float(question['two'])/float(numOfIterations)\np3 = float(question['three'])/float(numOfIterations)\np4 = float(question['four'])/float(numOfIterations)\np5 = float(question['five'])/float(numOfIterations)\n</code></pre>\n\n<p>Don't create five separate variables, create a list. Also, if you add the line <code>from __future__ import division</code> at the beginning of the file then dividing two ints will produce a float. Then you don't need to convert them to floats here.</p>\n\n<pre><code>print 'Q1 \\t Q2 \\t Q3 \\t Q4 \\t Q5'\nprint str(p1)+'\\t'+str(p2)+'\\t'+str(p3)+'\\t'+str(p4)+'\\t'+str(p5)\n</code></pre>\n\n<p>See if you had p1 a list, this would be much easier</p>\n\n<pre><code>end = time()\n\nprint 'it took ' +str(end-start)+ ' seconds'\n</code></pre>\n\n<p>For speed improvements you want to look at using numpy. It allows implementing efficient operations over arrays. </p>\n\n<p>In this precise case I'd use a multinomial distribution and solve the problem analytically rather then using monte carlo. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-26T15:50:49.213",
"Id": "6313",
"ParentId": "6311",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "6313",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-26T12:01:57.800",
"Id": "6311",
"Score": "5",
"Tags": [
"python",
"optimization"
],
"Title": "How can I optimize this Monte Carlo simulation running at 10,000,000 iterations?"
}
|
6311
|
<p>I need to create a protocol for sending data of various types over a socket connection. so I need to serialise the data to a byte stream. I only need signed and unsigned 32 bit integers, 64 bit integers, string and binary. It is only a start but if anyone can code review this I would really appreciate it.</p>
<pre><code>/* custom tlv protocol. byte1=type, bytes2-5=size, remaining=payload
Following types:
int32_t //signed int 32 bit
uint32_t //unsigned int 32 bit
uint64_t //unsigned int 64 bit
string - char* - int8_t*
byte* - unsigned char* -anything binary
Everything uses TLV. each message must contain type as first byte
currently a message is one tlv but expand so a message is a linked list of tlvs
*/
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
/* include stdint.h but as this is demo just use these here */
typedef unsigned char uint8_t;
typedef signed int int32_t;
typedef unsigned int uint32_t;
#ifdef WIN32
typedef unsigned __int64 uint64_t;
#else
typedef unsigned int64_t uint64_t;
#endif
enum data_type {DTYPE_S32 = 0, DTYPE_U32 = 1, DTYPE_U64 = 2, DTYPE_STRING = 3, DTYPE_BINARY = 4 };
struct tlv_msg
{
data_type datatype; /* datatypes - 5 types */
/* payload stored in a union */
union{
int32_t s32val; /* signed int 1 */
uint32_t u32val; /* 2 */
uint64_t u64val; /* 3 */
char* strval; /* 4 strings */
unsigned char* binval; /* 5 any binary data */
};
uint32_t bytelen; /* no. bytes of union/data part */
};
size_t tlv_encode(data_type type, uint64_t input_length, tlv_msg* inputdata,
unsigned char** outputdata, size_t *output_length);
/* allocation/de-allocation of memory */
size_t alloc_encode(data_type type, unsigned char** outputdata, size_t datasize = 0);
size_t alloc_decode(unsigned char* inputdata, tlv_msg** msg);
void free_encode(unsigned char** outputdata);
void free_decode(tlv_msg** msg);
size_t tlv_decode(unsigned char* inputdata, tlv_msg** msg);
void printbytes(unsigned char* bytes, size_t length);
void printmessage(tlv_msg* msg);
/* testing functions */
void tests32();
void testu32();
void testu64();
void teststring();
void testbinary();
int main()
{
//test encode/decond of various data values
tests32();
testu32();
testu64();
teststring();
testbinary();
return 0;
}
size_t tlv_encode(data_type type, uint64_t input_length, tlv_msg* inputdata,
unsigned char** outputdata, size_t *output_length)
{
if(!outputdata)
return 0;
//1 byte for type, 4 for length, plus data size
*output_length = (uint32_t)(1 + sizeof(uint32_t) + input_length);
unsigned char* p = *outputdata;
*p++ = (unsigned char)type;
for (int i = sizeof(uint32_t) - 1; i >= 0; --i)
*p++ = (unsigned char) ((input_length >> (i * 8)) & 0xFF);
/* next job is to append actual data on end */
while(input_length--) {
switch(inputdata->datatype) {
case DTYPE_S32: *p++ = (unsigned char)(inputdata->s32val >> (input_length * 8) & 0xFF); break;
case DTYPE_U32: *p++ = (unsigned char)(inputdata->u32val >> (input_length * 8) & 0xFF); break;
case DTYPE_U64: *p++ = (unsigned char)(inputdata->u64val >> (input_length * 8) & 0xFF); break;
case DTYPE_STRING: *p++ = *inputdata->strval++; break;
case DTYPE_BINARY: *p++ = *inputdata->binval++; break;
}
}
return *output_length;
}
size_t tlv_decode(unsigned char* inputdata, tlv_msg** msg) {
if(!msg)
alloc_decode(inputdata, msg);
unsigned char* p = inputdata;
/* skip first 5 bytes */
for(int i = 0; i < 5; ++i)
*p++;
int length = (*msg)->bytelen - 5;
while(length--) {
switch((*msg)->datatype) {
case DTYPE_S32:
(*msg)->s32val += *p++ << (length * 8);
break;
case DTYPE_U32:
(*msg)->u32val += *p++ << (length * 8);
break;
case DTYPE_U64:
(*msg)->u64val += *p++ << (length * 8);
break;
case DTYPE_STRING:
*(*msg)->strval++ = (char)*p++;
break;
case DTYPE_BINARY:
*(*msg)->binval++ = (unsigned char)*p++;
break;
default:
printf("tlv_decodegeneric error!!! unrecognised datatype %u\n", (*msg)->datatype);
break;
}
}
/* rewind to beginning of strings */
switch((*msg)->datatype) {
case DTYPE_STRING:
length = (*msg)->bytelen-5;
while(length--)
*(*msg)->strval--;
break;
case DTYPE_BINARY:
length = (*msg)->bytelen-5;
while(length--)
*(*msg)->binval--;
break;
}
return 0;
}
/* allocate for new message to be encoded */
size_t alloc_encode(data_type type, unsigned char** outputdata, size_t datasize) {
size_t allosize = datasize;
if(allosize == 0) {
switch(type) {
case DTYPE_S32: allosize = 4; break;
case DTYPE_U32: allosize = 4; break;
case DTYPE_U64: allosize = 8; break;
default:
printf("alloc_encode error!!! no datasize for data type %u\n", type);
return 0;
}
}
allosize += 5; /* append type and size fields */
*outputdata = (unsigned char*)malloc(allosize);
return allosize;
}
size_t alloc_decode(unsigned char* inputdata, tlv_msg** msg) {
/* check if already malloc'd and if so free and realloc */
if(*msg)
printf("alloc_decode already called");
/* length of data is in bytes 1,2,3,4 */
size_t sz = 0;
unsigned char* p = inputdata;
/*first byte is type */
unsigned char type = *p++;
for(int i = 0; i < 4; ++i)
sz += (unsigned char) (*p++ >> ((3-i) * 8) & 0xFF);
if(!sz)
printf("ERROR! zero bytes size found in input data\n");
*msg = (tlv_msg*)malloc(sizeof(tlv_msg));
if(*msg) {
(*msg)->bytelen = sz + 5; /* plus size for header type and length */
(*msg)->datatype = (data_type)type;
if(type == DTYPE_STRING)
(*msg)->strval = (char*)malloc((*msg)->bytelen);
else if(type == DTYPE_BINARY)
(*msg)->binval = (unsigned char*)malloc((*msg)->bytelen);
/* set safe defaults */
switch(type) {
case 0: (*msg)->s32val = 0; break;
case 1: (*msg)->u32val = 0; break;
case 2: (*msg)->u64val = 0; break;
case 3: *(*msg)->strval = 0; break;
case 4: *(*msg)->binval = 0; break;
}
}
/* add on 5 for type and length */
sz += 5;
return sz;
}
void free_encode(unsigned char** outputdata) {
free(*outputdata);
}
void free_decode(tlv_msg** msg) {
switch((*msg)->datatype) {
case DTYPE_STRING: free((*msg)->strval); break;
case DTYPE_BINARY: free((*msg)->binval); break;
}
free(*msg);
}
void printmessage(tlv_msg* msg) {
switch(msg->datatype) {
case DTYPE_S32: printf("%i\n", msg->s32val); break;
case DTYPE_U32: printf("%u\n", msg->u32val); break;
case DTYPE_U64: printf("%u\n", msg->u64val); break;
case DTYPE_STRING: printf("%s\n", msg->strval); break;
case DTYPE_BINARY: printbytes(msg->binval, msg->bytelen-5); break;
default: printf("unknown data type\n"); break;
}
}
void printbytes(unsigned char* bytes, size_t length) {
for(size_t i = 0; i < length; ++i) {
char c = 0;
div_t stResult = div(bytes[i], 16);
printf("%X%X ", stResult.quot, stResult.rem);
}
printf("\n");
}
void teststring() {
/* test string type encode/decode */
tlv_msg msgstr;
msgstr.datatype = DTYPE_STRING; /* ie string type */
char* hellomsg = "Hello World!";
printf("testing string encode/decode, value to encode: %s\n", hellomsg);
size_t szlen = strlen(hellomsg)+1;
msgstr.strval = (char*)malloc(szlen);
strcpy(msgstr.strval, hellomsg);
msgstr.bytelen = szlen;
size_t output_length = 0;
unsigned char* outputmsg = 0;
size_t ret = alloc_encode(DTYPE_STRING, &outputmsg, msgstr.bytelen);
tlv_encode(msgstr.datatype, msgstr.bytelen, &msgstr, &outputmsg, &output_length);
/* print bytes as hex */
printbytes(outputmsg, output_length);
tlv_msg* decode_msg = 0;
size_t bytes = alloc_decode(outputmsg, &decode_msg);
tlv_decode(outputmsg, &decode_msg);
printmessage(decode_msg);
printf("completed testing string encode/decode, decoded value: %s\n", decode_msg->strval);
free_encode(&outputmsg);
free_decode(&decode_msg);
}
void tests32() {
/* test signed int 32 bit type encode/decode */
tlv_msg msg;
msg.datatype = DTYPE_S32;
msg.bytelen = 4;
msg.s32val = -65999;
printf("testing s32 encode/decode, input value: %d\n", msg.s32val);
size_t output_length = 0;
unsigned char* outputmsg = 0;
size_t ret = alloc_encode(DTYPE_S32, &outputmsg, msg.bytelen);
tlv_encode(msg.datatype, msg.bytelen, &msg, &outputmsg, &output_length);
/* print bytes as hex */
printf("Hex string: ");
printbytes(outputmsg, output_length);
tlv_msg* decode_msg = 0;
size_t bytes = alloc_decode(outputmsg, &decode_msg);
tlv_decode(outputmsg, &decode_msg);
printmessage(decode_msg);
printf("decoded u32 value: %d\n", decode_msg->s32val);
free_encode(&outputmsg);
free_decode(&decode_msg);
}
void testu32() {
/* test unsigned int 32 bit type encode/decode */
tlv_msg msg;
msg.datatype = DTYPE_U32;
msg.bytelen = 4;
msg.u32val = 0xFFFFFFFF; //257;
printf("testing u32 encode/decode, input value: %u\n", msg.u32val);
size_t output_length = 0;
unsigned char* outputmsg = 0;
size_t ret = alloc_encode(DTYPE_U32, &outputmsg, msg.bytelen);
tlv_encode(msg.datatype, msg.bytelen, &msg, &outputmsg, &output_length);
/* print bytes as hex */
printf("Hex string: ");
printbytes(outputmsg, output_length);
tlv_msg* decode_msg = 0;
size_t bytes = alloc_decode(outputmsg, &decode_msg);
tlv_decode(outputmsg, &decode_msg);
printmessage(decode_msg);
printf("decoded u32 value: %u\n", decode_msg->u32val);
free_encode(&outputmsg);
free_decode(&decode_msg);
}
void testu64() {
/* test unsigned int 64 bit type encode/decode */
tlv_msg msg;
msg.datatype = DTYPE_U64;
msg.bytelen = 8;
msg.u64val = 0xFFFF;
printf("testing u64 encode/decode, input value: %u\n", msg.u64val);
size_t output_length = 0;
unsigned char* outputmsg = 0;
size_t ret = alloc_encode(DTYPE_U64, &outputmsg, msg.bytelen);
tlv_encode(msg.datatype, msg.bytelen, &msg, &outputmsg, &output_length);
/* print bytes as hex */
printf("Hex string: ");
printbytes(outputmsg, output_length);
tlv_msg* decode_msg = 0;
size_t bytes = alloc_decode(outputmsg, &decode_msg);
tlv_decode(outputmsg, &decode_msg);
printmessage(decode_msg);
printf("decoded u64 value: %u\n", decode_msg->u64val);
free_encode(&outputmsg);
free_decode(&decode_msg);
}
void testbinary(){
tlv_msg msgstr;
msgstr.datatype = DTYPE_BINARY; /* ie binary data type */
unsigned char binmsg[] = { 'a', 'b', 'c', '\0', 'a', 'b', 'c', '\0' };
printf("testing binary encode/decode, value to encode is abcnullabcnull\n");
msgstr.binval = (unsigned char*)malloc(sizeof(binmsg));
memcpy(msgstr.binval, binmsg, sizeof(binmsg));
msgstr.bytelen = sizeof(binmsg);
size_t output_length = 0;
unsigned char* outputmsg = 0;
size_t ret = alloc_encode(DTYPE_BINARY, &outputmsg, msgstr.bytelen);
tlv_encode(msgstr.datatype, msgstr.bytelen, &msgstr, &outputmsg, &output_length);
/* print bytes as hex */
printbytes(outputmsg, output_length);
tlv_msg* decode_msg = 0;
size_t bytes = alloc_decode(outputmsg, &decode_msg);
tlv_decode(outputmsg, &decode_msg);
printmessage(decode_msg);
//not sure a printout is required for binary
free_encode(&outputmsg);
free_decode(&decode_msg);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-26T22:24:44.997",
"Id": "9805",
"Score": "1",
"body": "look up htonl() and family of functions."
}
] |
[
{
"body": "<p>If I were to see a point in converting data types to a message, that could only be to be able to send such messages across the network without having to perform any further interpretation of their internal structure. However, your scheme produces messages that still require interpretation before they can be sent: the type of the message has to be examined in order to figure out how to transmit its payload, since the message will contain the actual data in the case of fixed-length types, but a pointer to the data in the case of variable-length types.</p>\n\n<p>I think it would make a lot more sense to construct your messages in such a way that they can be sent as binary blocks, without having to know anything more than their length.</p>\n\n<p>A message is supposed to be nothing else but two things: a length, and a body of data. When you are thinking at the message level and writing functions that send and receive messages, you should <em>not</em> be concerned with the internal structure of the data contained within the messages. Therefore, the notion of a \"data type\" is not pertinent at this level.</p>\n\n<p>At the level where you have just received a block of data of a known length, you can now start interpreting it in order to extract the payload from it. The first byte can contain the data type enum, while the remaining bytes can be the actual value. </p>\n\n<ul>\n<li><p>In the case of fixed-length data types, assertions can be in place to ensure that the length of the data is equal to the size of the value plus one for the first byte which contained the data type enum. </p></li>\n<li><p>For variable-length data types, the length of the value is the length of the data minus one for the first byte which contained the data type enum.</p></li>\n</ul>\n\n<p>An added advantage of doing things this way is that you only have to make one memory allocation per message, not two, one for the message struct and one for the variable-length data contained therein. Fewer allocations equal reduced memory fragmentation, which can be extremely important if your application runs for a long time.</p>\n\n<p>Another consideration you should bear in mind is whether your underlying transport mechanism offers efficient buffering or not. If, by any chance, it does offer efficient buffering, then you might gain performance by reading/writing bytes directly to/from the transport mechanism, instead of allocating and filling message structures. </p>\n\n<p>So, I do not have specific points to address in your code, because in my opinion it needs to be completely re-written. </p>\n\n<p>Next time you write it, please refrain from using hard-coded constants such as 4 where you should have sizeof(int32_t), 8 in some places where you should have sizeof(int64_t), 8 in other places where you should have a manifest constant called \"BITS_PER_BYTE\" (or BPB for brevity) etc. The reason we use manifest constants is not because their values might change, but because their names document our intentions and clarify the code.</p>\n\n<p>Also, for fixed-length data types, it is a good idea to heed @Loki Astari's advice, and pay due attention to the endianness of your data: always use a specific known endianness for data that is meant to be shared between different machines, and what better choice is there than <a href=\"https://en.wikipedia.org/wiki/Endianness#In_networking\" rel=\"nofollow\">Network Byte Order</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-29T16:33:25.870",
"Id": "9912",
"Score": "0",
"body": "Thank you for your comments. I am puzzled on your main point which is the use of the type. First you say that a type is not required, then you go on to say that the first byte can contain the data type enum. I will be using this protocol over a network tcp connection and frequently I will get half a message or 3 messages. So I don't see how I can do without a type. I don't want to be converting numbers to strings and vice versa. So I was a little confused. Are you suggesting that each 'message' sent should be a length and payload. and then within payload would be type followed by data?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-29T16:39:36.537",
"Id": "9915",
"Score": "0",
"body": "@user619818 Exactly. (I am sorry if I was not clear enough in the text of the answer.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-23T10:55:06.157",
"Id": "483084",
"Score": "0",
"body": "`BITS_PER_BYTE` already exists and is called `CHAR_BIT` in `<limits.h>`"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-27T08:53:06.830",
"Id": "6328",
"ParentId": "6315",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "6328",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-26T19:19:49.683",
"Id": "6315",
"Score": "5",
"Tags": [
"c"
],
"Title": "Protocol code to encode/decode various data types"
}
|
6315
|
<p>This program implements a <a href="http://sourceforge.net/projects/sgrep/" rel="nofollow noreferrer">sorted grep</a>, that is, a specialized version of <code>grep</code> for sorted files. It uses binary search for the lines of a file that begin with a certain string.</p>
<p>You can copy and paste the code in a file and run it as:</p>
<pre><code>$> runhaskell sgrep.hs "string to find" sorted_file
</code></pre>
<p>I'm looking for suggestions about style, efficiency, and correctness.</p>
<pre><code>module Main where
import Data.List (isPrefixOf)
import Data.Maybe (isNothing, fromJust)
import System.Environment (getArgs)
import System.IO
-- Chunk of a file
data Chunk = Chunk Handle Integer Integer
-- Is char newline?
isNL :: Char -> Bool
isNL c = c == '\n'
-- Are we at the beginning of file?
isBOF :: Handle -> IO Bool
isBOF = (fmap (== 0)) . hTell
-- Go to beginning of line
goToBOL :: Handle -> IO ()
goToBOL h = do
bof <- isBOF h
if bof
then return ()
else do
eof <- hIsEOF h
if eof
then do
hSeek h RelativeSeek (-2)
goToBOL h
else do
c <- hGetChar h
if isNL c
then return ()
else do
hSeek h RelativeSeek (-2)
goToBOL h
getCurrentLine :: Handle -> IO String
getCurrentLine h = goToBOL h >> hGetLine h
getPrevLine :: Handle -> IO (Maybe String)
getPrevLine h = do
goToBOL h
bof <- isBOF h
if bof
then return Nothing
else do
hSeek h RelativeSeek (-2)
goToBOL h
bof <- isBOF h
if bof
then return Nothing
else do
hSeek h RelativeSeek (-2)
goToBOL h
line <- hGetLine h
return $ Just line
goTo :: Handle -> Integer -> IO ()
goTo h i = do
hSeek h AbsoluteSeek i
search :: Chunk -> String -> IO (Maybe String)
search (Chunk h start end) str
| start >= end = return Nothing
| otherwise = do
if mid == (end - 1)
then return Nothing
else do
goTo h mid
midLine <- getCurrentLine h
prevLine <- getPrevLine h
-- putStrLn $ "*** " ++ show start ++ " " ++ show end ++ " " ++ show mid ++ " " ++ midLine ++ ", " ++ show prevLine
if str `isPrefixOf` midLine && ((isNothing prevLine) || not (str `isPrefixOf` (fromJust prevLine)))
then return $ Just midLine
else if str < midLine
then search (Chunk h start mid) str
else search (Chunk h mid end) str
where mid = (start + end) `div` 2
sgrep :: Handle -> String -> IO ()
sgrep h s = do
len <- hFileSize h
match <- search (Chunk h 0 len) s
-- putStrLn $ show match
c <- hGetContents h
putStrLn . unlines $ takeWhile (isPrefixOf s) (lines c)
main :: IO ()
main = do
args <- getArgs
let s = head args
putStrLn s
let fname = head $ tail args
withFile fname ReadMode (\h -> sgrep h s)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-26T19:57:29.410",
"Id": "9798",
"Score": "0",
"body": "@Dan I've flagged it for migration. The only thing left now is waiting for someone to see the flag."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-26T20:25:15.160",
"Id": "9799",
"Score": "1",
"body": "You should run this through [HLint](http://community.haskell.org/~ndm/hlint/). It gives many good suggestions for improvement."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-27T16:12:38.910",
"Id": "9832",
"Score": "0",
"body": "Thank all for your suggestions. You can find the result of my efforts [on github](https://github.com/lbolla/HSGrep)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-01T07:31:32.317",
"Id": "9999",
"Score": "0",
"body": "For who's interested, I've implemented a more efficient versionn using bytestrings. Code and benchmarks are available [here](http://lbolla.info/blog/2011/11/30/hsgrep-benchmarking/)."
}
] |
[
{
"body": "<p>Use your monads! Your code exhibits the walking-right antipattern. You can avoid it with <code>when</code> and <code>guard</code>. Consider <code>goToBOL</code>. This is how I would write it:</p>\n\n<pre><code>-- Go to beginning of line\ngoToBOL :: Handle -> IO ()\ngoToBOL h = do\n bof <- isBOF h\n when (not bof) $ do \n eof <- hIsEOF h\n if eof then do hSeek h RelativeSeek (-2)\n goToBOL h\n else do c <- hGetChar h\n when (not $ isNL c) $ do\n hSeek h RelativeSeek (-2)\n goToBOL h\n</code></pre>\n\n<p>In your other functions, namely <code>getPrevLine</code> and <code>search</code>, you'd better use <code>MaybeT IO x</code> instead of <code>IO (Maybe x)</code> as you can use the monadic combinators better when you do so.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-26T21:57:01.027",
"Id": "6319",
"ParentId": "6318",
"Score": "6"
}
},
{
"body": "<p>In addition to @FUZxxl's points:</p>\n\n<p>You call <code>sgrep</code> only from the last line of <code>main</code>, and the parameters are the wrong way round. Change to</p>\n\n<pre><code>sgrep :: String -> Handle -> IO ()\nsgrep s h = do\n ...\n</code></pre>\n\n<p>and</p>\n\n<pre><code> ...\n withFile fname ReadMode (sgrep s)\n</code></pre>\n\n<p>And I'd pattern match the command line arguments (assuming you don't need the benefits of <a href=\"http://www.haskell.org/ghc/docs/latest/html/libraries/base-4.4.1.0/System-Console-GetOpt.html\" rel=\"nofollow\">System.Console.GetOpt</a>):</p>\n\n<pre><code>main :: IO ()\nmain = do\n (s : fname : _) <- getArgs\n putStrLn s\n withFile fname ReadMode (sgrep s)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-27T14:27:58.380",
"Id": "6334",
"ParentId": "6318",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "6319",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2011-11-26T18:24:19.293",
"Id": "6318",
"Score": "6",
"Tags": [
"sorting",
"haskell",
"file",
"search"
],
"Title": "Sorted grep in Haskell"
}
|
6318
|
<p><em>Before you say anything: Due to project constraints, we cannot use Boost and we cannot use C++11 (yet;</em> perhaps <em>this will change</em> some <em>day).</em></p>
<p>The fact that I was unable to use smart pointers was nagging on me for some time, so I decided to cough up my own implementation, and it was surprisingly simple. So, I'd like you to have a look at it. Btw. I decided to use a linked list instead of a ref-counter to avoid <code>new</code>ing counters.</p>
<p>I ran some unit tests and couldn't find a problem. Perhaps you can suggest improvements?</p>
<hr>
<p>Here is my <code>SharedPtr.h</code>:</p>
<pre><code>#ifndef __NET_UTIL_SHARED_PTR_H__
#define __NET_UTIL_SHARED_PTR_H__
#include <stddef.h>
// since we cannot use boost nor C++11, nor TR1, we have to reinvent the wheel, sigh
namespace net {
namespace util {
class SharedPtrBase {
private:
mutable SharedPtrBase const* left;
mutable SharedPtrBase const* right;
protected:
SharedPtrBase();
SharedPtrBase(SharedPtrBase const& from);
~SharedPtrBase();
void leave() const; // Note: leaving is idempotent
void join(SharedPtrBase const* where) const;
void assertWrapper(bool) const;
public:
bool isSingleton() const;
};
template <typename T> struct Deallocator {
private:
bool doDelete; // not const to be def. assignable
public:
// Implicit Constructor on purpose!
Deallocator(bool doDelete = true) : doDelete(doDelete) {}
bool willDelete() const {
return doDelete;
}
void operator()(T* t) const {
if (doDelete)
delete t;
}
};
template <typename T, typename Delete = Deallocator<T> >
class SharedPtr : private SharedPtrBase {
private:
Delete del;
T* ptr;
void drop() {
if (ptr && isSingleton()) {
del(ptr);
ptr = NULL;
}
leave();
}
public:
// SharedPtr(p,false) will not delete the pointer! Useful for Stackobjects!
explicit SharedPtr(T* ptr = NULL, Delete del = Delete())
: SharedPtrBase(), del(del), ptr(ptr) {
}
SharedPtr(SharedPtr const& from)
: SharedPtrBase(from), del(from.del), ptr(from.ptr) {
}
~SharedPtr() {
drop();
}
SharedPtr& operator=(SharedPtr const& from) {
if (&from != this) {
drop();
del = from.del;
ptr = from.ptr;
join(&from);
}
return *this;
}
bool operator==(SharedPtr const& with) const {
return ptr == with.ptr;
}
bool operator==(T* with) const {
return ptr == with;
}
bool operator<(SharedPtr const& with) const {
return ptr < with.ptr;
}
bool operator<(T* with) const {
return ptr < with;
}
T& operator*() const {
return *operator->();
}
T* operator->() const {
assertWrapper(ptr);
return ptr;
}
//T* release() {
// leave();
// T* const p = ptr;
// ptr = NULL;
// return p;
//}
};
}
}
#endif
</code></pre>
<p>And my <code>SharedPtr.cpp</code>:</p>
<pre><code>#include "util/SharedPtr.h"
#include <assert.h>
namespace net {
namespace util {
SharedPtrBase::SharedPtrBase()
: left(this), right(this) {
}
SharedPtrBase::SharedPtrBase(SharedPtrBase const& from)
: left(this), right(this) {
join(&from);
}
SharedPtrBase::~SharedPtrBase() {
leave();
}
// Note: leaving is idempotent.
// Try as much as you like, you will never leave yourself.
void SharedPtrBase::leave() const {
left->right = right;
right->left = left;
}
void SharedPtrBase::join(SharedPtrBase const* where) const {
assert(where);
leave();
assert(where->left && where->right);
left = where->left;
left->right = this;
right = where;
right->left = this;
}
void SharedPtrBase::assertWrapper(bool condition) const {
assert(condition);
}
bool SharedPtrBase::isSingleton() const {
return left == this;
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-26T23:05:46.477",
"Id": "9806",
"Score": "0",
"body": "There should be `reinvent-the-wheel` tag!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-27T02:23:50.540",
"Id": "9814",
"Score": "2",
"body": "PS. Don't use double underscore in your identifiers. Or identifiers that begin with single underscore followed by a capitol letter. Here `__NET_UTIL_SHARED_PTR_H__` is reserved for the implementation."
}
] |
[
{
"body": "<p>OK. Lets see..</p>\n\n<pre><code>void SharedPtrBase::leave() const {\n left->right = right;\n right->left = left;\n}\n</code></pre>\n\n<p>This removes you from the list, but does not reset your own left and right pointers. This is OK when you call it from the destructor() or join(). But what about release()?</p>\n\n<p>Lets look at release().</p>\n\n<pre><code> T* release() {\n leave();\n T* const p = ptr;\n ptr = NULL;\n return p;\n }\n</code></pre>\n\n<p>You have just released the pointer so that other functions can use it (and potentially free it). But all other members in the ring still have it (the pointer). What you should do is set the pointer to NULL in all members in the ring.</p>\n\n<p>I just spent two minutes and found two bugs. Implementing Shared pointer is not as simple as you think. It took them a while to get the boost version working correctly in all situations. So though it is a nice project implementing it safely is not as simple as you think.</p>\n\n<p>SharedPtrBase base is used to implement the underlying ring. But users can now potentially use it as a base class pointer:</p>\n\n<pre><code>SharedPtrBase* x = new SharedPtr<int>();\n\ndelete x; // Undefined behavior (destructor is not virtual).\n</code></pre>\n\n<p>Yes I know this is stupid. But the point is people get into weird situations and it may happen. It is your responsibility to prevent your class from being used incorrectly. A couple of solutions, make it privately inherited (as you have done), or the method I would use is to make a member (rather than a parent) to control the ring. Then your class can not be abused (and you do not need to make the destructor virtual).</p>\n\n<p>I personally (but this one is a personal opinion) don't like the use of a pointer in join:</p>\n\n<pre><code>void join(SharedPtrBase const* where) const;\n</code></pre>\n\n<p>By making it a reference you don't need to check that where is NULL and it should always be used with a known object on the other end (<code>where</code>). I would just have made this a reference as that implicitly conveys this requirement to the user and thus reduces the chances of misuse.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-27T00:13:48.050",
"Id": "9807",
"Score": "0",
"body": "Thanks for your feedback, but your last comment is not valid, because I use private inheritance. Regarding `release` this is the way release was supposed to work. Actually I think I will remove the method completely, because it is not needed right now, and as you point out it has unclear semantics (for me it says, \"THIS object relinquishes control\", buy you understand it as \"EVERY object relinquishes control\"). Besides that, any objections?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-27T00:16:37.170",
"Id": "9808",
"Score": "2",
"body": "You are correct I missed the private inheritance. But personally I would still make it a member."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-27T00:20:16.073",
"Id": "9809",
"Score": "0",
"body": "Regarding \"smart pointers are not trivial\": Absolutely, and I truly hate reinventing the wheel, but the difference is, I do not make the claim that my implementation comes anywhere near the boost implementation (I'd never be **that** delusional). However, as long as I need less functionality the feature-subset might be small enough for me to manage, right? And the choice is: My own smart pointers or no smart pointers at all!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-27T00:28:28.633",
"Id": "9810",
"Score": "1",
"body": "<quote>\"THIS object relinquishes control\"</quote> The trouble is that `THIS` is really the collection of shared pointers. What you may have been trying to implement is reset() which resets a single shared pointer to NULL (or another pointer) but if you are releasing the pointer then all members of the group must release it otherwise there may be multiple points of ownership and the point is you want to have a single point of ownership (in this case group ownership but a single point of ownership)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-27T00:32:07.177",
"Id": "9811",
"Score": "0",
"body": "Yes, I'm convinced. Doesn't make sense in my case, ... too expensive, ... removed. :)"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-26T23:57:11.430",
"Id": "6321",
"ParentId": "6320",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "6321",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-26T23:05:20.970",
"Id": "6320",
"Score": "1",
"Tags": [
"c++",
"smart-pointers",
"reinventing-the-wheel"
],
"Title": "Shared Pointer implementation"
}
|
6320
|
<p>I took a challenge on <a href="http://www.codeeval.com/open_challenges/37/" rel="nofollow">CodeEval</a>. Although the code seems to work for the examples taken from the site, I feel it is not really pretty and must be more complicated than it should be.</p>
<blockquote>
<p><strong>Description:</strong></p>
<p>The sentence 'A quick brown fox jumps over the lazy dog' contains
every single letter in the alphabet. Such sentences are called
pangrams. You are to write a program, which takes a sentence, and
returns all the letters it is missing (which prevent it from being a
pangram). You should ignore the case of the letters in sentence, and
your return should be all lower case letters, in alphabetical order.
You should also ignore all non US-ASCII characters.In case the input
sentence is already a pangram, print out the string NULL.</p>
</blockquote>
<pre><code>import sys
filepath = sys.argv[1]
f = open(filepath)
wholealphabet = ('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')
for line in f:
sortedletters = list(set(line.lower()))
i = 0
while i != len(sortedletters):
if wholealphabet.count(sortedletters[i]) != 0:
i = i + 1
else:
sortedletters.pop(i)
missingletters = ""
for letter in wholealphabet:
if sortedletters.count(letter) == 0:
missingletters +=letter
if len(missingletters) == 0:
print("NULL")
else:
print(missingletters)
</code></pre>
|
[] |
[
{
"body": "<p>One of Python's greatest strengths is its built-in capability to use sets directly. I don't feel you've used sets to their fullest extent here. I'd also like to point out the <code>with</code> statement, which you should probably use to handle file handles.</p>\n\n<pre><code>from __future__ import with_statement\nimport sys\nfrom string import ascii_lowercase\nfilepath = sys.argv[1]\nwholealphabet = frozenset(ascii_lowercase)\n\n# Use with to handle file … handles\nwith open(filepath) as f:\n for line in f: # assume a line is a sentence, not exactly per spec?\n # sortedletters = list(set(line.lower())) # guaranteed to be *unsorted*\n missingletters = wholealphabet.difference(line.lower())\n if missingletters:\n print ''.join(sorted(missingletters))\n else:\n print 'NULL'\n</code></pre>\n\n<p>That's really all you need. Unless you want to reconsider the definition of a sentence. :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-27T04:50:33.927",
"Id": "9821",
"Score": "0",
"body": "wow it really is much simpler that way, didn't know about the with. It seems to work like the using statement in c#. I will do a research on each of the method used as I do not know them. I indeed forgot about actually doing the sort, I made some attempt with the interpreter at first and then pretty much copy pasted in a .py file. What did you mean about reconsidering the definition of a sentence? Wish I could upvote but I do not have the required rank yet. Thank you."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-27T05:06:41.227",
"Id": "9823",
"Score": "0",
"body": "Nevermind about the sentence definition I rereaded the answer and understood :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-28T23:33:54.210",
"Id": "9884",
"Score": "0",
"body": "FYI I moved the `from future…` to the top of the code, because (as I'm sure you've discovered) the code won't work otherwise."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-29T02:33:40.977",
"Id": "9889",
"Score": "1",
"body": "Indeed I had to change it, I also discover that string has a ascii_lowercase method which I used instead of letters.lower()"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-29T02:59:36.040",
"Id": "9890",
"Score": "0",
"body": "Great catch. So edited!"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-27T04:12:20.383",
"Id": "6324",
"ParentId": "6323",
"Score": "12"
}
},
{
"body": "<pre><code>import sys\nfilepath = sys.argv[1]\nf = open(filepath)\n</code></pre>\n\n<p>I recommend not using one letter variable names (usually). They make the code hard to read.</p>\n\n<pre><code>wholealphabet = ('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r',\n 's','t','u','v','w','x','y','z')\n</code></pre>\n\n<p>I'd have made this a string</p>\n\n<pre><code>wholealphabet = \"abcdefghijklmnopqrstuvwxyz\"\n</code></pre>\n\n<p>Shorter and works pretty much the same</p>\n\n<pre><code>for line in f:\n sortedletters = list(set(line.lower()))\n</code></pre>\n\n<p>Yeah, that's not sorted. </p>\n\n<pre><code> i = 0\n while i != len(sortedletters):\n if wholealphabet.count(sortedletters[i]) != 0: \n</code></pre>\n\n<p>This is the same as <code>sortedletters[i] in wholealphabet</code>, which is clearer.</p>\n\n<pre><code> i = i + 1\n else:\n sortedletters.pop(i)\n</code></pre>\n\n<p>Modifying a list while iterating over it is bound to be confusing. Its hard to see what you are doing here. The best way in python is usually to create a new list. Like this:</p>\n\n<pre><code>valid_letters = []\nfor letter in sortedletters:\n if letter in wholealphabet:\n valid_letters.append(letter)\n</code></pre>\n\n<p>See how much easier it is to see the result of that? In fact, you can even do it more compactly:</p>\n\n<pre><code>valid_letters = [letter for letter in sortedletters if letter in wholealphabet]\n\n\n missingletters = \"\"\n</code></pre>\n\n<p>Adding to a string can be expensive, I recommend using a list</p>\n\n<pre><code> for letter in wholealphabet:\n if sortedletters.count(letter) == 0:\n missingletters +=letter\n</code></pre>\n\n<p>Again, you can simplify this using a list comphrehension</p>\n\n<pre><code>missingletters = [letter for letter in wholealphabet if letter not in sortedletters]\n\n\n if len(missingletters) == 0:\n print(\"NULL\")\n else:\n print(missingletters)\n</code></pre>\n\n<p>As kojrio points out, if you use sets in python you can implement this very easily. His advice to use a with statement is also good. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-27T05:01:47.757",
"Id": "9822",
"Score": "0",
"body": "I agree that the string is really easier to see that the list of char. I was wondering if there wasn't already a way to test if a char is a valid letter if I had been in c++ I would have casted to a int and would have compared with the ascii table. Indeed forgot the sort that was pretty bad, didn't have enough test case to spot it. I find list comprehension to be hard to read but maybe it's just because I am not used to see it like that. I'll read about it. Thank you for your help."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-27T15:30:13.363",
"Id": "9829",
"Score": "1",
"body": "@Tommy, list comprehensions can be hard to read until you get used to them."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-27T15:34:39.313",
"Id": "9831",
"Score": "0",
"body": "yes, I guess it something you get used to just like lambda expression and then start loving."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-27T04:21:18.760",
"Id": "6325",
"ParentId": "6323",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "6324",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2011-11-27T02:58:15.993",
"Id": "6323",
"Score": "9",
"Tags": [
"python",
"beginner",
"programming-challenge"
],
"Title": "Pangrams CodeEval challenge"
}
|
6323
|
<p>It is advised that such questions be free from criticism such as:</p>
<p><em>Library X already implements this code better; use that instead.</em></p>
<p>However, if it appears that the author is <em>unaware</em> of a better implementation (thus not writing the code for learning/practice), then he/she should be informed of that. Such questions should <em>not</em> use this tag.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-27T04:28:21.897",
"Id": "6326",
"Score": "0",
"Tags": null,
"Title": null
}
|
6326
|
For when you know you are reinventing the wheel, but are doing it anyways. Questions with this tag involve code that is already fully implemented (such as from a library).
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-27T04:28:21.897",
"Id": "6327",
"Score": "0",
"Tags": null,
"Title": null
}
|
6327
|
<p>How could I improve this code?
I used a position interface to avoid code duplication, can it be done better?
Can I reduce the amount of code somehow?</p>
<pre><code>interface PositionInterface
{
double getPosition(PageAreaInterface pArea);
}
private double getMinPosition(Collection<PageAreaInterface> pAreas, PositionInterface pPosition)
{
double lMinPosition = Double.MAX_VALUE;
for (PageAreaInterface lArea : pAreas)
{
lMinPosition = Math.min(lMinPosition, pPosition.getPosition(lArea));
}
return lMinPosition;
}
private double getTop(Collection<PageAreaInterface> pAreas)
{
return getMinPosition(
pAreas,
new PositionInterface()
{
@Override
public double getPosition(PageAreaInterface pArea)
{
return pArea.getBoundingBox().getTop();
}
}
);
}
private double getLeft(Collection<PageAreaInterface> pAreas)
{
return getMinPosition(
pAreas,
new PositionInterface()
{
@Override
public double getPosition(PageAreaInterface pArea)
{
return pArea.getBoundingBox().getLeft();
}
}
);
}
private double getMaxPosition(Collection<PageAreaInterface> pAreas, PositionInterface pPosition)
{
double lMaxPosition = Double.MIN_VALUE;
for (PageAreaInterface lArea : pAreas)
{
lMaxPosition = Math.max(lMaxPosition, pPosition.getPosition(lArea));
}
return lMaxPosition;
}
private double getBottom(Collection<PageAreaInterface> pAreas)
{
return getMaxPosition(
pAreas,
new PositionInterface()
{
@Override
public double getPosition(PageAreaInterface pArea)
{
return pArea.getBoundingBox().getBottom();
}
}
);
}
private double getRight(Collection<PageAreaInterface> pAreas)
{
return getMaxPosition(
pAreas,
new PositionInterface()
{
@Override
public double getPosition(PageAreaInterface pArea)
{
return pArea.getBoundingBox().getRight();
}
}
);
}
</code></pre>
|
[] |
[
{
"body": "<p>It looks fine. Downvote me, but if there is no more possible comparisons I would write four <em>simple</em> <code>for</code> loops instead of the four inner classes and the interface. I think it would be a little bit more readable and mean less code. </p>\n\n<p>Another possibility is creating four <a href=\"http://docs.oracle.com/javase/6/docs/api/java/util/Comparator.html\" rel=\"nofollow\"><code>Comparator</code>s</a> and calling <a href=\"http://docs.oracle.com/javase/6/docs/api/java/util/Collections.html#min%28java.util.Collection,%20java.util.Comparator%29\" rel=\"nofollow\"><code>Collections.min()</code></a> and <a href=\"http://docs.oracle.com/javase/6/docs/api/java/util/Collections.html#max%28java.util.Collection,%20java.util.Comparator%29\" rel=\"nofollow\"><code>Collections.max()</code></a>. It could be an abstract <code>PareAreaComparator</code> with four subclasses:</p>\n\n<pre><code>public abstract class PareAreaComparator implements Comparator<PageAreaInterface> {\n\n public PareAreaComparator() {\n }\n\n @Override\n public int compare(final PageAreaInterface o1, final PageAreaInterface o2) {\n final BouningBox boundingBox1 = o1.getBoundingBox();\n final BouningBox boundingBox2 = o2.getBoundingBox();\n return compare(boundingBox1, boundingBox2);\n }\n\n protected abstract int compare(BouningBox boundingBox1, BouningBox boundingBox2);\n}\n</code></pre>\n\n<p>Everyone (should) know <code>Comparator</code>s, so newcomers are probably more familiar with them than a custom interface which means a little bit easier maintenance.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-27T13:39:16.963",
"Id": "9826",
"Score": "1",
"body": "I see what you mean. The reason why I went for the inner classes and the interface was more to reduce code-logic-duplication rather than code-line-duplication. When the logic is this simple though, I think I agree with you. Thanks"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-27T13:02:48.217",
"Id": "6332",
"ParentId": "6330",
"Score": "2"
}
},
{
"body": "<p>Another alternative. </p>\n\n<p><strong>Nutshell</strong></p>\n\n<ol>\n<li>Don't put type into name (<code>PageAreaInterface</code> etc.)</li>\n<li>Lose the Hungarian; appropriately-short methods remove its utility.</li>\n<li>Create an <code>enum</code> and method to get specific coordinates.</li>\n<li>Create <code>getMinimum</code> and <code>getMaximum</code> methods in a <code>PageAreaCollection</code> taking an <code>enum</code>.</li>\n</ol>\n\n<hr>\n\n<p><strong>Justifications</strong> (working backwards)</p>\n\n<p><em>PageAreaCollection</em></p>\n\n<p>Static utility methods strike me as un-OO, particularly when there are other options.</p>\n\n<p>Create a type, with type-appropriate methods: code shrinks, and reads better:</p>\n\n<pre><code>min = PageAreaUtils.findMinimum(pageAreas, TOP); // Contrast with...\nmin = pageAreas.findMinimum(TOP);\n</code></pre>\n\n<p>Shorter is good, but which reads nicer? Which is more communicative?</p>\n\n<p>With static imports, you're still left with:</p>\n\n<pre><code>min = findMinimum(pageAreas, TOP); // Minimum pageAreas?! No...\nmin = findMinimumTop(pageAreas); // Doesn't read right.\nmin = findMinimumTopIn(pageAreas); // Better?\nmin = findMinimum(TOP).in(pageAreas); // Better?\n</code></pre>\n\n<p>IMO the amount of extra work/code to remove the method from its rightful place (a method of a <code>pageArea</code> collection) isn't worth the effort.</p>\n\n<p><em><code>Enum</code> in bounding box</em></p>\n\n<p>The <code>enum</code> and utility method could live in the collection, too, if the bounding box class isn't yours to finagle.</p>\n\n<pre><code>// In bounding box, collection, or standalone.\npublic enum POSITION { TOP, LEFT, BOTTOM, RIGHT }\n\n// In bounding box or collection.\npublic double getPosition(POSITION pos) {\n switch (pos) {\n case TOP: return getTop();\n case LEFT: return getLeft();\n case BOTTOM: return getBottom();\n case RIGHT: return getRight();\n }\n throw new RuntimeException(\"Bad position provided: \" + pos);\n}\n</code></pre>\n\n<p><em>Min/max position locators in <code>PageAreaCollection</code> class</em></p>\n\n<p>This is essentially the same as the previous suggestion to use <code>Collections.min/max</code>, but I'd still wrap it all up so the mainline code doesn't have to see how it's implemented. This way or that, it's significantly cleaner, with an appropriately-named <code>Comparator</code>.</p>\n\n<pre><code>Collection<PageArea> pageAreas;\n\npublic double getMinimumPosition(MyRect.POSITION pos) {\n double min = Double.MAX_VALUE;\n for (PageArea area : pageAreas) {\n min = Math.min(min, area.getBoundingBox().getPosition(pos));\n }\n return min;\n}\n\npublic double getMaximumPosition(MyRect.POSITION pos) {\n double max = Double.MIN_VALUE;\n for (PageArea area : pageAreas) {\n max = Math.min(max, area.getBoundingBox().getPosition(pos));\n }\n return max;\n}\n</code></pre>\n\n<p>Essentially the same if <code>getPosition()</code> needs to be in the collection. My quibble with having the method in the bounding box is that it makes getting the position a bit bulky; I'd actually <em>prefer</em> this:</p>\n\n<pre><code>area.getBoundingBox(pos) // or area.getBoundingBoxPosition(pos)?\n</code></pre>\n\n<p><em>Hungarian</em></p>\n\n<p>Ew. A method that's a dozen lines long doesn't need differentiation between parameters and locals; it's obvious. At <em>most</em> I could see naming member variables, but even that... Meh.</p>\n\n<p><em>Interface naming</em></p>\n\n<p>A <code>PageAreaInterface</code> is just a <code>PageArea</code>. An <em>implementation</em> may deserve a special name, but it'd be a \"special\" <code>PageArea</code> in that it implements specific functionality likely worth naming. It's the same reason we don't name things <code>IWhatever</code> anymore. The interface <em>is</em> the <code>Whatever</code>, implementations provide specificity and deserve naming.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-27T17:19:13.170",
"Id": "9834",
"Score": "0",
"body": "Cool. Thanks for your thoughts. It is not shown in the code but all those static functions are in a certain builder class - but you are definitely right, they should be moved to their appropriate object, I like the getBoundingBoxPosition (so that getBoundingBox still returns a box). I agree with the hungarian part (code convention policy). The \"do not put type\" is a new one to me - I think I like it, thanks! One thing though, if no type then why the PageAreaCollection? (instead of e.g. PageAreas?)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-27T17:25:26.220",
"Id": "9836",
"Score": "0",
"body": "@j-a No reason; just what I happened to use--you're right, it's probably redundant, particularly if the collection type is unspecified."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-27T15:50:07.097",
"Id": "6335",
"ParentId": "6330",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "6335",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-27T12:02:57.837",
"Id": "6330",
"Score": "3",
"Tags": [
"java"
],
"Title": "Interface for obtaining the bounding box for a collection of elements"
}
|
6330
|
<p>I have already made a function of multiplication of long numbers, addition of long numbers, subtraction of long numbers and division of long numbers. But division takes a very long time, how it could be improved? Here is my code:</p>
<pre><code> /// removes unnecessary zeros
vector<int> zero(vector<int> a)
{
bool f=false;
int size=0;
for(int i=a.size()-1;i>=0;i--)
{
if(a[i]!=0)
{
f=true;
size=i;
break;
}
}
if(f)
{
vector<int> b(size+1);
for(int i=0;i<size+1;i++)
b[i]=a[size-i];
return b;
}
else
return a;
}
/// a+b
vector<int> sum(vector<int> a,vector<int> b)
{
if(a.size()>b.size())
{
vector<int> rez(3000);
int a_end=a.size()-1;
int remainder=0,k=0,ans;
for(int i=b.size()-1;i>=0;i--)
{
ans=a[a_end]+b[i]+remainder;
if(ans>9)
{
rez[k]=ans%10;
remainder=ans/10;
}
else
{
rez[k]=ans;
remainder=0;
}
k++;
a_end--;
}
int kk=k;
for(int i=a.size();i>kk;i--)
{
ans=a[a_end]+remainder;
if(ans>9)
{
rez[k]=ans%10;
remainder=ans/10;
}
else
{
rez[k]=ans;
remainder=0;
}
k++;
a_end--;
}
if(remainder!=0)
{
rez[k]=remainder;
}
return zero(rez);
}
else
{
vector<int> rez(3000);
int b_end=b.size()-1;
int remainder=0,k=0,ans;
for(int i=a.size()-1;i>=0;i--)
{
ans=b[b_end]+a[i]+remainder;
if(ans>9)
{
rez[k]=ans%10;
remainder=ans/10;
}
else
{
rez[k]=ans;
remainder=0;
}
k++;
b_end--;
}
int kk=k;
for(int i=b.size();i>kk;i--)
{
ans=b[b_end]+remainder;
if(ans>9)
{
rez[k]=ans%10;
remainder=ans/10;
}
else
{
rez[k]=ans;
remainder=0;
}
k++;
b_end--;
}
if(remainder!=0)
{
rez[k]=remainder;
}
return zero(rez);
}
}
/// a & b comparison
int compare(vector<int> a,vector<int> b)
{
if(a.size()>b.size())
return 1;
if(b.size()>a.size())
return 2;
int r=0;
for(int i=0;i<a.size();i++)
{
if(a[i]>b[i])
{
r=1;
break;
}
if(b[i]>a[i])
{
r=2;
break;
}
}
return r;
}
/// a-b
vector<int> subtraction(vector<int> a,vector<int> b)
{
vector<int> rez(1000);
int a_end=a.size()-1;
int k=0,ans;
for(int i=b.size()-1;i>=0;i--)
{
ans=a[a_end]-b[i];
if(ans<0)
{
rez[k]=10+ans;
a[a_end-1]--;
}
else
{
rez[k]=ans;
}
k++;
a_end--;
}
int kk=k;
for(int i=a.size();i>kk;i--)
{
ans=a[a_end];
if(ans<0)
{
rez[k]=10+ans;
a[a_end-1]--;
}
else
{
rez[k]=ans;
}
k++;
a_end--;
}
return zero(rez);
}
/// a div b
vector<int> div(vector<int> a,vector<int> b)
{
vector<int> rez(a.size());
rez=a;
int comp=-1;
vector<int> count(1000);
vector<int> one(1);
one[0]=1;
while(comp!=0 || comp!=2)
{
comp=compare(rez,b);
if(comp==0)
break;
rez=subtraction(rez,b);
count=sum(count,one);
}
count=sum(count,one);
return count;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-27T14:08:29.067",
"Id": "9827",
"Score": "0",
"body": "If it's production code I would use a 3rd party BigInt/BigNumeric lib. I suppose there are some good, optimized library on the internet."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-27T14:11:43.990",
"Id": "9828",
"Score": "0",
"body": "@palacsint, thanks, but i want to do it without any libs"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-27T15:32:38.990",
"Id": "9830",
"Score": "3",
"body": "@KamilHismatullin, don't. Use libs. The only reason not to use an external library is for learning purposes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-27T16:33:07.990",
"Id": "9833",
"Score": "0",
"body": "Echo @WinstonEwert assertion. But do you just want comments on the division or do you want us to comment on the state of the rest of the code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-27T23:42:28.803",
"Id": "62772",
"Score": "0",
"body": "Have you considered breaking down the problem into subproblems involving powers of 2, and then using bit-shifting to perform the bit arithmetic?"
}
] |
[
{
"body": "<p>You could try implementing long division.</p>\n\n<p>Example:\n13587643180765 / 153483</p>\n\n<p>1) Find first dividend:</p>\n\n<p><b>1358764</b>3180765 / 153483 #1358764 > 153483</p>\n\n<p>2) Divide it by divisor (e.g by repeated subtraction, like you are doing</p>\n\n<p>1358764 / 153483 = 8</p>\n\n<p>3) Find the remainder (could be the result of previous computation)</p>\n\n<p>1358764 % 153483 = 130900</p>\n\n<p>4) Bring down the next digit to the end of the remainder.</p>\n\n<p>135876<b>4</b>3180765<br />\n130900<b>4</b></p>\n\n<p>Repeat steps 2-4 until you have reached the last digit in the dividend.</p>\n\n<hr>\n\n<p>Since 13587643180765 / 153483 = 88528652, it would take that many subtractions your way.</p>\n\n<p>With long division, there's going to be at most 9 * digits_in_quotient subtractions (in step 2), in this case at most 8 * 9 = 72 subtractions (and in fact 8+8+5+2+8+6+5+2 = 44 subtractions)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-27T13:12:31.170",
"Id": "6333",
"ParentId": "6331",
"Score": "3"
}
},
{
"body": "<p>I would do a binary search on the answer. Roughly: you know <code>a/b</code> is between <code>0</code> and <code>a</code>. So just pretend you're looking for the answer in that range. For each guess <code>g</code>, compute the product <code>b*g</code>. If it's bigger than <code>a</code>, try something smaller on your next guess; otherwise, try something bigger on your next guess. The number of multiplications you have to make will be logarithmic in <code>a</code>. I don't think this would be much slower than long division, and conceptually it's much easier (less error-prone).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-28T00:34:39.913",
"Id": "6342",
"ParentId": "6331",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "6333",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-27T12:33:29.630",
"Id": "6331",
"Score": "0",
"Tags": [
"c++"
],
"Title": "very large A divide at a very large B"
}
|
6331
|
<p>I've recently discovered the power of sed; regular expressions seem like they'll take a lifetime to master. This tiny script uses both to add a zero before the single digit in file names.</p>
<p>Can this be done more easily without sed? Is the regex sound? </p>
<pre><code>#!/bin/bash
# > addzero.sh <
# Adds a zero before the single digit in file names separated by an underscore.
# Designed to help keep files in sequence in directory listings. Otherwise, you get listings like
# "_0.txt, _1.txt, _10.txt, _11.txt, _12.txt, ..., _2.txt, _20.txt, _21.txt, _22.txt, ..."
for filename in $(ls -1 ./*); do
if [[ $filename =~ _[0-9]\. ]]; then
new_filename=$(echo $filename | sed -n 's/_\([0-9]\)\./_0\1\./p')
mv $filename $new_filename
fi
done
</code></pre>
|
[] |
[
{
"body": "<h2>What's wrong</h2>\n\n<pre><code>for filename in $(ls -1 ./*); do\n</code></pre>\n\n<p>Ouch! As a general rule (with very few exceptions), <a href=\"http://mywiki.wooledge.org/ParsingLs\" rel=\"nofollow noreferrer\"><strong>do not use <code>ls</code> in scripts</strong></a>. What you wrote is almost equivalent to <code>for filename in ./*; do</code>, except that if there are any non-printable characters, whitespace characters, or <code>\\[?*</code> in the file names, they will be mangled if you use <code>ls</code>. You don't need the <code>./</code> (except to ensure that the file name doesn't start with a <code>-</code>) but it doesn't hurt.</p>\n\n<pre><code>[[ $filename =~ _[0-9]\\. ]]\n</code></pre>\n\n<p>could be written in a slightly simpler and more portable way: <code>[[ $filename = *_[0-9].* ]]</code>. And since you can use a simple glob pattern, you might as well not have iterated over all file names: <code>for filename in *_[0-9].*; do</code>. But there's a better way to express your script, to take advantage of <code>BASH_REMATCH</code>; see below.</p>\n\n<pre><code>echo $filename\n</code></pre>\n\n<p><strong>Always put double quotes around variable and command substitutions.</strong> Exception: when you understand why you need to leave the double quotes off and why it's safe to do so. When the shell sees a variable substitution (<code>$foo</code> or <code>${foo}</code>) or a command substitution (<code>`foo`</code> or <code>$(foo)</code>) outside double quotes, the result of the substitution undergoes word splitting and globbing (filename generation). That was one of the problems with <code>$(ls -1 ./*)</code> earlier. This should be <code>echo \"$filename\"</code>.</p>\n\n<p>In fact, it would be better <code>printf \"%s\" \"$filename\"</code>, because <code>echo</code> itself performs expansions. In bash, unless you've set non-default options to enable backslash expansion, the only problem is that a few arguments beginning with a <code>-</code> look like option, and in this specific case the filename will begin with <code>./</code>.</p>\n\n<p>There is an edge case where your sed call won't work: if you have a file name that ends with a newline character. This doesn't happen in practice unless someone has made a mistake (like a rogue script or a bad copy-paste) or is deliberately trying to trick your script — so watch out in security contexts.</p>\n\n<p>Incidentally, this is one of the few cases where it's safe to leave out the double quotes around a command substitution: in a variable assignment, there is an implicit pair of double quotes around the right-hand side, so <code>new_filename=$(…)</code> is equivalent to <code>new_filename=\"$(…)\"</code>. Note that this does not extend to <code>export VARIABLE=\"$(value)\"</code>, where the double quotes are necessary.</p>\n\n<p>We now turn to your question about the use of <code>sed</code>. It is not necessary here; you can perform this substitution in bash. Bash has a pattern replacement <a href=\"http://www.gnu.org/s/bash/manual/bash.html#Shell-Parameter-Expansion\" rel=\"nofollow noreferrer\">parameter substitution</a> feature, but it's limited to a constant replacement text. Bash also has a way to extract substrings from regexp matches with <code>=~</code>, through the <code>BASH_REMATCH</code> <a href=\"http://www.gnu.org/s/bash/manual/bash.html#Bash-Variables\" rel=\"nofollow noreferrer\">variable</a>. After the match, <code>${BASH_REMATCH[0]}</code> contains the portion of the string matched by the regexp, <code>${BASH_REMATCH[1]}</code> contains the portion matched by the first parenthesized group and so on.</p>\n\n<pre><code>mv $filename $new_filename\n</code></pre>\n\n<p>Again, double quotes.</p>\n\n<hr>\n\n<h2>A working script</h2>\n\n<p>One possibility is to extract the text to replace from the regexp match, then perform a string replacement on it. Since I'm not using <code>./*</code>, the file name may begin with a <code>-</code>, so I take care to use <code>--</code> on the call to <code>mv</code> to ensure that the file name isn't seen as an option.</p>\n\n<pre><code>for filename in *; do\n if [[ $filename =~ _[0-9]\\. ]]; then\n from=${BASH_REMATCH[0]}\n mv -- \"$filename\" \"${filename//$from/${from/_/_0}}\"\n fi\ndone\n</code></pre>\n\n<p>Another possibility is to match the whole file name as a regexp and splice a <code>0</code> into the bits. Note that this will behave differently in a corner case: if there are several occurrences of <code>_[0-9]\\.</code>, the code above replaces the first occurrence, while this replaces the last occurrence.</p>\n\n<pre><code>for filename in *; do\n if [[ $filename =~ ^(.*_)([0-9]\\..*)$ ]]; then\n mv -- \"$filename\" \"${BASH_REMATCH[1]}0${BASH_REMATCH[2]}\"\n fi\ndone\n</code></pre>\n\n<p>You can also use other constructs and avoid regexps altogether, but it's more complicated. An advantage is that the script then works in all shells, not just bash.</p>\n\n<pre><code>for filename in *_[0-9].*; do\n digit=${filename%.${filename##*_[0-9].}}; digit=${digit##*.}\n mv -- \"$filename\" \"${filename%%_[0-9].*}_0${digit}.${filename#*_[0-9].*}\"\ndone\n</code></pre>\n\n<p>There are other methods to perform this kind of file renaming. If you're on Debian or derivative (including Ubuntu) or have the <code>rename</code> Perl script that's floating around (note that this is not the standard Linux <code>rename</code> utility):</p>\n\n<pre><code>rename 's/_([0-9]\\.)/_0$1/' *_[0-9].*\n</code></pre>\n\n<p>Or with mmv:</p>\n\n<pre><code>mmv -x '*_[0-9].*' '#1_0#2.#3'\n</code></pre>\n\n<p>Or in zsh, after <code>autoload zmv</code>:</p>\n\n<pre><code>zmv '(*_)([0-9].*)' '${1}0$2'\n</code></pre>\n\n<h2>Further reading</h2>\n\n<p>The <a href=\"https://unix.stackexchange.com/tags/rename\">rename</a> and <a href=\"https://unix.stackexchange.com/tags/rename\">quoting</a> tags on <a href=\"https://unix.stackexchange.com/\">Unix Stack Exchange</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-28T06:05:46.620",
"Id": "9845",
"Score": "0",
"body": "Wow. Duly noted on excluding `ls`. It's given me headaches before, and my kludgy solution was to change the $IFS from a space to a line break, then restore it at the end of the script. This was just the kind of insight I was hoping for. Thanks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-28T13:07:51.237",
"Id": "9853",
"Score": "0",
"body": "Very thorough! Deserves more than one upvote, really :-)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-28T00:16:16.233",
"Id": "6341",
"ParentId": "6337",
"Score": "7"
}
},
{
"body": "<p>I wouldn't use regular expressions at all here. I'd use <code>printf</code> to pad the digits, and bash glob-patterns to extract the digits.</p>\n\n<pre><code>shopt -s extglob\nfor filename in *; do\n tmp=${filename%.txt} # remove the \".txt\" extension\n digits=${tmp##*_} # remove everything up to the final underscore\n case $digits in\n +([0-9])) \n # 'digits' contains only digits\n newname=${filename%_*}_$(printf \"%02d\" $digits).txt\n mv \"$filename\" \"$newname\"\n ;;\n esac\ndone\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-28T01:42:53.333",
"Id": "6343",
"ParentId": "6337",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "6341",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-27T22:00:44.593",
"Id": "6337",
"Score": "2",
"Tags": [
"regex",
"bash",
"sed"
],
"Title": "Adding a zero to file names"
}
|
6337
|
<p>I have the following code for binary search</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Diagnostics;
namespace BinarySearch
{
public class IntComparer : Comparer<int>
{
public override int Compare(int x, int y)
{
if (x == y)
{
return 0;
}
else if (x > y)
{
return 1;
}
else
{
return -1;
}
}
}
public static class BinarySearcher
{
public static bool BinarySearch(this int[] array, int value)
{
uint bottom = 0;
uint top = (uint)array.Length - 1;
uint middle = top >> 1;
while (top >= bottom)
{
if (array[middle] == value)
{
return true;
}
else if (array[middle] > value)
{
top = middle - 1;
}
else
{
bottom = middle + 1;
}
middle = (bottom + top) >> 1; //to avoid overflow
}
return false;
}
public static bool BinarySearch<T>(T item, T[] array, IComparer<T> comparer)
{
uint bottom = 0;
uint top = (uint)array.Length - 1;
uint middle = top >> 1;
while (top >= bottom)
{
int compareResult = comparer.Compare(array[middle], item);
if (compareResult == 0)
{
return true;
}
else if (compareResult > 0)
{
top = middle - 1;
}
else
{
bottom = middle + 1;
}
middle = (bottom + top) >> 1; // middle = bottom + ((top - bottom) / 2); ?
}
return false;
}
public static bool BinarySearchRec<T>(T item, T[] array, IComparer<T> comparer)
{
uint bottom = 0;
uint top = (uint)array.Length - 1;
return BinarySearchRec<T>(item, array, comparer, bottom, top);
}
private static bool BinarySearchRec<T>(T item, T[] array, IComparer<T> comparer, uint bottom, uint top)
{
if (bottom > top)
{
return false;
}
uint middle = (bottom + top) >> 1;
int compareResult = comparer.Compare(array[middle], item);
if (compareResult > 0)
{
return BinarySearchRec(item, array, comparer, bottom, middle - 1);
}
else if (compareResult < 0)
{
return BinarySearchRec(item, array, comparer, middle + 1, top);
}
else
{
return true;
}
}
}
class Program
{
private const int ITERATIONS = 1000000;
static void Main(string[] args)
{
int[] sortedArray = {1,2,3,4,5,6,7,8,9,10};
Console.WriteLine(BinarySearcher.BinarySearch<int>(10, sortedArray, new IntComparer()));
Console.WriteLine(BinarySearcher.BinarySearchRec<int>(14, sortedArray, new IntComparer()));
Console.WriteLine(sortedArray.BinarySearch(1));
int[] sortedArray2 = new int[ITERATIONS];
for (int i = 0; i < ITERATIONS; i++)
{
sortedArray2[i] = i;
}
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
for (int i = 0; i < ITERATIONS; i++)
{
sortedArray2.BinarySearch(0);
}
stopWatch.Stop();
Console.WriteLine("Time required for execution: " + stopWatch.ElapsedMilliseconds + "ms");
stopWatch.Reset();
stopWatch.Start();
for (int i = 0; i < ITERATIONS; i++)
{
BinarySearcher.BinarySearchRec<int>(0, sortedArray2, new IntComparer());
}
stopWatch.Stop();
Console.WriteLine("Time required for execution: " + stopWatch.ElapsedMilliseconds + "ms");
stopWatch.Reset();
stopWatch.Start();
for (int i = 0; i < ITERATIONS; i++)
{
BinarySearcher.BinarySearch<int>(0, sortedArray2, new IntComparer());
}
stopWatch.Stop();
Console.WriteLine("Time required for execution: " + stopWatch.ElapsedMilliseconds + "ms");
Console.ReadLine();
}
}
}
</code></pre>
<p>I should add user input checks</p>
<p>What is the best way to implement public generic method for binary search? Maybe there is a better way to do so rather than with Comparer?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-28T10:26:58.143",
"Id": "9849",
"Score": "0",
"body": "In C# both the System.Generic.List class and the System.Array class already have generic BinarySearch() methods which work with Comparer delegates, or with objects implementing IComparable. They are known to work very well, and they perform actual search, meaning that they return the index of the item found, (or, if not found, the negated index at which it should be inserted,) instead of what your methods do, which is to simply answer the question of whether an item exists in an array.\n\nSo, why are you trying to re-invent this wheel?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-28T12:14:33.430",
"Id": "9851",
"Score": "0",
"body": "prepering for an interview"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-06T11:46:31.403",
"Id": "10213",
"Score": "0",
"body": "So, how did your interview go, @lukas?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-06T12:14:35.867",
"Id": "10214",
"Score": "0",
"body": "rescheduled :P ..."
}
] |
[
{
"body": "<p>The best way to implement a public generic method for binary search is by invoking the <code>BinarySearch()</code> method of <code>System.Array</code>. (Better yet, don't implement such a method at all, and call <code>System.Array.BinarySearch()</code> directly.)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-28T08:05:29.233",
"Id": "6350",
"ParentId": "6338",
"Score": "0"
}
},
{
"body": "<p>If a question of this sort pops up in a job interview, it may be a trick question, and you might actually be expected to demonstrate that you are conscious about not re-inventing the wheel. A big part of the value of .Net is that it is a very rich environment which provides programmers with lots of things already built-in and ready to use, (not to mention tested, debugged, and known to work problem-free,) so an essential skill for a .Net programmer is to know what is already there so that they do not waste time re-implementing it and debugging it.</p>\n\n<p>If you can rule out the scenario of the trick question, then here is what I'd say:</p>\n\n<ol>\n<li>Make your method return an <code>int</code>, not a <code>bool</code>, as the built-in binary search methods do.</li>\n<li>Make an additional overload that works with <code>System.Comparison<T></code> instead of <code>System.IComparer<T></code>.</li>\n<li>Make an additional overload that works with neither <code>Comparison<T></code> nor <code>IComparer<T></code>, but instead it assumes that <code>T</code> implements <code>IComparable<T></code>.</li>\n<li>Keep the <code>middle = bottom + ((top - bottom) / 2)</code> part, it is supposed to avoid arithmetic overflow if by any chance you are sorting an array with an incredibly large number of elements. (Not very important, but it demonstrates attention to detail.)</li>\n<li>Code the <code>public override int Compare(int x, int y)</code> method as follows:\n<code>{ return x - y; }</code> ;-)</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-28T12:40:07.177",
"Id": "6355",
"ParentId": "6338",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-27T22:34:34.250",
"Id": "6338",
"Score": "2",
"Tags": [
"c#",
"algorithm",
"library",
"binary-search"
],
"Title": "Generic binary search"
}
|
6338
|
<h2>Regular and Irregular Expressions</h2>
<p><a href="https://en.wikipedia.org/wiki/Regular_expression" rel="nofollow noreferrer">Regular expressions</a> are a powerful form of <a href="https://en.wikipedia.org/wiki/Declarative_programming" rel="nofollow noreferrer">declarative programming language</a>, mainly used for pattern matching within strings. Students of computer science know them as the user-friendly face to the abstruse field of <a href="https://en.wikipedia.org/wiki/Finite-state_machine" rel="nofollow noreferrer">finite automata</a>. The rest of us think of them as string matching using wildcards. </p>
<p>There are <a href="https://www.regular-expressions.info/refflavors.html" rel="nofollow noreferrer">many different dialects</a> of regular expressions, all subtly different. Therefore, when asking questions, <strong><em>always</em></strong> <strong>include the specific programming language or tool</strong> (<em>e.g.,</em> Perl, Ruby, Python, Java, JavaScript, vi, emacs, sed, lex, grep, <em>etc.</em>) you are using. Otherwise you may get answers that won’t work for you.</p>
<p>Depending on which flavor you’re using, modern regular expressions can allow backreferences, conditional subpatterns, regex subroutines, code callouts, positive and negative lookahead/lookbehind assertions, and even recursion. This rich feature set allows them to parse far more than the <a href="https://en.wikipedia.org/wiki/Regular_language" rel="nofollow noreferrer">strictly regular languages</a> for which they were originally named. Today we still call these pattern-matching languages <em>regular expressions</em> (or <em>regexes</em> for short), even though the <em>reg-</em> part is little more than an historical artifact which no longer applies.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2011-11-28T01:57:06.430",
"Id": "6344",
"Score": "0",
"Tags": null,
"Title": null
}
|
6344
|
Regular expressions are a declarative language, mainly used for pattern matching within strings. Please include a tag specifying the programming language you are using, together with this tag.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-28T01:57:06.430",
"Id": "6345",
"Score": "0",
"Tags": null,
"Title": null
}
|
6345
|
<p>I am sure you can find many weak spots, please let me know about them.
My main question is if this is a sensible approach to separate the construction phase from the constructed phase. </p>
<p>Basically I have a set of objects that needs to be transformed into similar (but different) objects. Once transformed I want to be able to query these later.</p>
<p>So I have a PartitionedContainersBuilder which deals with the transformation part and I have a PartitionedContainer which represents the transformed query-able.</p>
<p>What I do like with this is that there is no invalid state anywhere and little risk of doing mistakes with member variables. Had Java been able to return two values then I would probably have solved it differently. However with that said, I know for example that calling it builder and build may not be the best thing (it is not the builder pattern).</p>
<p>I would prefer having the constructor in PartitionedContainer do the work rather than a static build - would that be better? My gut feeling says yes, but is there a tangible advantage? </p>
<pre><code>public class PartitionedContainers {
static class PartitionedContainersBuilder
{
private LogicalExcelAreaInterface buildLogicalExcelArea(ContainerNodeInterface pContainer, PapyrusInterface pPapyrus)
{
// TODO: introduce LeafItemContainer to remove if cases
if (pContainer.getItem() != null)
{
return pContainer.getItem().getLogicalExcelArea(pPapyrus);
} else {
return new MutableLogicalExcelArea(1, 1)
.withCellWidth(0, 0, pPapyrus.getWidth())
.withCellHeight(0, 0, pPapyrus.getHeight());
}
}
public PartitionedContainers build(final ContainerNodeInterface pRootContainer, final Map<ContainerInterface, PapyrusInterface> pPapyrusFromContainer)
{
final Map<PartitionedContainerInterface, PapyrusInterface> lPapyrusFromContainer = new HashMap<PartitionedContainerInterface, PapyrusInterface>();
final Map<ContainerNodeInterface, MutablePartitionedContainer> lPartitionedContainerFromContainer = new HashMap<ContainerNodeInterface, MutablePartitionedContainer>();
for (final ContainerNodeInterface lNode : new NodeCollections<ContainerNodeInterface>().getAllSortedTopDown(pRootContainer))
{
lPartitionedContainerFromContainer.put(
lNode,
new MutablePartitionedContainer(lNode.getElement(), buildLogicalExcelArea(lNode, pPapyrusFromContainer.get(lNode)))
);
if (!lNode.isRoot()) {
lPartitionedContainerFromContainer.get(lNode).withParent(lPartitionedContainerFromContainer.get(lNode.getParent()));
lPartitionedContainerFromContainer.get(lNode.getParent()).withAdditionalChild(lPartitionedContainerFromContainer.get(lNode));
}
lPapyrusFromContainer.put(lPartitionedContainerFromContainer.get(lNode), pPapyrusFromContainer.get(lNode));
}
return new PartitionedContainers(lPartitionedContainerFromContainer.get(pRootContainer), lPapyrusFromContainer);
}
}
PartitionedContainerInterface mRootContainer;
Map<PartitionedContainerInterface, PapyrusInterface> mPapyrusFromContainer;
private PartitionedContainers(PartitionedContainerInterface pRootContainer, Map<PartitionedContainerInterface, PapyrusInterface> pPapyrusFromContainer)
{
mRootContainer = pRootContainer;
mPapyrusFromContainer = pPapyrusFromContainer;
}
public PartitionedContainerInterface getRoot()
{
return mRootContainer;
}
public static PartitionedContainers build(ContainerNodeInterface pRootContainer, final Map<ContainerInterface, PapyrusInterface> pPapyrusFromContainer)
{
return new PartitionedContainersBuilder().build(pRootContainer, pPapyrusFromContainer);
}
public PapyrusInterface getPapyrusFromContainer(PartitionedContainerInterface pContainer)
{
return mPapyrusFromContainer.get(pContainer);
}
}
</code></pre>
|
[] |
[
{
"body": "<p>First of all, you are right, what you have there is not a builder class, but more like a factory class. Which is roughly equivalent to a static factory method.</p>\n\n<p>Now, the question of using constructors vs static factory methods is one over which there has been a lot of talk, and for the most part no conclusive, universally-applicable answers. (Just search for \"c# constructor vs static factory method\" and you will see.) However, specifically for your case, where both the constructed class and the code constructing it are private within another class, the advantages of \"discoverability\" and \"recognizability\" that the <code>new</code> keyword has are not applicable, so I'd definitely go with a factory method or class.</p>\n\n<p>With regards to whether you should be using a factory class or a static factory method, I think that the factory class is fine. The overhead for the generation of an additional object which gets immediately discarded is negligible, (especially compared to the amount of work that the object will do,) and might even be optimized away by the compiler. On the other hand, having a factory class instead of a static factory method could turn out to be useful if in the future you decide to introduce some state into your builder.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-28T07:46:53.630",
"Id": "6349",
"ParentId": "6346",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "6349",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-28T02:06:05.083",
"Id": "6346",
"Score": "2",
"Tags": [
"java"
],
"Title": "Separate construction phase from constructed phase"
}
|
6346
|
<p>I'm trying to figure out what is best and fastest implementation of a browser-like find and highlight function inside a website using JavaScript.
This function is for <strong>one</strong> HTML element <strong>without</strong> any children. Of course it can be expanded to elements with children with some simple loops. That is not part of question.
I wrote this small code to make something working here:</p>
<p><strong>CSS</strong></p>
<pre><code>span.highlight{background:yellow; padding:3px;}
</code></pre>
<p><strong>HTML</strong></p>
<pre><code><input type="search"/>
<p>The Ama...</p>
</code></pre>
<p><strong>JavaScript</strong></p>
<pre><code>var s = document.querySelector('input[type="search"]'),
p = document.querySelector('p'),
find = function(){
var words = p.innerText.split(' ');
for(var i=0; i<words.length; i++){
if(words[i].toLowerCase() == s.value.toLowerCase()){
words[i] = '<span class="highlight">' + words[i] + "</span>";
p.innerHTML = words.join(' ');
}
else{
}
}
}
s.addEventListener('keydown', find , false);
s.addEventListener('keyup', find , false);
</code></pre>
<p>This code is working fine. Checkout live example <strong><a href="http://jsbin.com/ebucaz" rel="nofollow">here</a></strong>. But this is not fast and sometimes crash the browser. How can I make this functionality with a better approach?</p>
<p>Please note I don't want a full code review here. So don't remind me that <code>querySelector</code> is not supported in IE7 and same things.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-28T05:39:56.857",
"Id": "9844",
"Score": "0",
"body": "Is there a point in getting and lowercasing words on each call to `find()`? Why not just do that once on `onload`? My javascript-fu is pretty low, so even if it's something obvious please explain..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-28T06:12:26.297",
"Id": "9846",
"Score": "0",
"body": "Because I don't wanna mess `words` array with converting it to lower case. I'm keeping element's actual text in that array"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-28T06:19:03.233",
"Id": "9847",
"Score": "0",
"body": "Ah yes you need the actual text to highlight it. Still I think it would be significantly faster if you've built the array once and outside of the loop, you could keep two values for each word (the lowercase to compare and the original to highlight)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-29T00:16:30.973",
"Id": "9886",
"Score": "1",
"body": "It occurs to me you can use [`Array.reduce`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/Reduce) here. Something like `p.innerHTML = p.innerText.split(' ').reduce(function (prev, cur) {return prev + ' ' + ((cur.toLowerCase() === s.value.toLowerCase()) ? '<span class=\"highlight\">' + cur + \"</span>\" : c;}, \"\")`. While so many browsers have yet to implement a fast reduce it's not the best approach, so I'm not giving it as an answer, but food for thought."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-09-24T10:47:20.927",
"Id": "193351",
"Score": "0",
"body": "I've described here why building a selfmade highlighting function is a bad idea: http://stackoverflow.com/questions/119441/highlight-a-word-with-jquery/32758672#32758672"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-05-11T16:09:35.350",
"Id": "239533",
"Score": "1",
"body": "Btw: I just want to mention that innerHTML is evil as it will destroy all events inside that element and re-create the DOM. Also innerHTML is slower than the normal createElement (see [this](http://stackoverflow.com/a/11854965/3894981) for further information). If you are searching for a solution intended for every situation you might be interested in [mark.js](https://markjs.io/)."
}
] |
[
{
"body": "<p>Let's start by optimising your code. Simply said, loops are the danger here.</p>\n\n<ol>\n<li>A <code>while</code> loop can be quicker than a <code>for</code> loop, especially in cases like this. Get the length once.</li>\n<li>Avoid looking into arrays. Do <code>word = words[i]</code> once, which is much faster.</li>\n<li>You are joining in every iteration. You should join once only after you have updated your array.</li>\n<li>I guess the empty <code>else</code> isn't done yet.</li>\n</ol>\n\n<p></p>\n\n<pre><code>var s = document.querySelector('input[type=\"search\"]'),\n p = document.querySelector('p'),\n find = function(){\n var words = p.innerText.split(' '),\n i = words.length,\n word = '';\n\n while(--i) {\n word = words[i];\n if(word.toLowerCase() == s.value.toLowerCase()){\n words[i] = '<span class=\"highlight\">' + word + \"</span>\";\n }\n else{\n\n } \n }\n\n p.innerHTML = words.join(' ');\n }\n\ns.addEventListener('keydown', find , false);\ns.addEventListener('keyup', find , false);\n</code></pre>\n\n<p>Last but surely not least, <a href=\"http://www.developer.nokia.com/Community/Wiki/JavaScript_Performance_Best_Practices\" rel=\"nofollow\">the page you want to read</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-28T23:39:32.063",
"Id": "9885",
"Score": "0",
"body": "I'm curious if it would be faster to use a stack. `while (words) { word = words.pop(); …}`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-29T09:43:17.387",
"Id": "9897",
"Score": "0",
"body": "There's really no need for another function call. You want to avoid those. Plus popping out the value doesn't benefit you. It's cute, but not faster I'm afraid :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-02-06T19:42:35.637",
"Id": "221889",
"Score": "0",
"body": "the negative while for speed is a good option likely due to its deterministic nature"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-28T17:00:21.563",
"Id": "6365",
"ParentId": "6347",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-28T04:29:32.010",
"Id": "6347",
"Score": "3",
"Tags": [
"javascript"
],
"Title": "Better \"find and highlight\" implementation in HTML element"
}
|
6347
|
<p>I've just finished my solution to the <a href="http://en.wikipedia.org/wiki/Dining_philosophers_problem" rel="nofollow">Dining Philosopher's Problem</a>, but I am not confident with my code because I am still newbie to the concurrency world. I would appreciate it if you could leave me some feedback. </p>
<p>Here is my main class:</p>
<pre><code>public class DiningPhilosophersTable {
//An array holding all the chopsticks
private final Chopstick[] chopsticks = new Chopstick[5];
/*Constructor for the main class
* Creates all the chopsticks
* Creates and starts all the threads*/
public DiningPhilosophersTable(){
putChopsticksOnTheTable();
Thread t1 = new Thread(new Philosopher("First",this.chopsticks[4],this.chopsticks[0]));
Thread t2 = new Thread(new Philosopher("Second",this.chopsticks[0],this.chopsticks[1]));
Thread t3 = new Thread(new Philosopher("Third",this.chopsticks[1],this.chopsticks[2]));
Thread t4 = new Thread(new Philosopher("Fourth",this.chopsticks[2],this.chopsticks[3]));
Thread t5 = new Thread(new Philosopher("Fifth",this.chopsticks[3],this.chopsticks[4]));
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
}
/*Initialise the chopsticks in the array*/
private void putChopsticksOnTheTable(){
for(int i = 0;i < chopsticks.length;i++)
chopsticks[i]= new Chopstick();
}
public static void main(String[] args){
new DiningPhilosophersTable();
}
}
</code></pre>
<p>Here is the <code>Philosopher</code> class:</p>
<pre><code>public class Philosopher extends Thread{
private static final int MAX_EATING_TIME = 1000;
private static final int MAX_THINKING_TIME = 800;
private final Random randomise = new Random();
private final Chopstick _leftChopstick;
private final Chopstick _rightChopstick;
private final String _name;
private State _state;
/* Enumeration class that holds
* information about the possible
* Philosopher's states
*/
public enum State {
EATING, THINKING, WAITING
}
/*
* Main constructor for the Philosopher class
* @param name the name of the Philosopher
* @param leftChopstick the chopstick that is currently on the left of the Philosopher
* @param rightChopstick the chopstick currently on the right of the Philosopher
*
*/
public Philosopher(String name, Chopstick leftChopstick, Chopstick rightChopstick) {
System.out.println(name +"Started");
this._leftChopstick = leftChopstick;
this._rightChopstick = rightChopstick;
this._name = name;
}
/*
* The method eat that uses two chopsticks. It blockes the two Chopstick
* objects so they could not be changed then it changes their state
* as well as the state of the philosopher
* At the end of the method, the chopsticks' state is reverted and
* the Philosopher goes into the Thinking state
*/
private void eat() throws InterruptedException {
synchronized(_leftChopstick){
while(_leftChopstick.isUsed() || _rightChopstick.isUsed())
try{
this.setPhilosopherState(Philosopher.State.WAITING);
_leftChopstick.wait();
}catch (InterruptedException e){}
synchronized(_rightChopstick) {
try{
Thread.sleep(1);
_leftChopstick.setUsed(true);
_rightChopstick.setUsed(true);
this.setPhilosopherState(Philosopher.State.EATING);
Thread.sleep(randomise.nextInt(MAX_EATING_TIME));
}
finally {
_leftChopstick.setUsed(false);
_rightChopstick.setUsed(false);
_leftChopstick.notify();
_rightChopstick.notify();
}
}
}
think();
}
/*
* This method only changes the state
* of the Philosopher to Thinking
*/
private void think() throws InterruptedException{
this.setPhilosopherState(Philosopher.State.THINKING);
Thread.sleep(randomise.nextInt(MAX_THINKING_TIME));
}
/*
* Set the current state of the Philosopher
*/
private void setPhilosopherState(State state){
this._state = state;
System.out.println(System.currentTimeMillis() +":"+ _state +", "+ _name+";");
}
/*
* Get the current state of the Philosopher
*/
public State getPhilosopherState(){
return _state;
}
/*
* The method is invoked with the start of the thread
* and runs the eat function for 10 times
*/
public void run(){
for(int i =0; i< 10;i++){
try {
eat();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Succesfully finished: " +_name);
}
}
</code></pre>
<p>And the last class:</p>
<pre><code>public class Chopstick {
private boolean _isUsed;
/*
* @return the current state of the chopstick
*/
public boolean isUsed(){
return _isUsed;
}
/*
* @param usedFlag the new state of the chopstick
*/
public void setUsed(boolean usedFlag){
_isUsed = usedFlag;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-28T13:04:40.367",
"Id": "9852",
"Score": "5",
"body": "Why does Philosopher extend Thread?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-28T14:47:05.387",
"Id": "9855",
"Score": "0",
"body": "Since I need 5 Philosophers on the table I thought It might be a good idea to make them concurrent."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-28T15:04:01.963",
"Id": "9857",
"Score": "4",
"body": "But you could change Philosopher to simply implement `Runnable` and it would still work - this is good practice. Alternatively you could change `new Thread(new Philosopher(...))` to `new Philosopher(...)` but this is not considered good practice. As it is you create `Thread` instances which you never call `start()` on, which is at best pointless and at worst wasteful of a limited OS resource."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-28T18:16:33.013",
"Id": "9874",
"Score": "1",
"body": "The formatting of the indentation of `eat()` does **NOT** match how the statements are actually (not) nested, which gives the impression of a completely different outcome. And yes, implement `Runnable` instead of extending thread."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-28T19:11:22.297",
"Id": "9876",
"Score": "0",
"body": "The reason I decided to extend Thread is that I read in some lectures that Thread defines abstraction for worker and Runnable for work. And I might have gotten a bit confused."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-02T22:13:18.647",
"Id": "10087",
"Score": "1",
"body": "Do you want to demonstrate the possible deadlock with this code? Or is it supposed to be a deadlock-free implementation?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-16T00:40:27.267",
"Id": "31446",
"Score": "0",
"body": "In my opinion, there is no need to test for `leftChopstick.isUsed()` in a while condition, as it always be false, when philosopher acquire its monitor."
}
] |
[
{
"body": "<p>Just a quick note:</p>\n\n<pre><code>synchronized(_leftChopstick){\n while(_leftChopstick.isUsed() || _rightChopstick.isUsed()) \n</code></pre>\n\n<p>Here you should synchronize on <code>_rightChopstick</code> too since <code>isUsed</code> could be called from other threads concurrently.</p>\n\n<blockquote>\n <p>[...] synchronization has no effect unless both read and write operations are synchronized.</p>\n</blockquote>\n\n<p>From <em>Effective Java, 2nd Edition, Item 66: Synchronize access to shared mutable data</em>.</p>\n\n<blockquote>\n <p>Locking is not just about mutual exclusion; it is also about memory visibility. \n To ensure that all threads see the most up-to-date values of shared mutable \n variables, the reading and writing threads must synchronize on a common lock.</p>\n</blockquote>\n\n<p>From <em>Java Concurrency in Practice, 3.1.3. Locking and Visibility</em>.</p>\n\n<p>Another (and better) solution is using <code>AtomicBoolean</code>s.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-28T14:49:36.960",
"Id": "9856",
"Score": "0",
"body": "Hmm.. I am synchronizing on it a few lines further down. I cannot w8 on _rightChopstick outside the synchronizing block for it. I'm sorry I might be missunderstanding your idea."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-29T09:29:35.323",
"Id": "9896",
"Score": "0",
"body": "When you read a variable which is written by multiple threads you should synchronize the access. I mean before you access it, not later. *Java Concurrency in Practice* is a really good book on this topic, if you have time read it, it's worth the time."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-30T18:05:45.093",
"Id": "9953",
"Score": "0",
"body": "Do you suggest I use only _rightChopstick.isUsed() in my while loop?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-16T00:46:52.497",
"Id": "31447",
"Score": "0",
"body": "@palacsint there is no need to lock on `_rightChopstick` before testing its availability as write access always occures in synchronized region"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-21T07:44:59.500",
"Id": "31702",
"Score": "0",
"body": "@Zee: I'm just saying that you should synchronize on that variable too. Sorry for the late answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-21T07:54:39.733",
"Id": "31703",
"Score": "0",
"body": "@maks: Sorry, I have to disagree. Check the edit, please."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-28T13:46:16.727",
"Id": "6358",
"ParentId": "6348",
"Score": "6"
}
},
{
"body": "<p>Instead of Chopstick class you could use java.util.concurrent.locks.Lock directly.\nPossible implementation (not starvation free)</p>\n\n<pre><code>private void eat() {\n if (_leftChopstick.tryLock()) {\n try {\n if (_rightChopStick.tryLock()) {\n try {\n Thread.sleep(randomise.nextInt(MAX_EATING_TIME));\n }\n finally {\n _rightChopStick.unlock();\n }\n }\n }\n finally {\n _leftChopstick.unlock();\n }\n }\n think();\n} \n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-08T20:52:21.517",
"Id": "6627",
"ParentId": "6348",
"Score": "2"
}
},
{
"body": "<p>Theoretically deadlock can occur in your code(There is a small probability, especially this probability rises when you run your code on a single core system). </p>\n\n<p>Suppose such situation in which philosophers are enumerated clockwise.\n<strong>1st</strong> philosophers acquire a lock on left chopstick, then test if left and right chopstics are free(at start they can be free) and right after that <strong>2nd</strong> philosopher(which sits right to first) also acquire a lock on his left chopstick. So the 1st philosopher will be blocked on his right chopstick's monitor. </p>\n\n<p><strong>3rd</strong> and <strong>4th</strong> philosophers repeat described process after 1st and 2nd philosopher. </p>\n\n<p>And the lst <strong>5th</strong> philosophers will acquire a lock on his left chopstick's monitor and will be blocked on his right chopsticks monitor while testing its availability.</p>\n\n<p>This probability is rather small but it can occur. And if it can occur then I think it is not a valid code. Deadlock's propability has to be equal to 0, then it will be a valid code.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-16T00:21:09.043",
"Id": "19645",
"ParentId": "6348",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-28T06:30:14.820",
"Id": "6348",
"Score": "10",
"Tags": [
"java",
"multithreading",
"dining-philosophers"
],
"Title": "Dining Philosophers"
}
|
6348
|
<p>I'm new to Haskell and functional programming and I did for training purpose a basic program where you can:</p>
<ul>
<li>create a directory (consisting of a name and an array of sub-directories)</li>
<li>create an entry (consisting for a title and a content)</li>
<li>remove and entry or a directory</li>
<li>view an entry</li>
<li>do a directory listing</li>
</ul>
<p>The available commands are:</p>
<ul>
<li>ls</li>
<li>cd <em>dir</em> or cd .. (to go to parent)</li>
<li>mkdir <em>dirname</em></li>
<li>view <em>entry</em></li>
<li>exit</li>
<li>help</li>
</ul>
<p>Notes:</p>
<ul>
<li>There is not dependencies on Hackage (out of the box "The Haskell Platform" is enough).</li>
<li>I corrected the source for hlint and now there is "no suggestions".</li>
</ul>
<p>`</p>
<pre><code>import Data.Maybe
import Data.List (sortBy,elemIndex,intercalate)
import Data.Function (on)
import System.IO (stdout,hFlush)
import System.Directory (doesFileExist)
-- -- -- -- -- -- -- -- -- -- -- --
-- DATA and their functions
-- -- -- -- -- -- -- -- -- -- -- --
-- Ex: - Directory { name = "dir1", directories = Directory { name = "dir2" } }
-- - path for dir2 will be ["dir2", "dir1"]
-- - getCurrentDirectory function get 'root Directory' + 'path' and return the directory at 'path'
data Entry = Entry { title :: String
,content :: String } deriving (Show, Read)
data Directory = Directory { name :: String,
directories :: [Directory],
entries :: [Entry] } deriving (Show, Read)
-- Add an entry into the directory tree.
addEntry :: Directory -> [String] -> Entry -> Directory
addEntry dir [] newEntry = addDirectoryEntry dir newEntry
addEntry dir path newEntry = replaceDirectoryInPath dir (tail path) $ addDirectoryEntry currentDir newEntry
where currentDir = getCurrentDirectory dir path
-- Add a directory into the directory tree.
addDirectory :: Directory -> [String] -> Directory -> Directory
addDirectory dir [] newDir = addDirectoryDirectory dir newDir
addDirectory dir path newDir = replaceDirectoryInPath dir (tail path) $ addDirectoryDirectory currentDir newDir
where currentDir = getCurrentDirectory dir path
-- Remove an entry from the directory tree.
removeEntry :: Directory -> [String] -> Entry -> Directory
removeEntry dir [] e = removeDirectoryEntry dir e
removeEntry dir path e = replaceDirectoryInPath dir (tail path) $ removeDirectoryEntry currentDir e
where currentDir = getCurrentDirectory dir path
-- Remove a directory from the directory tree.
removeDirectory :: Directory -> [String] -> Directory -> Directory
removeDirectory dir [] d = removeDirectoryDirectory dir d
removeDirectory dir path d = replaceDirectoryInPath dir (tail path) $ removeDirectoryDirectory currentDir d
where currentDir = getCurrentDirectory dir path
-- Add an entry in a directory
addDirectoryEntry :: Directory -> Entry -> Directory
addDirectoryEntry dir e = Directory {
name = name dir,
directories = directories dir,
entries = sortBy (compare `on` title) (e : entries dir)
}
-- Add a directory in a directory
addDirectoryDirectory :: Directory -> Directory -> Directory
addDirectoryDirectory dir d = Directory {
name = name dir,
directories = sortBy (compare `on` name) (d : directories dir),
entries = entries dir
}
-- Remove an entry from a directory
removeDirectoryEntry :: Directory -> Entry -> Directory
removeDirectoryEntry dir e = Directory {
name = name dir,
directories = directories dir,
entries = filter ((title e /= ) . title) (entries dir)
}
-- Remove a directory from a directory
removeDirectoryDirectory :: Directory -> Directory -> Directory
removeDirectoryDirectory dir d = Directory {
name = name dir,
directories = filter ((name d /= ) . name) (directories dir),
entries = entries dir
}
-- Replace a directory in the specified path
-- Input: dir "xxx/yyy/zzz" "aaa"
-- Does: dir' = xxx/yyy/aaa
-- Returns: dir'
replaceDirectoryInPath :: Directory -> [String] -> Directory -> Directory
replaceDirectoryInPath dir [] newDir = addDirectoryDirectory (removeDirectoryDirectory dir newDir) newDir
replaceDirectoryInPath dir path newDir =
replaceDirectoryInPath dir (tail path) $ addDirectoryDirectory (removeDirectoryDirectory currentDir newDir) newDir
where currentDir = getCurrentDirectory dir path
-- Return the last directory specified by path
-- dir "xxx/yyy/zzz" returns zzz
getCurrentDirectory :: Directory -> [String] -> Directory
getCurrentDirectory dir [] = dir
getCurrentDirectory dir path = getCurrentDirectory (fromJust (getDirectory dir (last path))) (init path)
-- Return entry from dir by name
getEntry :: Directory -> String -> Maybe Entry
getEntry dir s = if length e > 0 then Just $ head e else Nothing
where e = filter ((== s) . title) (entries dir)
-- Return directory from dir by name
getDirectory :: Directory -> String -> Maybe Directory
getDirectory dir s = if length d > 0 then Just $ head d else Nothing
where d = filter ((== s) . name) (directories dir)
-- -- -- -- -- -- -- -- -- -- -- --
-- The application
-- -- -- -- -- -- -- -- -- -- -- --
main :: IO ()
main = do
let filename = "EntryBook.dat"
dir <- loadData filename
ls dir
newDir <- prompt dir []
saveData filename newDir
return ()
-- Prompt
prompt :: Directory -> [String] -> IO Directory
prompt dir path = do
putStr "/"
putStr $ intercalate "/" (reverse path)
putStr "$ "
hFlush stdout
userInput <- getLine
case strip userInput of
"exit" -> return dir
"" -> prompt dir path
xd -> do
(msg, newDir, newPath) <- dispatch (strip userInput) dir path
if msg == ""
then do
ls $ getCurrentDirectory newDir newPath
prompt newDir newPath
else do
putStrLn msg
prompt newDir newPath
where currentDir = getCurrentDirectory dir path
-- Dispatch user commands
dispatch :: String -> Directory -> [String] -> IO (String, Directory, [String])
dispatch "ls" dir path = do
itemsNr <- ls currentDir
return (show itemsNr ++ " element(s) found", dir, path)
where currentDir = getCurrentDirectory dir path
dispatch ('c':'d':' ':s) (dir) (path) = do
let (msg, newPath) = cd dir path s
return (msg, dir, newPath)
dispatch ('v':'i':'e':'w':' ':xs) (dir) (path) = do
let e = getEntry currentDir xs
if isJust e
then do
displayEntry $ fromJust e
return ("", dir, path)
else
return (xs ++ ": no such entry", dir, path)
where currentDir = getCurrentDirectory dir path
dispatch "new" dir path = do
e <- newEntry
let newDir = addEntry dir path e
return ("", newDir, path)
dispatch ('m':'k':'d':'i':'r':' ':xs) (dir) (path) = do
let newDir = addDirectory dir path $ Directory xs [] []
return ("", newDir, path)
dispatch ('r':'m':' ':xs) (dir) (path) = return $ rm dir path xs
dispatch "help" dir path = do
help
return ("", dir, path)
dispatch xs dir path = return (xs ++ ": command not found\nType 'help' for all available commands.", dir, path)
-- Directory listing
ls :: Directory -> IO Int
ls dir = do
putStrLn $ "Directory name: " ++ name dir
putStrLn "Directory listing:"
mapM_ (\a -> putStrLn ("d| " ++ name a)) (directories dir)
mapM_ (\a -> putStrLn ("e| " ++ title a)) (entries dir)
return $ length (directories dir) + length (entries dir)
-- -- -- -- -- -- -- -- -- -- -- --
-- The functions
-- -- -- -- -- -- -- -- -- -- -- --
-- Change directory
cd :: Directory -> [String] -> String -> (String, [String])
cd dir path dest =
case dest of
"/" -> ("", [last path])
"" -> ("", path)
"." -> ("", path)
".." -> if length path > 0 then ("", tail path) else ("", path)
xs -> do
let d = getDirectory (getCurrentDirectory dir path) xs
if isJust d
then
("", name (fromJust d) : path)
else
(xs ++ ": no such directory", path)
-- Remove an entry or a directory
rm :: Directory -> [String] -> String -> (String, Directory, [String])
rm dir path xs = do
let d = getDirectory currentDir xs
if isJust d
then do
let newDir = removeDirectory dir path $ fromJust d
("", newDir, path)
else do
let e = getEntry currentDir xs
if isJust e
then do
let newDir = removeEntry dir path $ fromJust e
("", newDir, path)
else
(xs ++ ": no such directory or entry", dir, path)
where currentDir = getCurrentDirectory dir path
-- Print Help
help :: IO ()
help = do
putStrLn "Available commands:"
putStrLn "- exit: exit the application"
putStrLn "- ls: list directory contents"
putStrLn "- cd [dir]: change the current directory to dir"
putStrLn "- mkdir [dir]: create a new directory [dir]"
putStrLn "- view [entry]: display the content of entry"
putStrLn "- new: open the entry creation screen"
putStrLn "- help: display this help"
-- Create entry from user input
newEntry :: IO Entry
newEntry = do
putStrLn "Entry title: "
title <- getLine
putStrLn "Entry content (type // to end): "
content <- getMultilineText
return $ Entry title content
-- Get multiline text from user input
getMultilineText :: IO String
getMultilineText = do
text <- getLine
if text == "//"
then return ""
else do
newText <- getMultilineText
return $ text ++ newText
-- Display an entry
displayEntry :: Entry -> IO ()
displayEntry e = do
putStrLn ""
putStrLn $ "Title: " ++ title e
putStrLn "Content: "
putStrLn $ content e
exitOnInput <- getLine
return ()
-- Save data to disk
saveData :: String -> Directory -> IO ()
saveData filename dir = do
writeFile filename $ show dir
return ()
-- Load data from disk
loadData :: String -> IO Directory
loadData filename = do
fileExist <- doesFileExist filename
if fileExist
then do
contents <- readFile filename
let dir = read contents :: Directory
return dir
else return $ Directory "root" [] []
-- -- -- -- -- -- -- -- -- -- -- --
-- Helper function
-- -- -- -- -- -- -- -- -- -- -- --
strip :: String -> String
strip = lstrip . rstrip
lstrip :: String -> String
lstrip = dropWhile (`elem` " \t")
rstrip :: String -> String
rstrip = reverse . lstrip . reverse
split :: Char -> String -> [String]
split delim [] = [""]
split delim (c:cs)
| c == delim = "" : rest
| otherwise = (c : head rest) : tail rest
where
rest = split delim cs
</code></pre>
<p>I would be pleased with any advises concerning the data structure, the code style or anything else. Thank you.</p>
|
[] |
[
{
"body": "<p>Here are a few things that could be done in your code.</p>\n\n<pre><code>{-# LANGUAGE TemplateHaskell, ViewPatterns #-}\n</code></pre>\n\n<p>I use template haskell to derive data lenses, which make your directory access a little more succinct. I also use ViewPatterns so that the dispatch on string prefixes are easier.</p>\n\n<pre><code>import Data.Maybe\nimport Data.List (sortBy,groupBy,elemIndex,intercalate,stripPrefix)\nimport Data.Function (on)\nimport System.IO (stdout,hFlush)\nimport System.Directory (doesFileExist)\nimport Control.Monad\n\nimport Control.Applicative\n\nimport Data.Lens.Template (makeLenses)\nimport Data.Lens.Lazy\n</code></pre>\n\n<p>Notice the underscores in member names, these are converted to their lense equivalents by makeLenses</p>\n\n<pre><code>data Entry = Entry { _title :: String, _content :: String }\n deriving (Show, Read)\n\ndata Directory = Directory \n { _name :: String, _directories :: [Directory], _entries :: [Entry] }\n deriving (Show, Read)\n\n$( makeLenses [''Directory, ''Entry])\n</code></pre>\n\n<p>These few functions are tight. There is nothing more to be done with them I think. However, it should be noted that Entry and Directory have complementary functions everywhere. Perhaps it is profitable to abstract the common skeleton.</p>\n\n<pre><code>-- Add an entry into the directory tree.\naddEntry :: Directory -> [String] -> Entry -> Directory\naddEntry dir [] newEntry = addDirectoryEntry dir newEntry\naddEntry dir path newEntry = replaceDirectoryInPath dir (tail path) \n $ addDirectoryEntry currentDir newEntry\n where currentDir = getCurrentDirectory dir path\n\n-- Add a directory into the directory tree.\naddDirectory :: Directory -> [String] -> Directory -> Directory\naddDirectory dir [] newDir = addDirectoryDirectory dir newDir\naddDirectory dir path newDir = replaceDirectoryInPath dir (tail path) \n $ addDirectoryDirectory currentDir newDir\n where currentDir = getCurrentDirectory dir path\n\n-- Remove an entry from the directory tree.\nremoveEntry :: Directory -> [String] -> Entry -> Directory\nremoveEntry dir [] e = removeDirectoryEntry dir e\nremoveEntry dir path e = replaceDirectoryInPath dir (tail path) \n $ removeDirectoryEntry currentDir e\n where currentDir = getCurrentDirectory dir path\n\n-- Remove a directory from the directory tree.\nremoveDirectory :: Directory -> [String] -> Directory -> Directory\nremoveDirectory dir [] d = removeDirectoryDirectory dir d\nremoveDirectory dir path d = replaceDirectoryInPath dir (tail path) \n $ removeDirectoryDirectory currentDir d\n where currentDir = getCurrentDirectory dir path\n</code></pre>\n\n<p>We start getting use out of the lenses here. Compare it to your code.</p>\n\n<pre><code>-- Add an entry in a directory\naddDirectoryEntry :: Directory -> Entry -> Directory\naddDirectoryEntry dir e = entries ^%= (sortBy (compare `on` _title)) . (e :) $ dir\n\n-- Add a directory in a directory\naddDirectoryDirectory :: Directory -> Directory -> Directory\naddDirectoryDirectory dir d = directories ^%= (sortBy (compare `on` _name)) . (d :) $ dir\n\n-- Remove an entry from a directory\nremoveDirectoryEntry :: Directory -> Entry -> Directory\nremoveDirectoryEntry dir e = entries ^%= (filter ((_title e /=) . _title)) $ dir\n\n-- Remove a directory from a directory\nremoveDirectoryDirectory :: Directory -> Directory -> Directory\nremoveDirectoryDirectory dir d = directories ^%= (filter ((_name d /=) . _name)) $ dir\n\n-- Replace a directory in the specified path\n-- Input: dir \"xxx/yyy/zzz\" \"aaa\"\n-- Does: dir' = xxx/yyy/aaa\n-- Returns: dir'\nreplaceDirectoryInPath :: Directory -> [String] -> Directory -> Directory\nreplaceDirectoryInPath dir [] newDir = addDirectoryDirectory \n (removeDirectoryDirectory dir newDir) newDir\nreplaceDirectoryInPath dir path newDir =\n replaceDirectoryInPath dir (tail path) \n $ addDirectoryDirectory (removeDirectoryDirectory currentDir newDir) newDir\n where currentDir = getCurrentDirectory dir path\n\n-- Return the last directory specified by path\n-- dir \"xxx/yyy/zzz\" returns zzz\ngetCurrentDirectory :: Directory -> [String] -> Directory\ngetCurrentDirectory dir [] = dir\ngetCurrentDirectory dir path = getCurrentDirectory \n $ fromJust (getDirectory dir (last path))) (init path)\n\n-- Return entry from dir by name\ngetEntry :: Directory -> String -> Maybe Entry\ngetEntry dir s = if length e > 0 then Just $ head e else Nothing\n where e = filter ((== s) . _title) (_entries dir)\n\n-- Return directory from dir by name\ngetDirectory :: Directory -> String -> Maybe Directory\ngetDirectory dir s = if length d > 0 then Just $ head d else Nothing\n where d = filter ((== s) . _name) (_directories dir)\n\n-- -- -- -- -- -- -- -- -- -- -- --\n-- The application\n-- -- -- -- -- -- -- -- -- -- -- --\nfilename = \"EntryBook.dat\"\n\nmain :: IO ()\nmain = loadData filename >>= (\\dir -> ls dir >> prompt dir []) >>= saveData filename\n\n-- Prompt\nprompt :: Directory -> [String] -> IO Directory\nprompt dir path = do \n putStr $ concat [\"/\",intercalate \"/\" (reverse path), \"$ \"]\n hFlush stdout\n userInput <- getLine\n\n case strip userInput of\n \"exit\" -> return dir\n \"\" -> prompt dir path\n xd -> domore dir path xd \n where currentDir = getCurrentDirectory dir path\n domore dir path xd = do\n (msg, newDir, newPath) <- dispatch xd dir path\n if msg == \"\" then\n (ls $ getCurrentDirectory newDir newPath) >> return ()\n else putStrLn msg\n prompt newDir newPath\n</code></pre>\n\n<p>With ViewPatterns, we can match on string prefixes</p>\n\n<pre><code>-- Dispatch user commands\ndispatch :: String -> Directory -> [String] -> IO (String, Directory, [String])\ndispatch \"ls\" dir path = do\n itemsNr <- ls currentDir\n return (show itemsNr ++ \" element(s) found\", dir, path)\n where currentDir = getCurrentDirectory dir path\ndispatch (stripPrefix \"cd \" -> Just xs) dir path = return (msg, dir, newPath)\n where (msg, newPath) = cd dir path xs\ndispatch (stripPrefix \"view \" -> Just xs) dir path = case getEntry currentDir xs of\n Just x -> displayEntry x >> return (\"\", dir, path)\n _ -> return (xs ++ \": no such entry\", dir, path)\n where currentDir = getCurrentDirectory dir path\ndispatch \"new\" dir path = newEntry >>= \\e -> return (\"\", addEntry dir path e, path)\ndispatch (stripPrefix \"mkdir \" -> Just xs) dir path = return (\"\", newDir, path)\n where newDir = addDirectory dir path $ Directory xs [] []\ndispatch (stripPrefix \"rm \" -> Just xs) dir path = return $ rm dir path xs\ndispatch \"help\" dir path = help >> return (\"\", dir, path)\ndispatch xs dir path = return (xs ++ \n \": command not found\\nType 'help' for all available commands.\", dir, path)\n</code></pre>\n\n<p>Notice the reduction in code for the dispatched commands.</p>\n\n<pre><code>-- Directory listing\nls :: Directory -> IO Int\nls dir = do\n putStrLn $ \"Directory name: \" ++ (_name dir)\n putStrLn \"Directory listing:\"\n mapM_ (putStrLn . (\"d| \" ++) . _name) $ _directories dir\n mapM_ (putStrLn . (\"e| \" ++) . _title) $ _entries dir\n return $ length (_directories dir) + length (_entries dir)\n\n-- -- -- -- -- -- -- -- -- -- -- --\n-- The functions\n-- -- -- -- -- -- -- -- -- -- -- --\n-- Change directory\ncd :: Directory -> [String] -> String -> (String, [String])\ncd dir path dest =\n case dest of\n \"/\" -> (\"\", [last path])\n \"\" -> (\"\", path)\n \".\" -> (\"\", path)\n \"..\" -> (\"\", if null path then path else tail path)\n xs -> case getDirectory (getCurrentDirectory dir path) xs of\n Just x -> (\"\", _name x : path)\n Nothing -> (xs ++ \": no such directory\", path)\n\n-- Remove an entry or a directory\nrm :: Directory -> [String] -> String -> (String, Directory, [String])\nrm dir path xs = fromMaybe (xs ++ \": no such directory or entry\", dir, path)\n $ myfn (getDirectory, removeDirectory) `mplus` myfn (getEntry, removeEntry)\n where currentDir = getCurrentDirectory dir path\n myfn (fna, fnb) = fna currentDir xs >>= \\x -> return (\"\", fnb dir path x, path)\n</code></pre>\n\n<p>We can profitably use unlines to simulate heredocs in haskell.</p>\n\n<pre><code>-- Print Help\nhelp :: IO ()\nhelp = putStrLn $ unlines [\n \"Available commands:\",\n \"- exit: exit the application\",\n \"- ls: list directory contents\",\n \"- cd [dir]: change the current directory to dir\",\n \"- mkdir [dir]: create a new directory [dir]\",\n \"- view [entry]: display the content of entry\",\n \"- new: open the entry creation screen\",\n \"- help: display this help\"]\n\n-- Create entry from user input\nnewEntry :: IO Entry\nnewEntry = getPromptLine \"Entry title: \" <*\n putStrLn \"Entry content (type // to end): \" >>= (<$> getMultilineText) . Entry\n\n\ngetPromptLine :: String -> IO String\ngetPromptLine prompt = putStrLn prompt >> getLine \n\n-- Get multiline text from user input\ngetMultilineText :: IO String\ngetMultilineText = getLine >>= checkEnd\n where checkEnd \"//\" = return []\n checkEnd t = (++) t <$> getMultilineText\n\n-- Display an entry\ndisplayEntry :: Entry -> IO ()\ndisplayEntry e = putStrLn (unlines [\"\", \"Title: \" ++ (_title e),\n \"Content: \", _content e]) >> getLine >> return ()\n\n-- Save data to disk\nsaveData :: String -> Directory -> IO ()\nsaveData filename dir = writeFile filename $ show dir\n\n-- Load data from disk\nloadData :: String -> IO Directory\nloadData filename = check =<< doesFileExist filename\n where check True = read <$> readFile filename\n check False = return $ Directory \"root\" [] []\n\n-- -- -- -- -- -- -- -- -- -- -- --\n-- Helper function\n-- -- -- -- -- -- -- -- -- -- -- --\nstrip :: String -> String\nstrip = lstrip . rstrip\n\nlstrip :: String -> String\nlstrip = dropWhile (`elem` \" \\t\")\n\nrstrip :: String -> String\nrstrip = reverse . lstrip . reverse\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-06-16T05:42:32.990",
"Id": "12631",
"ParentId": "6351",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-28T10:18:18.930",
"Id": "6351",
"Score": "3",
"Tags": [
"haskell"
],
"Title": "Basic Directory / 'Text entry' create / delete / traversal (bash inspired) in Haskell"
}
|
6351
|
<p>I've put together this extremely simple text diff function a while ago:</p>
<pre><code>function diff($old, $new) {
$old = trim($old);
$new = trim($new);
if($old == $new) {
return $new;
}
$old = explode(" ", $old);
$new = explode(" ", $new);
$result = "";
$length = max(count($old), count($new));
for($i = 0; $i < $length; $i++) {
if(!isset($new[$i])) {
$result .= "<del>{$old[$i]}</del>";
continue;
}
if(!isset($old[$i])) {
$result .= "<ins>{$new[$i]}</ins> ";
continue;
}
if($old[$i] != $new[$i]) {
$result .= "<del>{$old[$i]}</del><ins>{$new[$i]}</ins> ";
continue;
}
$result .= "{$new[$i]} ";
}
$result = str_replace(array("</ins> <ins>", "</del> <del>"), " ", $result);
return trim($result);
}
$string1 = "Hello World!! Please review my diff function. Be gentle.";
$string2 = "Hello world! Please critique my diff function. Be extra vigilant.";
echo diff($string1, $string2);
// Hello <del>World!!</del><ins>world!</ins> Please <del>review</del><ins>critique</ins> my diff function. Be <del>gentle.</del><ins>extra vigilant.</ins>
</code></pre>
<p>The html output is:</p>
<blockquote>
<p>Hello <del>World!!</del>world! Please <del>review</del>critique my diff function. Be <del>gentle.</del>extra vigilant.</p>
</blockquote>
<p>The purpose of the function wasn't something important, as I can't even remember why I built it (found in my sandbox directory, which is full of little experiments). Is it any good? I've always used <a href="http://pear.php.net/package/Text_Diff/" rel="nofollow">PEAR Text_Diff</a> for text diffs, but if I'm not doing anything inherently wrong in my simple function, I'd love to use it instead.</p>
<p>Any suggestions on an easy way to move html out of the function?</p>
|
[] |
[
{
"body": "<p>It looks fine. A few notes:</p>\n\n<p>1, Use <a href=\"http://php.net/manual/en/function.max.php\" rel=\"nofollow\"><code>max</code></a> instead of </p>\n\n<pre><code>$length = count($old) > count($new) ? count($old) : count($new);\n</code></pre>\n\n<p>2, Consider testing with newlines, tabs and maybe other whitespace characters.</p>\n\n<p>3, <a href=\"http://en.wikipedia.org/wiki/Longest_common_subsequence\" rel=\"nofollow\">http://en.wikipedia.org/wiki/Longest_common_subsequence</a> could be useful if you want a better algorithm.</p>\n\n<p>4, For removing HTML out of the function create a class which does it and delegate the calls to it. For example:</p>\n\n<pre><code>public interface Decorator {\n\n public function delete($input);\n\n public function insert($input);\n\n public function removeUnnecessaryMarkers($input);\n}\n\npublic class HtmlDecorator {\n public function delete($input) {\n return \"<del>{$input}</del>\";\n }\n public function insert($input) {\n return \"<ins>{$input}</ins>\";\n }\n public function removeUnnecessaryMarkers($input) {\n return str_replace(array(\"</ins> <ins>\", \"</del> <del>\"), \" \", $input); \n }\n}\n</code></pre>\n\n\n\n<pre><code>...\nif(!isset($new[$i])) {\n $result .= $decorator->delete($old[$i]);\n continue;\n}\n...\n</code></pre>\n\n<p>(I haven't tested that this is a valid PHP syntax or not. Feel free to fix it.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-29T10:30:45.073",
"Id": "9898",
"Score": "0",
"body": "Thanks! Don't worry if the syntax is valid, you've given me a lot to work with. I'll edit the answer if I find any syntax mistakes."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-28T13:42:30.667",
"Id": "6357",
"ParentId": "6352",
"Score": "2"
}
},
{
"body": "<p>It looks like the program can only handle replacements, up to the ends.\nLike if you gave it</p>\n\n<pre><code>A B C D E\nA C D E\n</code></pre>\n\n<p>it would say B was replaced by C, C by D, D by E, and E deleted. That's four changes, instead of just the one change of deleting B.</p>\n\n<p>There's another way, where you can work out the details.\nIt is to have two indices, <code>i</code> and <code>j</code>.\nWhen <code>old[i] == new[j]</code>, both <code>i</code> and <code>j</code> are incremented.\nOtherwise you go into a diagonal search comparing elements like this:</p>\n\n<pre><code>i+1, j+0\ni+0, j+1\n\ni+2, j+0\ni+1, j+1\ni+0, j+2\n\ni+3, j+0\ni+2, j+1\ni+1, j+2\ni+0, j+3\n</code></pre>\n\n<p>until you get a match. Then you know how many elements in between were inserted or deleted.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-30T02:27:24.243",
"Id": "9931",
"Score": "0",
"body": "Yep, testing it with larger texts definitely show its weaknesses. I found the script in my sandbox of tricks, it's possible that it's a quick script I've built for a very specific purpose. I'll definitely try the indices as a quick hack. Searching for diff engines I've found this [excellent fine granularity engine](https://github.com/gorhill/PHP-FineDiff) ([demo here](http://www.raymondhill.net/finediff/viewdiff-ex.php)) so I'll probably throw away my script and use it instead... There are some [open issues](https://github.com/gorhill/PHP-FineDiff/issues) but overall its great."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-30T02:17:37.660",
"Id": "6395",
"ParentId": "6352",
"Score": "1"
}
},
{
"body": "<p>Would have posted this as a comment, but have only just signed up to add this input so not got that privalige yet! Have you had a look at the <a href=\"http://code.google.com/p/google-diff-match-patch/\" rel=\"nofollow\">google-diff-match-patch</a> library? There might be some good algorithmic ideas you could take away from that? There's no php example, but they've got a few other language options in there.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-30T10:41:24.603",
"Id": "6402",
"ParentId": "6352",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "6357",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-28T11:02:24.807",
"Id": "6352",
"Score": "3",
"Tags": [
"php"
],
"Title": "Simple text diff function"
}
|
6352
|
<p>A small greedy algorithm to position boxes in a grid.</p>
<p>Version A</p>
<pre><code>int lCurrentIndex = 0;
BoxInchesInterface lPreviousBbox = lSortedBboxes.iterator().next();
double lEndPositionForCurrentIndex = pDimension.getEnd(lPreviousBbox);
for (BoxInchesInterface lBbox : lSortedBboxes)
{
boolean lIsFirstIteration = lBbox == lPreviousBbox;
if (!lIsFirstIteration && pDimension.getStart(lBbox) >= lEndPositionForCurrentIndex) {
lCurrentIndex += 1;
lEndPositionForCurrentIndex = pDimension.getEnd(lBbox);
} else if (pDimension.getEnd(lBbox) < lEndPositionForCurrentIndex) {
lEndPositionForCurrentIndex = pDimension.getEnd(lBbox);
}
lIndexFromBbox.put(lBbox, lCurrentIndex);
lPreviousBbox = lBbox;
}
return lIndexFromBbox;
</code></pre>
<p>Version B</p>
<pre><code>int lCurrentIndex = 0;
Iterator<BoxInchesInterface> lItor = lSortedBboxes.iterator();
BoxInchesInterface lPreviousBbox = lItor.next();
double lEndPositionForCurrentIndex = pDimension.getEnd(lPreviousBbox);
lIndexFromBbox.put(lPreviousBbox, lCurrentIndex);
while (lItor.hasNext())
{
BoxInchesInterface lBbox = lItor.next();
if (pDimension.getStart(lBbox) >= lEndPositionForCurrentIndex)
{
lCurrentIndex += 1;
lEndPositionForCurrentIndex = pDimension.getEnd(lBbox);
} else if (pDimension.getEnd(lBbox) < lEndPositionForCurrentIndex) {
lEndPositionForCurrentIndex = pDimension.getEnd(lBbox);
}
lIndexFromBbox.put(lBbox, lCurrentIndex);
lPreviousBbox = lBbox;
}
</code></pre>
<p>Version A has the advantage of fewer variables but has to make sure to check for the first case when the <code>lBbox</code> is equal to <code>lPreviousBox</code>. Version B has the advantage that <code>lPreviousBox</code> is always different from <code>lBbox</code>, but has to deal with the iterator.</p>
<p>Which one would be better practice? Any suggestions for improvement?</p>
<p>(and I should add that concurrency is not an issue in this case.)</p>
|
[] |
[
{
"body": "<p>Version A is definitely better, as it employs a more familiar pattern to get the job done, and it makes use of bit of trivial code (<code>boolean lIsFirstIteration = lBbox == lPreviousBbox</code>) to save you from duplication of non-trivial code. (<code>lIndexFromBbox.put(lPreviousBbox, lCurrentIndex)</code>)</p>\n\n<p>I would trivialize the trivial code even more, by saying <code>bool IsFirstIteration = true</code> right before entering the loop, and <code>IsFirstIteration = false</code> as the last instruction of the loop. Note that even though this is two lines of code instead of one, its complexity is smaller, because it deals with constants, not with variables.</p>\n\n<p>I could perhaps give more advise if you explained what you mean by 'algorithm to position boxes in a grid'. A grid is generally thought of as a two-dimensional structure, but I only see operations in one dimension, on variables which are defined outside of the code fragment that you provided, so... what is this code trying to accomplish?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-29T16:07:40.743",
"Id": "9910",
"Score": "0",
"body": "You are correct, it is a 2 dimensional grid. This algorithm is run once for rows and once for columns. That is why it uses an interface \"Dimension\" so that it can be re-used both for the vertical and for the horizontal positioning. What the algorithm does is it takes boxes of arbitrary sizes and not overlapping and assign them a position as if they would each take one cell in a grid."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-28T13:04:58.667",
"Id": "6356",
"ParentId": "6354",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "6356",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-28T11:41:03.967",
"Id": "6354",
"Score": "5",
"Tags": [
"java"
],
"Title": "Positioning boxes in a grid"
}
|
6354
|
<p>I'm struggling for a while now with the readability of my code, I after I tried to get as much insight as possible (for my standards). On my level, I think I understand and use it <em>all right</em> for my level. </p>
<p>But I'm still having big chunks of mixed html/css in the presentation. Often I have a mediocre complex multi-dimensional array as a return value and on the actual presentation page, I iterate through it, but still do a lot of stuff with it.</p>
<p>So I'm looking now into template engines like Smarty, but I can't get my head around it, how I would save some actual code with it in examples like the following where I iterate and work with the array in the presentation:</p>
<pre><code>$courseinfo = new courseinfo($_SESSION['course_short']);
$row = $courseinfo->get_all();
$default = $courseinfo->get_default();
$prices = $courseinfo->get_prices();
$month_min_show = 5;
//color settings for prices
$colorlow = '#6F6';
$colormid = '#09F';
$colorhigh = '#F90';
$colorspecial = '#F0F';
$colorfull = 'rgba(255,0,0,0.3)';
/* CONTENT CALENDAR
-----------------
-----------------
*/
echo '<div id="calendar">';
$count['month'] = 0;
foreach($row as $month)
{
$lastcourse = end($month['course']);
$laststart = $lastcourse['date'];
$enddate = new DateTime($laststart);
$enddate->modify('+ '.($lastcourse['length']-1).' days');
$iterate = new DateTime('01-'.date('m',strtotime($laststart)).'-'.$month['year']);
if (!isset($stored['year']) || isset($stored['year']) && $stored['year'] != $month['year'])
{
if($count['month'] > $month_min_show) { break;} // don't show next year if $month_min_show months already displayed
if(isset($stored['year'])) { echo '<br /><br /><br /><div style="margin-top:-10px"></div>';}
echo '<span class="year" style="float:left;">'.$month['year'].'</span>';
echo '<div style="float:right;margin-top:-20px;padding-right:5px;">';
echo '<div style="float:left;font-size:12px;font-weight:bold;">PRICES '.$month['year'].'</div>';
echo '<div class="pricelegend" style="background-color:'.$colorfull.'">fully booked</div>';
if (in_array('low',$prices[$month['year']])) { echo '<div class="pricelegend" style="background-color:'.$colorlow.'">'.$default['price_low'].' &euro;</div>'; }
if (in_array('mid',$prices[$month['year']])) { echo '<div class="pricelegend" style="background-color:'.$colormid.'">'.$default['price_mid'].' &euro;</div>'; }
if (in_array('high',$prices[$month['year']])) { echo '<div class="pricelegend" style="background-color:'.$colorhigh.'">'.$default['price_high'].' &euro;</div>'; }
if (in_array('custom',$prices[$month['year']])) { echo '<div class="pricelegend" style="background-color:'.$colorspecial.'">Special Offer</div>';}
echo '</div><div style="clear:both;"></div><hr width="800px;" align="left"/>';
}
echo '<div class="m_start">'.mb_strtoupper($month['monthname'],'UTF-8').'<br />';
echo '<span class="yearsmall">'.$month['year'].'</span>';
echo '</div>';
echo '<div class="courses">';
echo '<div style="float:left;width:10px;">&nbsp;</div>';
while($iterate<=$enddate)
{
$dayname = strftime('%a',$iterate->format('U'));
if ($dayname == "So" OR $dayname == "Sa") { $daycolor = "#999"; } else { $daycolor = "#FFF";}
echo '<div class="dayname" id="'.$iterate->format('dmY').'" style="color:'.$daycolor.'">'.$dayname.'</div>';
$iterate->modify('+ 1 days');
}
echo '<br />';
$lineswitch = 0;
foreach($month['course'] as $course)
{
$date = $course['date'];
$date = new DateTime("$date");
$coursewidth = $course['length']*20-2;
if($course['class'] == 'low') { $pricecolor = $colorlow; }
elseif($course['class'] == 'mid') { $pricecolor = $colormid; }
elseif($course['class'] == 'high') { $pricecolor = $colorhigh; }
else {$pricecolor = $colorspecial;}
if($course['user'] >= $course['usermax']) { $pricecolor = $colorfull; }
if(isset($_SESSION['course_id']) && $_SESSION['course_id'] == $course['id']) { $bordercolor = 'border-color:#FFF';} else {$bordercolor = '';}
if($course['user'] < $course['usermax']) { echo '<a class="clink" id="'.$course['id'].'" href="'.$_SESSION['book_url'].'?course='.$course['id'].'" target="_self">'; }
echo '<div class="course" style="background-color:'.$pricecolor.';'.$bordercolor.';width:'.$coursewidth.'px;margin-top:'.$lineswitch*17 .'px;margin-left:'.(10+($date->format('d')-1)*20).'px">';
if($course['user'] < $course['usermax'])
{
echo '<span class="coursestart">&nbsp;'.$date->format('d').'</span>';
if($course['length'] > 1)
{
echo '-';
$date->modify('+ '.($course['length']-1).' days');
echo '<span class="courseend">'.$date->format('d').'&nbsp;</span>';
}
}
else { echo '<span style="color:#000;">x</span>'; }
echo '</div>';
if($course['user'] < $course['usermax']) {echo '</a>';}
unset($date);
if ($lineswitch == 0) { $lineswitch = 1;} else {$lineswitch = 0;}
}
echo '</div>';
echo '<div class="m_end"></div>';
echo '<div style="clear:both;"></div><br />';
$stored['year'] = $month['year'];
$count['month']++;
}
echo '</div>';
</code></pre>
<p>Here's an example of the array I'm iterating through:</p>
<pre><code>Array ( [04.2012] =>
Array ( [monthname] => April [year] => 2012 [course] =>
Array (
[0] => Array ( [id] => 106 [date] => 2012-04-02 14:00:00 [length] => 3 [class] => mid [price] => 110 [user] => 0 [usermax] => 20 [day] => 02 [week] => 14 [dayname] => Mo [hours] => 3 )
[1] => Array ( [id] => 107 [date] => 2012-04-03 10:00:00 [length] => 3 [class] => mid [price] => 110 [user] => 0 [usermax] => 20 [day] => 03 [week] => 14 [dayname] => Di [hours] => 3 )
[2] => Array ( [id] => 108 [date] => 2012-04-05 14:00:00 [length] => 3 [class] => mid [price] => 110 [user] => 0 [usermax] => 20 [day] => 05 [week] => 14 [dayname] => Do [hours] => 3 )
)
)
</code></pre>
<p>This is quite a bit of code as you can see, just so you can get an idea how I still have to <em>work</em> a lot with the array. </p>
<ul>
<li><strong>So how could I split this into smaller chunks or just make it more readable and easier to work with ?</strong></li>
</ul>
<p>Hope I could make clear what I want here...and sure if you find anything else that's totally stupid in this code, give me a word!</p>
<p>I wouldn't know how a template engine would help as it still is a lot of <code>if</code>s and dynamic changes in there. </p>
<p><em>Sidenote: I'm working alone and always will, so the separation is just for me.</em></p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-28T11:11:48.623",
"Id": "62839",
"Score": "0",
"body": "I would suggest using a PHP framework such as [cakePHP](http://www.cakephp.org). These frameworks use an MVC (model View Controller) architecture which will help you separate your business logic from presentation code."
}
] |
[
{
"body": "<p>Thank you for the perfect example of the <strong>real-life</strong> piece of presentation logic.<br>\nMost people pushing some primitive templating solutions just have no idea of such a complex cases existence. </p>\n\n<p>Three rules for you to get it right:</p>\n\n<ol>\n<li>Use PHP as a template engine. </li>\n<li>Output not an HTML tag nor text constant using PHP echo but use straight HTML only.</li>\n<li>Move ALL data preparations to the business logic part. </li>\n</ol>\n\n<p>Format ALL your data in the business logic.<br>\nPass only scalars to the template. No datetime objects!<br>\nNo complex logic - use only basic PHP syntax in the template.</p>\n\n<p>So, foreach your data twice: </p>\n\n<ul>\n<li>first time to do all the data preparations and formatting.</li>\n<li>and next time to do the actual output in the template.</li>\n</ul>\n\n<p>So, PHP code become like this</p>\n\n<pre><code>$count['month'] = 0;\nforeach($row as $i => $month)\n{\n $month['lastcourse'] = end($month['course']);\n $month['laststart'] = $month['lastcourse']['date'];\n $month['enddate'] = new DateTime($month['laststart']);\n $month['enddate']->modify('+ '.($month['lastcourse']['length']-1).' days');\n $month['iterate'] = new DateTime('01-'.date('m',strtotime($month['laststart'])).'-'.$month['year']);\n $month['showyear'] = (!isset($stored['year']) || isset($stored['year']) && $stored['year'] != $month['year']);\n $month['monthname'] = mb_strtoupper($month['monthname'],'UTF-8');\n $row[$i] = $month;\n} \n</code></pre>\n\n<p>while template as clean as this</p>\n\n<pre><code><div id=\"calendar\">\n<? foreach($row as $month): ?>\n <? if ($month['showyear']): ?>\n <? if ($stored['year']): ?>\n <br /><br /><br /><div style=\"margin-top:-10px\"></div>\n <? endif ?>\n <span class=\"year\" style=\"float:left;\"><?=$month['year']?></span>\n <div style=\"float:right;margin-top:-20px;padding-right:5px;\">\n <div style=\"float:left;font-size:12px;font-weight:bold;\">PRICES <?=$month['year']?></div>\n <div class=\"pricelegend\" style=\"background-color:<?=$colorfull?>\">fully booked</div>\n some code removed\n </div><div style=\"clear:both;\"></div><hr width=\"800px;\" align=\"left\"/>\n <? endif ?>\n <div class=\"m_start\"><?=$month['monthname']?><br />\n <span class=\"yearsmall\"><?=$month['year']?></span>\n </div>\n <div class=\"courses\">\n <div style=\"float:left;width:10px;\">&nbsp;</div>\n<? endforeach ?>\n</div>\n</code></pre>\n\n<p>I am not going to reformat all your code, but just to give you an idea. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-28T11:36:57.047",
"Id": "9863",
"Score": "0",
"body": "After reading this now for a couple of times, I totally dig this! It's a lightweight and plain simple approach to handle my problem. I will try to rewrite my own code now and see how it goes - might come back for further questions. I will leave the question still open in case someone else has a few more words to say! Thanks so much!!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-28T11:40:34.803",
"Id": "9864",
"Score": "3",
"body": "Feel free to ask. I am developing such an approach for years and hope I have something to share from the experience I've got."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-28T12:11:02.153",
"Id": "9865",
"Score": "2",
"body": "Inline styles and shorthand PHP tags are usually a no-go. Apart from that good job. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-28T19:17:49.840",
"Id": "9877",
"Score": "2",
"body": "@Daveo The shorthand PHP tags that cause trouble (currently) are `<?` and `<%`. Using `<?=` is fine."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-28T11:26:51.753",
"Id": "6361",
"ParentId": "6359",
"Score": "28"
}
},
{
"body": "<p>Working with this batch:</p>\n\n<pre><code>//color settings for prices\n$colorlow = '#6F6'; \n$colormid = '#09F'; \n$colorhigh = '#F90'; \n$colorspecial = '#F0F';\n$colorfull = 'rgba(255,0,0,0.3)';\n\n// ...\n// ...\n// ...\n\nif (in_array('low',$prices[$month['year']])) { echo '<div class=\"pricelegend\" style=\"background-color:'.$colorlow.'\">'.$default['price_low'].' &euro;</div>'; }\nif (in_array('mid',$prices[$month['year']])) { echo '<div class=\"pricelegend\" style=\"background-color:'.$colormid.'\">'.$default['price_mid'].' &euro;</div>'; }\nif (in_array('high',$prices[$month['year']])) { echo '<div class=\"pricelegend\" style=\"background-color:'.$colorhigh.'\">'.$default['price_high'].' &euro;</div>'; }\nif (in_array('custom',$prices[$month['year']])) { echo '<div class=\"pricelegend\" style=\"background-color:'.$colorspecial.'\">Special Offer</div>';}\n</code></pre>\n\n<p>One way to do it would be to use something like this:</p>\n\n<pre><code># place your colors into an array instead\n$colors = array();\n$colors['low'] = '#6F6'; \n$colors['mid'] = '#09F'; \n$colors['high'] = '#F90'; \n$colors['special'] = '#F0F';\n$colors['full'] = rgba(255,0,0,0.3);\n\n# price legend array, since your code appears to be checking each one\n$priceLegend = array();\n$priceLegend[] = 'low';\n$priceLegend[] = 'mid';\n$priceLegend[] = 'high';\n$priceLegend[] = 'custom';\n\n// ...\n// ...\n// ...\n</code></pre>\n\n<p>Then on the html output side:</p>\n\n<pre><code><div class=\"pricelegend\" style=\"background-color:<?php echo $colors['full']; ?>\">fully booked</div>\n<?php\n foreach($priceLegend as $key => $value) {\n if (in_array($value,$prices_array[$months_array['year']])) {\n $priceBackclr = $colors_array[$value];\n $priceDisplay = $defaults_array['price_'.$value];\n $priceDisplay .= ($priceDisplay != 'Special Offer') ? ' &euro' : '';\n ?>\n <div class=\"pricelegend\" style=\"background-color:<?php echo $priceBackclr; ?>\"><?php echo $priceDisplay; ?></div>';\n <?php\n }\n}\n?>\n</div><div style=\"clear:both;\"></div><hr width=\"800px;\" align=\"left\"/>\n</code></pre>\n\n<p>It looks like a lot more code, but making changes should not be so tough; make one change here then the others will follow.. I mean, for the price legend's (for example) div style or something..</p>\n\n<p>Anyway, it is just one of the many ways to do it.. And you can apply this to other sections of code... There are better methods out there; hope more will post here.</p>\n\n<p>[EDIT] Additional option/code provided as a result of on-going comment exchange [ EDIT]</p>\n\n<p>Place this function in one of your includes if you'd like:</p>\n\n<pre><code># function does the in_array for you\nfunction findInArrayAndReturnAsArray($valueToFind, $arrayToFindIn, $outputType) {\n # use $outputType so that if you would like, \n # you can reuse this function to do other stuff like find \n # another value in another array\n\n $outputArray = array();\n\n if ($outputType = 'price') {\n if (in_array($valueToFind, $arrayToFindIn)) {\n\n $outputArray[] = $colors_array[$valueToFind];\n $temp = $defaults_array['price_'.$valueToFind];\n $temp .= ($priceDisplay != 'Special Offer') ? ' &euro' : '';\n $outputArray[] = temp;\n }\n } \n\n return $outputArray;\n\n}\n</code></pre>\n\n<p>Then in your template, if you need to display it, use it this way:</p>\n\n<pre><code># go through each item in the price legend array and grab the results and then echo them with the html\nforeach($priceLegend as $key => $value) {\n $priceLegendDisplay = findInArrayAndReturnAsString($value , $prices_array[$months_array['year']], 'price');\n echo = '<div class=\"pricelegend\" style=\"background-color:'.$priceLegendDisplay[0].'\">'.$priceLegendDisplay[1].'</div>';\n}\n</code></pre>\n\n<p>The function <code>can</code> help <code>DRY</code> out your code. It can act flexible enough to accommodate other actions based on <code>$outputType</code> values you set and code for. Imagine that function stored away somewhere, and then your output page simply calls it. Then if you can, create your own class that will contain functions like these that handle how to output data. It might appear like a <code>controller</code> and <code>view</code> from the MVC design pattern, but with fine tuning you can turn it into a pure <code>view</code>. So I guess what I'm saying is.. To use a design pattern, object oriented approach, as well as keeping in mind to stay true to <code>Don't Repeat Yourself</code> principle.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-28T13:11:38.453",
"Id": "9866",
"Score": "0",
"body": "+1 for your effort or even more for the idea - because I see were you want to push me. Your code is more automated one could say. In this special case it wouldn't make sense though, but that doesn't lower the idea. Thanks for that too! Great to have different input!!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-28T14:16:43.680",
"Id": "9867",
"Score": "0",
"body": "Glad to have helped. I was actually going to post about creating more classes an DRY'd out functions, and then make them work dynamically with css, but I wasn't sure it would make sense since it'd somewhat be like suggesting a lot of code reformating.. But anyway, thanks!!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-28T15:01:19.693",
"Id": "9868",
"Score": "0",
"body": "At this stage it might be a bit too much for me to reformat my whole coding, but I'm always eager to learn, especially when it's about structuring. Could you give a rough example how you would do that please ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-29T11:08:54.477",
"Id": "9900",
"Score": "0",
"body": "@danontheline, is there a chance that you're already using a design pattern for your code? I would definitely suggest OOP and DRY programing, that's for sure, but I wanna ask first in case you already have a design pattern in use.."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-29T21:56:13.500",
"Id": "9927",
"Score": "0",
"body": "Okay, here are two links that I feel might give you a good refresh on OOP: http://net.tutsplus.com/tutorials/php/oop-in-php/ and http://www.phpfreaks.com/tutorial/oo-php-part-1-oop-in-full-effect ..Next, I personally apply OOP even to small projects like a simple survey or petition page. I go procedural when I need to whip up something quick to see if the idea works. Then I go OOP on it. :D Try to apply it to all your projects. As for DRY.. A rough example would be.. Let me update my answer..."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-28T12:40:09.997",
"Id": "6362",
"ParentId": "6359",
"Score": "6"
}
},
{
"body": "<p>You might also consider using a template engine like <a href=\"https://twig.symfony.com/\" rel=\"nofollow noreferrer\">Twig</a> or <a href=\"https://www.smarty.net/\" rel=\"nofollow noreferrer\">Smarty</a>.</p>\n\n<p>They both provide complete separation of display and logic.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-01-25T17:27:55.683",
"Id": "185988",
"ParentId": "6359",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "6361",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-28T10:50:55.057",
"Id": "6359",
"Score": "38",
"Tags": [
"php",
"html",
"datetime",
"layout"
],
"Title": "Displaying courses in an HTML calendar"
}
|
6359
|
<p>Please review my JavaScript code below. I want to colspan and rowspan automatically if adjacent cells have sames value. For example like this.</p>
<pre><code><table id="BeforeTable" border="1">
<tr><td>A</td><td>B</td><td>B</td><td>C</td><td>D</td></tr>
<tr><td>E</td><td>F</td><td>G</td><td>C</td><td>D</td></tr>
</table>
<br>
<table id="AfterTable" border="1">
<tr><td>A</td><td colspan="2">B</td><td rowspan="2">C</td><td rowspan="2">D</td></tr>
<tr><td>E</td><td>F</td><td>G</td></tr>
</table>
</code></pre>
<p>I have finished coding but I feel it is not sophisticated and I want to know more better way to solve the issue. Could you review my code below and give me any suggestions. (or if there is any solutions about this such as JavaScript libraries, please let me know.)</p>
<pre><code><table id="BeforeTable" border="1">
<tr><td>A</td><td>B</td><td>B</td><td>C</td><td>D</td></tr>
<tr><td>E</td><td>F</td><td>G</td><td>C</td><td>D</td></tr>
</table>
<br>
<script type="text/javascript">
$(document).ready(function(){
doColSpan();
doRowSpan();
deleteCellsByCol();
deleteCellsByRow();
});
function doColSpan(){
var colSpanCount = 1;
var tObj=document.getElementById("BeforeTable");
for(var i=0; i<tObj.rows.length; i++){
if(tObj.rows[i]!=null){
for(var j in tObj.rows[i].cells){
if(tObj.rows[i].cells[j].innerHTML){
if(colSpanCount > 1){
colSpanCount--;
continue;
}
colSpanCount = getColSpanCount(tObj, i, j);
if(colSpanCount > 1){
tObj.rows[i].cells[j].colSpan = colSpanCount;
}
}
}
}
}
}
function getColSpanCount(tObj, i, j){
colSpanCount = 1;
nextX = parseInt(j);
while(true){
nextX++;
if(isEqualToNextRightCell(tObj, i, j, nextX)){
colSpanCount++;
continue;
}else{
break;
}
}
return colSpanCount;
}
function isEqualToNextRightCell(tObj, i, j, nextX){
return tObj.rows[i].cells[nextX] && tObj.rows[i].cells[j].innerHTML == tObj.rows[i].cells[nextX].innerHTML
}
function doRowSpan(){
var tObj=document.getElementById("BeforeTable");
for(var i=0; i<tObj.rows.length; i++){
if(tObj.rows[i]!=null){
for(var j in tObj.rows[i].cells){
if(tObj.rows[i].cells[j].innerHTML){
rowSpanCount = getRowSpanCount(tObj, i, j);
if(rowSpanCount > 1){
tObj.rows[i].cells[j].rowSpan = rowSpanCount;
}
}
}
}
}
}
function getRowSpanCount(tObj, i, j){
rowSpanCount = 1;
nextY = parseInt(i);
while(true){
nextY++;
if(isEqualToNextUnderCell(tObj, i, j, nextY)){
rowSpanCount++;
continue;
}else{
break;
}
}
return rowSpanCount;
}
function isEqualToNextUnderCell(tObj, i, j, nextY){
return tObj.rows[nextY] && tObj.rows[nextY].cells[j] && tObj.rows[i].cells[j].innerHTML == tObj.rows[nextY].cells[j].innerHTML
}
function deleteCellsByCol(){
var s="";
var tObj=document.getElementById("BeforeTable");
for(var i=0; i<tObj.rows.length; i++){
if(tObj.rows[i]!=null){
for(var j in tObj.rows[i].cells){
if(tObj.rows[i].cells[j].innerHTML){
for(var k = 1; k < tObj.rows[i].cells[j].colSpan; k++){
tObj.rows[i].deleteCell(parseInt(j) + 1);
}
}
}
}
}
}
function deleteCellsByRow(){
var deletedCount = 0;
var tObj=document.getElementById("BeforeTable");
for(var i=0; i<tObj.rows.length; i++){
if(tObj.rows[parseInt(i)+1]){
for(var j in tObj.rows[i].cells){
rowSpanCount = tObj.rows[i].cells[j].rowSpan;
if(rowSpanCount > 1){
for(var k in tObj.rows[parseInt(i)+1].cells){
if(tObj.rows[i].cells[j].innerHTML == tObj.rows[parseInt(i)+1].cells[k].innerHTML){
tObj.rows[parseInt(i)+1].deleteCell(k);
}
}
}
}
}
}
}
</script>
</code></pre>
|
[] |
[
{
"body": "<ol>\n<li>I don't see a reason why these functions should be in the global scope. The easiest fix for that is to put everything inside your function called with <code>$(document).ready</code>.</li>\n<li><p><code>isEqualToNextRightCell</code>: Use the identity operation for comparison unless you're absolutely sure you want type conversion done automatically in the comparison. You also forgot the semicolon. <a href=\"https://stackoverflow.com/questions/359494/javascript-vs-does-it-matter-which-equal-operator-i-use\">Reference</a></p>\n\n<pre><code>function isEqualToNextRightCell(tObj, i, j, nextX){\n return tObj.rows[i].cells[nextX] &&\n tObj.rows[i].cells[j].innerHTML === tObj.rows[i].cells[nextX].innerHTML;\n}\n</code></pre></li>\n<li><p><code>getColSpanCount</code>: Declare your variables, or they will be global. Also, you can tighten this up a bit by bringing your <code>if</code> into your <code>while</code>:</p>\n\n<pre><code>function getColSpanCount(tObj, i, j) {\n var colSpanCount = 1,\n nextX = parseInt(j, 10);\n while (isEqualToNextRightCell(tObj, i, j, ++nextX)) {\n colSpanCount++;\n }\n return colSpanCount;\n}\n</code></pre></li>\n<li><p><code>doColSpan</code>: You make a minor, but all-too-common JS mistake here by referencing Array.length directly in the for loop. When possible, store the length once and recycle it. You can also improve readability and performance by storing the array elements as you loop. Furthermore, you treat your arrays inconsistently. tObj.rows you loop over using old-style syntax. tObj.rows[i].cells you loop over using <code>for … in</code> syntax, which is cool, but isn't implemented everywhere yet. Here's how I would write it:</p>\n\n<pre><code>function doColSpan() {\n var colSpanCount = 1,\n tObj = document.getElementById(\"BeforeTable\"),\n i = tObj.rows.length,\n j,\n numCells,\n row,\n cell;\n while (i-- > 0) {\n row = tObj.rows[i];\n if (row) {\n j = 0;\n numCells = row.cells.length;\n while (j < numCells) {\n cell = row.cells[j];\n if (cell.innerHTML) {\n if (colSpanCount > 1) {\n colSpanCount--;\n continue;\n }\n colSpanCount = getColSpanCount(tObj, i, j);\n if (colSpanCount > 1) {\n cell.colSpan = colSpanCount;\n }\n }\n }\n }\n }\n}\n</code></pre></li>\n</ol>\n\n<p>The rest of the code is much like the above, so I won't reiterate it. If you apply these principles throughout the code it should help. Don't forget to use a <a href=\"http://www.jshint.com/\" rel=\"nofollow noreferrer\">code analyzer</a> to help weed out the easy-to-fix stuff.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-29T11:55:38.713",
"Id": "9901",
"Score": "0",
"body": "Thank you very much! you gave me a lot of information I'v never knew. such as.."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-29T12:01:09.070",
"Id": "9902",
"Score": "0",
"body": ">1 The easiest fix for .. <br/> I will do it right now. To be honest .. I did not know the differences between inside \"$(document).ready\" and its outside. Additionally,.."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-29T12:13:27.193",
"Id": "9904",
"Score": "0",
"body": ">2 Use the identity.. <br/> I'm reading the reference as you wrote. .."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-29T12:41:48.800",
"Id": "9905",
"Score": "0",
"body": "I understood the meant of '===' finally. I will use it at another situations."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-29T03:44:13.487",
"Id": "6375",
"ParentId": "6363",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "6375",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-28T15:59:40.890",
"Id": "6363",
"Score": "3",
"Tags": [
"javascript"
],
"Title": "Spanning Table Cells automatically between same value cells"
}
|
6363
|
<p>For trivial reasons, I decided to have a go at differentiating dates. Low and behold having no idea how much of a non-trivial task it was to become.</p>
<p>It was <em>originally a small</em> sidetrack from a project I'm doing.</p>
<p>And, whilst performance isn't a huge concern here, the code I've posted below performs highly optimally in comparison to its alternative (shown below it). This is preferred, as originally this was used in a real-time program, and without other changes to the high-level algorithm, the cost of re-calculating the date difference every frame (up to 60FPS) was creating a significant run-time penalty.</p>
<p>But what I'm looking for in my solution, is algorithmic improvements, not optimizations (it runs more than fast enough). Such as removing the for loop for calculating which years are leap years (perhaps using 365.242199 constant?).</p>
<p>And especially techniques on how to <strong>get rid</strong> of that huge tree of comparisons for the initial swap; that just doesn't look like good practice... ever. I'm sure it can be done in the algorithm, but my attempts failed and I ran out of time.</p>
<pre><code>long calculate_seconds_between(
uint Y1, uint M1, uint D1, uint H1, uint m1, uint S1,
uint Y2, uint M2, uint D2, uint H2, uint m2, uint S2
)
{
bool invert = false;
if (Y1 > Y2) {
invert = true;
} else if (Y1 == Y2) {
if (M1 > M2) {
invert = true;
} else if (M1 == M2) {
if (D1 > D2) {
invert = true;
} else if (D1 == D2) {
if (H1 > H2) {
invert = true;
} else if (H1 == H2) {
if (m1 > m2) {
invert = true;
} else if (m1 == m2 && S1 > S2) {
invert = true;
}
}
}
}
}
if (invert) {
std::swap(Y1, Y2);
std::swap(M1, M2);
std::swap(D1, D2);
std::swap(H1, H2);
std::swap(m1, m2);
std::swap(S1, S2);
}
static const int month_days_sum[] = {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365};
const uint Y1_days = month_days_sum[M1 - 1];
const uint Y2_days = month_days_sum[M2 - 1];
int years_days = (Y2 - Y1) * 365;
// Leap Years
for (uint i = Y1 + 1; i < Y2;) {
if (is_leap_year(i)) {
++years_days;
i += 4;
} else {
++i;
}
}
const bool lY1 = is_leap_year(Y1) && (M1 < 2 || (M1 == 2 && D1 < 29));
const bool lY2 = is_leap_year(Y2) && (M2 > 2 || (M2 == 2 && D2 > 28));
if (Y1 == Y2) {
if (lY1 && lY2) ++years_days;
} else {
if (lY1) ++years_days;
if (lY2) ++years_days;
}
// Convert years to seconds
const long years_seconds = years_days * 86400;
// Time difference in seconds
const long S1s = ((Y1_days + D1) * 86400) + (H1 * 3600) + (m1 * 60) + S1;
const long S2s = ((Y2_days + D2) * 86400) + (H2 * 3600) + (m2 * 60) + S2;
const long total = years_seconds + (S2s - S1s);
if (invert) return -total;
else return total;
}
</code></pre>
<p>Standard C++ Alternative
Note: <em>very slow, up to (8000 / 35) 228x slower than the above.</em></p>
<pre><code>time_t calculate_seconds_between2(
const uint Y1, const uint M1, const uint D1, const uint H1, const uint m1, const uint S1, // YY/MM/DD HH:mm:SS
const uint Y2, const uint M2, const uint D2, const uint H2, const uint m2, const uint S2
)
{
time_t raw;
time(&raw);
struct tm t1, t2;
gmtime_r(&raw, &t1);
t2 = t1;
t1.tm_year = Y1 - 1900;
t1.tm_mon = M1 - 1;
t1.tm_mday = D1;
t1.tm_hour = H1;
t1.tm_min = m1;
t1.tm_sec = S1;
t2.tm_year = Y2 - 1900;
t2.tm_mon = M2 - 1;
t2.tm_mday = D2;
t2.tm_hour = H2;
t2.tm_min = m2;
t2.tm_sec = S2;
time_t tt1, tt2;
tt1 = mktime(&t1);
tt2 = mktime(&t2);
return (tt2 - tt1);
}
</code></pre>
<p>As shown in the Unit Testing, every single date (excluding tests on time) from 1990 to 2020 has been tested against every date from 1990 to 2020 (n^2) without failure, so the algorithm appears to be correct in terms of accuracy against the GNU implementation on my platform.</p>
<p>Unit Testing Code: <a href="http://pastie.org/2933904">http://pastie.org/2933904</a></p>
<p>Benchmark Code: <a href="http://pastie.org/2933893">http://pastie.org/2933893</a></p>
<p>Tagged with C as this is barely a far cry from being completely transferable.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-28T21:17:18.193",
"Id": "9878",
"Score": "0",
"body": "Did you get `is_leap_year()` correct? Remember you need to check for 100 and 400 year boundaries."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-28T21:31:35.060",
"Id": "9879",
"Score": "0",
"body": "I don't see why you are using gmtime_r() at the top. If you set the other fields to blank they will be set up correctly: struct tm t1 = {0}; Also the second way not only takes into account leap year but also leap seconds and any missed days that were removed from the calendar for that local (so it is doing significantly more work)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-28T21:58:57.800",
"Id": "9881",
"Score": "0",
"body": "@LokiAstari yes that function is correct, directly implemented from the Wikipedia page haha. As mentioned already however, accuracy is not the issue here."
}
] |
[
{
"body": "<p>I think if i was doing it, I'd try to structure it more like the standard code: turn each Y/M/D/H/m/S into seconds since some epoch, then use fairly straightforward subtraction to compute the difference.</p>\n\n<pre><code>unsigned calculate_seconds_between2(unsigned Y1, unsigned M1, unsigned D1, unsigned H1, unsigned m1, unsigned S1,\n unsigned Y2, unsigned M2, unsigned D2, unsigned H2, unsigned m2, unsigned S2)\n{\n // JSN = seconds since some epoch:\n unsigned T1 = JSN(Y1, M1, D1, H1, m1, S1);\n unsigned T2 = JSN(Y2, M2, D2, H2, m2, S2);\n return T1>T2 ? T1-T2 : T2-T1;\n}\n</code></pre>\n\n<p>For the seconds since epoch, I'd probably use something like a normal Julian Day Number, but with a more recent epoch (to reduce magnitudes, and with them the possibility of overflow), then calculate seconds into the day, something like this:</p>\n\n<pre><code>unsigned JSN(unsigned Y, unsigned M, unsigned D, unsigned H, unsigned m, unsigned S) {\n static const int unsigned secs_per_day = 24 * 60 * 60;\n return mJDN(Y-1900, M, D) * secs_per_day + H * 3600 + m * 60 + S;\n}\n</code></pre>\n\n<p>That leaves only calculating the modified JDN. It's not exactly transparent, but:</p>\n\n<pre><code>unsigned mJDN(unsigned Y, unsigned M, unsigned D) { \n return 367*Y - 7*(Y+(M+9)/12)/4 + 275*M/9 + D;\n}\n</code></pre>\n\n<p>This formula is from a 1991 <a href=\"http://groups.google.com/group/sci.astro/msg/56ace0ac38a46441?hl=en\" rel=\"nofollow\">Usenet post</a> by Tom Van Flandern, with an even more modified JDN (i.e., an even more recent epoch).</p>\n\n<p>Another way to help avoid overflow would be to model it a bit more closely after your code: compute a difference in days, and a difference in seconds, and only then convert the days to seconds, and add on the difference in seconds within the day:</p>\n\n<pre><code>unsigned time_diff(/* ...*/) { \n unsigned D1 = JDN(Y1, M1, D1);\n unsigned D2 = JDN(Y2, M2, D2);\n\n unsigned T1 = H1 * 3600 + m1 * 60 + S1;\n unsigned T2 = H2 * 3600 + m2 * 60 + S1;\n\n if (D1 == D2)\n return T1>T2 ? T1-T2 : T2-T1;\n return D1>D2 ? (D1-D2)*secs_per_day + T1-T2 : (D2-D1)*secs_per_day + T2-T1;\n}\n</code></pre>\n\n<p>In particular, this would make it easier to avoid overflow while still using standard Julian day numbers. This would be useful if (for example) you were using standard Julian day numbers for other purposes, so you wanted to re-use those standard routines.</p>\n\n<p>I haven't run full regression tests for accuracy (since the point is more about the overall structure than the actual code implementing it), but I'm reasonably certain the approach can/will produce accurate results. A quick test for speed indicates that it should be reasonably competitive in that regard as well -- at least with the compilers I have handy, it's fairly consistently somewhat faster. Even if (for example) I've messed something up in transcribing Tom's formula into C++, I doubt that fixing it will have any major effect on speed.</p>\n\n<p>Readability is open to a bit more question. Most of this code is <em>very</em> simple and straightforward, with one line of nearly impenetrable \"magic math\". Yours \"distributes\" the complexity, so there's no one part that's terribly difficult, but also no part that's really easy, obvious, or reusable either.</p>\n\n<p>Edit: As written this produces the absolute value of the difference. Eliminating that simplifies the code to something like this:</p>\n\n<pre><code>int mJDN(int Y, int M, int D) { \n return 367*Y - 7*(Y+(M+9)/12)/4 + 275*M/9 + D;\n}\n\nint JSN(ull Y, ull M, ull D, ull H, ull m, ull S) {\n static const int secs_per_day = 24 * 60 * 60;\n return mJDN(Y-1900, M, D) * secs_per_day + H * 3600 + m * 60 + S;\n}\n\nint calculate_seconds_between3(int Y1, int M1, int D1, int H1, int m1, int S1,\n int Y2, int M2, int D2, int H2, int m2, int S2)\n{\n int T1 = JSN(Y1, M1, D1, H1, m1, S1);\n int T2 = JSN(Y2, M2, D2, H2, m2, S2);\n return T2-T1;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-28T22:10:09.870",
"Id": "9882",
"Score": "0",
"body": "I'm going to have to go over this soon, but this solution is great, it *shamelessly* kills my solution in terms of performance, and maintains the accuracy.\n\nHowever, there is something strange going on with the sign, it doesn't always output the correct sign, ie it reports the difference between 23rd and 18th of a month is 5, when since 23rd > 18th, its -5 backwards (as defined by the behaviour of the previous two examples). Hopefully I'll find where this lies later though."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-28T22:22:00.040",
"Id": "9883",
"Score": "0",
"body": "@Daniel: Sorry, I must have misunderstood what your `invert` was supposed to do, and thought the intent was to produce an absolute difference. Producing a negative/positive is actually a bit simpler (see edit)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-29T01:05:50.923",
"Id": "9887",
"Score": "0",
"body": "Thanks a tonne mate, this is definitely the best solution. Regression tests show 100% accuracy for the time periods I am using."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-03T19:24:01.723",
"Id": "376919",
"Score": "0",
"body": "For the @jerry-coffin 's answer, if your date is not correct, i.e., for a date 2010-02-29 12:00:00, it will assume date as 2010-03-01 12:00:00. If you are not sure your dates are exactly correct, this method will fail. Be cautious!"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-28T17:58:47.510",
"Id": "6367",
"ParentId": "6364",
"Score": "5"
}
},
{
"body": "<p>Both methods have bugs:</p>\n<ul>\n<li><p>The first method takes no account of leap seconds, whereas the second might (depending on the platform).</p>\n</li>\n<li><p>The second method isn't guaranteed to return its result in units of seconds (although the use of <code>gmtime_r()</code>, suggests you're targeting POSIX, which does make that guarantee).</p>\n</li>\n</ul>\n<hr />\n<p>I had to infer some definitions, because the review is incomplete (and the linked code was inaccessible when I attempted to access it):</p>\n<pre><code>#include <ctime>\n#include <utility>\n\nusing uint = unsigned int;\n</code></pre>\n<p>I also needed to add a definition of <code>is_leap_year</code> in the first function:</p>\n<pre><code>auto const is_leap_year = [](uint y){ return y%4 ? 0 : y%100 ? 1 : y%400 == 0; };\n</code></pre>\n<p>I could then add a benchmark, and a <code>main()</code> to run it:</p>\n<pre><code>template<typename F>\nstruct benchmark\n{\n const F func;\n benchmark(F func) : func{std::move(func)} {}\n\n auto operator()() const \n {\n decltype(func(0,0,0,0,0,0,0,0,0,0,0,0)) sum = 0;\n for (auto year = 1900; year <= 2000; ++year)\n for (auto month = 1; month <= 12; ++month)\n sum += func(year, month, 20, 12, 0, 0,\n 2000, 6, 1, 8, 0, 0);\n return sum;\n }\n};\n</code></pre>\n\n<pre><code>#include <chrono>\n#include <ostream>\n\ntemplate<typename T>\nstruct time_printer\n{\n T func;\n\n friend std::ostream& operator<<(std::ostream& os, const time_printer& p)\n {\n using Duration\n = std::chrono::duration<double, std::chrono::milliseconds::period>;\n auto begin = std::chrono::steady_clock::now();\n p.func();\n auto end = std::chrono::steady_clock::now();\n Duration time_taken = end - begin;\n return os << time_taken.count();\n }\n};\n\ntemplate<typename T>\ntime_printer<T> print_time(T fun) { return {fun}; }\n</code></pre>\n \n<pre><code>#include <iostream>\nint main()\n{\n std::clog << "Method 1: "\n << print_time(benchmark(calculate_seconds_between)) << std::endl;\n std::clog << "Method 2: "\n << print_time(benchmark(calculate_seconds_between2)) << std::endl;\n}\n</code></pre>\n<p>This gives me a baseline ratio of about 100 between the two methods (after removing the unnecessary call to <code>std::time</code> in the second function). <code>std::mktime()</code> is always likely to be slower, as it must update <code>tm_yday</code> and (significantly) <code>tm_wday</code> in the passed structure.</p>\n<hr />\n<p>Let's now have a look at the function:</p>\n<p>The big <code>if</code>/<code>else</code> chain is ugly, as you noticed. The usual fix is to include <code><tuple></code>:</p>\n<pre><code>auto t1 = std::tie(Y1, M1, D1, H1, m1, S1),\n t2 = std::tie(Y2, M2, D2, H2, m2, S2);\n\nauto invert = t2 < t1;\nif (invert) std::swap(t1, t2);\n</code></pre>\n<p>As an alternative to recording <code>invert</code>, we can simply recurse with the arguments swapped:</p>\n<pre><code>auto t1 = std::tie(Y1, M1, D1, H1, m1, S1),\n t2 = std::tie(Y2, M2, D2, H2, m2, S2);\n\nif (t2 < t1)\n return - calculate_seconds_between(Y2, M2, D2, H2, m2, S2,\n Y2, M2, D2, H2, m2, S2);\n</code></pre>\n<p>Both of these changes are below the noise floor in my performance measurements.</p>\n<hr />\n<p>We can simplify the calculation of <code>lY1</code> and <code>lY2</code> given that we've almost calculated the day-in-year just before. Move the addition of <code>Yn_days</code> and <code>Dn</code>, then we can just use that day number:</p>\n<pre><code>const uint Y1_days = month_days_sum[M1 - 1] + D1;\nconst uint Y2_days = month_days_sum[M2 - 1] + D2;\n\n\nstatic const uint feb_29th = 60;\nconst bool lY1 = is_leap_year(Y1) && Y1_days < feb_29th;\nconst bool lY2 = is_leap_year(Y2) && M2 > 2;\n\n// Time difference in seconds\nconst long S1s = ((Y1_days) * 86400) + (H1 * 3600) + (m1 * 60) + S1;\nconst long S2s = ((Y2_days) * 86400) + (H2 * 3600) + (m2 * 60) + S2;\n</code></pre>\n<p>(I fixed the logic for <code>lY2</code> - it's a shame you didn't include the unit tests, as I think you have missed at least one, with the end date being 29 February).</p>\n<hr />\n<p>We can also simplify the calculation of first and last leap day to avoid branching:</p>\n<pre><code>years_days += lY1 + lY2 - (Y1 == Y2);\n</code></pre>\n<p>Alternatively, we could just conditionally include the first and/or last year into the loop:</p>\n<pre><code>for (uint i = Y1 + (Y1_days < feb_29th); i <= Y2 - (M2 > 2);) {\n if (is_leap_year(i)) {\n ++years_days;\n i += 4;\n } else {\n ++i;\n }\n}\n</code></pre>\n<hr />\n<p>We can remove two of the multiplications by 86400, by summing days first. We can eliminate all the paired multiplications like this:</p>\n<pre><code>// compute total seconds\nconst long days = years_days + Y2_days - Y1_days;\nconst long hours = days*24 + H2 - H1;\nconst long minutes = hours*60 + m2 - m1;\nreturn minutes*60 + S2 - S1;\n</code></pre>\n<p>Here, we avoid the subtle bug in the original, where <code>years_days * 86400</code> (<code>int * int</code> => <code>int</code>) could overflow (remember, <code>INT_MAX</code> can be as low as 65536<code>) before being widened to </code>long years_seconds`.</p>\n<hr />\n<h1>My version</h1>\n<pre><code>#include <ctime>\n#include <tuple>\n#include <utility>\n\nusing uint = unsigned int;\n\nlong calculate_seconds_between(\n const uint Y1, const uint M1, const uint D1,\n const uint H1, const uint m1, const uint S1,\n const uint Y2, const uint M2, const uint D2,\n const uint H2, const uint m2, const uint S2)\n{\n auto const\n t1 = std::tie(Y1, M1, D1, H1, m1, S1),\n t2 = std::tie(Y2, M2, D2, H2, m2, S2);\n\n if (t2 < t1)\n return - calculate_seconds_between(Y2, M2, D2, H2, m2, S2,\n Y2, M2, D2, H2, m2, S2);\n\n int years_days = (Y2 - Y1) * 365;\n\n // Leap Years\n auto const is_leap_year\n = [](uint y){ return y%4 ? 0 : y%100 ? 1 : y%400 == 0; };\n for (uint i = Y1 + (M1 > 2); i < Y2 + (M2 > 2);) {\n if (is_leap_year(i)) {\n ++years_days;\n i += 4;\n } else {\n ++i;\n }\n }\n\n static const uint month_days_sum[] =\n {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365};\n const uint Y1_days = month_days_sum[M1 - 1] + D1;\n const uint Y2_days = month_days_sum[M2 - 1] + D2;\n\n // compute total seconds\n const long days = years_days + Y2_days - Y1_days;\n const long hours = days*24 + H2 - H1;\n const long minutes = hours*60 + m2 - m1;\n return minutes*60 + S2 - S1;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-04T09:08:36.687",
"Id": "195797",
"ParentId": "6364",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "6367",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-28T16:19:24.413",
"Id": "6364",
"Score": "6",
"Tags": [
"c++",
"optimization",
"c",
"algorithm"
],
"Title": "Date Time - Seconds Difference"
}
|
6364
|
<p>I've written a table of contents parser for a FOSS wiki project I maintain in my spare time. The class takes a HTML string, injects anchor takes before each H1,H2 etc. and then generates the contents for the headers.</p>
<p>My main concern is boundary checks within the code. I haven't got any unit tests for it as it's a bit hard to test without a slightly contrived set of example text.</p>
<p>I'm after any glaring issues, or easier ways of doing the tree parsing the way I've done it. I'm reluctant to wrap the <code>InsertToc</code> method in a giant try/catch but instead have all all edge cases catered for.</p>
<p>The source is <a href="http://hg.shrinkrays.net/roadkill/src/b9d816ade3fd/Roadkill.Core/Text/TocParser.cs" rel="nofollow">here</a> as well.</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HtmlAgilityPack;
public class TocParser
{
private Header _previousHeader;
/// <summary>
/// Replaces all {TOC} tokens with the HTML for the table of contents. This method also inserts
/// anchored name tags before each H1,H2,H3 etc. tag that the contents references.
/// </summary>
public string InsertToc(string html)
{
HtmlDocument document = new HtmlDocument();
document.LoadHtml(html);
HtmlNodeCollection elements = document.DocumentNode.ChildNodes;
// The headers are stored in a flat list to start with
List<Header> rootHeaders = new List<Header>();
ParseHtmlAddAnchors(document.DocumentNode, rootHeaders, "h1");
// Try parsing all H2 headers (as H1 is technically the page title).
if (rootHeaders.Count == 0)
ParseHtmlAddAnchors(document.DocumentNode, rootHeaders, "h2");
// Add a fake root for the tree
Header rootHeader = new Header("","h0");
rootHeader.Children.AddRange(rootHeaders);
foreach (Header header in rootHeaders)
{
header.Parent = rootHeader;
}
StringBuilder builder = new StringBuilder();
builder.AppendLine("<div class=\"toc\">");
builder.AppendLine("<div class=\"toc-title\">Contents [<a class=\"toc-showhide\" href=\"#\">hide</a>]</div>");
builder.AppendLine("<div class=\"toc-list\">");
builder.AppendLine("<ul>");
GenerateTocList(rootHeader, builder);
builder.AppendLine("</ul>");
builder.AppendLine("</div>");
builder.AppendLine("</div>");
return document.DocumentNode.InnerHtml.Replace("{TOC}",builder.ToString());
}
/// <summary>
/// Generates the ToC contents HTML for the using the StringBuilder.
/// </summary>
private void GenerateTocList(Header parentHeader, StringBuilder htmlBuilder)
{
// Performs a level order traversal of the H1 (or H2) trees
foreach (Header header in parentHeader.Children)
{
htmlBuilder.AppendLine("<li>");
htmlBuilder.AppendFormat(@"<a href=""#{0}"">{1}&nbsp;{2}</a>", header.Id, header.GetTocNumber(), header.Title);
if (header.Children.Count > 0)
{
htmlBuilder.AppendLine("<ul>");
GenerateTocList(header, htmlBuilder);
htmlBuilder.AppendLine("</ul>");
}
htmlBuilder.AppendLine("</li>");
}
}
/// <summary>
/// Parses the HTML for H1,H2, H3 etc. elements, and adds them as Header trees, where
/// rootHeaders contains the H1 root nodes.
/// </summary>
private void ParseHtmlAddAnchors(HtmlNode parentNode, List<Header> rootHeaders, string rootTag)
{
foreach (HtmlNode node in parentNode.ChildNodes)
{
if (node.Name.StartsWith("h"))
{
Header header = new Header(node.InnerText,node.Name);
if (_previousHeader != null && header.Level > _previousHeader.Level)
{
// Add as a new child
header.Parent = _previousHeader;
_previousHeader.Children.Add(header);
}
else if (_previousHeader != null)
{
// Add as a sibling
while (_previousHeader.Parent != null && _previousHeader.Level > header.Level)
{
_previousHeader = _previousHeader.Parent;
}
header.Parent = _previousHeader.Parent;
if (header.Parent != null)
header.Parent.Children.Add(header);
}
// Add an achor tag after the header as a reference
HtmlNode anchor = HtmlNode.CreateNode(string.Format(@"<a name=""{0}""></a>",header.Id));
node.PrependChild(anchor);
if (node.Name == rootTag)
rootHeaders.Add(header);
_previousHeader = header;
}
else if (node.HasChildNodes)
{
ParseHtmlAddAnchors(node, rootHeaders, rootTag);
}
}
}
/// <summary>
/// Represents a header and its child headers, a tree with many branches.
/// </summary>
private class Header
{
public string Id { get; set; }
public string Tag { get; set; }
public int Level { get; private set; }
public List<Header> Children { get; set; }
public Header Parent { get; set; }
public string Title { get; set; }
public Header(string title, string tag)
{
Children = new List<Header>();
Title = title;
Tag = tag;
int level = 0;
int.TryParse(tag.Replace("h", ""),out level); // lazy (aka hacky) way of tracking the level using HTML H number
Level = level;
ShortGuid guid = ShortGuid.NewGuid();
Id = string.Format("{0}{1}", Title.EncodeTitle(), guid);
}
public string GetTocNumber()
{
string result = SiblingNumber().ToString();
if (Parent != null && Level > 1)
{
Header parent = Parent;
while (parent != null && parent.Level > 0)
{
result += "." + parent.SiblingNumber();
parent = parent.Parent;
}
}
return new String(result.ToArray().Reverse().ToArray<char>());
}
public int SiblingNumber()
{
if (Parent != null)
{
for (int i = 0; i < Parent.Children.Count; i++)
{
if (Parent.Children[i] == this)
return i +1;
}
}
return 1;
}
public override bool Equals(object obj)
{
Header header = obj as Header;
if (header == null)
return false;
return header.Id.Equals(Id);
}
public override int GetHashCode()
{
return Id.GetHashCode();
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-29T16:35:36.293",
"Id": "9914",
"Score": "0",
"body": "The comment beginning `Try parsing all H2 headers` is at best misleading. A more useful comment there would say why `h2` is parsed iff no `h1` was found."
}
] |
[
{
"body": "<p>I'd be weary of solutions that builds the HTML by hand. Work with the DOM and let it write out the HTML for you. HAP can do that for you.</p>\n\n<p>Don't create one-time use extension methods. It appears you created an extension method for strings to encode your titles. If you can't use it anywhere else in your code, it doesn't belong as an extension. I'd argue that it should be a regular static method of your <code>Header</code> class as it might be specific to how you want your headers encoded. In this context, it is confusing to see that call there.</p>\n\n<p>Your logic in your headers to get the \"sibling number\" and TOC prefix is more complicated than it needs to be. Especially the <code>GetTocNumber()</code> method, the logic is very confusing to glance at. I was having a hard enough time trying to figure out what it was doing. The string reversal at the end really killed it. They both could be done simpler. In fact, they could be calculated at once on construction with some refactoring.</p>\n\n<p>That leads in to the critical thing that's missing in most of these methods, comments... there's not a lot of <em>useful</em> ones in there. Your comments should be explaining what is happening in the code that couldn't be determined at first glance. The code really should be self-documenting. When it isn't, you need to say what it's doing in comments. But no one cares that the next line will add some item to a list. You should me saying things like, \"we need to ensure we don't have an empty list because...\" or at least explain why some actions are needed.</p>\n\n<p>I did a lot more that I thought I would do but I would rewrite it more like this.</p>\n\n<p>p.s., I don't know what your HTML would look like so I don't know how the nesting actually worked. But this should give you an idea how it could be better implemented (IMHO).</p>\n\n<pre><code>//Does this really need to create instances of this class?\npublic static class TocParserEx\n{\n //Does this really need to be an instance method?\n public static string InsertToc(string html)\n {\n var doc = new HtmlDocument();\n doc.LoadHtml(html);\n\n //only place the TOC if there is a TOC section labeled\n var tocPlaceholder = doc.DocumentNode\n .DescendantNodes()\n .OfType<HtmlTextNode>()\n .Where(t => t.Text == \"{TOC}\")\n .FirstOrDefault();\n if (tocPlaceholder != null)\n {\n var newToc = HtmlNode.CreateNode(@\"<div class=\"\"toc\"\">\n <div class=\"\"toc-title\"\">Contents [<a class=\"\"toc-showhide\"\" href=\"\"#\"\">hide</a>]</div>\n <div class=\"\"toc-list\"\"></div>\n</div>\");\n tocPlaceholder.ParentNode.ReplaceChild(newToc, tocPlaceholder);\n\n AddHeaderAnchors(doc.DocumentNode, Header.Root);\n AddTocEntries(Header.Root, newToc.Descendants(\"div\").Last());\n }\n\n return doc.DocumentNode.WriteTo();\n }\n\n /// <summary>\n /// Adds anchors to headers found in the node to the parent header.\n /// </summary>\n /// <param name=\"root\">The root node which contains the headers</param>\n /// <param name=\"parentHeader\">The parent header</param>\n private static void AddHeaderAnchors(HtmlNode root, Header parentHeader)\n {\n // Find all child headers\n var headerName = \"h\" + (parentHeader.Level + 1);\n var headers = root.ChildNodes\n .Where(e => Header.IsHeader(e) && e.Name == headerName)\n .Select(e => Header.FromNode(e, parentHeader))\n .ToList();\n\n foreach (var header in headers)\n {\n var replacement = HtmlNode.CreateNode(String.Format(\"<a name=\\\"{0}\\\"/>\", header.Id));\n\n //populate any subheaders\n AddHeaderAnchors(header.Node, header);\n\n //replace the found header with the wrapper\n header.Node.ParentNode.ReplaceChild(replacement, header.Node);\n replacement.AppendChild(header.Node);\n }\n }\n\n /// <summary>\n /// Adds the child headers to the TOC section.\n /// </summary>\n /// <param name=\"rootHeader\">The header which contains the sections to be added</param>\n /// <param name=\"tocSection\">The TOC section to add to</param>\n private static void AddTocEntries(Header rootHeader, HtmlNode tocSection)\n {\n var ul = tocSection.AppendChild(HtmlNode.CreateNode(\"<ul/>\"));\n foreach (var header in rootHeader.Children)\n {\n var entry = ul.AppendChild(CreateTocEntry(header));\n\n if (header.Children.Any())\n {\n AddTocEntries(header, entry);\n }\n }\n }\n\n private static HtmlNode CreateTocEntry(Header header)\n {\n return HtmlNode.CreateNode(String.Format(@\"<li>\n <a href=\"\"#{0}\"\">{1}&nbsp;{2}</a>\n</li>\", header.Id, header.Section, header.Title));\n }\n}\n\n//this class really should be lightweight\npublic class Header\n{\n public static Header Root { get { return _root; } }\n private static readonly Header _root = new Header();\n\n public string Title { get; private set; }\n public string Tag { get; private set; }\n public string Id { get; private set; }\n public int Level { get; private set; }\n public HtmlNode Node { get; private set; }\n public Header Parent { get; private set; }\n public ReadOnlyCollection<Header> Children { get { return _children.AsReadOnly(); } }\n public int EntryNumber { get; private set; }\n public string Section { get; private set; }\n\n private List<Header> _children;\n\n private Header() : this(HtmlNode.CreateNode(\"<h0/>\"), null) { }\n private Header(HtmlNode node, Header parent)\n {\n Title = node.InnerText;\n Tag = node.Name;\n Id = EncodeTitle(Title) + ShortGuid.NewGuid();\n Level = Int32.Parse(Tag.Substring(1));\n Node = node;\n Parent = parent ?? _root;\n _children = new List<Header>();\n\n if (parent == null)\n {\n EntryNumber = 1;\n Section = \"1\";\n }\n else\n {\n parent._children.Add(this);\n EntryNumber = parent.Children.Count;\n Section = parent.Section + \".\" + EntryNumber;\n }\n }\n\n public static Header FromNode(HtmlNode node, Header parent)\n {\n if (parent == null)\n return _root;\n if (node == null)\n throw new ArgumentNullException(\"node\");\n return new Header(node, parent);\n }\n\n public static bool IsHeader(HtmlNode node)\n {\n return System.Text.RegularExpressions.Regex.IsMatch(node.Name, @\"h\\d\");\n }\n\n private static string EncodeTitle(string title)\n {\n //encode the title (whatever your logic is)\n return String.Concat(title.Where(Char.IsLetterOrDigit));\n }\n}\n</code></pre>\n\n<p>And the \"HTML\" I tested it on:</p>\n\n<pre class=\"lang-html prettyprint-override\"><code><p>{TOC}</p>\n<h1>This is a title!!!</h1>\n<h1>Here's another title!!!</h1>\n</code></pre>\n\n<p>Generates something like this:</p>\n\n<pre class=\"lang-html prettyprint-override\"><code><p><div class=\"toc\">\n <div class=\"toc-title\">Contents [<a class=\"toc-showhide\" href=\"#\">hide</a>]</div>\n <div class=\"toc-list\"><ul><li>\n <a href=\"#ThisisatitlefyxTAeHYp0y2KaQOvD89JA\">1.1&nbsp;This is a title!!!</a>\n</li><li>\n <a href=\"#HeresanothertitleD3FHM3IpO0OAuNRRtmS1vw\">1.2&nbsp;Here's another title!!!</a>\n</li></ul></div>\n</div></p>\n<a name=\"ThisisatitlefyxTAeHYp0y2KaQOvD89JA\"><h1>This is a title!!!</h1></a>\n<a name=\"HeresanothertitleD3FHM3IpO0OAuNRRtmS1vw\"><h1>Here's another title!!!</h1></a>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-30T10:15:45.160",
"Id": "9936",
"Score": "0",
"body": "Hi Jeff thanks for the feedback, a few things - the extension method is used elsewhere in the project quite a lot, the HAP I'm using is 1.x as 2 is quite buggy still. I was hoping the code would be fairly self documenting but obviously not. It's creating a BST and doing in-order searches for each header (leaf) in the tree, to find what level that header is. The string is reversed as it's built from the bottom up.I agree about the statics although I did want it to be threadsafe. I'll probably borrow bits of your code but I don't want to rewrite the whole thing, making it more readable."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-29T23:44:02.000",
"Id": "6394",
"ParentId": "6369",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-28T18:34:43.120",
"Id": "6369",
"Score": "1",
"Tags": [
"c#",
"html"
],
"Title": "HTML Table of contents parser"
}
|
6369
|
<p>I am looking for feedback on coding style. I know this function already exists, and I would never use my version over a well tested one. I am just practicing.</p>
<pre><code>double Clib_atof(char s[])
{
double val, power, rtn;
int i, sign;
for (i = 0; isspace(s[i]); i++);
sign = (s[i] == '-') ? -1 : 1;
if (s[i] == '+' || s[i] == '-') ++i;
for (val = 0.0; isdigit(s[i]); ++i) {
val = 10.0 * val + (s[i] - '0');
}
if (s[i] == '.') {
++i;
}
for (power = 1.0; isdigit(s[i]); ++i) {
val = 10.0 * val + (s[i] - '0');
power *= 10.0;
}
rtn = (sign * val / (power));
// Next work on exponent
if (s[i] == 'e') {
int j, esign;
int eval = 0;
fprintf(stdout, "e found\n");
for (j = i + 1; isspace(s[j]); ++j);
esign = (s[j] == '-') ? -1 : 1;
if (s[j] == '+' || s[j] == '-') ++j;
for (; isdigit(s[j]); ++j) {
eval = 10 * eval + (s[j] - '0');
}
fprintf(stdout, "eval = %d\n", eval);
int l;
for (l = 0; l < eval; l++) {
(esign >= 0) ? (rtn *= 10) : (rtn /= 10);
}
}
// Finally return the solution
return rtn;
}
</code></pre>
|
[] |
[
{
"body": "<pre><code>double Clib_atof(char s[])\n{\n double val, power, rtn;\n int i, sign;\n for (i = 0; isspace(s[i]); i++);\n</code></pre>\n\n<p>Looks too much like the <code>;</code> was an accident. I suggest using <code>{/\\*empty\\*/}</code> instead to make it clear you did it on purpose. Or I might write it as a <code>while</code> loop.</p>\n\n<pre><code> sign = (s[i] == '-') ? -1 : 1;\n if (s[i] == '+' || s[i] == '-') ++i;\n for (val = 0.0; isdigit(s[i]); ++i) {\n val = 10.0 * val + (s[i] - '0');\n }\n</code></pre>\n\n<p>I dislike the use of a for loop here. The initializer condition doesn't really have any to do with the loop control. Repeating the loop until some condition becomes true feels like a <code>while</code> loop. With a <code>for</code> loop I think of iterating or counting not testing.</p>\n\n<pre><code> if (s[i] == '.') {\n ++i;\n }\n for (power = 1.0; isdigit(s[i]); ++i) {\n val = 10.0 * val + (s[i] - '0');\n power *= 10.0;\n }\n\n rtn = (sign * val / (power));\n</code></pre>\n\n<p>I wouldn't use abbreviations like <code>rtn</code> and <code>val</code>. They make the code harder to read. I don't think any of those parens are necessary. </p>\n\n<pre><code> // Next work on exponent\n if (s[i] == 'e') {\n int j, esign; \n int eval = 0;\n</code></pre>\n\n<p>I look at this and think evaluate, but I don't think that is what you meant.</p>\n\n<pre><code> fprintf(stdout, \"e found\\n\");\n for (j = i + 1; isspace(s[j]); ++j);\n</code></pre>\n\n<p>Why would you allow space here? Why <code>j</code>? Why didn't you stick with <code>i</code>?</p>\n\n<pre><code> esign = (s[j] == '-') ? -1 : 1;\n if (s[j] == '+' || s[j] == '-') ++j;\n for (; isdigit(s[j]); ++j) {\n eval = 10 * eval + (s[j] - '0');\n }\n</code></pre>\n\n<p>I note that this is pretty much the same as a previous block of code. Consider extracting the common bits into a function:</p>\n\n<pre><code> fprintf(stdout, \"eval = %d\\n\", eval);\n int l;\n for (l = 0; l < eval; l++) {\n (esign >= 0) ? (rtn *= 10) : (rtn /= 10);\n }\n</code></pre>\n\n<p>I suspect using a <code>pow()</code> function would be more fruitful.</p>\n\n<pre><code> }\n\n // Finally return the solution\n return rtn;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-28T19:13:42.123",
"Id": "6371",
"ParentId": "6370",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "6371",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-28T18:43:26.773",
"Id": "6370",
"Score": "5",
"Tags": [
"c",
"converting",
"reinventing-the-wheel",
"floating-point"
],
"Title": "Implementation of the atof() function"
}
|
6370
|
<p>I'm using the below code to try and make it easy to do sensible calculations for different variables, i.e. pressure + height is nonsensical, and pressure in atm += pressure in bar should add taking units into account. I've tried playing round with dynamic and static cast as well as CRTP on the advice of other fine members of the stack exchange community, but couldn't get those methods working. My code as is works but the + operator returns a Variable type not a Pressure type.</p>
<p>It's all in one file at the moment as I haven't messed with declaring template types in implementation files.</p>
<pre><code>#ifndef PARENT_VARIABLE_H_
#define PARENT_VARIABLE_H_
#include <string>
#include <map>
#include <stdio.h>
#include <typeinfo>
#include <boost/assign.hpp>
template <typename V,typename D> // To let different variables use different S.F.
struct Variable{
/*
* This structure is a abstract base class from which all dimensional variables
* are derived. Derived variables may be operated with and units will be largely
* automatically handled.
*/
protected:
//Functions
Variable(V v, std::string u,std::string * m_type, D conversions [], const std::map<std::string,short> * units);
//~Variable();
bool check_type(const std::string & two) const;
V consistant_units(const Variable & two) const;
//Variables
V value;
std::string unit;
const std::map<std::string, short> * valid_units; //contains all units for which conversions have been defined.
D * conversion; //An n by n array for calculating conversions
std::string * type;
public:
V get_value() const;
std::string get_unit() const;
void change_unit(const std::string & new_unit);
//Overloaded operators
//Changes self
Variable & operator+= (const Variable &t);
//Returns new Variable type
Variable & operator+(const Variable & other) const;
};
//////////////////////////////////////////////////////////////////////////////////////////////////////
/*
* Class functions
*/
FILE * E_FILE;
void warning(const std::string & message){ //Placeholder function I'm not sure what I want to do with my warning messages yet
E_FILE = fopen ("error_file.txt","w");
std::cout<<message; // might change to output file
fclose (E_FILE);
}
template<typename V,typename D>
Variable<V,D>::Variable(V v, std::string u, std::string * m_type, D conversions [], const std::map<std::string,short> * units){
value = v;
unit = u;
conversion = conversions;
valid_units = units;
type = m_type;
}
template <typename V,typename D>
V Variable<V,D>::get_value() const{
return value;
}
template <typename V,typename D>
std::string Variable<V,D>::get_unit() const{
return unit;
}
template <typename V,typename D>
void Variable<V,D>::change_unit(const std::string & new_unit){
if (valid_units->find( new_unit ) == valid_units->end()){//Check the unit is defined
std::string message = new_unit +" is not a valid unit. /n";
warning(message);
}
else{
int target = valid_units->find(new_unit)->second;
int original = valid_units->find(unit)->second;
value*=conversion[ (original*valid_units->size()) + target];
unit=new_unit;
}
}
template <typename V,typename D>
bool Variable<V,D>::check_type(const std::string & two) const{
if(*type!=two){
std::string message = two + " is not the same as "
+ *type + " adding them is nonsensical. /n";
warning(message);
return false;
}
return true;
}
template <typename V,typename D>
V Variable<V,D>::consistant_units(const Variable<V,D> & two) const{
if (unit!=two.unit){
std::string message = *type+
" units different, answer is in "+ unit + " /n";
warning(message);
int target = valid_units->find(unit)->second;
int original = valid_units->find(two.unit)->second;
return (two.value)*conversion[ (original*valid_units->size()) + target];
}
return two.value;
}
template <typename V,typename D>
Variable<V,D> & Variable<V,D>::operator +=(const Variable<V,D> & t){
if (check_type(*t.type)){
V other_value = consistant_units(t);
value += other_value;
}
return *this;
}
template <typename V,typename D>
Variable<V,D> & Variable<V,D>::operator+(const Variable<V,D> &other) const {
return Variable(*this) += other;
}
/////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////
/*
* Pressure
*/
template <typename V>
class Pressure : public Variable<V,double> {
public:
Pressure(V v,std::string u);
//~Pressure();
};
///////////////////////////////////////////////////////////////////////////////////////////////////////
/*
* Pressure
*/
static const std::map<std::string, short> PRESSURE_UNITS =
boost::assign::map_list_of("kPa",0)("atm",1)("psi",2);
static double PRESSURE_CONVERSION[3][3]= {{1,0.009869232667,0.145037738},
{101.325,1,14.6959488},
{6.89475729,0.0680459639,1}};
static std::string PRESSURE_TYPE = "Pressure";
template <typename V>
Pressure<V>::Pressure(V v, std::string u) : Variable<V,double>(v,u,&PRESSURE_TYPE,PRESSURE_CONVERSION[0],&PRESSURE_UNITS){
}
#endif /* PARENT_VARIABLE_H_ */
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-29T08:33:24.323",
"Id": "9894",
"Score": "0",
"body": "Last night I thought that perhaps flattening this out by getting rid of the Pressure class and instead making a friend Pressure function which calls the Variable constructor with arguments for value and unit, everything else is automatically assigned by the function. Then I'd just need one friend function for each variable type. What's your thoughts."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-29T19:53:07.250",
"Id": "9922",
"Score": "0",
"body": "Can you also show some example code of how your Variable and Pressure class is going to be used? Also important is what kind of misuse should your class prevent?"
}
] |
[
{
"body": "<p>A first look at the Variable base class:</p>\n\n<p>I assume this must always exist!<br>\nThus you should make it a reference (Unless there is some way to change this dynamically. Given the current interface I can's see a way to change it).</p>\n\n<pre><code>const std::map<std::string, short> * valid_units; //contains all units for which conversions have been defined.\n</code></pre>\n\n<p>Why would you have a pointer to a string?</p>\n\n<pre><code>std::string * type;\n</code></pre>\n\n<p>It should either be an object or a reference. To me it looks like the type and the method for converting to another type is really all one object that the variable should hold a <code>reference</code> too as a single entity. How you hold the reference can be a C++ style reference or a C++ template traits type depending on how you see it working.</p>\n\n<p>Have no idea how this works or how you are setting it up.<br>\nSo obviously we are missing a lot of commenting.</p>\n\n<pre><code>D * conversion; //An n by n array for calculating conversions\n</code></pre>\n\n<p>Constructor comments!</p>\n\n<pre><code>Variable(V v, std::string u,std::string * m_type, D conversions [], const std::map<std::string,short> * units);\n</code></pre>\n\n<ul>\n<li>V is passed by value. Since this is a template type I would rather it was passed by const reference this will avoid any nasty surprises in the future then a heavy type is used for V.</li>\n<li>u Again pass by const reference.</li>\n<li>m_type: Why are you passing a pointer (even if you store as a pointer internally you want to pass by reference (thus it can never be NULL)).</li>\n<li>D here D is a single dimension array. But above you say it is a N*N array. That's inconsistent.</li>\n<li>units again pass by reference (even if you store a pointer internally).</li>\n</ul>\n\n<p>Desstructor</p>\n\n<pre><code>//~Variable();\n</code></pre>\n\n<p>Commented out? If this is a base class you better have a good reason for not makeing this virtual. And if there is a good reason it should be well documented here.</p>\n\n<p>Checking the type! Why would you pass a string to check the type?</p>\n\n<pre><code>bool check_type(const std::string & two) const;\n</code></pre>\n\n<p>The only operation you can perform is to check if two <code>Variable</code> have the same type or not. Thus this function should take a const reference to another <code>Variable</code> object and you can return true/false if their types are same/different.</p>\n\n<p>Have no idea what this is supposed to do. More documentation needed.</p>\n\n<pre><code>V consistant_units(const Variable & two) const;\n</code></pre>\n\n<p>Ok. That's obvious.</p>\n\n<pre><code>V value;\n</code></pre>\n\n<p>Not as obvious what this does:</p>\n\n<pre><code>std::string unit;\n</code></pre>\n\n<p>OK. Personal opinio: <code>I hate Getters/Setters</code>. Best way to break your objects encapsulation ever invented. Also it tightly couples your class to always providing this interface in the future as somebody will use it and then you will have to maintain it.</p>\n\n<pre><code>V get_value() const;\n</code></pre>\n\n<p>OK. I can see why you may want to get the value. But return by reference. Also you need to provide a const version that returns a const reference to the value. Unless you wanted to use the value as part of a copy constructor in which case you should implement the copy constructor.</p>\n\n<pre><code>std::string get_unit() const;\n</code></pre>\n\n<p>No reason to be able to get the unit!. You need it because of the way you implemented check_type(). But you are leaking your abstraction here. Prefer to change check_type(). The other reason to leak this is for streaming purposes, but a better solution would be to implement a print method.</p>\n\n<p>OK. Self modification.</p>\n\n<pre><code>Variable & operator+= (const Variable &t);\n</code></pre>\n\n<p>But what reference are you returning here?</p>\n\n<pre><code>Variable & operator+(const Variable & other) const;\n</code></pre>\n\n<h3>EDIT: (Based on extended question)</h3>\n\n<blockquote>\n <p>I'm not sure what you mean by \"I assume this must always exist! Thus you should make it a reference.\"</p>\n</blockquote>\n\n<p>Will it ever be NULL? If it is never NULL then pass by reference.</p>\n\n<blockquote>\n <p>Why a pointer to a string; I want a single string, \"Pressure\", for all Pressure instances, then a different one, \"Length\" for all Length types.</p>\n</blockquote>\n\n<p>The create your set of types somewhere. And pass references to these types to your variable.</p>\n\n<blockquote>\n <p>My first instance was to use static inside the class but as I understand it this would cause both Pressure and Length to have the same string, type.</p>\n</blockquote>\n\n<p>You could have a static in the class:</p>\n\n<pre><code>struct Variable\n{\n /* STUFF */\n static std::string const PresureType;\n static std::string const LengthType;\n};\n</code></pre>\n\n<p>Now in the constructor of the object you would pass one of these values (by reference).</p>\n\n<pre><code>Variable pressure(15, \"Bar\", PresureType, myConversions, myUnits);\n</code></pre>\n\n<blockquote>\n <p>If I was to use a reference wouldn't I have to assign it on deceleration. Is there something I'm missing here?</p>\n</blockquote>\n\n<p>Not sure what you mean. You are already passing it to the cosntructor. There is no change.</p>\n\n<blockquote>\n <p>I'm passing a string that I've already got from another Variable it's a function that's meant to be called solely from within the class but I can see why this is confusing/bad design.</p>\n</blockquote>\n\n<p>Yes get rid of it. Methods are actions that can be performed on your object (any method that does not look like a verb is probably not really part of the class).</p>\n\n<blockquote>\n <p>I thought the reference was to a copied instance of the lhs which has been += to the rhs. I was also under the impression using the default copy constructor was fine as only value and unit need to be unique. Is this wrong?</p>\n</blockquote>\n\n<p>You are returning a reference to a local variable. That variable goes out of scope and will be destroyed at the end of the method. If you turn on your compiler warnings it will tell you about this.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-29T17:15:29.207",
"Id": "9920",
"Score": "0",
"body": "Thanks for the advice. Could you clarify a few things as posted above."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-29T17:25:14.527",
"Id": "9921",
"Score": "0",
"body": "By which I mean I've extended my question above as I couldn't fit my response in the comments."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-29T10:01:28.423",
"Id": "6378",
"ParentId": "6373",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "6378",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-29T00:48:29.347",
"Id": "6373",
"Score": "3",
"Tags": [
"c++"
],
"Title": "Performing calculations for different variables"
}
|
6373
|
<p>I've not posted binding specific messages to the gridview part. This shows updating that particular message or message from a list of messages databound with an XML file. My main concern is omitting redundant code in the <code>else</code> part. Any suggestions?</p>
<pre><code>protected void grdMessage_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
DataRow xRow;
DataSet mdsRedirect = new DataSet();
mdsRedirect.ReadXml(st);
if (Request["MessageID"] != null && Convert.ToInt16(Request["MessageID"]) != 0)
{
//Find specific item from XML and set updated value
mdsRedirect.Tables[0].DefaultView.RowFilter = "MessageID=" + Convert.ToInt16(Request["MessageID"]);
if (mdsRedirect.Tables[0].DefaultView.Count > 0)
{
mdsRedirect.Tables[0].DefaultView[0]["MessageText"] = ((TextBox)(grdMessage.Rows[e.RowIndex].FindControl("txtupdMessage"))).Text;
mdsRedirect.Tables[0].DefaultView.RowFilter = string.Empty;
}
else {
xRow = mdsRedirect.Tables[0].Rows[e.RowIndex];
xRow["MessageText"] = ((TextBox)(grdMessage.Rows[e.RowIndex].FindControl("txtupdMessage"))).Text;
}
}
else
{
xRow = mdsRedirect.Tables[0].Rows[e.RowIndex];
xRow["MessageText"] = ((TextBox)(grdMessage.Rows[e.RowIndex].FindControl("txtupdMessage"))).Text;
}
grdMessage.EditIndex = -1;
mdsRedirect.WriteXml(st);
mdsRedirect.Dispose();
getxml();//read XML file and bind it
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-29T13:45:46.930",
"Id": "9907",
"Score": "1",
"body": "Telling us what the code does is a code start."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-29T16:48:57.450",
"Id": "9916",
"Score": "0",
"body": "I've not posted binding specific message to gridview part. This shows updating that particular message or message from list of messages databound with XML file. My main concern was to omit redundant code in else part. Any suggestion?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-07T18:15:56.493",
"Id": "107100",
"Score": "0",
"body": "You can simplify `DataSet mdsRedirect = new DataSet();` through `mdsRedirect.Dispose();` by wrapping the creating within a `using` block."
}
] |
[
{
"body": "<p>Not sure if it's \"optimized\", but here's something of a simplification:</p>\n\n<pre><code> protected void grdMessage_RowUpdating(object sender, GridViewUpdateEventArgs e)\n {\n string messageIdString = Request[\"MessageID\"];\n int messageId = messageIdString == null ? 0 : Convert.ToInt16(messageIdString);\n\n using (DataSet mdsRedirect = new DataSet())\n {\n DataTable table = mdsRedirect.Tables[0];\n string updateMessageText = ((TextBox)grdMessage.Rows[e.RowIndex].FindControl(\"txtupdMessage\")).Text;\n\n mdsRedirect.ReadXml(st);\n table.DefaultView.RowFilter = messageId == 0 ? table.DefaultView.RowFilter : \"MessageID=\" + messageId;\n if ((messageId != 0) && (table.DefaultView.Count > 0))\n {\n // Find specific item from XML and set updated value\n table.DefaultView[0][\"MessageText\"] = updateMessageText;\n table.DefaultView.RowFilter = string.Empty;\n }\n else\n {\n table.Rows[e.RowIndex][\"MessageText\"] = updateMessageText;\n }\n\n grdMessage.EditIndex = -1;\n mdsRedirect.WriteXml(st);\n }\n\n getxml(); // read XML file and bind it\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-29T16:50:56.420",
"Id": "9917",
"Score": "0",
"body": "This is much better and thanks for reminding me about **Using**, but is there any way we can omit UpdateRowMessageText to be appear twice and make it still work?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-29T16:53:25.017",
"Id": "9918",
"Score": "0",
"body": "It possibly can with some convoluted looking `if` statements. Let me try that out and see what you think."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-29T17:04:47.100",
"Id": "9919",
"Score": "0",
"body": "See how that works for you."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-29T14:47:46.993",
"Id": "6382",
"ParentId": "6379",
"Score": "2"
}
},
{
"body": "<p>I'm not a C# guru, so just some general advice:</p>\n\n<p>This line is really-really long, hard to read and there are too many dots in it:</p>\n\n<pre><code>mdsRedirect.Tables[0].DefaultView[0][\"MessageText\"] = ((TextBox)(grdMessage.Rows[e.RowIndex].FindControl(\"txtupdMessage\"))).Text;\n</code></pre>\n\n<p>The code use <code>mdsRedirect.Tables[0]</code> a lot of times, create a local variable for that at the beginning of the method:</p>\n\n<pre><code>MyTable table = mdsRedirect.Tables[0];\n...\ntable.DefaultView[0][\"MessageText\"] = ((TextBox)(grdMessage.Rows[e.RowIndex].FindControl(\"txtupdMessage\"))).Text;\n</code></pre>\n\n<p>I would also extract the following method:</p>\n\n<pre><code>private String getTextFromRow(int rowIndex) {\n Row row = grdMessage.Rows[rowIndex];\n Control control = row.FindControl(\"txtupdMessage\");\n TextBox textBox = (TextBox) control;\n return textBox.Text;\n}\n</code></pre>\n\n<p>Then the code:</p>\n\n<pre><code>MyTable table = mdsRedirect.Tables[0];\n...\ntable.DefaultView[0][\"MessageText\"] = getTextFromRow(e.RowIndex);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-29T22:01:21.907",
"Id": "6393",
"ParentId": "6379",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "6382",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-29T13:04:43.017",
"Id": "6379",
"Score": "1",
"Tags": [
"c#"
],
"Title": "Updating messages from a list of messages"
}
|
6379
|
<p>I tried creating a quick tooltip plugin using the jquery and jquery ui position. Is the way I have used the enclosure are right and is the use of position right since in ff it seem to have some memory problem..it remembers the previous position when I refresh the page after the first time. below is the code </p>
<p>This need the latest jquery & jquery ui</p>
<pre><code> $.fn.tooltip = function(options) {
var defaults = {
my : "left center",
at : "right top",
collision : "none",
offset : "0 0"
}
var options = $.extend(defaults, options);
return this.each(function() {
var $this = $(this);
var tip = $("<span class='tooltip'>" + $this.attr('tooltip') + "</span>");
tip.css({
width : options.width
});
$this.after(tip);
tip.position({
my : options.my,
at : options.at,
of : $this,
collision : options.collision,
offset : options.offset
});
$this.add(tip).hover(function() {
var timeoutId = $this.data('timeoutId');
if(timeoutId) {
clearTimeout(timeoutId);
}
tip.fadeIn("slow");
}, function() {
var timeoutId = setTimeout(function() {
tip.fadeOut("slow");
}, 650);
$this.data('timeoutId', timeoutId);
});
});
};
$(function() {
$('#input1').tooltip();
$('#input2').tooltip();
});
</code></pre>
<p>css style</p>
<pre><code> .tooltip {
display: none;
position: absolute;
background-color: #ffaa5e;/* #F5F5B5; */
border: 1px solid #DECA7E;
color: #303030;
font-family: sans-serif;
font-size: 12px;
line-height: 18px;
padding: 10px 13px;
position: absolute;
text-align: center;
top: 0;
left: 0;
z-index: 3;
}
</code></pre>
<p>html code to test this</p>
<p><a href="http://jsfiddle.net/HE8QN/" rel="nofollow">http://jsfiddle.net/HE8QN/</a></p>
<p>thanks</p>
|
[] |
[
{
"body": "<p>Try this type of closure</p>\n\n<pre><code> $this.add(tip).hover(function() {\n return function() {\n var timeoutId = $this.data('timeoutId');\n if(timeoutId) {\n clearTimeout(timeoutId);\n }\n tip.fadeIn(\"slow\");\n };\n\n }(), function() {\n return function() {\n var timeoutId = setTimeout(function() {\n tip.fadeOut(\"slow\");\n }, 650);\n $this.data('timeoutId', timeoutId);\n };\n }());\n</code></pre>\n\n<p>Just dont forget to tell if it solves the problem. Good luck.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-30T11:04:37.550",
"Id": "6405",
"ParentId": "6383",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-29T15:05:12.370",
"Id": "6383",
"Score": "2",
"Tags": [
"javascript",
"jquery",
"jquery-ui"
],
"Title": "can we use of $this in closure for jquery plugin"
}
|
6383
|
<p>I am new to OOP and have written a products class. All is working fine but I am unsure which of the below version of a method within this class is best?</p>
<p>The first gets the variables from within the object and the second passes the variables into the class. Both work. I originally had it as the first version but things seems to be running slow and then changed it to the second.</p>
<pre><code>public function getProductURLstart(){
$select = "SELECT l.URL, p.id FROM logins AS l
INNER JOIN Pages AS p ON l.id = p.clientID
WHERE l.id = '$this->skID' AND p.productPage = 1";
$res = mssql_query($select);
$r = mssql_fetch_row($res);
$url = trim($r[0]);
$page_id = $r[1];
return $url .'/index.aspx?pageID='. $page_id . '&prodID=$this->prodID';
}
</code></pre>
<p>OR</p>
<pre><code>static function getProductURLstart($skID, $prodId){
$select = "SELECT l.URL, p.id FROM logins AS l
INNER JOIN Pages AS p ON l.id = p.clientID
WHERE l.id = '$skID' AND p.productPage = 1";
$res = mssql_query($select);
$r = mssql_fetch_row($res);
$url = trim($r[0]);
$page_id = $r[1];
return $url .'/index.aspx?pageID='. $page_id . '&prodID=$prodId';
}
</code></pre>
|
[] |
[
{
"body": "<p>Which is the better should not depend on <em>mainly</em> speed. I think you should post more code (at least the name of class and its responsibilities or the list of its functions).</p>\n\n<p>Some other notes:</p>\n\n<ol>\n<li><p>It's really hard to read code which contains one character long variable names:</p>\n\n<pre><code>$r = mssql_fetch_row($res);\n</code></pre>\n\n<p>You have to decode them. I'd rename it to <code>$row</code>. The same true for the SQL queries: <code>logins AS l</code>. I would let it be <code>logins</code>.</p></li>\n<li><p>In the second version there are three variable naming convention: <code>$skID</code>, <code>$prodId</code>, <code>$page_id</code>. Try to be consistent and use just one: they should be <code>$skId</code>, <code>$prodId</code>, <code>$pageId</code> or <code>$skID</code>, <code>$prodID</code>, <code>$pageID</code> or <code>$sk_id</code>, <code>$prod_id</code>, <code>$page_id</code>. (I think the first, the <code>camelCase</code> version is the most readable.)</p></li>\n<li><p>There is no error handling in the code. What happens when the query returns empty results?</p></li>\n<li><p>Probably the code is vulnerable to SQL injections: <a href=\"http://en.wikipedia.org/wiki/SQL_injection\" rel=\"nofollow\">http://en.wikipedia.org/wiki/SQL_injection</a></p></li>\n<li><p>Try accessing database attributes with keys not numeric indexes.</p>\n\n<pre><code>$url = trim($r[0]); \n$page_id = $r[1];\n</code></pre>\n\n<p>The following would be more readable:</p>\n\n<pre><code>$url = trim($r[\"url\"]); \n$page_id = $r[\"id\"];\n</code></pre></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-30T10:27:52.067",
"Id": "9937",
"Score": "0",
"body": "wow, thanks for you advice, however I was looking for help with OOP and Im still none the wiser..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-30T11:02:11.033",
"Id": "9939",
"Score": "0",
"body": "\"I think you should post more code (at least the name of class and its responsibilities or the list of its functions).\" :-)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-29T21:45:30.520",
"Id": "6392",
"ParentId": "6384",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-29T15:21:14.670",
"Id": "6384",
"Score": "3",
"Tags": [
"php",
"object-oriented"
],
"Title": "OOP php method - pass parameters in or get from inside object"
}
|
6384
|
<p>I made a small command line tool to help my Italian studies. Any thoughts on how it could be improved? I can't think of much but would like to be proved wrong.</p>
<pre><code>import random
class RegularVerb(object):
def __init__(self, name):
self._name = name
def name(self):
return self._name
def _make(self, verb_end):
return self.name()[:-3] + verb_end
def _build_condizionale_semplice(self, verb_forms, prefix):
def verb_base(prefix):
return (prefix + condizionale_semplice_base
for condizionale_semplice_base in
['rei', 'resti', 'rebbe', 'remmo', 'reste', 'rebbero']
)
return dict(zip(verb_forms, verb_base(prefix)))
class EreVerb(RegularVerb):
def __init__(self, name, verb_forms):
super(EreVerb, self).__init__(name)
self._condizionale_semplice = self._build_condizionale_semplice(verb_forms, 'e')
def condizionale_semplice(self, verb_form):
return self._make(self._condizionale_semplice[verb_form])
class IreVerb(RegularVerb):
def __init__(self, name, verb_forms):
super(IreVerb, self).__init__(name)
self._condizionale_semplice = self._build_condizionale_semplice(verb_forms, 'i')
def condizionale_semplice(self, verb_form):
return self._make(self._condizionale_semplice[verb_form])
class AreVerb(RegularVerb):
def __init__(self, name, verb_forms):
super(AreVerb, self).__init__(name)
self._condizionale_semplice = self._build_condizionale_semplice(verb_forms, 'e')
def condizionale_semplice(self, verb_form):
return self._make(self._condizionale_semplice[verb_form])
class Questioner():
def __init__(self, verb_forms, verbs):
self._verb_forms = verb_forms
self._verbs = verbs
def _handle_answer(self, user_answer, correct_answer):
if user_answer == correct_answer:
print "bravo!"
else:
print "no, correct form is:", correct_answer
def ask_random_condizionale_semplice(self):
def ask(verb_form, verb):
print "condizionale semplice for {0} in {1}?".format(verb.name(), verb_form),
self._handle_answer(raw_input(), verb.condizionale_semplice(verb_form))
ask(random.choice(self._verb_forms), random.choice(self._verbs))
def build_regular_verbs(verbs, verb_forms):
def make(verb):
if verb[-3:] == 'are':
return AreVerb(verb, verb_forms)
elif verb[-3:] == 'ire':
return IreVerb(verb, verb_forms)
elif verb[-3:] == 'ere':
return EreVerb(verb, verb_forms)
else:
raise Exception("not a regular verb")
return [make(v) for v in verbs]
def build_questioner(verb_forms, regular_verbs):
return Questioner(verb_forms,
build_regular_verbs(
regular_verbs,
verb_forms
)
)
if __name__ == "__main__":
questioner = build_questioner(
['I sg', 'II sg', 'III sg', 'I pl', 'II pl', 'III pl'],
['passare', 'mettere', 'sentire'],
)
while True:
questioner.ask_random_condizionale_semplice()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-29T16:04:28.020",
"Id": "9909",
"Score": "1",
"body": "hmm now after posting.. I see that the class RegularCondizionaleSemplice is actually useless and could easily be refactored into each type of verb."
}
] |
[
{
"body": "<p>Maybe this could provide of a more neat way of relating verbs with veb_forms:</p>\n\n<pre><code>verb_binder = dict(are=AreVerb, ire=IreVerb, ere=EreVerb)\n\ndef build_regular_verbs(verbs, verb_forms):\n def make(verb):\n try:\n return verb_binder[verb[-3:]](verb, verb_forms)\n except KeyError:\n raise Exception(\"not a regular verb\")\n\n return [make(v) for v in verbs]\n</code></pre>\n\n<p>not sure if verb_binder dictionary should be a module global or local to the function or maybe it should be located elsewhere, but this is the idea.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-29T20:21:36.783",
"Id": "6388",
"ParentId": "6385",
"Score": "3"
}
},
{
"body": "<p>You should be able to delete this method:</p>\n\n<pre><code>def condizionale_semplice(self, verb_form):\n return self._make(self._condizionale_semplice[verb_form])\n</code></pre>\n\n<p>from the <code>Ere</code>, <code>Are</code>, and <code>Ire</code> classes and add it to the <code>RegularVerb</code> class, since it is the same for all three. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-02T10:51:06.920",
"Id": "10057",
"Score": "0",
"body": "And what would you do with self._condizionale_semplice? (I am not too found of the idea having it used in the super class and let the basic class set it?)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-02T14:54:11.213",
"Id": "10067",
"Score": "0",
"body": "I don't have time to look too closely, but I would assume you could merge it together with `condizionale_semplice`. There's probably more that can be done here. If I get a chance, I'll edit my post with some more suggestions tonight."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-01T15:43:32.300",
"Id": "6451",
"ParentId": "6385",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "6388",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-29T15:59:44.127",
"Id": "6385",
"Score": "7",
"Tags": [
"python"
],
"Title": "Command line tool for Italian language studies"
}
|
6385
|
<p>I'm very new to python and scripting in general. I've come up with the following function to find the first and last IP when an IP range string is inputted. I want to only use base Python (and not download any libraries essentially).</p>
<p>Example:</p>
<pre><code>genRange("1.2.3.*"):
Start IP = 1.2.3.0
End IP = 1.2.3.255
genRange("1.*"):
Start IP = 1.0.0.0
End IP = 1.255.255.255
genRange("1.2.3.4"):
Start IP = 1.2.3.4
End IP =
NotRange
</code></pre>
<p>This seems very hardcoded to me, because it really is. Is there a a better way to do this that is obvious/jumps out at you?</p>
<p>I still need to handle invalid input.</p>
<pre><code>def genRange(ipRangeString):
startIP = ""
endIP = ""
if '.' in ipRangeString:
ipV = 4
if ':' in ipRangeString:
ipV= 6
if ipV == 4:
parts = ipRangeString.split(".")
i = 0
for item in parts:
if item != "*":
if 0 <= int(item) <= 255:
if (i<=3):
startIP = startIP + item + '.'
if (i==3): startIP = startIP[:-1]
i+= 1
else:
tempSIP = startIP
endIP = startIP
while (i<=3):
endIP = endIP + "255"
startIP = startIP + "0"
if (i<3):
endIP = endIP + '.'
startIP = startIP + '.'
i+= 1
print "Start IP = ", startIP
print " End IP = ", endIP
if not (endIP):
print "NotRange"
</code></pre>
|
[] |
[
{
"body": "<p>The first thing that jumps out at me is that this is a single function, with no classes and only one possible use. But without context, I couldn't comment on whether or not that's good. Since the snippet is so short and limited, your only motivation for changing it is that you might want to use it in a larger context. So I'm going to assume a larger context which may or may not apply.</p>\n\n<p>The second thing, then, is that there are no comments. I can look at this code, see the ipV is 4 or 6, see \"Start IP\" and \"End IP\", and figure out that this is computing an IP address range for IPv4. But the function name doesn't really tell me that. Just for maintainability sake, you might want to do something about that. </p>\n\n<p>The third thing that jumps out at me is that this function does nothing useful. It has two (conditionally 3) print statements as side effects, which means that you can't use these results. You might want to separate the computation of the range from the printing of the results. This is where I have to assume a larger context. If you just want to print those 2 or 3 lines, why bother modifying working code to begin with other than to maybe add some comments for the future. What if you want to accept ranges (10.0.1.5-50)? Heck, what if you want ranges with holes (10.0.5-10.2-100)?</p>\n\n<p>Fourth, your variable i is the index of item in the loop, which is used in a lot of logic in your function. See <a href=\"https://stackoverflow.com/questions/522563/accessing-the-index-in-python-for-loops\">https://stackoverflow.com/questions/522563/accessing-the-index-in-python-for-loops</a> for some discussion on that. Specifically, don't manage your own loop index variable. I see why you are doing so; to loop the necessary times between 1.* and 1.1.*. You can do this a few different ways. Statically, you need 4 parts to your IPv4 addresses. You could iterate over the range 4 and generate these 4 parts. You could iterate over your input parts and append the missing parts as needed once complete. I don't actually have a strong opinion of the right way, only that your way looks funny to me.</p>\n\n<p>Fifth, tempSIP. important? used?</p>\n\n<p>Punchline without assuming a larger context: Add a comment about usage. Add a comment about the program logic. Rename the function to have IP in the name. Delete tempSIP.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-30T14:39:15.650",
"Id": "9947",
"Score": "0",
"body": "Thank you very much for the input. You were correct in assuming thist is going to be used in much larger context. The print statements I have were just for debugging, I will be passing startIP, endIP, and the NotRange flag as well and using them elsewhere in code. Also completely forgot about the built in indexing of enumerate() and also forgot to remove tempSIP after a code change :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-30T14:42:31.743",
"Id": "9948",
"Score": "0",
"body": "Also, the second part of your fourth point was the reason I wanted input, because it seems funny to me as well. Sure it works, but it just doesn't look like the best code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-30T14:49:43.813",
"Id": "9949",
"Score": "0",
"body": "Well, then one more comment about this. Does your context require assignable addresses? Remember that `*.255` is multicast and won't be assigned to a machine. Of course, if you are assigning addresses (Hey, it's a use case; I wrote a network simulator for security research.), you should consider making an IPRange iterator. Computing the range returns an IPRange object with start, end, and the python iterator interface. Abstracting the iteration is doubly important if you do assignment in a range with holes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-30T16:30:06.543",
"Id": "9952",
"Score": "0",
"body": "`*.255` could be assignable and not a multicast address ofc, but there's no worries there. The big picture here is I'm simply prepping the input from human being the range to be a start/end IP address that plug into an SQL query to match startIP <= IP <= endIP. I am however getting closer to understanding how to think in python based on your replies, and I'll experiment with it. Thanks greatly ccoakley :)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-29T19:15:43.410",
"Id": "6387",
"ParentId": "6386",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "6387",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-29T18:02:09.077",
"Id": "6386",
"Score": "2",
"Tags": [
"python",
"strings"
],
"Title": "Finding the first and last IP in an IP range string"
}
|
6386
|
<p>I am refactoring code which contains many lines of <code>NSString* image = [@"ipad_" stringByAppendingString:imageOrigName];</code> and wondered which is more optimized:</p>
<pre><code>stringByAppendingString:
</code></pre>
<p>or</p>
<pre><code>stringWithFormat:
</code></pre>
<p>In the first, you take one <code>NSString</code> object and concatenate another onto its tail. In the second, you can use a formatter:</p>
<pre><code>NSString* image = [NSString stringWithFormat:@"ipad_%@", imageOrigName];
</code></pre>
<p>The result is the same, but for optimization purposes, which is better?</p>
<p>For the above example, I would expect that a simple concatenation would be faster than having it parse the string for '%' symbols, find a matching type (<code>NSString</code> for the <code>%@</code>), and do all its background voodoo.</p>
<p>However, what happens when we have (sloppily written?) code which contains multiple <code>stringByAppendingString</code>s?</p>
<pre><code>NSString* remainingStr = [NSString stringWithFormat:@"%d", remaining];
NSString* msg = "You have ";
msg = [msg stringByAppendingString:remainingStr];
msg = [msg stringByAppendingString:@" left to go!"];
if (remaining == 0)
msg = [msg stringByAppendingString:@"Excellent Job!"];
else
msg = [msg stringByAppendingString:@"Keep going!"];
</code></pre>
<p>Here, a single <code>stringWithFormat</code> (or <code>initWithFormat</code> if we use <code>[NSString alloc]</code>) would seem to be the smarter path:</p>
<pre><code>NSString* encouragementStr = (remaining == 0 ? @"Excellent Job!" : @"Keep going!");
NSString* msg = [NSString stringWithFormat:@"You have %d left to go! %@", remaining, encouragementStr];
</code></pre>
<p>Thoughts? Sites/blogs that you've found that helps answer this?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-29T20:43:13.717",
"Id": "9924",
"Score": "2",
"body": "Have you tried profiling them? Chances are the difference isn't enough to notice. That said, this seems to be about improving working code, so it'd be better on codereview.SE."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-29T20:44:22.647",
"Id": "9925",
"Score": "1",
"body": "It would be easy to test this yourself with a couple of loops and some logging statements."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-29T21:07:18.743",
"Id": "9926",
"Score": "0",
"body": "Related: http://stackoverflow.com/questions/8275131/pros-and-cons-of-using-nsstring-stringwithstringsome-string-versus-some/8275225"
}
] |
[
{
"body": "<p>The only way to know is to measure it.</p>\n\n<p>And, of course, the only reason to measure it is if it actually matters; if you have a real world performance issue that can be tracked to this code.</p>\n\n<p>If not, don't worry about it.</p>\n\n<p>However, there are a few issues to consider:</p>\n\n<ul>\n<li>every <code>append*</code> is going to cause an allocation and memory copying, those are expensive</li>\n<li>every <code>*WithFormat:</code> is going to cause a string to be parsed (and there will be allocations/copying)</li>\n<li>all of this is likely entirely moot unless you are doing this 10s of thousands of times often. If you are, it begs the question as to why?</li>\n</ul>\n\n<p>And, finally, note that this kind of string manipulation is going to make localization more difficult.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T15:49:49.150",
"Id": "76045",
"Score": "0",
"body": "Is every call to append* really going to cause an allocation? http://stackoverflow.com/a/3730437/37020"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-29T20:44:13.440",
"Id": "6390",
"ParentId": "6389",
"Score": "4"
}
},
{
"body": "<p>You should benchmark the two methods to see which is faster. Example:</p>\n\n<pre><code>double startTime1 = CACurrentMediaTime() / CLOCKS_PER_SEC;\n\nNSString* testString1 = [@\"fragmentOne\" stringByAppendingString: @\"fragmentTwo\"];\n\ndouble endTime1 = CACurrentMediaTime() / CLOCKS_PER_SEC;\n\n\ndouble startTime2 = CACurrentMediaTime() / CLOCKS_PER_SEC;\n\nNSString* testString2 = [NSString stringWithFormat: @\"fragmentOne%@\", @\"fragmentTwo\"];\n\ndouble endTime2 = CACurrentMediaTime() / CLOCKS_PER_SEC;\n\n\ndouble diff1 = (endTime1 - startTime1) * 1000000000000000;\ndouble diff2 = (endTime2 - startTime2) * 1000000000000000;\n\nNSLog(@\"stringByAppendingString time: %f\", diff1);\nNSLog(@\"stringWithFormat time: %f\", diff2);\n</code></pre>\n\n<p>I probably could have just run the test myself in the time it took to write this, but whatever, now you know how to benchmark methods :) If it were me, I'd use <code>stringWithFormat</code> because it tends to make for more human-readable code.</p>\n\n<p>Hope this helps!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-12-28T11:06:07.857",
"Id": "213951",
"Score": "0",
"body": "what is the unit of `diff1` ? microseconds?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-29T20:47:48.177",
"Id": "6391",
"ParentId": "6389",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "6390",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-29T20:35:57.567",
"Id": "6389",
"Score": "4",
"Tags": [
"objective-c"
],
"Title": "stringByAppendingString: vs. stringWithFormat:"
}
|
6389
|
<p>The basic idea is to replace all special expressions, e.g., <code>[%InvoiceNo%]</code>, <code>[%DueDate%]</code>, in a string with the properties of an object, <code>Invoice invoice</code>.</p>
<pre><code>string str = "Your invoice [%InvoiceNo%] will be due on [%DueDate%]";
Invoice invoice = new Invoice { InvoiceNo = "123456", DueDate = DateTime.Parse("2011.12.29") };
string result = GetNewValue(str, invoice);
//The expected result is: Your invoice 123456 will be due on 11/29/2011
</code></pre>
<p>I think the simplest way to implement <code>GetNewValue()</code> could be</p>
<pre><code>private string GetNewValue(string str, Invoice invoice)
{
str = str.Replace("[%InvoiceNo%]", invoice.InvoiceNo);
str = str.Replace("[%DueDate%]", invoice.DueDate.ToString());
return str;
}
</code></pre>
<p>However, in my case, <code>Invoice</code> has a hundred properties and the target string only contains one or two properties. I rewrite <code>GetNewValue()</code> in the way I think it should work more efficiently. Here is my code</p>
<pre><code>private string GetNewValue(string str, Invoice invoice)
{
List<string> expressions = new List<string>();
List<string> fields = new List<string>();
var startIndices = str.IndicesOf("[%");
var endIndices = str.IndicesOf("%]");
int startLen = "[%".Length;
int endLen = "%]".Length;
for (int i = 0; i < startIndices.Count; i++)
{
expressions.Add(str.Substring(startIndices[i],
endIndices[i] - startIndices[i] + endLen));
fields.Add(str.Substring(startIndices[i] + startLen,
endIndices[i] - startIndices[i] - startLen));
}
for (int i = 0; i < expressions.Count; i++)
str = str.Replace(expressions[i], invoice.GetValueByName(fields[i]).ToString());
return str;
}
</code></pre>
<p>StringExtender <code>IndicesOf()</code></p>
<pre><code>public static List<int> IndicesOf(this string target, string search)
{
List<int> indices = new List<int>();
int startIndex = 0;
int index;
while ((index = target.IndexOf(search, startIndex)) > -1)
{
indices.Add(index);
startIndex = index + 1;
}
return indices;
}
</code></pre>
<p><code>GetValueByName()</code> using Reflection</p>
<pre><code>public class Invoice
{
// Properties
......
public object GetValueByName(string name)
{
PropertyInfo myProperty = typeof(Invoice).GetProperty(name);
return myProperty.GetValue(this, null);
}
}
</code></pre>
<p>How can I improve this code? Fast, less memory usage, or one-liner<br>
Don't tell me the first approach is better. Orz<br>
Thanks :)</p>
|
[] |
[
{
"body": "<p>You can do it in one loop instead of getting all the indexes separately. Just off the top of my head:</p>\n\n<pre><code> string str = \"Your invoice [%InvoiceNo%] will be due on [%DueDate%]\";\n\n int startIndex = 0;\n\n while ((startIndex = str.IndexOf(\"[%\", startIndex)) > -1)\n {\n int endIndex = str.IndexOf(\"%]\", startIndex);\n string exp = str.Substring(startIndex, endIndex - startIndex + 2);\n string field = str.Substring(startIndex + 2, endIndex - startIndex - 2);\n str = str.Replace(exp, invoice.GetValueByName(field).ToString());\n startIndex = 0;\n }\n</code></pre>\n\n<p>Some points to note here:</p>\n\n<ol>\n<li>I assume you are guaranteed to see the %] if you find the [%</li>\n<li>I didn't test for edge cases like what if <code>str = \"[%invoice%]\"</code></li>\n</ol>\n\n<p>This is a neat solution but the more I think about your problem the more I wonder if you can engineer it so you pass what fields you want to your invoice object and it just returns you the correct string so you don't need to mess around with placeholders... food for thought :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-30T07:01:45.097",
"Id": "9934",
"Score": "0",
"body": "This solution is brilliant!! I like it :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T02:57:43.953",
"Id": "502053",
"Score": "0",
"body": "I ran into this thread while looking for a library to do something similar. Our requirements looked to be a little different but very similar in concept. I've created a small [library](https://github.com/dgwaldo/ObjectTextTokens) that allows you template @obj.prop@ placeholders into strings and replace them with other things in a property."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-30T05:30:21.407",
"Id": "6398",
"ParentId": "6397",
"Score": "2"
}
},
{
"body": "<p><code>str.Replace</code> does a lot of copying behind the scenes. Especially if you have a complex string, you'd be better off with a <code>StringBuilder</code> in a loop. Something like (untested code):</p>\n\n<pre><code>StringBuilder sb = new StringBuilder();\nint idx = 0;\nwhile (true) {\n int nextIdx = str.IndexOf(\"[%\", idx);\n if (nextIdx < 0) break;\n // Copy unexpanded text\n sb.Append(str, idx, nextIdx - idx);\n // Find end\n int endIdx = str.IndexOf(\"%]\", nextIdx);\n if (endIdx < 0) throw new Exception(\"Unmatched [%\");\n // Copy the substitution and then skip past it\n string field = str.Substring(nextIdx + 2, endIdx - nextIdx + 2);\n sb.Append(GetValueByName(invoice, field));\n idx = nextIdx + 2;\n}\n// Copy the tail.\nsb.Append(str, idx, str.Length - idx);\nreturn sb.ToString();\n</code></pre>\n\n<p>NB I've assumed that GetValueByName is now a static field - it makes no sense to me for it to be a method of Invoice, as that both pushes functionality into Invoice which is nothing to do with invoicing, and limits its applicability. I would be tempted to make it an extension method of object.</p>\n\n<p>Also, I've used your <code>[%</code> for consistency, but when I do things like this I prefer to use <code>{</code> and reuse <code>string.Format</code>'s syntax. I also handle <code>:formattingString</code> and take an IFormatProvider as an argument.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-02T03:08:01.413",
"Id": "10050",
"Score": "0",
"body": "what if the old value is: A{2,2}. I will replace it by accident :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-02T07:32:32.433",
"Id": "10055",
"Score": "0",
"body": "@WalterHuang, what do you mean by \"the old value\"? The format string? I could turn that around and ask what if it was `[%2,2%]`? You have to consider whether your use cases are going to require an escaping mechanism."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-02T12:36:13.773",
"Id": "10059",
"Score": "0",
"body": "hmm ... OK, you are right :)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-30T11:14:16.533",
"Id": "6406",
"ParentId": "6397",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "6398",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-30T03:42:22.040",
"Id": "6397",
"Score": "1",
"Tags": [
"c#",
".net",
"reflection"
],
"Title": "Replace all occurrences with the properties of an object"
}
|
6397
|
<p>I recently started learning binary tree. Following is the code for a typical node for a tree (no code review required for that):</p>
<pre><code>typedef unsigned int uint;
template<typename T>
class BinaryNode
{
T t_Data;
BinaryNode *pt_Left, *pt_Right;
public:
BinaryNode (const T &data) : t_Data(data), pt_Left(0), pt_Right(0) {}
void Insert (const T &data)
{
if(this->t_Data == data)
return;
BinaryNode<T> *&pNode = (data < this->t_Data)? this->pt_Left : this->pt_Right;
if(pNode == 0) pNode = new BinaryNode<T>(data);
else pNode->Insert(data);
}
template<uint SIZE>
static
BinaryNode<T>* GenerateTree (const T (&arr)[SIZE])
{
return GenerateTree(arr, SIZE);
}
static
BinaryNode<T>* GenerateTree (const T *arr, const uint SIZE)
{
BinaryNode<T> *pHead = new BinaryNode<T>(arr[0]);
for(uint i = 0; i < SIZE; i++)
pHead->Insert(arr[i]);
return pHead;
}
operator const T& () const { return t_Data; }
BinaryNode* const getLeft () const { return pt_Left; }
BinaryNode* const getRight () const { return pt_Right; }
};
</code></pre>
<p>For example to populate this tree with <code>char</code> nodes, one need to call the <code>Generate</code> function as,</p>
<pre><code>const char letters[] = {'F', 'B', 'G', 'A', 'D', 'I', 'C', 'E', 'I', 'H'};
BinaryNode<char> *pHead = BinaryNode<char>::GenerateTree(letters);
</code></pre>
<p><strong>Question</strong>:
I wanted to implement, its <strong>pre-order, in-order, post-order</strong> traversals in <strong>recursive as iterative</strong> manner. We pass a traversing <code>vector<> vTraversal</code> to all functions to populate the traversal results.</p>
<p>Recursive is very simple:</p>
<pre><code>template<typename T>
void PreOrderRecursive (const BinaryNode<T>* const pNode, vector<T> &vTraverse)
{
if(pNode == 0)
return;
vTraverse.push_back(*pNode);
PreOrderRecursive(pNode->getLeft(), vTraverse);
PreOrderRecursive(pNode->getRight(), vTraverse);
}
template<typename T>
void InOrderRecursive (const BinaryNode<T>* const pNode, vector<T> &vTraverse)
{
if(pNode == 0)
return;
InOrderRecursive(pNode->getLeft(), vTraverse);
vTraverse.push_back(*pNode);
InOrderRecursive(pNode->getRight(), vTraverse);
}
template<typename T>
void PostOrderRecursive (const BinaryNode<T>* const pNode, vector<T> &vTraverse)
{
if(pNode == 0)
return;
PostOrderRecursive(pNode->getLeft(), vTraverse);
PostOrderRecursive(pNode->getRight(), vTraverse);
vTraverse.push_back(*pNode);
}
</code></pre>
<p>You can see the recursive functions are easily understandable and can relate to each other.</p>
<p>However, in iterative functions, I have a <strong><em>problem</em></strong>. I am able to find a good solution for pre-order traversal, a little complex solution for in-order traversal and <strong>no elegant solution</strong> for post-order traversal:</p>
<pre><code>template<typename T>
void PreOrderIterative (const BinaryNode<T>* const pNode, vector<T> &vTraversal)
{
vector<const BinaryNode<T>*> record;
record.push_back(pNode);
while(record.size() != 0)
{
const BinaryNode<T> *pN = record.back();
record.pop_back();
if(pN == 0)
continue;
record.push_back(pN->getRight());
record.push_back(pN->getLeft());
vTraversal.push_back(*pN);
}
}
template<typename T>
void InOrderIterative (const BinaryNode<T>* const pNode, vector<T> &vTraversal)
{
vector<const BinaryNode<T>*> record;
record.push_back(pNode);
while(true)
{
const BinaryNode<T> *pN = record.back();
record.pop_back();
if(pN == 0)
{
if(record.size() == 0)
break;
vTraversal.push_back(*record.back());
record.pop_back();
continue;
}
record.push_back(pN->getRight());
record.push_back(pN);
record.push_back(pN->getLeft());
}
}
template<typename T>
void PostOrderIterative (const BinaryNode<T>* const pNode, vector<T> &vTraversal)
{
// :(
}
</code></pre>
<p>Is there a way by which I can make all 3 iterative solution relating to each other in the same way as recursive traversal ?</p>
|
[] |
[
{
"body": "<p>Did you mean to make this private?</p>\n\n<pre><code>class BinaryNode\n{\npublic:\n T t_Data;\n BinaryNode *pt_Left, *pt_Right;\n</code></pre>\n\n<p>I'm not sure I agree with the interface design presented for this data structure. If you're doing this as just a practice exercise I suppose it's probably okay. However, if you're planning to reuse this in production code or real-world projects it's a good idea to follow the same interface design as the stl for consistency. In particular, you don't want client code to be able to manipulate those binary nodes since those are just implementation details.</p>\n\n<p>To better separate the concerns, one idea you can try is to define an outer structure that contains a <code>BinaryNode</code>. Something along the lines of this:</p>\n\n<pre><code>template <typename T>\nclass BinaryTree\n{\npublic:\n BinaryTree() : root(0) {}\n // rest of your interface methods here\n // Insert, GenerateTree etc.\n // ...\n\nprivate:\n struct BinaryNode\n {\n T data;\n BinaryNode *left, *right;\n void Insert(const T &data_);\n }; \n BinaryNode *root;\n};\n</code></pre>\n\n<hr>\n\n<p>For your <code>GenerateTree</code> method, it's better if you have it take iterators instead so it works with other containers besides raw arrays. It only requires a minor change to <code>GenerateTree</code>:</p>\n\n<pre><code>template <typename FORWARD>\nstatic BinaryNode<T>* GenerateTree (FORWARD begin, const FORWARD &end)\n{\n if(begin == end) return;\n\n BinaryNode<T> *pHead = new BinaryNode<T>(*begin);\n while(++begin != end)\n {\n pHead->Insert(*begin);\n }\n return pHead;\n}\n</code></pre>\n\n<p>You can even take this a step further by providing a constructor that directly accepts iterators. Then your example usage would look like:</p>\n\n<pre><code>const char letters[] = {'F', 'B', 'G', 'A', 'D', 'I', 'C', 'E', 'I', 'H'};\nsize_t size = sizeof(letters);\nBinaryTree<char> letter_tree(letters, letters + size);\n</code></pre>\n\n<hr>\n\n<p>Your <code>PreOrderIterative</code> function uses <code>std::vector</code> as a stack. Why not refactor it to use <code>std::stack</code> directly and improve readability?</p>\n\n<pre><code>void PreOrderIterative (const BinaryNode<T>* const pNode, vector<T> &vTraversal)\n{\n stack<const BinaryNode<T>*> record;\n record.push(pNode);\n while( !record.empty() )\n {\n const BinaryNode<T> *pN = record.top();\n record.pop();\n\n if(pN->getRight()) record.push(pN->getRight());\n if(pN->getLeft()) record.push(pN->getLeft());\n vTraversal.push_back(*pN);\n }\n}\n</code></pre>\n\n<p>I haven't looked at <code>InOrderIterative</code> in too much detail but I'd imagine a similar refactor can be applied to it as well. I'll leave it as an exercise for you.</p>\n\n<p>For <code>PostOrderRecursive</code>, it looks like you want to visit the nodes in this order:</p>\n\n<pre><code> 7\n / \\\n 3 6\n / \\ / \\\n1 2 4 5\n</code></pre>\n\n<p>One way to do this iteratively is to start at the root and as you 'walk' the tree expand its right node first then expand the left node afterwards. You can keep track of which nodes to visit with a stack similar to <code>PreOrderIterative</code>. As you visit each node you'll add it to <code>vTraversal</code>. Once done <code>vTraversal</code> will contain the correct order except in reverse. Apply <code>std::reverse</code> to get the final result:</p>\n\n<pre><code>template<typename T>\nvoid PostOrderIterative (const BinaryNode<T>* const root, vector<T> &vTraversal)\n{\n if(!root) return;\n\n //start with the root\n stack<const BinaryNode<T>*> visit_nodes;\n visit_nodes.push(root);\n while( !visit_nodes.empty() )\n {\n // visting the node on top of stack\n const BinaryNode<T> *curr_node = visit_nodes.top();\n vTraversal.push_back(*curr_node);\n visit_nodes.pop();\n\n // add nodes that still need to be visited and expand.\n // right needs to be handled before left so push in reverse order.\n if( curr_node->getLeft() ) visit_nodes.push(curr_node->getLeft());\n if( curr_node->getRight() ) visit_nodes.push(curr_node->getRight());\n }\n\n // vTraveral contains the desired order but in reverse.\n std::reverse(vTraversal.begin(), vTraversal.end());\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-01T01:03:45.793",
"Id": "6434",
"ParentId": "6399",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "6434",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-30T06:44:49.640",
"Id": "6399",
"Score": "4",
"Tags": [
"c++",
"algorithm",
"binary-search"
],
"Title": "Binary tree traversal algorithms"
}
|
6399
|
<p>Here's my attempt to replace first occurrence of <code>pattern</code> in file with spaces. Effectively deleting it, and hopefully will allow me to "delete" it in a large file, without rewriting it.</p>
<pre><code>#define MAX_LINE_LENGTH
int removeFirstOccurenceInFile(const char* fileName, const char* pattern) {
FILE* f = fopen(fileName,"r+");
if (f == NULL) {
perror("Can't open input file");
return 0;
}
char buf[MAX_LINE_LENGTH] = {'\0'};
char spaces[MAX_LINE_LENGTH];
int unreadBytes = 0;
char* patInBuf = NULL;
while (1) {
if (patInBuf != NULL) break;
unreadBytes += strlen(buf);
if (fgets(buf,sizeof(buf),f) == NULL) break;
patInBuf = strstr(buf,pattern);
}
if (patInBuf == NULL) {
fprintf(stderr,"No '%s' found in '%s'\n",pattern,fileName);
fclose(f);
return 0;
}
int delFrom = patInBuf-buf;
memset(spaces,' ',delFrom);
fseek(f,unreadBytes+delFrom, SEEK_SET);
fwrite(spaces,1,strlen(pattern),f);
fclose(f);
return 1;
}
</code></pre>
<p>I'm not sure about the error handling. I considered using <code>goto</code> instead of the usual error handling:</p>
<pre><code> if (patInBuf == NULL) {
fprintf(stderr,"No '%s' found in '%s'\n",pattern,fileName);
retval = -1;
goto cleanup;
}
...
cleanup:
fclose(f);
return retval;
</code></pre>
<p>Are there other problems? Will that indeed be efficient?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-30T18:44:30.067",
"Id": "9954",
"Score": "0",
"body": "Did you test this code before posting it here?\nDid you test it with an input file consisting of multiple lines with the sought-for string somewhere in the middle?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-30T18:53:38.757",
"Id": "9955",
"Score": "0",
"body": "@MikeNakis, yes I did. Not too extensively, but it worked. Didn't it work for you?"
}
] |
[
{
"body": "<p>My advice would be to abandon the idea of treating the file as a text file in order to search through it, but then as a binary file in order to write into it. Your calculation of the offset to seek to is flimsy, and guaranteed not to work if the file has non-single-character end-of-line markers, (LF in Unix, but CR+LF in Windows,) if it starts with a unicode BOM, or if it contains any UTF8-encoded characters.</p>\n\n<p>You need to either treat the file as a binary file all the way, in which case you will have to write your own code to read chunks and search through them, or to treat it as a text file all the way, meaning that every time you will be creating a new file and then swapping it with the original.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-30T19:05:19.017",
"Id": "9957",
"Score": "0",
"body": "Are you sure that plain old C knows about the BOM, or UTF-8? I'm pretty sure many of those things were invented long after C. I'm not sure that it doesn't tuck the whole EOL, whatever it is, to the buffer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-30T19:13:40.143",
"Id": "9958",
"Score": "0",
"body": "No, I am not sure, but I do not think that there are any guarantees about these matters, so it is probably not wise to be sure about the opposite, either. And when in doubt, it is a good idea to play it safe."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-30T19:15:46.910",
"Id": "9960",
"Score": "0",
"body": "If you do not want to play it safe, then I guess that yours seems to be the most efficient way to achieve this bizarre thing that you are trying to achieve. (Writing your own code to read the file as binary has the potential of performing just as well, but it would be quite complicated.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-30T19:25:50.747",
"Id": "9962",
"Score": "0",
"body": "I'm actually pretty sure the standard dictate that fgets will read and store the exact number of bytes it read. Your approach is much less efficient, so I guess it worth *checking* the standard instead of fearing it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-30T19:40:29.147",
"Id": "9963",
"Score": "0",
"body": "I do not have \"the definitive specification of the standard C library\" handy; I just looked at a couple of reference places and they were not specific at all about the question of exactly how many bytes will be read and stored by fgets. Anyway, I do not want to argue about it: I am not suggesting that I have a strong case here, if even I have a case at all."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-30T19:01:09.977",
"Id": "6420",
"ParentId": "6400",
"Score": "1"
}
},
{
"body": "<p>I think you have the error codes the other way around. It's more common to return 0 on success and 1 (or any non-zero number) on failure, especially for debugging. If you actually need to deviate from this, then comments could help with specification.</p>\n\n<p>As for the <code>goto</code>, it is good to avoid using it whenever possible. Based on that little snippet, it looks like you could've used a function instead, at least if other this were needed in other places.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-11-25T05:21:40.277",
"Id": "70774",
"ParentId": "6400",
"Score": "2"
}
},
{
"body": "<p>As @Mike Nakis began with suggesting treating the file as text all the way, OP's code has undefined behavior UB in using <code>fseek()</code></p>\n\n<pre><code>int fseek(FILE *stream, long int offset, int whence);\n</code></pre>\n\n<blockquote>\n <p>For a text stream, either <code>offset</code> shall be zero, or <code>offset</code> shall be a value returned by\n an earlier successful call to the <code>ftell</code> function on a stream associated with the same file\n and <code>whence</code> shall be <code>SEEK_SET</code>. C11dr §7.21.9.2 4</p>\n</blockquote>\n\n<p>This mean performing an <code>ftell()</code> before each <code>fgets()</code> and using that position for <code>fseek()</code> when a pattern is found. And let's use a <code>do while()</code></p>\n\n<pre><code> long position;\n do {\n // if (patInBuf != NULL) break;\n // unreadBytes += strlen(buf);\n position = ftell(f);\n if (position == -1L) break;\n if (fgets(buf,sizeof(buf),f) == NULL) break;\n patInBuf = strstr(buf,pattern);\n } while (patInBuf != NULL);\n ...\n // replace pattern with spaces\n\n // print _whole buffer\n if (fseek(f,position, SEEK_SET)) Handle_Failure();\n fputs(buf, f);\n</code></pre>\n\n<p>Other mundane things:</p>\n\n<ol>\n<li><p><code>#define MAX_LINE_LENGTH</code> certainly needs a number like <code>#define MAX_LINE_LENGTH 1000</code> </p></li>\n<li><p>Nice use of <code>const</code> in <code>removeFirstOccurenceInFile(const char* fileName, const char* pattern)</code></p></li>\n<li><p>Use of <code>goto</code> in error handle is a reasonable exception to the never use <code>goto</code>. Useful when multiple error points. In the end, rather have code do complete error checking with <code>goto</code> than elegant without error checking and without <code>goto</code>.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-30T01:03:47.057",
"Id": "75197",
"ParentId": "6400",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-30T09:51:22.077",
"Id": "6400",
"Score": "2",
"Tags": [
"c",
"file",
"error-handling",
"file-structure"
],
"Title": "Replace first occurrence of pattern in file"
}
|
6400
|
<p>I would like tips on my CODE, map structure (How I should seperate the code, more files, etc). What I can do about the func.php file as a file with just a bunch of functions, doesn't seem to be the best approach for it.
And generally just a code review how I can improve on it.</p>
<p>createaccount.php</p>
<pre><code><?php
require_once 'init.php';
if (isset($_POST['submit'])) {
if (isset($_SESSION['token']) && $_POST['token'] == $_SESSION['token']) {
$errors = array();
if (!empty($_POST['username'])) {
if (strlen($_POST['username']) < 3 || strlen($_POST['username']) > 20) {
$errors[] = 'The username must be between 3 and 20 characters long';
}
if (!preg_match("/^[_a-zA-Z0-9]+$/", $_POST['username'])) {
$errors[] = 'The username must contain only letters and numbers and _';
}
$STH = $DBH->prepare("SELECT username FROM users WHERE username = ?");
$STH->execute(array($_POST['username']));
if ($STH->rowCount() > 0) {
$errors[] = 'The username is already taken';
}
} else {
$errors[] = 'The username field is required';
}
if (!empty($_POST['password'])) {
if (strlen($_POST['password']) < 4) {
$errors[] = 'The password must be at least 4 characters long';
}
if ($_POST['password'] != $_POST['passconf']) {
$errors[] = 'The passwords must match';
}
} else {
$errors[] = 'The password field is required';
}
if (!empty($_POST['email'])) {
if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$errors[] = 'Must be a valid email adress';
} else {
$STH = $DBH->prepare("SELECT email FROM users WHERE email = ?");
$STH->execute(array($_POST['email']));
if ($STH->rowCount() > 0) {
$errors[] = 'The email adress is already taken';
}
}
} else {
$errors[] = 'The email adress is required';
}
$resp = recaptcha_check_answer (PRIVATE_KEY,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
if (!$resp->is_valid) {
$errors[] = 'The reCAPTCHA wasn\'t entered correctly. Go back and try it again.';
}
if (empty($errors)) {
$salt = salt();
$password = sha1(sha1($_POST['password'] . $salt));
$activation_key = md5($_POST['username'] . $_POST['email']);
$STH = $DBH->prepare("INSERT INTO users (username, password, salt, email, activation_key, created) VALUES(:username, :password, :salt, :email, :activation_key, :created)");
$STH->bindParam(':username', $_POST['username']);
$STH->bindParam(':password', $password);
$STH->bindParam(':salt', $salt);
$STH->bindParam(':email', $_POST['email']);
$STH->bindParam(':activation_key', $activation_key);
$STH->bindParam(':created', time());
$STH->execute();
if ($DBH->lastInsertId()) {
header("Location: activate.php");
exit;
} else {
// Log
}
}
}
}
$token = md5(uniqid(rand(), true));
$_SESSION['token'] = $token;
?>
<!DOCTYPE html>
<html>
<head>
<title>Heroes of Legacy - Create Account</title>
</head>
<body>
<?php
if (isset($errors)) {
foreach ($errors as $error) {
echo $error . "<br />\n";
}
}
?>
<form method="post" action="createaccount.php">
<input type="hidden" name="token" value="<?php echo $token; ?>" />
Username <input type="text" name="username" value="" />
Password <input type="password" name="password" value="" />
Confirm Password <input type="password" name="passconf" value="" />
Email Adress <input type="email" name="email" value="" />
<?php echo recaptcha_get_html(PUBLIC_KEY); ?>
<input type="submit" name="submit" value="Create Account" />
</form>
</body>
</html>
</code></pre>
<p>init.php</p>
<pre><code><?php
session_start();
require_once 'config.php';
require_once 'func.php';
try {
$DBH = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
}
catch(PDOException $e) {
echo $e->getMessage();
}
function salt() {
mt_srand(microtime(true)*100000 + memory_get_usage(true));
return md5(uniqid(mt_rand(), true));
}
require_once 'lib/recaptchalib.php';
define('PUBLIC_KEY', '');
define('PRIVATE_KEY', '');
</code></pre>
<p>config.php</p>
<pre><code><?php
$hostname = 'localhost';
$username = 'root';
$password = '';
$dbname = 'hol';
</code></pre>
<p>login.php</p>
<pre><code><?php
require_once 'init.php';
if (logged_in()) {
header("Location: index.php");
exit;
}
if (isset($_POST['submit'])) {
if (isset($_SESSION['token']) && $_POST['token'] == $_SESSION['token']) {
$errors = array();
if (!empty($_POST['username']) && !empty($_POST['password'])) {
$STH = $DBH->prepare("SELECT id, salt, password, banned FROM users WHERE username = ?");
$STH->execute(array($_POST['username']));
if ($STH->rowCount() > 0) {
$user = $STH->fetch();
$passconf = sha1(sha1($_POST['password'] . $user['salt']));
if ($passconf != $user['password']) {
$errors[] = 'The password you entered is incorrect';
unset($user);
} else {
session_regenerate_id();
$_SESSION['userid'] = $user['id'];
$_SESSION['hash'] = sha1($_SESSION['userid'] . $_SERVER['HTTP_USER_AGENT']);
unset($user);
header("Location: index.php");
exit;
}
} else {
$errors[] = 'The username is incorrect';
}
} else {
$errors[] = 'You must enter a username and password!';
}
}
}
$token = md5(uniqid(rand(), true));
$_SESSION['token'] = $token;
?>
<!DOCTYPE html>
<html>
<head>
<title>Heroes of Legacy - Log in</title>
</head>
<body>
<?php
if (isset($errors)) {
foreach ($errors as $error) {
echo $error . "<br />\n";
}
}
?>
<form method="post" action="login.php">
<input type="hidden" name="token" value="<?php echo $token; ?>" />
Username <input type="text" name="username" value="" />
Password <input type="password" name="password" value="" />
<input type="submit" name="submit" value="Log in" />
</form>
</body>
</html>
</code></pre>
<p>func.php</p>
<pre><code><?php
function logged_in() {
if (isset($_SESSION['userid'])
&& isset($_SESSION['hash'])) {
$session_check = sha1($_SESSION['userid'] . $_SERVER['HTTP_USER_AGENT']);
if ($_SESSION['hash'] == $session_check)
return true;
}
return false;
}
function logout() {
session_unset();
session_destroy();
header("Location: index.php");
exit;
}
</code></pre>
<p>That's about it.</p>
<p>-- UPDATE:</p>
<pre><code><?php
//Temporary solution
$request = trim(strtolower($_REQUEST['username']));
usleep(150000);
//Let's say this is data grabbed from a database...
$users = array('asdf', 'Peter', 'Peter2', 'George');
$valid = 'true';
foreach($users as $user) {
if( strtolower($user) == $request )
$valid = 'false';
}
echo $valid;
?>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-30T10:54:56.233",
"Id": "9938",
"Score": "0",
"body": "Too much code without context. Tell us what you're trying to do..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-30T11:02:28.403",
"Id": "9940",
"Score": "0",
"body": "It's an simple authentication system... Read my context in the top, and ull see what im looking for, cheers"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-30T11:09:13.763",
"Id": "9941",
"Score": "0",
"body": "Well not what I meant, I can see it's a simple authentication system and I can read what you're looking for. I meant context for your code, some of the stuff you're doing are extremely weird, and their purpose may be outside the code you've provided. Does it work, have you actually tested it? - and more specifically can a user login with her password, after login out? It doesn't seem so..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-30T11:14:46.963",
"Id": "9942",
"Score": "0",
"body": "The code is working? What is weird? Yes, the user can login .. when the user logged out?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-30T11:33:48.760",
"Id": "9943",
"Score": "0",
"body": "Sorry I didn't get that you are using individual salts at first. That's weird, highly unconventional and potentially dangerous, see my answer."
}
] |
[
{
"body": "<p>There seems to be a fair amount of paranoia in your code: </p>\n\n<pre><code>function salt() {\n mt_srand(microtime(true)*100000 + memory_get_usage(true));\n return md5(uniqid(mt_rand(), true));\n}\n</code></pre>\n\n<p>here <code>mt_srand(microtime(true)*100000 + memory_get_usage(true));</code> is unused. If you consider using it, you should simplify it, you don't get a better salt that way.</p>\n\n<pre><code>$password = sha1(sha1($_POST['password'] . $salt));\n</code></pre>\n\n<p>Here you hash the password + salt twice. That <a href=\"https://crypto.stackexchange.com/questions/779/hashing-or-encrypting-twice-to-increase-security\">doesn't provide for any more security</a>, than simply hashing it once. Not to mention that your salt is already hashed, which is also redundant. </p>\n\n<p>And what's with the individual salts? That's actually not a very good idea, you shouldn't store the hashed password and the salt in the same storage. If someone get's access to your database, she has everything she needs for a common brute force attack. It would be a little more secure if you simply had a variable somewhere with a common salt for every password. Although <a href=\"https://softwareengineering.stackexchange.com/a/121629/25936\">I'm not advocating security through obscurity</a>, separating hash from salt would be saner. </p>\n\n<pre><code>if (strlen($_POST['username']) < 3 || strlen($_POST['username']) > 20) \n</code></pre>\n\n<p>It would be better to do something like: </p>\n\n<pre><code>$lengthUsername = $_POST['username'];\nif (lengthUsername < 3 || lengthUsername > 20) {\n</code></pre>\n\n<p>to not call the function twice. The performance issue is minuscule, but you <a href=\"http://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">should avoid repeating code</a> anyway. The <code>if (isset($_POST['submit'])) { ... }</code> is too long. You could move some of the functionality (let's say the database stuff) into a function and just call the function in the <code>if</code> block. </p>\n\n<blockquote>\n <p>What I can do about the func.php file as a file with just a bunch of functions, doesn't seem to be the best approach for it.</p>\n</blockquote>\n\n<p>It depends. If you use everything that's in it everywhere, then it's ok. If not you should brake it to smaller function collection files and include as needed. But since you are doing this the procedural way, it's ok to have one or more function collections. Have you considered an OO approach? I'm not saying you should, just curious. </p>\n\n<p>Other than that, your code looks fine. Kudos for using PDO and prepared statements, that's a wise decision. Also good that you are calling <code>exit</code> after <code>location()</code>, <code>location()</code> will fail with a notice if headers already sent. </p>\n\n<hr>\n\n<p>As for the update:</p>\n\n<ul>\n<li>Why sleep at all?</li>\n<li>The code is fairly small, it would be an overkill to rewrite in OO</li>\n</ul>\n\n<p>Unless you already have a User model, in which case you could just add the functionality there:</p>\n\n<pre><code>class User {\n\n function usernameExists($username) {\n $username = trim(strtolower($username); \n $usernames = $this->getUsernames();\n\n foreach($users as $user) {\n if(strtolower($user) == $request) {\n return false\n }\n }\n\n return true;\n }\n\n function getUsernames() {\n // return list of usernames from db\n }\n\n}\n</code></pre>\n\n<p>and you would call in in the ajax script as:</p>\n\n<pre><code>include(\"User.php\");\n\n$user = new User();\n\nif($user->usernameExists($_REQUEST['username'])) {\n echo \"false\";\n exit;\n}\n\necho \"true\"\n</code></pre>\n\n<p>The code is a lot more than with the procedural style, but you can use <code>User::usernameExists()</code> everywhere now, if you need it. Also note that I've pushed <code>strtolower</code> into the class, if you use it elsewhere such comparison normalizations and possible validations should be in the class method not in the calling code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-30T11:52:12.130",
"Id": "9944",
"Score": "0",
"body": "I have always thought that a individual salt was more appropriated, I guess not.\n\nAbout OO, yes, I've considered that, but I'm quite unsure of how I should do it. A User class, I assume, but should I put the validation in the method, or have a method for validation or a class for validation?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-30T11:54:22.500",
"Id": "9945",
"Score": "0",
"body": "Also, If u look at my updated question - How would I treat the following code there in OO? As, that \"file\" is called from an AJAX request, to check the username.."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-30T11:57:08.250",
"Id": "9946",
"Score": "0",
"body": "If you are unsure, you shouldn't try and convert it. Study OO concepts a bit and then start coding. The bad thing with OO is that there isn't a \"one fits all\" solution. You could have a Session class (for token etc), and a User class... And a validation class... it depends on what the concerns & responsibilities are (http://en.wikipedia.org/wiki/Single_responsibility_principle)... As for the individual salt, you can post a question at crypto.stackexchange.com for more educated answers, mine was mostly empirical."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-30T11:32:39.260",
"Id": "6407",
"ParentId": "6401",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "6407",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-30T09:52:52.293",
"Id": "6401",
"Score": "1",
"Tags": [
"php"
],
"Title": "Review on my current structure and tips on improvement"
}
|
6401
|
<p>I have inherited an application which uses LINQ-to-Entities for ORM and don't have a great deal of exposure to this.</p>
<p>There are many examples like this throughout the application. Could you tell me where to start in refactoring this code?</p>
<p>I appreciate that it's a large chunk of code, however the query isn't particularly performant and I wondered what you thought the main bottlenecks are in this case.</p>
<pre><code> /// <summary>
/// Get templates by username and company
/// </summary>
/// <param name="companyId"></param>
/// <param name="userName"></param>
/// <returns></returns>
public List<BrowsingSessionItemModel> GetItemBrowsingSessionItems(
int companyId,
string userName,
Boolean hidePendingDeletions,
Boolean hideWithAppointmentsPending,
Boolean hideWithCallBacksPending,
int viewMode,
string searchString,
List<int?> requiredStatuses,
List<int?> requiredSources,
string OrderBy,
BrowsingSessionLeadCustomField fieldFilter)
{
try
{
IQueryable<Lead> exclude1;
IQueryable<Lead> exclude2;
IQueryable<Lead> exclude3;
//To prepare call backs pending
if (hideWithCallBacksPending == true)
{
exclude1 = (from l1 in db.Leads
where (l1.Company_ID == companyId)
from l2 // Hiding Pending Call Backs
in db.Tasks
.Where(o => (o.IsCompleted ?? false == false)
&& (o.TaskType_ID == (int)RecordEnums.TaskType.PhoneCall)
&& (o.Type_ID == (int)RecordEnums.RecordType.Lead)
&& (o.Item_ID == l1.Lead_ID)
&& (o.Due_Date > EntityFunctions.AddDays(DateTime.Now, -1))
)
select l1);
}
else
{
exclude1 = (from l1 in db.Leads
where (0 == 1)
select l1);
}
//To prepare appointments backs pending
if (hideWithAppointmentsPending == true)
{
exclude2 = (from a1 in db.Leads
where (a1.Company_ID == companyId)
from a2 // Hiding Pending Appointments
in db.Tasks
.Where(o => (o.IsCompleted ?? false == false)
&& (o.TaskType_ID == (int)RecordEnums.TaskType.Appointment)
&& (o.Type_ID == (int)RecordEnums.RecordType.Lead)
&& (o.Item_ID == a1.Lead_ID)
&& (o.Due_Date > EntityFunctions.AddDays(DateTime.Now, -1))
)
select a1);
}
else
{
exclude2 = (from a1 in db.Leads
where (0 == 1)
select a1);
}
//To prepare deletions
if (hidePendingDeletions == true)
{
exclude3 = (from d1 in db.Leads
where (d1.Company_ID == companyId)
from d2 // Hiding Pending Deletions
in db.LeadDeletions
.Where(o => (o.LeadId == d1.Lead_ID))
select d1);
}
else
{
exclude3 = (from d1 in db.Leads
where (0 == 1)
select d1);
}
IQueryable<Lead> list = (from t1 in db.Leads
from t2
in db.LeadSubOwners
.Where(o => t1.Lead_ID == o.LeadId && o.Expiry >= DateTime.Now)
.DefaultIfEmpty()
where (t1.Company_ID == companyId)
where ((t2.Username == userName) && (viewMode == 1)) || ((t1.Owner == userName) && (viewMode == 1)) || ((viewMode == 2)) // Either owned by the user or mode 2 (view all)
select t1).Except(exclude1).Except(exclude2).Except(exclude3);
// Filter sources and statuses seperately
if (requiredStatuses.Count > 0)
{
list = (from t1 in list
where (requiredStatuses.Contains(t1.LeadStatus_ID))
select t1);
}
if (requiredSources.Count > 0)
{
list = (from t1 in list
where (requiredSources.Contains(t1.LeadSource_ID))
select t1);
}
// Do custom field filter here
if (fieldFilter != null)
{
string stringIntegerValue = Convert.ToString(fieldFilter.IntegerValue);
switch (fieldFilter.FieldTypeId)
{
case 1:
list = (from t1 in list
from t2
in db.CompanyLeadCustomFieldValues
.Where(o => t1.Lead_ID == o.Lead_ID && fieldFilter.TextValue == o.LeadCustomFieldValue_Value)
select t1);
break;
case 2:
list = (from t1 in list
from t2
in db.CompanyLeadCustomFieldValues
.Where(o => t1.Lead_ID == o.Lead_ID && stringIntegerValue == o.LeadCustomFieldValue_Value)
select t1);
break;
default:
break;
}
}
List<Lead> itemsSorted; // Sort here
if (!String.IsNullOrEmpty(OrderBy))
{
itemsSorted = list.OrderBy(OrderBy).ToList();
}
else
{
itemsSorted = list.ToList();
}
var items = itemsSorted.Select((x, index) => new BrowsingSessionItemModel
{
Id = x.Lead_ID,
Index = index + 1
});
return items.ToList();
}
catch (Exception ex)
{
logger.Info(ex.Message.ToString());
return new List<BrowsingSessionItemModel>();
}
}
</code></pre>
|
[] |
[
{
"body": "<p>You're right... this is a large chunk of code that is a little difficult to digest. With that said, several things come to mind.</p>\n\n<ul>\n<li><p>First off, this method is way too large. This is not a style issue perse... In this case, it's so large, it will not be JIT Optimized because the resulting IL will be too large. Break this up into logical sub-functions.</p></li>\n<li><p>I would suggest you push portions (<em>if not all</em>) of this back to the database using a SPROC, VIEW, or more likely a combination of the two. I would buy some donuts for your DB folks and make a new friend.</p></li>\n<li><p>If that is not an option, I would drop back to ADO.NET and build a single dynamic query that incorporates all the 'exclude' calls, main list call, and the filtering in one shot. This will be a little tedious but should provide you something that is a lot more performant. Keep in mind that old-style ADO.NET is between 150%-300% faster then even the best ORM. That's not a critism because they are really valueable in some areas, especially if you can leverage near-caching options. That said, they're not a solution for everything.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-30T20:28:29.473",
"Id": "6425",
"ParentId": "6403",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "6425",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-30T10:59:13.683",
"Id": "6403",
"Score": "1",
"Tags": [
"c#",
"linq",
"entity-framework",
"asp.net-mvc-3"
],
"Title": "Optimising multi-part LINQ to Entities query"
}
|
6403
|
<p>To illustrate how to do leader election with Apache Zookeeper I've created an straightforward application and I would like to have to threading part of the application reviewed.
I've created a simple class (<code>Speaker</code>) which outputs an unique identifier to a file on a regular interval. I've implemented the <code>Runnable</code> interface and start it with a <code>ScheduledExecutorService</code> with a fixed delay like this: </p>
<pre><code>scheduler.scheduleWithFixedDelay(speaker, 0, delay, TimeUnit.MILLISECONDS);
</code></pre>
<p>The <code>Speaker</code> class also implements a <code>Listener</code> interface so it can register itself to a <code>Monitor</code> (running in a separate thread, communicating to the Zookeeper server) which can enable or disable the output to the file. </p>
<p>My review question (besides general code review): Is this the best way to start and stop functionality in a scheduled thread? </p>
<p>Speaker & Speaker Server:</p>
<p>Complete project: <a href="https://github.com/cyberroadie/zookeeper-leader" rel="nofollow">https://github.com/cyberroadie/zookeeper-leader</a></p>
<p>Code explanation: <a href="http://cyberroadie.wordpress.com/2011/11/24/implementing-leader-election-with-zookeeper/" rel="nofollow">http://cyberroadie.wordpress.com/2011/11/24/implementing-leader-election-with-zookeeper/</a></p>
<pre><code>public class Speaker implements Runnable, NodeMonitor.NodeMonitorListener {
private String message;
private String processName;
private long counter = 0;
private volatile boolean canSpeak = false;
public Speaker(String message) throws IOException, InterruptedException, KeeperException {
this.message = message;
this.processName = getUniqueIdentifier();
}
private static String getUniqueIdentifier() {
String processName = ManagementFactory.getRuntimeMXBean().getName();
String processId = processName.substring(0, processName.indexOf("@"));
return "pid-" + processId + ".";
}
public void run() {
try {
if (canSpeak) {
handleTask();
}
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
}
public void handleTask() throws IOException {
FileWriter fstream = new FileWriter("out.txt");
BufferedWriter out = new BufferedWriter(fstream);
out.write(message + ": " + counter++ + " " + processName + "\n");
out.close();
}
@Override
public void startSpeaking() {
this.canSpeak = true;
}
@Override
public void stopSpeaking() {
this.canSpeak = false;
}
@Override
public String getProcessName() {
return processName;
}
}
</code></pre>
<p>Speaker Server:</p>
<pre><code>public class SpeakerServer {
final static Logger logger = LoggerFactory.getLogger(SpeakerServer.class);
private static final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
private static NodeMonitor monitor;
private static void printUsage() {
System.out.println("program [message] [wait between messages in millisecond]");
}
public static void main(String[] args) {
if (args.length < 2) {
printUsage();
System.exit(1);
}
long delay = Long.parseLong(args[1]);
Speaker speaker = null;
try {
speaker = new Speaker(args[0]);
monitor = new NodeMonitor();
monitor.setListener(speaker);
monitor.start();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
scheduler.scheduleWithFixedDelay(speaker, 0, delay, TimeUnit.MILLISECONDS);
logger.info("Speaker server started with fixed time delay of " + delay + " milliseconds.");
}
}
</code></pre>
|
[] |
[
{
"body": "<p>you could also look at using a fixed thread pool. That way, if one thread becomes blocked for some reason, say the disk became full, the threads would wait in a queue until the blocked thread terminated. That way you wouldn't loose any unique id's or run into memory problems if too many threads became blocked.</p>\n\n<p>Hope that helps,</p>\n\n<p>Ross</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-30T12:50:02.313",
"Id": "6409",
"ParentId": "6404",
"Score": "1"
}
},
{
"body": "<p>I'd consider stopping the scheduler (or canceling the task) on a <code>stopSpeaking</code> call and restarting it on a <code>startSpeaking</code> call (or resubmitting the <code>Runnable</code>). I'm not familiar with Zookeeper, I don't know anything about the typical usage, so if stop/startSpeaking calls arrives often it won't be the best solution but it seems cleaner if there are long breaks between <code>stopSpeaking</code> and <code>startSpeaking</code> calls.</p>\n\n<p>A few notes about the code:</p>\n\n<ol>\n<li><p>Consider using SLF4J to log the exceptions too instead of <code>printStackTrace()</code>.</p></li>\n<li><p>Close the <code>BufferedWriter</code> in a <code>finally</code> block:</p>\n\n<pre><code>final BufferedWriter out = new BufferedWriter(fstream);\ntry {\n ...\n} finally {\n out.close();\n}\n</code></pre></li>\n<li><p><code>System.exit</code> isn't a nicest way to stop an entire application, especially hidden in a <code>catch</code> block of a <code>run</code> method. I'd rethrow the <code>IOException</code> as a <code>RuntimeException</code> (or a <code>RuntimeException</code> subclass):</p>\n\n<pre><code>@Override\npublic void run() {\n if (!canSpeak) {\n return;\n }\n try {\n handleTask();\n } catch (final IOException e) {\n throw new RuntimeException(e);\n }\n}\n</code></pre>\n\n<p>then use the <code>ScheduledFuture</code> of <code>scheduleWithFixedDelay</code> to wait for the <code>RuntimeException</code>:</p>\n\n<pre><code>final ScheduledFuture<?> speakerFuture = \n scheduler.scheduleWithFixedDelay(speaker, 0, delay, TimeUnit.MILLISECONDS);\nlogger.info(\"Speaker server started with fixed time delay of \" + delay + \" milliseconds.\");\ntry {\n speakerFuture.get();\n} finally {\n scheduler.shutdown();\n}\n</code></pre>\n\n<p>Disclaimer: I don't like the usage of <code>RuntimeException</code> here, but unfortunately the <code>scheduleAtFixedRate</code> accepts only <code>Runnable</code> objects (not <code>Callable</code>s which could throw any <code>Exception</code>).</p>\n\n<p>Please notice the <a href=\"http://www.codinghorror.com/blog/2006/01/flattening-arrow-code.html\" rel=\"nofollow\">guard clause</a> also.</p></li>\n<li><p>I'm not completely sure that <code>ScheduledExecutorService</code> guarantees whether scheduled task will always run in the same thread or not. (I suppose it does not.) Furthermore, the <code>counter</code> field in the <code>Speaker</code> class could be synchronized properly due to volatile piggybacking but I'd use a defensive strategy here and use <code>AtomicInteger</code> for the counter to make it less error-prone.</p></li>\n<li><p>I'd check <code>null</code>s in the constructor of <code>Speaker</code>. <a href=\"http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Preconditions.html\" rel=\"nofollow\">checkNotNull from Guava</a> is a great choice for that.</p>\n\n<pre><code>this.message = checkNotNull(message, \"message cannot be null\");\n</code></pre>\n\n<p>(Also see: <em>Effective Java, 2nd edition, Item 38: Check parameters for validity</em>)</p></li>\n<li><p><a href=\"http://en.wikipedia.org/wiki/SLF4J\" rel=\"nofollow\">SLF4J supports <code>{}</code></a>, use that:</p>\n\n<pre><code>logger.info(\"Speaker server started with fixed time delay of {} milliseconds.\", delay);\n</code></pre></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-14T22:28:39.180",
"Id": "13668",
"ParentId": "6404",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-30T11:02:41.733",
"Id": "6404",
"Score": "3",
"Tags": [
"java",
"multithreading"
],
"Title": "Switching functionality on and off in a Scheduled Thread"
}
|
6404
|
<p>What do you think about this core EF method ?</p>
<p>Also, Notice that it returns IQueryable: </p>
<p>Could that be a performance danger when extended improperly ? How ?</p>
<p>Please accept the fact that <code>Includes</code> and <code>OrderBy</code> parameters are <code>string</code> type.</p>
<pre><code>public IQueryable<TEntity> GetEntitySetMultipleTables(Expression<Func<TEntity, bool>> WhereExpression = null,
string OrderBy = null,
int TotalResults = int.MaxValue, int SkippedResults = 0, string[] Includes = null)
{
if (OrderBy != null)
{
string orderbyProperty = OrderBy;
if (OrderBy.IndexOf(' ') > -1) // Direction
{
orderbyProperty = OrderBy.Substring(0, OrderBy.IndexOf(' '));
}
if (typeof(TEntity).GetProperty(orderbyProperty) == null)
OrderBy = null;
}
if ((SkippedResults > 0) && (OrderBy == null))
{
OrderBy = GetPrimaryKeyName();
}
//Base EntitySet
IQueryable<TEntity> results;
ObjectQuery<TEntity> objectSetResults = Context.CreateObjectSet<TEntity>();
if (Includes == null)
results = objectSetResults.AsQueryable();
else
{
foreach (var include in Includes)
{
objectSetResults = objectSetResults.Include(include.Trim());
}
results = objectSetResults.AsQueryable();
}
//Filter by Where Expression
if (WhereExpression != null)
results = results.Where(WhereExpression);
//Order Results
if (OrderBy != null)
{
results = results.OrderBy(OrderBy);
}
//Skip Records
if (SkippedResults > 0)
results = results.Skip(SkippedResults);
//Take Specific Amount of records
if (TotalResults != int.MaxValue)
results = results.Take(TotalResults);
//Run the LINQ Query and return the results
return results;
}
</code></pre>
<p>Thanks in advance.</p>
|
[] |
[
{
"body": "<p>I'm not sure how this code works (I had to invent <code>GetPrimaryKeyName</code>) and I can't find a <code>IQueryable<T></code> that has an <code>OrderBy</code> that takes a string parameter. So faking it as much as possible, I came up with this:</p>\n\n<pre><code> public IQueryable<TEntity> GetEntitySetMultipleTables(\n Expression<Func<TEntity, bool>> whereExpression = null,\n string orderBy = null,\n int? totalResults = null,\n int? skippedResults = null,\n string[] includes = null)\n {\n PropertyInfo orderbyProperty;\n int directionIndex;\n\n if (orderBy == null)\n {\n directionIndex = -1;\n orderbyProperty = null;\n }\n else\n {\n directionIndex = orderBy.IndexOf(' ');\n\n // Direction.\n if (directionIndex > -1)\n {\n orderBy = orderBy.Substring(0, directionIndex);\n }\n\n orderbyProperty = typeof(TEntity).GetProperty(orderBy);\n }\n\n if ((skippedResults != null) && ((int)skippedResults > 0) && (orderbyProperty == null))\n {\n orderbyProperty = typeof(TEntity).GetProperty(GetPrimaryKeyName());\n }\n\n // Base EntitySet.\n ObjectQuery<TEntity> objectSetResults = Context.CreateObjectSet<TEntity>();\n var results = includes == null\n ? objectSetResults.AsQueryable()\n : includes.Aggregate(objectSetResults, (current, include) => current.Include(include.Trim())).AsQueryable();\n\n // Filter by Where Expression.\n if (whereExpression != null)\n {\n results = results.Where(whereExpression);\n }\n\n // Order Results.\n if (orderbyProperty != null)\n {\n results = directionIndex > -1\n ? results.OrderByDescending(result => orderbyProperty.GetValue(result, null))\n : results.OrderBy(result => orderbyProperty.GetValue(result, null));\n }\n\n // Skip Records.\n if ((skippedResults != null) && ((int)skippedResults > 0))\n {\n results = results.Skip((int)skippedResults);\n }\n\n // Take Specific Amount of records.\n if ((totalResults != null) && (totalResults > 0))\n {\n results = results.Take((int)totalResults);\n }\n\n // Run the LINQ Query and return the results.\n return results;\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-30T23:24:31.027",
"Id": "6432",
"ParentId": "6410",
"Score": "1"
}
},
{
"body": "<p>A few thoughts:</p>\n\n<ul>\n<li>Passing in what are essentially booleans that are checked within the\nmethod is a code smell that should lead you to ask the question \"How\nmany responsibilities does this method have?\".</li>\n<li>I see no reason at all to pass in a string called OrderBy. I know\nyou say that we should just accept that, but I can't think of a\nsingle good reason not to refactor that to be a Predicate (especially\nsince you seem to use it as if it is a Predicate in what must be your\nown custom overloaded extension method).</li>\n<li>The method \"GetPrimaryKey\" is very misleading in that it apparently\nreturns a single string, but a Primary Key can consist of multiple\ncolumns.</li>\n<li>Another code smell that indicates too many responsibilities (and poor\nnaming) are comments explaining simple code. You should be\nrefactoring those blocks into methods or objects.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-31T15:26:06.843",
"Id": "7340",
"ParentId": "6410",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-30T13:32:53.370",
"Id": "6410",
"Score": "1",
"Tags": [
"c#",
"entity-framework"
],
"Title": "Review on core EF repository method"
}
|
6410
|
<p>The <a href="http://www.microsoft.com/net/" rel="nofollow noreferrer">.NET Framework</a> is not specific to any one programming language. The <a href="/questions/tagged/c%23" class="post-tag" title="show questions tagged 'c#'" rel="tag">c#</a>, <a href="/questions/tagged/vb.net" class="post-tag" title="show questions tagged 'vb.net'" rel="tag">vb.net</a>, <a href="/questions/tagged/c%2b%2b-cli" class="post-tag" title="show questions tagged 'c++-cli'" rel="tag">c++-cli</a>, and <a href="/questions/tagged/f%23" class="post-tag" title="show questions tagged 'f#'" rel="tag">f#</a> programming languages from Microsoft, as well as many other languages from other vendors, all use the same <a href="/questions/tagged/.net" class="post-tag" title="show questions tagged '.net'" rel="tag">.net</a> <a href="/questions/tagged/framework" class="post-tag" title="show questions tagged 'framework'" rel="tag">framework</a>.</p>
<p>The .NET Framework includes a large <a href="/questions/tagged/library" class="post-tag" title="show questions tagged 'library'" rel="tag">library</a> of <a href="/questions/tagged/functions" class="post-tag" title="show questions tagged 'functions'" rel="tag">functions</a> as part of the Base Class Library (BCL), including those related to user interface design, data access, database connectivity, <a href="/questions/tagged/cryptography" class="post-tag" title="show questions tagged 'cryptography'" rel="tag">cryptography</a>, development of web applications, mathematical algorithms, and network communications. This extensive library simplifies development and makes it easy to rapidly develop new applications.</p>
<h2>Getting help</h2>
<ul>
<li><a href="http://en.wikipedia.org/wiki/.NET_Framework" rel="nofollow noreferrer">.NET Framework Wikipedia Link</a></li>
</ul>
<h2>Versions of .NET</h2>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/t357fb32%28v=vs.90%29.aspx" rel="nofollow noreferrer">What's New in the .NET Framework Version 2.0</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/bb822048%28v=vs.90%29.aspx" rel="nofollow noreferrer">What's New in the .NET Framework Version 3.0</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/bb332048%28v=vs.90%29.aspx" rel="nofollow noreferrer">What's New in the .NET Framework Version 3.5</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/vstudio/ms171868%28v=vs.100%29.aspx" rel="nofollow noreferrer">What's New in the .NET Framework 4</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/ms171868(v=vs.110).aspx" rel="nofollow noreferrer">What's New in the .NET Framework 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8</a></li>
</ul>
<h2>Stable release</h2>
<ul>
<li>.Net Framework 4.8 / 10 May 2019;</li>
<li><a href="https://github.com/dotnet/corefx" rel="nofollow noreferrer">.NET Core</a> 2.2 / 12 Apr 2018;</li>
</ul>
<h2><a href="http://msdn.microsoft.com/en-us/library/0xy59wtx.aspx" rel="nofollow noreferrer">Garbage collector</a></h2>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/ee787088.aspx" rel="nofollow noreferrer">Fundamentals of Garbage Collection</a>.</li>
<li><a href="http://msdn.microsoft.com/en-us/library/ms973837.aspx" rel="nofollow noreferrer">How does the .NET Garbage Collector work?</a></li>
<li><a href="http://stackoverflow.com/questions/151051/when-should-i-use-gc-suppressfinalize">When should I use GC.SuppressFinalize()?</a></li>
</ul>
<h3>Free .NET Programming Books (C# / F# / VB / Nemerle / Visual Studio)</h3>
<ul>
<li><a href="http://www.techotopia.com/index.php/C_Sharp_Essentials" rel="nofollow noreferrer">C# Essentials</a></li>
<li><a href="http://en.wikibooks.org/wiki/C_Sharp_Programming" rel="nofollow noreferrer">C# Programming - Wikibook</a></li>
<li><a href="http://www.csharpcourse.com/" rel="nofollow noreferrer">C# Yellow Book</a> (intro to programming)</li>
<li><a href="http://www.charlespetzold.com/dotnet/index.html" rel="nofollow noreferrer">Charles Petzold's .NET Book Zero</a></li>
<li><a href="http://www.brpreiss.com/books/opus6/" rel="nofollow noreferrer">Data Structures and Algorithms with Object-Oriented Design Patterns in C#</a></li>
<li><a href="http://weblogs.asp.net/zeeshanhirani/archive/2008/12/05/my-christmas-present-to-the-entity-framework-community.aspx" rel="nofollow noreferrer">Entity Framework</a></li>
<li><a href="https://docs.microsoft.com/en-us/archive/blogs/microsoft_press/free-ebook-moving-to-microsoft-visual-studio-2010" rel="nofollow noreferrer">Moving to Microsoft Visual Studio 2010</a></li>
<li><a href="http://it-ebooks.info/book/703/" rel="nofollow noreferrer">Programming in F# 3.0</a></li>
<li><a href="http://asaha.com/ebook/AMTQ2NjA-/Nemerle.pdf" rel="nofollow noreferrer">Nemerle</a></li>
<li><a href="http://www.programmersheaven.com/2/CSharpBook" rel="nofollow noreferrer">Programmer's Heaven C# School Book</a> (covers C# 1.0 and 2.0)</li>
<li><a href="http://www.albahari.com/threading/" rel="nofollow noreferrer">Threading in C#</a></li>
<li><a href="http://www.techotopia.com/index.php/Visual_Basic_Essentials" rel="nofollow noreferrer">Visual Basic Essentials</a></li>
<li><a href="http://www.infoq.com/minibooks/vsnettt" rel="nofollow noreferrer">Visual Studio Tips and Tricks</a> (VS 2003-2005 only)</li>
<li><a href="http://openmymind.net/FoundationsOfProgramming.pdf" rel="nofollow noreferrer">Foundations Of Programming</a></li>
</ul>
<hr />
<h2>Useful .NET Libraries</h2>
<p><strong>Mathematics</strong></p>
<ul>
<li><a href="http://mathnetnumerics.codeplex.com/" rel="nofollow noreferrer">Math.NET Numerics</a> - special functions, linear algebra, probability models, random numbers, interpolation, integral transforms, and more.</li>
</ul>
<p><strong>Package managers for external libraries</strong></p>
<ul>
<li><a href="http://nuget.codeplex.com/" rel="nofollow noreferrer">NuGet</a> (formerly known as NuPack) - Microsoft (developer-focused package management system for the .NET platform intent on simplifying the process of incorporating third-party libraries into a .NET application during development).</li>
<li><a href="http://openwrap.org" rel="nofollow noreferrer">OpenWrap</a> - Sebastien Lambla - Open Source Dependency Manager for .NET applications.</li>
</ul>
<p><strong>Build Tools</strong></p>
<ul>
<li><a href="http://sourceforge.net/projects/dnpb/" rel="nofollow noreferrer">Prebuild</a> - Generate project files for all Visual Studio versions, including major IDEs and tools like SharpDevelop, MonoDevelop, NAnt, and Autotools.</li>
</ul>
<p><strong>Dependency Injection/Inversion of Control</strong></p>
<ul>
<li><a href="http://msdn.microsoft.com/unity" rel="nofollow noreferrer">Unity Framework</a> - Microsoft</li>
<li><a href="http://sourceforge.net/projects/structuremap" rel="nofollow noreferrer">StructureMap</a> - Jeremy Miller</li>
<li><a href="http://www.castleproject.org/projects/windsor/" rel="nofollow noreferrer">Castle Windsor</a></li>
<li><a href="http://ninject.org/" rel="nofollow noreferrer">Ninject</a></li>
<li><a href="http://www.springframework.net/" rel="nofollow noreferrer">Spring Framework</a></li>
<li><a href="http://code.google.com/p/autofac/" rel="nofollow noreferrer">Autofac</a></li>
<li><a href="http://simpleinjector.codeplex.com" rel="nofollow noreferrer">Simple Injector</a></li>
<li><a href="http://mef.codeplex.com/" rel="nofollow noreferrer">Managed Extensibility Framework</a></li>
<li><a href="https://github.com/grumpydev/TinyIoC" rel="nofollow noreferrer">TinyIoC</a></li>
</ul>
<p><strong>Logging</strong></p>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/ff664569(PandP.50).aspx" rel="nofollow noreferrer">Logging Application Block</a> - Microsoft</li>
<li><a href="http://logging.apache.org/log4net/" rel="nofollow noreferrer">Log4Net</a> - Apache</li>
<li><a href="http://code.google.com/p/elmah/" rel="nofollow noreferrer">Error Logging Modules and Handlers (ELMAH)</a></li>
<li><a href="http://www.nlog-project.org/" rel="nofollow noreferrer">NLog</a></li>
<li><a href="http://logging.codeplex.com" rel="nofollow noreferrer">CuttingEdge.Logging</a></li>
<li><a href="http://netcommon.sourceforge.net" rel="nofollow noreferrer">Logging Abstraction API "Common.Logging"</a></li>
</ul>
<p><strong>Validation</strong></p>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/ff664356(PandP.50).aspx" rel="nofollow noreferrer">Validation Application Block</a> - Microsoft</li>
<li><a href="http://xval.codeplex.com/" rel="nofollow noreferrer">xVal</a></li>
<li><a href="http://fluentvalidation.codeplex.com/" rel="nofollow noreferrer">Fluent Validation</a></li>
</ul>
<p><strong>Design by Contract</strong></p>
<ul>
<li><a href="http://research.microsoft.com/en-us/projects/contracts/" rel="nofollow noreferrer">Microsoft Code Contracts</a></li>
<li><a href="http://www.codeproject.com/KB/cs/LinFu_Part5.aspx?msg=2417857" rel="nofollow noreferrer">LinFu</a></li>
<li><a href="http://conditions.codeplex.com" rel="nofollow noreferrer">CuttingEdge.Conditions</a></li>
</ul>
<p><strong>Compression</strong></p>
<ul>
<li><a href="http://www.icsharpcode.net/OpenSource/SharpZipLib/" rel="nofollow noreferrer">SharpZipLib</a></li>
<li><a href="http://www.codeplex.com/dotnetzip" rel="nofollow noreferrer">DotNetZip</a></li>
<li><a href="http://www.codeplex.com/YUICompressor" rel="nofollow noreferrer">YUI Compressor</a> (CSS and JavaScript minification)</li>
<li><a href="http://aspnet.codeplex.com/releases/view/40584" rel="nofollow noreferrer">AjaxMinifier (in other downloads)</a> (CSS and JavaScript minification. Also includes MSBuild task)</li>
<li><a href="http://sevenzipsharp.codeplex.com/" rel="nofollow noreferrer">SevenZipSharp</a> to pack, unpack a lot of different packages (including <a href="http://en.wikipedia.org/wiki/RAR" rel="nofollow noreferrer">RAR</a>, <a href="http://en.wikipedia.org/wiki/7-Zip" rel="nofollow noreferrer">7-Zip</a>, etc.)</li>
<li><a href="http://zipstorer.codeplex.com/" rel="nofollow noreferrer">ZipStorer</a> A pure C# class to store files in the ZIP format</li>
</ul>
<p><strong>Ajax</strong></p>
<ul>
<li><a href="http://www.codeplex.com/AjaxControlToolkit" rel="nofollow noreferrer">Ajax Control Toolkit</a> - Microsoft</li>
<li><a href="http://www.codeplex.com/AjaxPro" rel="nofollow noreferrer">AJAXNet Pro</a></li>
<li><a href="http://awesome.codeplex.com" rel="nofollow noreferrer">ASP.NET MVC Project Awesome</a> - Ajax helpers for ASP.NET MVC</li>
</ul>
<p><strong>Data Mapper</strong></p>
<ul>
<li><a href="http://xmldatamapper.codeplex.com/" rel="nofollow noreferrer">XmlDataMapper</a></li>
<li><a href="http://automapper.codeplex.com/" rel="nofollow noreferrer">AutoMapper</a></li>
<li><a href="http://code.google.com/p/dapper-dot-net/" rel="nofollow noreferrer">Dapper</a></li>
<li><a href="https://github.com/robconery/massive" rel="nofollow noreferrer">Massive</a></li>
<li>Data accessors from the <a href="http://msdn.microsoft.com/en-us/library/ff664742%28PandP.50%29.aspx" rel="nofollow noreferrer">Data Access Application Block</a></li>
<li><a href="http://valueinjecter.codeplex.com" rel="nofollow noreferrer">ValueInjecter</a></li>
</ul>
<p><strong>ORM</strong></p>
<ul>
<li><a href="http://weblogs.asp.net/scottgu/archive/2010/07/16/code-first-development-with-entity-framework-4.aspx" rel="nofollow noreferrer">Entity Framework</a> - Microsoft</li>
<li><a href="http://www.hibernate.org/343.html" rel="nofollow noreferrer">NHibernate</a> and <a href="http://fluentnhibernate.org/" rel="nofollow noreferrer">FluentNHibernate</a></li>
<li><a href="http://www.castleproject.org/projects/activerecord/" rel="nofollow noreferrer">Castle ActiveRecord</a></li>
<li><a href="http://subsonicproject.com/" rel="nofollow noreferrer">Subsonic</a></li>
<li><a href="http://xmldatamapper.codeplex.com/" rel="nofollow noreferrer">XmlDataMapper</a></li>
<li><a href="http://truss.codeplex.com/" rel="nofollow noreferrer">Truss</a> Data binding and real time property synchronisation library</li>
</ul>
<p><strong>Charting/Graphics</strong></p>
<ul>
<li><a href="http://www.microsoft.com/downloads/details.aspx?familyid=130F7986-BF49-4FE5-9CA8-910AE6EA442C&displaylang=en" rel="nofollow noreferrer">Microsoft Chart Controls for ASP.NET 3.5 SP1</a></li>
<li><a href="http://code.msdn.microsoft.com/mschart" rel="nofollow noreferrer">Microsoft Chart Controls for Windows Forms</a></li>
<li><a href="http://zedgraph.org/wiki/index.php?title=Main_Page" rel="nofollow noreferrer">ZedGraph Charting</a></li>
<li><a href="http://www.nplot.com/" rel="nofollow noreferrer">NPlot</a> - Charting for ASP.NET and Windows Forms</li>
<li><a href="http://imageresizingin.net/" rel="nofollow noreferrer">ImageResizer</a> - URL-driven image processing for both ASP.NET and .NET</li>
</ul>
<p><strong>PDF Creators/Generators</strong></p>
<ul>
<li><a href="http://www.pdfsharp.net/" rel="nofollow noreferrer">PDFsharp</a></li>
<li><a href="http://itextsharp.sourceforge.net/" rel="nofollow noreferrer">iTextSharp</a></li>
</ul>
<p><strong>Unit Testing/Mocking</strong></p>
<ul>
<li><a href="http://www.nunit.org/" rel="nofollow noreferrer">NUnit</a></li>
<li><a href="http://ayende.com/projects/rhino-mocks.aspx" rel="nofollow noreferrer">Rhino Mocks</a></li>
<li><a href="https://github.com/Moq/moq4" rel="nofollow noreferrer">Moq</a></li>
<li><a href="http://www.typemock.com/" rel="nofollow noreferrer">TypeMock.Net</a></li>
<li><a href="http://www.codeplex.com/xunit" rel="nofollow noreferrer">xUnit.net</a></li>
<li><a href="http://gallio.org" rel="nofollow noreferrer">Gallio</a>/<a href="http://www.mbunit.com/" rel="nofollow noreferrer">MbUnit</a></li>
<li><a href="http://github.com/machine/machine.specifications" rel="nofollow noreferrer">Machine.Specifications</a></li>
</ul>
<p><strong>Automated Web Testing</strong></p>
<ul>
<li><a href="http://seleniumhq.org" rel="nofollow noreferrer">Selenium</a></li>
<li><a href="http://watin.sourceforge.net/" rel="nofollow noreferrer">WatiN</a></li>
</ul>
<p><strong>Misc Testing/Quality Support/Behavior Driven Development (BDD)</strong></p>
<ul>
<li>Testdatagenerator <a href="http://nbuilder.org/" rel="nofollow noreferrer">NBuilder</a></li>
<li>BDD <a href="http://storyq.codeplex.com/" rel="nofollow noreferrer">StoryQ</a></li>
<li>BDD <a href="http://specflow.org/specflow/getting-started.aspx" rel="nofollow noreferrer">specflow</a></li>
</ul>
<p><strong>URL Rewriting</strong></p>
<ul>
<li><a href="http://urlrewriter.net/" rel="nofollow noreferrer">UrlRewriter.NET</a></li>
<li><a href="http://www.urlrewriting.net/" rel="nofollow noreferrer">UrlRewriting.Net</a></li>
<li><a href="http://urlrewriter.codeplex.com" rel="nofollow noreferrer">Url Rewriter and Reverse Proxy</a> - Managed Fusion/Nick Berardi</li>
</ul>
<p><strong>Web Debugging</strong></p>
<ul>
<li><a href="http://getglimpse.com" rel="nofollow noreferrer">Glimpse</a> - Firebug for your webserver</li>
</ul>
<p><strong>Controls</strong></p>
<ul>
<li><a href="http://www.componentfactory.com/windows-forms-products.php" rel="nofollow noreferrer">Krypton</a> - Free Windows Forms controls</li>
<li><a href="http://www.codeplex.com/sourcegrid/" rel="nofollow noreferrer">Source Grid</a> - A Grid control</li>
</ul>
<p><strong>MS Word/Excel Documents Manipulation</strong></p>
<ul>
<li><a href="http://docx.codeplex.com/" rel="nofollow noreferrer">DocX</a> to create, read, and manipulate formatted word documents. Easy syntax, working nicely, actively developed. No Microsoft Office necessary.</li>
<li><a href="http://www.carlosag.net/Tools/ExcelXmlWriter/" rel="nofollow noreferrer">Excel XML Writer</a> allows creation of .XLS (Excel) files. No Microsoft Office necessary. It has been a while since it has been updated. It also provides a <a href="http://ninject.org/" rel="nofollow noreferrer">code generator</a> to create code from already created XLS file (saved as XML).</li>
<li><a href="http://www.carlosag.net/Tools/ExcelXmlWriter/Generator.aspx" rel="nofollow noreferrer">Excel Reader</a> allows creation/reading of .XLS (Excel) files. No Microsoft Office necessary. It has been a while since it has been updated.</li>
<li><a href="http://www.codeproject.com/KB/office/ExcelReader.aspx" rel="nofollow noreferrer">Excel Package</a> allows creation/reading of .XLSX (Excel 2007) files. No Microsoft Office necessary. The author is gone, so it is out of date.</li>
<li><a href="http://epplus.codeplex.com/" rel="nofollow noreferrer">EPPlus</a> is based on <a href="http://excelpackage.codeplex.com/" rel="nofollow noreferrer">Excel Package</a> and allows creation and reading of .XLSX (Excel 2007). It is actually the most advanced even comparing to NPOI.</li>
<li><a href="http://npoi.codeplex.com/" rel="nofollow noreferrer">NPOI</a> is the .NET version of POI Java project at <a href="http://poi.apache.org/" rel="nofollow noreferrer">http://poi.apache.org/</a>. POI is an open source project which can help you read/write Excel, Word, and PowerPoint files. Latest sources available at <a href="https://github.com/tonyqus/npoi" rel="nofollow noreferrer">GitHub repository</a>.</li>
</ul>
<p><strong>Social Media</strong></p>
<ul>
<li><a href="http://linqtotwitter.codeplex.com/" rel="nofollow noreferrer">LINQ to Twitter</a> - LINQ-based wrapper for all Twitter API functionality in C#.</li>
<li><a href="http://facebooksdk.codeplex.com/" rel="nofollow noreferrer">Facebook C# SDK</a> - A toolkit for creating Facebook applications / integrating websites with Facebook using the new Graph API or the old rest API.</li>
</ul>
<p><strong>Serialization</strong></p>
<ul>
<li><a href="http://www.sharpserializer.com/en/index.html" rel="nofollow noreferrer">sharpSerializer</a> - XML/binary serializer for WPF, ASP.NET AND Silverlight.</li>
<li><a href="http://code.google.com/p/protobuf-net/" rel="nofollow noreferrer">protobuf-net</a> - .NET implementation of Google's cross-platform binary serializer (for all .NET platforms).</li>
</ul>
<p><strong>Machine learning</strong></p>
<ul>
<li><a href="https://github.com/encog/encog-dotnet-core" rel="nofollow noreferrer">Encog C#</a> - Neural networks</li>
<li><a href="http://www.aforgenet.com/framework/" rel="nofollow noreferrer">AForge.net</a> - AI, computer vision, genetic algorithms, machine learning</li>
</ul>
<p><strong>RESTFul Web Services</strong></p>
<ul>
<li><a href="http://restsharp.org/" rel="nofollow noreferrer">RestSharp</a> - Simple REST and HTTP API Client for .NET</li>
</ul>
<p><strong>Unclassified</strong></p>
<ul>
<li><a href="http://www.lhotka.net/" rel="nofollow noreferrer">CSLA Framework</a> - Business Objects Framework</li>
<li><a href="http://compositewpf.codeplex.com/" rel="nofollow noreferrer">Prism</a> - Composite UI application block for WPF, Silverlight and Windows Phone 7 - Microsoft patterns & practices</li>
<li><a href="http://msdn.microsoft.com/entlib" rel="nofollow noreferrer">Enterprise Library 5.0</a> - Logging, Exception Management, Caching, Cryptography, Data Access, Validation, Security, Policy Injection - Microsoft patterns & practices</li>
<li><a href="http://filehelpers.sourceforge.net/" rel="nofollow noreferrer">File helpers library</a></li>
<li><a href="http://www.itu.dk/research/c5/" rel="nofollow noreferrer">C5 Collections</a> - Collections for .NET</li>
<li><a href="http://quartznet.sourceforge.net/" rel="nofollow noreferrer">Quartz.NET</a> - Enterprise Job Scheduler for .NET Platform</li>
<li><a href="http://www.yoda.arachsys.com/csharp/miscutil/" rel="nofollow noreferrer">MiscUtil</a> - Utilities by Jon Skeet</li>
<li><a href="http://code.google.com/p/noda-time/" rel="nofollow noreferrer">Noda Time</a> - DateTime replacement (idiomatic port of Joda Time from Java)</li>
<li><a href="http://incubator.apache.org/lucene.net/" rel="nofollow noreferrer">Lucene.net</a> - Text indexing and searching</li>
<li><a href="http://www.codeplex.com/Json" rel="nofollow noreferrer">Json.NET</a> - LINQ over JSON</li>
<li><a href="http://www.codeplex.com/Flee" rel="nofollow noreferrer">Flee</a> - expression evaluator</li>
<li><a href="http://www.postsharp.org/" rel="nofollow noreferrer">PostSharp</a> - AOP</li>
<li><a href="http://www.ikvm.net/" rel="nofollow noreferrer">IKVM</a> - brings the extensive world of Java libraries to .NET.</li>
<li><a href="http://webserver.codeplex.com" rel="nofollow noreferrer">C# Webserver</a> - Embeddable webserver</li>
<li><a href="http://bcl.codeplex.com/releases/view/42783" rel="nofollow noreferrer">Long Path</a> - Microsoft</li>
<li><a href="http://goldparser.org/engine/index.htm" rel="nofollow noreferrer">.NET Engines for the GOLD Parsing System</a></li>
<li><a href="http://www.codeproject.com/KB/threads/smartthreadpool.aspx" rel="nofollow noreferrer">Smart Thread Pool</a> - Thread Pool management library</li>
<li><a href="http://ncqrs.org/" rel="nofollow noreferrer">NCQRS</a> - library for event-driven architectures (<a href="http://www.udidahan.com/2009/12/09/clarified-cqrs/" rel="nofollow noreferrer">CQRS</a>).</li>
<li><a href="https://github.com/soygul/NBug" rel="nofollow noreferrer">NBug</a> - Automated exception and error reporting tool (can generate minidumps)</li>
<li><a href="http://splicer.codeplex.com/" rel="nofollow noreferrer">Splicer.Net</a> - library for the .NET Framework that aims to simplify developing applications for editing and encoding audio and video using DirectShow.</li>
<li><a href="http://research.microsoft.com/en-us/projects/pex/" rel="nofollow noreferrer">Pex</a> - a tool for automatic test case generation</li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2011-11-30T13:52:27.087",
"Id": "6412",
"Score": "0",
"Tags": null,
"Title": null
}
|
6412
|
.NET is a software framework supporting a multi-language paradigm and supporting language interoperability. .NET applications are executed in a virtual machine (CLR) which provides a few important services: security, memory management and exception handling.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-30T13:52:27.087",
"Id": "6413",
"Score": "0",
"Tags": null,
"Title": null
}
|
6413
|
<pre><code>class User {
protected $DBH;
protected $STH;
public function __construct($DBH) {
$this->DBH = $DBH;
}
public function logged_in() {
if (isset($_SESSION['userid']) && isset($_SESSION['hash'])) {
$hash = sha1($_SESSION['userid'] . $_SERVER['HTTP_USER_AGENT']);
if ($_SESSION['hash'] == $hash)
return true;
}
return false;
}
public function login($username, $password) {
$password = sha1($password);
$this->STH = $this->DBH->prepare("SELECT id, banned, activated FROM users WHERE username = ? AND password = ?");
$this->STH->setFetchMode(PDO::FETCH_OBJ);
$this->STH->execute(array($username, $password));
if ($this->STH->rowCount() > 0)
return $this->STH->fetch();
}
public function create_account($username, $password, $email) {
$password = sha1($password);
$activation_key = md5($username . $email);
$this->DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
$this->STH = $this->DBH->prepare("INSERT INTO users(username, password, email, activation_key, created) VALUES(:username, :password, :email, :activation_key, :created)");
$this->STH->bindParam(':username', $username);
$this->STH->bindParam(':password', $password);
$this->STH->bindParam(':email', $email);
$this->STH->bindParam(':activation_key', $activation_key);
$this->STH->bindParam(':created', time());
$this->STH->execute();
} catch (PDOException $e) {
//$e->getMessage();
return false;
}
return true;
}
public function check_username($username) {
$this->STH = $this->DBH->prepare("SELECT username FROM users WHERE username = ?");
$this->STH->execute(array($username));
if ($this->STH->rowCount() > 0)
return false;
return true;
}
public function check_email($email) {
$this->STH = $this->DBH->prepare("SELECT email FROM users WHERE email = ?");
$this->STH->execute(array($email));
if ($this->STH->rowCount() > 0)
return false;
return true;
}
public function activate($key) {
$this->STH = $this->DBH->prepare("SELECT activation_key FROM users WHERE activation_key = ?");
$this->STH->execute(array($key));
if ($this->STH->rowCount() > 0) {
$this->STH = $this->DBH->prepare("UPDATE users SET activated = 1, activation_key = null WHERE activation_key = ?");
$this->STH->execute(array($key));
return true;
}
return false;
}
}
</code></pre>
<p>Am I doing this right?
What should I change? Add, etc. Should I use more try { } catch blocks/etc. Give me some tips on how to improve the code. (Better performance, etc).</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-01T06:57:05.617",
"Id": "9997",
"Score": "1",
"body": "It's quite impressive that you went from [this](http://codereview.stackexchange.com/questions/6401/review-on-my-current-structure-and-tips-on-improvement) to that so quickly. @vstm has excellent points, but your code is far from someone's who's unsure on OO. Nice."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-01T17:10:26.337",
"Id": "10018",
"Score": "0",
"body": "Thanks, anything I could improve? :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-01T17:23:36.737",
"Id": "10021",
"Score": "0",
"body": "@vstm answer covers me, I've added a comment there about exception logging, something I recently enquired about on Programmers SE http://programmers.stackexchange.com/questions/121434/is-it-more-sensible-to-log-exceptions-in-a-catch-all-or-in-a-base-exception-clas"
}
] |
[
{
"body": "<ul>\n<li><p>Regarding try/catch: this depends on whether your user class <strong>can handle errors</strong> or not.</p>\n\n<ul>\n<li><p>An exception you can't handle is for example if the SQL-statement has a syntax error or the SQL-server being down. You can't do anything about it programatically during runtime except for displaying a nice error message to the user. In that case I wouldn't surround the DB-code with try/catch but implement a global try/catch which does just display a nice error message to the user and log the errors for you, the developer.</p></li>\n<li><p>But if you have an exception because for example your username-field is <code>UNIQUE</code>and someone tries to insert an username which already exists you could resolve that problem automatically by just adding a number to the username and retry the insert (okay it's a dumb example, but I hope the point comes across). The pseudocode for this dumb example could be like:</p>\n\n<pre><code>$statement = $db->prepare(\"INSERT INTO user (username, ....) values (?, ...)\");\n$tryInsert = true;\n$tries = 0;\nwhile($tryInsert) {\n $insertName = $username;\n if($tries > 0) {\n $insertName .= $tries;\n }\n try {\n $statement->execute(array($insertName, ...));\n $tryInsert = false; // it worked, stop trying\n } catch(PDOException $e) {\n if($e->code() == \"23000\") {\n // 23000 means unique constraint violation, probably \n // duplicate username\n ++$tries;\n } else {\n // we can't handle the exception, therefore we just re-throw it\n throw $e;\n }\n }\n}\n</code></pre></li>\n</ul>\n\n<p>I think in your code are no exceptions which you could handle. If an exception occurs it is most probably due to some issue with the SQL-server or the SQL-statement is wrong. In that case it doesn't make sense to wrap any of your code in try/catch. But you should add some kind of <a href=\"http://php.net/manual/de/function.set-exception-handler.php\" rel=\"nofollow\">global exception handler</a> which displays a nice error message (like: oops something went wrong, the developers have been informed).</p></li>\n<li><p>In <code>login</code> change the last two lines to:</p>\n\n<pre><code>if (($row = $this->STH->fetch()) !== false)\n return $row;\n</code></pre>\n\n<p>The problem with <code>PDOStatement::recordCount()</code> is, that it's <a href=\"http://www.php.net/manual/de/pdostatement.rowcount.php\" rel=\"nofollow\">not portable for SELECT queries</a> and the above code does the same thing as your code.</p></li>\n<li><p>Then in <code>create_account</code>, you use <code>PDO::setAttribute</code> to change the PDO error mode of the supplied PDO-instance. Change that so that this is called when the PDO is initialized and not deep down in some mapper-class.</p></li>\n<li><p>Your <code>activate</code> method could be rewritten to just execute one query:</p>\n\n<pre><code>public function activate($key) {\n $this->STH = $this->DBH->prepare(\"UPDATE users SET activated = 1, activation_key = null WHERE activation_key = ?\"); \n $this->STH->execute(array($key));\n\n // rowCount is set to the number of rows affected by UPDATE\n return $this->STH->rowCount() > 0;\n}\n</code></pre></li>\n<li><p>Optional: This could be simplified:</p>\n\n<pre><code>if (isset($_SESSION['userid']) && isset($_SESSION['hash'])) {\n</code></pre>\n\n<p>To that:</p>\n\n<pre><code>if (isset($_SESSION['userid'], $_SESSION['hash'])) {\n</code></pre></li>\n<li><p>Optional: Consider using <a href=\"http://www.openwall.com/phpass/\" rel=\"nofollow\">phpass</a> for hashing your passwords. It's definitely more secure that just <code>sha1</code> with some salt thrown in and the class is simple to use. If you're doing this you would have to rework your <code>login</code> method a bit (meaning the password verification must be done in PHP when using phpass).</p></li>\n<li><p>If you like to change your <code>check_*</code>-methods you could do something like that:</p>\n\n<pre><code>protected function check_record($field, $value) {\n $this->STH = $this->DBH->prepare(\"SELECT COUNT(*) FROM users WHERE {$field} = ?\");\n $this->STH->execute(array($value));\n\n $count = $this->STH->fetchColumn();\n\n if($count !== false) {\n return (int)$count > 0;\n }\n\n return null;\n}\n\npublic function check_username($username) {\n return $this->check_record(\"username\", $username);\n}\n\npublic function check_email($username) {\n return $this->check_record(\"email\", $username);\n}\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-30T19:15:08.143",
"Id": "9959",
"Score": "0",
"body": "Could you rephrase/rewrite the first about try/catch I didn't really understand what you meant. Otherwise, thanks for a very good answer, I'll edit my code right away."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-30T19:21:47.650",
"Id": "9961",
"Score": "0",
"body": "If rowCount isn't portable with SELECT, does that mean I must change check_email, and check_username method? How?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-30T20:03:47.020",
"Id": "9964",
"Score": "0",
"body": "@John: thank you for your feedback. I have rewritten the part about try/catch - I hope it's clearer now. As for the check_* functions: I have added my version without rowCount it at the end of my answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-30T20:27:42.363",
"Id": "9965",
"Score": "0",
"body": "Thanks for the tips, Anything else you can think off? Else I will set this answer as correct..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-30T21:12:29.467",
"Id": "9970",
"Score": "0",
"body": "But how I can I log the \"error\" in example create_account method, If I don't do a try/catch there."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-01T17:20:27.227",
"Id": "10020",
"Score": "0",
"body": "@John You should log the error there. No point in logging every time there's an exception, you should let exceptions be thrown when you can't do anything to handle them. And you should implement a global exception catch all via `set_error_handler` as vstm suggests and log there. You need the catch all, for all the exceptions that you may not have predicted to catch and for those that it doesn't make sense to catch, so since you need it and it will catch all exceptions, it also makes sense to log there..."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-30T19:09:58.230",
"Id": "6421",
"ParentId": "6415",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "6421",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-30T16:06:20.617",
"Id": "6415",
"Score": "1",
"Tags": [
"php"
],
"Title": "OO Auth lib - On the right track?"
}
|
6415
|
<p>I started a hobby project which would be the first thing I do in C that is intended to be seen by someone else. I've been practicing for a while but I'm actually a beginner; I never wrote real software in C/C++ yet.</p>
<p>I wanted to know what is OK from my code, what is wrong and why, if it's clear/readable, and everything you can tell me about it would be fine. I have never shown any of my code to anyone and I have no clue if I'm doing well, or if it can't be worse--the latter being what I consider most likely. So I would like to know the reasons from people with experience with C/C++, and what you consider that I can improve/remove, etc.</p>
<p>The code is something I've just started, about a small voxel system for a <a href="http://www.minecraft.net" rel="nofollow">Minecraft</a>-like game. </p>
<p>The basic idea would be: </p>
<ol>
<li>to have an array of voxel types</li>
<li>to be able to assign rules to the voxel types (like functions/scripts to be called.. somehow?)</li>
<li>to have an array of game relevant states for each voxel. The state data would be mostly lighting and visibility values.</li>
<li>to be able to save and load state data as necessary</li>
</ol>
<p>etc... I have a lot of ideas but I still barely wrote some code and I would like to know other people's opinions before continuing, so I can improve the project instead of having to fix it later.</p>
<p>This is the link for the project files (only a .h and a .cpp, it's just started) at <a href="https://code.google.com/p/gvoxel/source/browse/#svn%2Ftrunk%2FGVoxel" rel="nofollow">google code</a></p>
<p>And here are some of the contents of the .h so you can give yourself an idea without opening the link:</p>
<pre><code>typedef struct _GVOXEL_RULE
{
GVOXELRULE_ID nRuleID;
INT32 nRuleValue; // this value is left for use by the rule function, not needed right now
} GVOXEL_RULE;
// here I'm planning to store the description of the voxel types
typedef struct _GVOXEL_DATA
{
GVOXEL_TYPE nVoxelType;
dword nRuleCount;
GVOXEL_RULE* pVoxelRules; // I'm thinking this should be separated to a "voxel rule manager" class or something similar
dword nVoxelCount; // store here the amount of voxels applying this reference (so we stop looking when the limit is reached)
} GVOXEL_DATA;
typedef struct _GVOXEL_STATE_1_0
{
GVOXEL_ID nVoxelID; // This id will be equal to the voxel index which may be handy
GVOXEL_TYPE nVoxelType; // This number will reference the table with voxel descriptions
word nMetadata; // This was described below.
byte nLightX; // This stores how much light (from 0 to 255) is receiving the face pointing to +X
byte nLightXN; // Same from below but for -X face
byte nLightY; // etc.
byte nLightYN; // etc..
byte nLightZ; // etc...
byte nLightZN; //
} GVOXEL_STATE_1_0, GVOXEL_STATE;
typedef struct _GVOXELCHUNK_DATA_1_0 //
{
volatile long nRefCount; // <-- This gives me the chills
dword nChunkID; // some chunk ID that makes sense in some other reference table. or not.
dword nWidth; // size of the array in the X dimension
dword nHeight; // size of the array in the Y dimension
dword nDepth; // size of the array in the Z dimension
GVOXEL_STATE_1_0* pVoxelStateList; // The count of voxel states will be nWidth*nHeight*nDepth
dword nExtendedDataSize; // size of optional data, if found in the file, to be loaded to the "pExtendedData" pointer.
void* pExtendedData; // If bExtendedData is 0, this variable should be set to 0 (null).
} GVOXELCHUNK_DATA_1_0, GVOXELCHUNK_DATA;
void gvCreateChunkData10( GVOXELCHUNK_DATA_1_0** ppChunkData );
void gvAcquireChunkData10( GVOXELCHUNK_DATA_1_0* pChunkData );
void gvFreeChunkData10( GVOXELCHUNK_DATA_1_0** ppChunkData );
#define gvCreateChunkData gvCreateChunkData10
#define gvFreeChunkData gvFreeChunkData10
#define gvAcquireChunkData gvAcquireChunkData10
// wchar_t* pFilename: Name of the source file to load chunk data from
// dword *nMaxChunks: if ppChunkData is NULL, the function returns here the number of chunks in the file. else stores the
// GVOXELCHUNK_DATA** ppChunkData:
INT32 gvLoadChunkFromFileW( wchar_t* pFilename, dword *inout_nMaxChunks, GVOXELCHUNK_DATA** ppChunkData );
//
INT32 gvSaveChunkToFileW( wchar_t* pFilename, dword nChunkCount, GVOXELCHUNK_DATA** ppChunkData );
#ifdef _TODO
INT32 gvLoadChunkFromFileA( char* pFilename, dword nMaxChunks, GVOXELCHUNK_DATA** ppChunkData );
INT32 gvSaveChunkToFileA( char* pFilename, dword nChunkCount, GVOXELCHUNK_DATA** ppChunkData );
#endif
#define gvLoadChunkFromFile gvLoadChunkFromFileW
#define gvSaveChunkToFile gvSaveChunkToFileW
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-30T19:01:43.917",
"Id": "9956",
"Score": "3",
"body": "c++ or C? Pick one."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-30T20:52:12.613",
"Id": "9966",
"Score": "0",
"body": "I'd rather C than C++, I don't feel comfortable with templates or other C++ features, but the compiler will allow me to add some C++ in case of need."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-01T21:57:56.830",
"Id": "10040",
"Score": "2",
"body": "@PabloAriel: The point is that they are two different languages, so any potential answers will need to know in which context to write their code. A C solution will be very different than a C++ solution."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-02T01:20:09.600",
"Id": "10047",
"Score": "0",
"body": "@EdS. I'd prefer to use C, I should remove those \"new\"s and make some \"malloc\" calls instead, to make it plain C, I guess?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-02T01:30:43.847",
"Id": "10048",
"Score": "0",
"body": "Yes [more chars]"
}
] |
[
{
"body": "<p><strong>Design</strong></p>\n\n<p>It looks like you have a design in mind, but it isn't all visible from the code posted.\nI'm anyway a little hazy on what you're really trying to model here, so let's step through it.</p>\n\n<ol>\n<li>3D array of voxel instances: this is your actual world state, got it.</li>\n<li><code>nVoxelType</code> is ... an index into some type array not shown? Well, we clearly need <em>some</em> connection between a voxel instance and it's type, however implemented</li>\n<li>now, what properties does a voxel type need? You show an array of rules, but it isn't clear how they interact with the type. If you're intending that each rule should represent something like <em>hit a voxel of type 7 with a pickaxe</em> or <em>set fire to a voxel of type 3</em>, I'm not sure a linear array will cut it.</li>\n</ol>\n\n<p>It might help to clarify things if you try sketching a game event: going from coordinates to a voxel instance is easy, but once you have that, what are you going to do to it?</p>\n\n<p><strong>Implementation</strong></p>\n\n<p>You say you probably want C rather than C++, but you can use similar polymorphism in either with a little effort, so designing the interaction is still more important than language choice.</p>\n\n<p>Eg. C++</p>\n\n<pre><code>class VoxelType\n{\npublic:\n // common interface for all types\n virtual void hitMeWithAPickaxe(Voxel *self) = 0;\n virtual void setFireToMe(Voxel *self) = 0;\n};\n\nclass DirtVoxelType: public VoxelType\n{\npublic:\n // specific implementation for this type\n void hitMeWithAPickaxe(Voxel *self);\n virtual void setFireToMe(Voxel *self);\n};\n</code></pre>\n\n<p>or in C:</p>\n\n<pre><code>struct VoxelType {\n int type;\n void (*hitMeWithAPickaxe)(struct Voxel *self);\n void (*setFireToMe)(struct Voxel *self);\n};\n\nvoid hitDirtWithAPickaxe(struct Voxel *);\nvoid setFireToDirt(struct Voxel *);\n\nstruct VoxelType VoxelTypeArray[] = {\n { DirtType, hitDirtWithAPickaxe, setFireToDirt },\n ...\n};\n</code></pre>\n\n<p>Obviously you can also use the time-honoured massive <em>switch/case</em> statement in either language too - the point is just that the selection of C or C++ isn't the driving force behind the design, the <em>design</em> is the driving force behind the implementation.</p>\n\n<p><code>volatile long nRefCount; // <-- This gives me the chills</code>\nI don't blame you - even if you already know your game is going to be multithreaded, I can't see this working. Either design concurrency and synchronisation in up-front, and do it properly, or omit it entirely and be prepared to do some re-design work later if one thread really isn't good enough.</p>\n\n<p><strong>Style</strong></p>\n\n<p><em>In approximate order of increasing subjectivity</em></p>\n\n<p>What is up with the <code>#define gvSaveChunkToFile gvSaveChunkToFileW</code> stuff? Is this intended to ease some cross-platform stuff later, or did you just copy it from elsewhere? IMO it's ugly and potentially confusing, so I'd remove it unless it adds something really worthwhile I can't see here.</p>\n\n<p>Likewise with all the <code>GVOXEL_STATE_1_0, GVOXEL_STATE</code> stuff - unless you're really planning to have, and deal with, multiple incompatible versions of the same structure at runtime (which sounds horrible), you can isolate any backwards-compatibility logic to the (de)serialization layer and remove the duplicate names in your main code.</p>\n\n<p>You're using lots of (what I think are) platform-specific typedefs, in case you care. Maybe <code>byte</code>, <code>dword</code> etc. are idiomatic on that platform so there is a big consistency benefit, but I'm not clear what other advantage they have over the standard types like <code>char</code>, <code>int8_t</code> or <code>uint8_t</code>.</p>\n\n<p>Subjectively I'm not a big fan of Hungarian notation as used here: you're just replicating the type and not adding any semantic information.</p>\n\n<p>Finally, and again subjectively, I don't like <code>ALL_UPPER_CASE</code> type names or <code>_LEADING_UNDERSCORE_UPPER_CASE</code> symbols, they get perilously close to the <code>__RESERVED_NAMES</code> and just tend to look ugly.\nI also don't see the need to typedef every struct; <code>struct VoxelState *</code> instead of <code>GVOXEL_STATE_1_0 *</code> seems clearer and easier to read</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-02T18:18:00.970",
"Id": "10074",
"Score": "1",
"body": "Looks good! At this stage, when there seem to be some decisions which are still undecidable without more information, it may help to switch to working top-down for a bit. Sketch the game loop, or the handling for a single event you're confident you understand. That should help clarify the demands on your types; switch between top-down and bottom-up until they meet in the middle :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-04T17:21:52.040",
"Id": "10160",
"Score": "0",
"body": "Thank you very much, I've applied most of what you said and it was also good the interfacing example, which I was not completely sure about the C version, and the recommendation to switch to the sketching thing and runtime behavior programming, which sometimes I forget too and forgetting makes everything lose any sense."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-02T14:46:49.267",
"Id": "6472",
"ParentId": "6419",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "6472",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-30T18:21:05.133",
"Id": "6419",
"Score": "6",
"Tags": [
"c",
"game"
],
"Title": "Game with voxels"
}
|
6419
|
<p>I'm currently in the process of creating a online work schedule for internal use. For this, the client needs to show the days of a single week.</p>
<p>I pass a week number and a year.
From that I get the first day of that week, by using <code>strtotime()</code> passing an argument in the format <code>[year]-W[weekno]-[dayofweek]</code>. Example: <code>strtotime('2011-48W-1');</code></p>
<p>With that function I create my table as mentioned earlier:</p>
<pre><code><table class="weekly">
<thead>
<tr>
<?php for($i = 1; $i <= 7; $i++): ?>
<th><?php echo $dage[$i] . " ". date("j/m", strtotime($year.'-W'.$week.'-'.$i)); ?></th>
<?php endfor; ?>
</tr>
</thead>
<tbody>
<tr>
<?php for($i = 1; $i <= 7; $i++): ?>
<td<?php if($i == 7) { echo ' class="last"'; } ?>>
<?php
$day = date("Y-m-d", strtotime($year.'-W'.$week.'-'.$i));
if(isset($entries[$day])):
foreach($entries[$day] as $entry):
?>
<div class="workEntry" title="<?php echo $entry->note; ?>">
<span>
<?php echo date("H:i", strtotime($entry->workStart)); ?>
<?php if($entry->workStart != "0000-00-00 00:00:00") { echo " - ".date("H:i", strtotime($entry->workEnd)); } ?>
</span>
<span>
<?php if($entry->userId == 0): ?>
Unspecifed
<?php else: ?>
<?php echo $entry->name; ?>, <?php echo $entry->pgroup; ?>
<?php endif; ?>
</span>
</div>
<?php endforeach;
endif; ?>
</td>
<?php endfor; ?>
</tr>
</tbody>
</table>
</code></pre>
<p>Well, it works, but I'm pretty sure that I'm reinventing the wheel, and doing a pretty bad job at it too. I'd like to know what you think and to hear any suggestions.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-17T10:12:42.040",
"Id": "16078",
"Score": "3",
"body": "You can find a solution to a similar problem at http://stackoverflow.com/questions/186431/calculating-days-of-week-given-a-week-number"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-29T10:57:20.320",
"Id": "97499",
"Score": "4",
"body": "Your best move would be decoupling logic from presentation."
}
] |
[
{
"body": "<p>I'm not 100% sure what the rest of your code is doing, but here is the code to get the days of a specified week using date:</p>\n\n<pre><code><?php \n// Set current date\n$date = '06/29/2014';\n// Parse into a Unix timestamp\n$ts = strtotime($date);\n// Find the year and the current week\n$year = date('o', $ts);\n$week = date('W', $ts);\n?>\n</code></pre>\n\n<p>Output would be like this:</p>\n\n<blockquote>\n <p>Monday Tuesday Wednesday Thursday Friday Saturday Sunday</p>\n</blockquote>\n\n<pre><code><?php for($i = 1; $i <= 7; $i++) { ?>\n<th><?php $ts = strtotime($year.'W'.$week.$i); print date(\"l\", $ts) . \"\\n\"; ?></th>\n<?php } ?>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-29T09:44:17.663",
"Id": "55594",
"ParentId": "6422",
"Score": "5"
}
},
{
"body": "<p>Three minor notes:</p>\n\n<ol>\n<li><p>From <em>Steve McConnell</em>, <em>Code Complete 2nd Edition</em>, <em>31.2 Layout Techniques</em>, p737:</p>\n\n<blockquote>\n <p>Using blank lines is a way to indicate how a program is organized. You can use them\n to divide groups of related statements into paragraphs, to separate routines from one\n another, and to highlight comments.</p>\n</blockquote>\n\n<p>It does not make sense if all groups contain only one line.</p></li>\n<li><p><code>strtotime($year.'-W'.$week.'-'.$i)</code> is used and duplicated multiple times in the code. You could extract it out to a function to remove the duplication.</p></li>\n<li><p>If I'm right you are iterating through the days of the week with this loop:</p>\n\n<blockquote>\n<pre><code><?php for($i = 1; $i <= 7; $i++): ?>\n</code></pre>\n</blockquote>\n\n<p>Renaming <code>$i</code> to <code>$weekday</code> or something similar would make it obvious and help readers/maintainers a lot.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-29T16:58:50.177",
"Id": "55616",
"ParentId": "6422",
"Score": "12"
}
},
{
"body": "<p>There is a lot of back and forth going on here.</p>\n\n<p>I think that I would just pick PHP and write the whole thing in PHP, you would eliminate a lot of confusion and obscurity by being able to remove the <code><?php ?></code> tags from all over the place along with being able to properly indent the code.</p>\n\n<p>You don't really have to worry about indenting the HTML tags inside of the PHP code, because that is just for looks on the developers side</p>\n\n<pre><code><?php\n echo \"<table class='weekly'><thead><tr>\";\n for($i = 1; $i <= 7; $i++){\n echo \"<th>\" . $dage[$i] . \" \". date(\"j/m\", strtotime($year.'-W'.$week.'-'.$i)) . \"</th>\";\n } \n\n echo \"</tr></thead><tbody><tr>\";\n for($i = 1; $i <= 7; $i++) {\n echo \"<td\"; \n if($i == 7) { echo \" class='last'\"; } \n echo \">\";\n $day = date(\"Y-m-d\", strtotime($year.'-W'.$week.'-'.$i));\n if(isset($entries[$day])) {\n foreach($entries[$day] as $entry) {\n echo \"<div class='workEntry' title='\" . $entry->note . \"'><span>\";\n echo date(\"H:i\", strtotime($entry->workStart));\n if($entry->workStart != \"0000-00-00 00:00:00\") \n { \n echo \" - \" . date(\"H:i\", strtotime($entry->workEnd)); \n } \n echo \"</span><span>\";\n if($entry->userId == 0) {\n echo \"Unspecifed\";\n }\n else {\n echo $entry->name . \",\" . $entry->pgroup;\n } \n echo \"</span></div>\"; \n }\n } \n echo \"</td>\";\n } \n echo \"</tr></tbody></table>\";\n?>\n</code></pre>\n\n<p>all I did here was translate your HTML/PHP code mix into straight PHP, this should render the same exact page as your code.</p>\n\n<p>Sometimes it is a good idea to mix PHP into HTML, but in this instance it is a better Idea to mix your HTML into your PHP, I think you can see that by looking at this code that it is much cleaner.</p>\n\n<hr>\n\n<p>@palacsint makes a good observation about <code>strtotime($year.'-W'.$week.'-'.$i)</code> so I have created a function for this purpose even though it will only be called twice. </p>\n\n<p>in this code I also changed <code>$i</code> to <code>$weekdayNo</code> a variation of @palacsint's suggestion, I also removed a lot of whitespace, <em>probably more than @palacsint or you would have done</em>.</p>\n\n<pre><code><?php\n\n function dayOfWeek($dayNumber) {\n return strtotime($year . '-W' . $week . '-' . $dayNumber);\n } \n\n echo \"<table class='weekly'><thead><tr>\";\n for($weekdayNo = 1; $weekdayNo <= 7; $weekdayNo++){\n echo \"<th>\" . $dage[$weekdayNo] . \" \". date(\"j/m\", dayOfWeek($weekdayNo)) . \"</th>\";\n } \n\n echo \"</tr></thead><tbody><tr>\";\n for($weekdayNo = 1; $weekdayNo <= 7; $weekdayNo++) {\n echo \"<td\"; \n if($weekdayNo == 7) { echo \" class='last'\"; } \n echo \">\";\n $day = date(\"Y-m-d\", dayOfWeek($weekdayNo));\n if(isset($entries[$day])) {\n foreach($entries[$day] as $entry) {\n echo \"<div class='workEntry' title='\" . $entry->note . \"'><span>\";\n echo date(\"H:i\", strtotime($entry->workStart));\n if($entry->workStart != \"0000-00-00 00:00:00\") { \n echo \" - \" . date(\"H:i\", strtotime($entry->workEnd)); \n } \n echo \"</span><span>\";\n if($entry->userId == 0) {\n echo \"Unspecifed\";\n }\n else {\n echo $entry->name . \",\" . $entry->pgroup;\n } \n echo \"</span></div>\"; \n }\n } \n echo \"</td>\";\n } \n echo \"</tr></tbody></table>\";\n?>\n</code></pre>\n\n<p><strong>Note:</strong> I don't know where <code>$year</code> and <code>$week</code> are being declared or created so you may encounter scope issues if you don't set those up correctly.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-04T15:45:31.493",
"Id": "98723",
"Score": "1",
"body": "+50 for addressing the `<?php ?>` tags all over the place - nice answer :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-03T16:10:49.987",
"Id": "56026",
"ParentId": "6422",
"Score": "9"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-30T20:11:19.813",
"Id": "6422",
"Score": "20",
"Tags": [
"php",
"html",
"datetime"
],
"Title": "Show days of single week"
}
|
6422
|
<p>I usually spent more time on refactoring than in developing itself. But this little piece of code is really hard to refactor. I'd like to keep it as short as possible, but it's quite undarstandable:</p>
<pre><code>foreach($all_headers as $uid => $h) // Intera gli headers
{
// Is the header valid?
$isInbox = $h->to == $mailbox->address;
$hasPin = ($pin = substr($h->subject, 0, 5)) !== false && is_numeric($pin);
$hasTitle = strlen($title = trim(substr($h->subject, 5))) > 0;
$isAllowed = $hasPin && call_user_func($pincall, $mailbox->address, $h->from, $pin);
$log->info("messaggio $uid: in:$isInbox pin:$hasPin alw:$isAllowed");
// Skip this header if not vlaid
if (!$isInbox || !$hasPin || !$isAllowed) continue;
// Add some properties to current header
$h->title = $hasTitle ? $title : null;
$h->pin = $pin;
$valid_headers[$uid] = $h;
}
</code></pre>
<p>Since i'm filtering <code>$all_headers</code> array, one cool idea would be using <code>array_filter</code> with some kind of mechanism to add/remove conditions "on the fly".</p>
<p>Thank you people, as always.</p>
|
[] |
[
{
"body": "<p>This won't make it shorter, but you might consider changing the condition checking to only do the actual check if needed instead of doing all of them at once, making you loose the advantage of the short-circuiting <code>||</code> operator.</p>\n\n<p>E.g.</p>\n\n<pre><code>if (!isInbox()) continue;\nif (!hasPing()) continue;\n...\n</code></pre>\n\n<hr>\n\n<p>Another possibility, that is even less short, is to create a filtering iterator, e.g.:</p>\n\n<pre><code>class ValidHeaderIterator extends FilterIterator \n{\n private $mailbox;\n private $pincall; \n\n public function __construct($headers, $mailbox, $pincall)\n {\n $this->mailbox = $mailbox;\n $this->pincall = $pincall;\n parent::__construct(new ArrayIterator($headers));\n }\n\n public function accept()\n {\n $header = $this->getInnerIterator()->current();\n return isInbox($header) && hasPin($header) && isAllowed($header);\n }\n\n public function isInbox($header)\n {\n return $header->to == $this->mailbox->address;\n }\n\n public function hasPin($header)\n {\n $pin = $this->getPin($header);\n return $pin !== false && is_numeric($pin);\n }\n\n public function getPin($header)\n {\n return substr($header->subject, 0, 5));\n }\n\n public function isAllowed($header)\n {\n return call_user_func($this->pincall,\n $this->mailbox->address,\n $header->from,\n $this->getPin());\n }\n}\n</code></pre>\n\n<p>The calling code would then look like: </p>\n\n<pre><code>foreach(new ValidHeaderIterator($headers, $mailbox, $pincall) as $header) {\n // do stuff\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-30T21:31:35.567",
"Id": "6429",
"ParentId": "6423",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "6429",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-30T20:15:11.727",
"Id": "6423",
"Score": "1",
"Tags": [
"php",
"php5"
],
"Title": "Refactoring a loop with many boolean conditions"
}
|
6423
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.