body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>I have a class that I inherited from someone else. It is doing a P/Invoke on <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/aa363852%28v=vs.85%29.aspx" rel="nofollow">CopyFileEx</a> to copy a file (we are using UNC shares if that matters). The code is marked <code>unsafe</code> but I thought you only needed to use that when dealing with raw pointers, if you are using <code>IntPtr</code> only your code does not need to be marked unsafe.</p>
<pre><code>public void Copy()
{
bool result;
unsafe
{
if (System.Environment.OSVersion.Version.Major > 5)
{
//only newer versions of windows support the no buffer flag
//(this is set because copying large files on a computer with limited ram will pretty much kill the computer)
result = CopyFileEx(SourceFile, TargetFile, new CopyProgressRoutine(CopyProgressEvent), IntPtr.Zero, ref Cancelflag, CopyFileFlags.COPY_FILE_NO_BUFFERING);
}
else
{
result = CopyFileEx(SourceFile, TargetFile, new CopyProgressRoutine(CopyProgressEvent), IntPtr.Zero, ref Cancelflag, 0);
}
}
//file copy failed so get the DLL error and throw an exception
if (result == false)
{
Win32Exception exc = new Win32Exception(Marshal.GetLastWin32Error());
throw exc;
}
}
//xcopy file progress event handler
private CopyProgressResult CopyProgressEvent(Int64 TotalFileSize, Int64 TotalBytesTransferred, Int64 StreamSize, Int64 StreamBytesTransferred, uint dwStreamNumber,
XCopy.CopyProgressCallbackReason dwCallbackReason, IntPtr hSourceFile, IntPtr hDestinationFile, IntPtr lpData)
{
//chunk of a file finished copying
if (dwCallbackReason == XCopy.CopyProgressCallbackReason.CALLBACK_CHUNK_FINISHED)
{
int currentFilePercent = Convert.ToInt32(Math.Round(TotalBytesTransferred * 100.0 / TotalFileSize));
//only send a new message when something changes (prevents flooding of messages)
if (currentFilePercent != LastFilePercent)
{
LastFilePercent = currentFilePercent;
//Report back the progress
ProgressCallback.Report(currentFilePercent);
}
}
//stop the copy?
if (Cancelflag == 1)
return XCopy.CopyProgressResult.PROGRESS_CANCEL;
else
return XCopy.CopyProgressResult.PROGRESS_CONTINUE;
}
//win32 API call
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool CopyFileEx(string lpExistingFileName, string lpNewFileName,
CopyProgressRoutine lpProgressRoutine, IntPtr lpData, ref Int32 pbCancel,
CopyFileFlags dwCopyFlags);
//xcopy event handler
public delegate CopyProgressResult CopyProgressRoutine(
Int64 TotalFileSize,
Int64 TotalBytesTransferred,
Int64 StreamSize,
Int64 StreamBytesTransferred,
uint dwStreamNumber,
CopyProgressCallbackReason dwCallbackReason,
IntPtr hSourceFile,
IntPtr hDestinationFile,
IntPtr lpData);
</code></pre>
<p>I think the <code>unsafe</code> is not needed but the person who wrote this originally claims he was getting intermittent errors during run-time when in production environments when it was not marked unsafe.</p>
<p>Was he right about needing <code>unsafe</code> or did he have a problem elsewhere that was just fixed at the same time that made it look like <code>unsafe</code> fixed the issue?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-04T21:16:50.130",
"Id": "38200",
"Score": "0",
"body": "Are you sure just using `System.Environment.OSVersion.Version.Major > 5` is okay? What happens if the program is run on another OS (say Unix)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-04T21:18:49.617",
"Id": "38201",
"Score": "3",
"body": "@Clockwork-Muse then I got much bigger problems when `[DllImport(\"kernel32.dll\", SetLastError = true, CharSet = CharSet.Auto)]` fails. This application is for internal office use, we do not have any non windows workstations this program could be run on."
}
] |
[
{
"body": "<p><code>unsafe</code> is purely a compile-time check. If it were needed the code wouldn’t compile. The runtime errors are caused by something else.</p>\n\n<p>Furthermore, <code>unsafe</code> is needed if and only if you are using unmanaged pointers (e.g. inside a <code>fixed</code> block).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-04T21:23:49.890",
"Id": "38203",
"Score": "0",
"body": "Actually, there is one other situation where `unsafe` is required: when using `fixed` buffers."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-04T21:02:19.923",
"Id": "24731",
"ParentId": "24730",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "24731",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-04T20:30:24.780",
"Id": "24730",
"Score": "2",
"Tags": [
"c#"
],
"Title": "Is this \"unsafe\" declaration unnecessary?"
}
|
24730
|
<p>In my Blackjack game so far, I have multiple classes that access each other frequently. For example, this is my <code>hit()</code> function for the <code>Game</code> class:</p>
<pre><code>void Game::hit(unsigned playerNum)
{
Card newCard = deck.deal();
players[playerNum].getPlayerHand()[0].getHandCards().push_back(newCard);
}
</code></pre>
<p>First, a new <code>Card</code> object is assigned a new card from the <code>Deck</code> object. However, the next line gets more complicated. Essentially:</p>
<ol>
<li><p>The specified player's <code>Hand</code> object vector is accessed. As such, it needs an index. I'm doing this so that I can easily destroy hands without looping.</p>
<pre><code>players[playerNum].getPlayerHand()[0]
</code></pre></li>
<li><p>In that one <code>Hand</code> object in the vector, its card vector is accessed.</p>
<pre><code>players[playerNum].getPlayerHand()[0].getHandCards()
</code></pre></li>
<li><p>That aforementioned card is pushed onto the player's hand card vector.</p>
<pre><code>players[playerNum].getPlayerHand()[0].getHandCards().push_back(newCard);
</code></pre></li>
</ol>
<p>Again, I'm using a <code>Hand</code> object so that I can easily destroy a player's cards at the end of each turn. In the game, different players can end up with a different number of cards at the end of each turn. If I assign each player a vector of cards instead, I would have to loop through the vector and pop each card. With a <code>Hand</code>, I can just pop the <code>Hand</code> and push a new one. However, using a <code>Hand</code> class here means more accessing, which complicates the code's flow.</p>
<p>What would be a good solution to this? I'm okay with either method (preferably the one with <code>Hand</code>), but they do have their pros and cons. If there is a better solution, I'd like to know about it.</p>
<p>Here are snippets of the relevant class' headers:</p>
<p><strong>Game.h</strong></p>
<pre><code>class Game
{
private:
std::vector<Player> players;
Deck deck;
public:
Game();
~Game();
};
</code></pre>
<p><strong>Player.h</strong></p>
<pre><code>class Player
{
private:
std::vector<Hand> playerHand;
public:
Player();
~Player();
std::vector<Hand>& getPlayerHand() {return playerHand;}
};
</code></pre>
<p><strong>Hand.h</strong></p>
<pre><code>class Hand
{
private:
std::vector<Card> cards;
public:
Hand();
~Hand();
std::vector<Card>& getHandCards() {return cards;}
};
</code></pre>
<p><strong>Card.h</strong></p>
<pre><code>class Card
{
private:
int rankValue;
char rank;
char suit;
std::string card;
public:
Card();
Card(char, char);
~Card();
};
</code></pre>
|
[] |
[
{
"body": "<p>This code:</p>\n\n<pre><code>void Game::hit(unsigned playerNum)\n{\n Card newCard = deck.deal();\n players[playerNum].getPlayerHand()[0].getHandCards().push_back(newCard);\n}\n</code></pre>\n\n<p>should read:</p>\n\n<pre><code>void Game::hit(unsigned playerNum)\n{\n Card newCard = deck.deal();\n players[playerNum].hit(newCard);\n}\n</code></pre>\n\n<p>The thing is, your classes shouldn't access each other like that. You shouldn't have getter methods that return the internal vectors. You should have methods that perform operations. If you do that, I think your question won't even come up.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-04T22:35:00.827",
"Id": "38206",
"Score": "0",
"body": "@JamalA, huh? Nothing I changed should be related to whether or not `Game::hit` is public."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-04T22:36:47.693",
"Id": "38207",
"Score": "0",
"body": "Sorry, that comment was submitted early on accident. Anyway, I'll take a look at how this could be changed since it doesn't work as it is."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-04T22:37:34.667",
"Id": "38208",
"Score": "0",
"body": "@JamalA, right, I'm assuming that you'll add a Player::hit function."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-04T22:38:58.347",
"Id": "38209",
"Score": "0",
"body": "Yes, I can do that. Regarding that, I'm not exactly sure how to \"distribute\" my functions among classes. I'll go ahead and post all the functions for Game and Player that I have so far."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-04T22:28:14.743",
"Id": "24736",
"ParentId": "24732",
"Score": "2"
}
},
{
"body": "<p>There appears to be some verbosity in these classes:</p>\n\n<ul>\n<li><p>The default constructor and destructor declarations are unneeded as the compiler will generate default ones automatically, which are still suitable for this use.</p></li>\n<li><p>The <code>rankVal</code> member doesn't quite belong to <code>Card</code>. The implementation will need to provide this value since it can vary among different games.</p></li>\n<li><p><code>Card</code> doesn't need a <code>card</code> member. It only needs <code>rank</code> and <code>suit</code> since they both help <em>define</em> the properties of a <code>Card</code>. Any member function that will return the value or display a <code>Card</code> should simply put these two data members together in some way.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-03T21:19:25.300",
"Id": "58957",
"ParentId": "24732",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "24736",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-04T21:28:29.560",
"Id": "24732",
"Score": "3",
"Tags": [
"c++",
"object-oriented",
"playing-cards"
],
"Title": "Accessing multiple data members in Blackjack classes"
}
|
24732
|
<p>I run into this often. I have two functions very similar, that if I combine would be more DRY but if I didn't would be easier to read and make more sense.</p>
<p>In this case I have two implementations of fade, one using <code>setInterval</code> and one using <code>setTimeout</code>.</p>
<p>How do I not get stuck deciding between Dry vs. readability. I hope this is not an opinion question that is not answerable.</p>
<pre><code> /*fade
** d:none
** n:uses setTimeout
**
*/
NS.prototype.fade = function (direction, max_time) {
var statics = {},
elements = this;
statics.elapsed = 0;
statics.granularity = 10;
if (statics.timeout_id) {
clearTimeout(statics.timeout_id);
}
(function next() {
var kindex,
opacity;
statics.elapsed += statics.granularity;
if (direction === 'up') {
for (kindex in elements) {
if (elements.hasOwnProperty(kindex)) {
opacity = statics.elapsed / max_time;
elements[kindex].style.opacity = opacity;
}
}
} else if (direction === 'down') {
for (kindex in elements) {
if (elements.hasOwnProperty(kindex)) {
elements[kindex].style.opacity = (max_time - statics.elapsed) / max_time;
}
}
}
if (statics.elapsed < max_time) {
statics.timeout_id = setTimeout(next, statics.granularity);
}
}());
};
/*fadeL
** d:none
** n:(L)inear. Uses setInterval. Better for short animations.
**
*/
NS.prototype.fadeL = function (direction, max_time) {
var statics = {},
elements = this;
statics.elapsed = 0;
statics.granularity = 10;
if (statics.timeout_id) {
clearInterval(statics.timeout_id);
}
(function next() {
var kindex,
opacity;
statics.elapsed += statics.granularity;
if (!statics.timeout_id) {
statics.timeout_id = setInterval(next, statics.granularity);
}
if (direction === 'up') {
for (kindex in elements) {
if (elements.hasOwnProperty(kindex)) {
opacity = statics.elapsed / max_time;
elements[kindex].style.opacity = opacity;
}
}
} else if (direction === 'down') {
for (kindex in elements) {
if (elements.hasOwnProperty(kindex)) {
elements[kindex].style.opacity = (max_time - statics.elapsed) / max_time;
}
}
}
if (statics.elapsed > max_time) {
clearInterval(statics.timeout_id);
}
}());
};
</code></pre>
|
[] |
[
{
"body": "<p>It's generally a good idea to remove duplication wherever possible. If you have two functions that are <strong>logically</strong> similar, but don't share code, you run the risk of <strong>code rot</strong> - updating one function and forgetting to apply similar changes to the other.</p>\n\n<p>There are a few ways I would suggesting working around this without sacrificing too much readability.</p>\n\n<ol>\n<li>Find common parts of each function and refactor them out into their\nown sub-functions </li>\n<li>Use higher-order functions to inject the unique\nlogic into a more generic base function</li>\n</ol>\n\n<p>I hardly know Javascript at all, so I can't be too specific on how to handle this case, but it looks like you only have a very small amount of code that isn't shared.</p>\n\n<pre><code>if (statics.timeout_id) {\n clearTimeout(statics.timeout_id); // fade\n clearInterval(statics.timeout_id); // fadeL\n}\n\n// .. snip ..\n\n// Added in fadeL\nif (!statics.timeout_id) {\n statics.timeout_id = setInterval(next, statics.granularity);\n}\n\n// .. snip ..\n\nif (statics.elapsed < max_time) { // fade\nif (statics.elapsed > max_time) { // fadeL\n statics.timeout_id = setTimeout(next, statics.granularity); // fade\n clearInterval(statics.timeout_id); // fadeL\n}\n</code></pre>\n\n<p>A really simple approach would be to make a base function that accepts a boolean value to differentiate between the slight changes in behavior:</p>\n\n<pre><code>NS.prototype.base_fade = function (direction, max_time, is_fade_l) {\n var statics = {},\n elements = this;\n statics.elapsed = 0;\n statics.granularity = 10;\n if (statics.timeout_id) {\n if (is_fade_l) { \n clearInterval(statics.timeout_id); \n } else { \n clearTimeout(statics.timeout_id); \n }\n } \n (function next() {\n var kindex,\n opacity;\n statics.elapsed += statics.granularity;\n if (is_fade_l && !statics.timeout_id) {\n statics.timeout_id = setInterval(next, statics.granularity);\n }\n if (direction === 'up') {\n for (kindex in elements) {\n if (elements.hasOwnProperty(kindex)) {\n opacity = statics.elapsed / max_time;\n elements[kindex].style.opacity = opacity;\n }\n }\n } else if (direction === 'down') {\n for (kindex in elements) {\n if (elements.hasOwnProperty(kindex)) {\n elements[kindex].style.opacity = (max_time - statics.elapsed) / max_time;\n }\n }\n }\n if (is_fade_l) {\n if (statics.elapsed > max_time) {\n clearInterval(statics.timeout_id);\n }\n } else {\n if (statics.elapsed < max_time) {\n statics.timeout_id = setTimeout(next, statics.granularity);\n }\n }\n }());\n};\n</code></pre>\n\n<p>Then call that function from <code>fade</code> and <code>fadeL</code> providing the correct boolean. This way, at least, you have a guarantee that the code that is logically the same will stay the same. It also takes up less space in your codebase, and doesn't require all that much more parsing to understand it mentally.</p>\n\n<p>You might be able to get more modular with this, and refactor some elements out into their own functions, but my own lack of knowledge of the language and the codebase means I'm not quite up to suggesting those changes. In general though, <strong>try to consolidate logically equivalent code wherever you can</strong>. It will make your life easier in the long run.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-04T22:42:25.977",
"Id": "24737",
"ParentId": "24734",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "24737",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-04T21:39:44.003",
"Id": "24734",
"Score": "2",
"Tags": [
"javascript"
],
"Title": "Concept - DRY code vs. Readable code?"
}
|
24734
|
<p>This is a follow-up to <a href="https://codereview.stackexchange.com/questions/24499/code-tidying-up">this</a> question my code has evolved since so I'm reposting my question.</p>
<p>What is the best way to tidy this up? How can this be refined? I am finding it's thrashing the layout quite a lot and the scroll function seems to lag.</p>
<pre><code>;(function ($, window) {
var main = $("#swab"),
sbContainer = $("#sb-container"),
sbContainerDiv = sbContainer.find("div"),
tblcontents = $('#tblcontents'),
tblcontentstwo = $('#tblcontents_2'),
button = $('#wrap_return, .thumb, #tblcontents'),
slideele = $('.site, .menu-panel'),
slideele2 = $('.site, .menu-panel_2');
function animate() {
sbContainerDiv.css({
"transform": "rotate(0deg)",
"-webkit-transform": "rotate(0deg)",
"-ms-transform": "rotate(0deg)",
"-moz-transform": "rotate(0deg)",
"-o-transform": "rotate(0deg)"
});
main.animate({
"right": "1%",
"left": "auto",
"top": "4px"
}, "slow");
}
function toggletwo() {
var toggleStatetwo = true;
$(tblcontents).on("click", function () {
if (toggleStatetwo) {
animate({
"top": "15%"
});
main.fadeOut(1000);
} else {
animate();
main.fadeIn(1000);
}
toggleStatetwo = !toggleStatetwo;
});
}
function toggleone() {
$(tblcontents).on("click", function () {
main.stop(true, true).animate();
});
}
var $window = $(window);
$window.resize(function () {
if (this.resizeTO) clearTimeout(this.resizeTO);
this.resizeTO = setTimeout(function () {
$(this).trigger('resizeEnd');
}, 500);
});
$window.on('resizeEnd', function () {
var winWidth = $window.width();
if (winWidth < 960) {
toggletwo();
animate();
} else {
toggleone();
}
});
$(document).scroll(function () {
animate();
});
var toggleState = true;
$('#toggle_div').on("click", function () {
if (toggleState) {
main.animate({
"right": "50%"
}, "slow");
} else {
main.animate({
"right": "1%",
"top": "4px"
}, "slow");
main.css("left", "auto");
}
toggleState = !toggleState;
});
$(tblcontents).effect("pulsate", {
times: 100
}, 2000).on('click', function () {
$(this).effect().stop(true, true);
$(this).animate({
"opacity": "1"
}, "fast");
});
$(button).on("click", function () {
animate({
"top": "4px"
}, "slow");
});
main.draggable()
$(function () {
sbContainer.swatchbook({
center: 6,
angleInc: 20,
speed: 700,
easing: 'ease',
proximity: 120,
neighbor: 20,
onLoadAnim: true,
initclosed: true,
closeIdx: 11,
openAt: -1
});
});
var toggleStatemenu2 = true;
$(tblcontentstwo).on("click", function () {
if (toggleStatemenu2) {
$(slideele2).animate({
top: '+=171'
}, 458, 'swing', function () {});
} else {
$(slideele2).animate({
top: '-=171'
}, 458, 'swing', function () {});
}
toggleStatemenu2 = !toggleStatemenu2;
});
var toggleStatemenu = true;
$(tblcontents).on("click", function () {
if (toggleStatemenu) {
$(slideele).animate({
left: '+=240'
}, 458, 'swing', function () {});
} else {
$(slideele).animate({
left: '-=240'
}, 458, 'swing', function () {});
}
toggleStatemenu = !toggleStatemenu;
});
})(jQuery, window, document);
</code></pre>
|
[] |
[
{
"body": "<p>Interesting question:</p>\n\n<p><strong>Naming</strong></p>\n\n<ul>\n<li>JavaScript uses lowerCamelCase variable and function names. ( <code>tblcontentstwo</code> -> <code>TblContentsTwo</code> or <code>TabelContents2</code></li>\n<li>Some of your prefixes like <code>sb</code> are not adding anything. I would drop those prefixes.</li>\n<li>Names like <code>slideele2</code> are unfortunate, ideally the name should reflect what is being slided (slid?)</li>\n</ul>\n\n<p><strong>Comments</strong></p>\n\n<ul>\n<li>You have no comments whatsoever, fortunately the code reads well</li>\n<li>Still, in some places, like <code>sbContainer.swatchbook(</code>, I have no clue what you are trying to accomplish</li>\n</ul>\n\n<p><strong>JSHint.com</strong></p>\n\n<ul>\n<li>Your code passes all checks, except for 1 semicolon, well done ;)</li>\n</ul>\n\n<p><strong>Readability</strong></p>\n\n<ul>\n<li>You don't use newlines consistently, more specifically you need more newlines in a few spots</li>\n<li>Also your indentation is off in places, I would use a site like <a href=\"http://jsbeautifier.org/\" rel=\"nofollow noreferrer\">http://jsbeautifier.org/</a></li>\n</ul>\n\n<p><strong>Don't Repeat Yourself</strong></p>\n\n<ul>\n<li><p>This looks like copy pasted code:</p>\n\n<pre><code>var toggleStatemenu2 = true;\n$(tblcontentstwo).on(\"click\", function () {\nif (toggleStatemenu2) {\n $(slideele2).animate({\n top: '+=171'\n }, 458, 'swing', function () {});\n} else {\n $(slideele2).animate({\n top: '-=171'\n }, 458, 'swing', function () {});\n}\ntoggleStatemenu2 = !toggleStatemenu2;\n});\nvar toggleStatemenu = true;\n$(tblcontents).on(\"click\", function () {\nif (toggleStatemenu) {\n $(slideele).animate({\n left: '+=240'\n }, 458, 'swing', function () {});\n} else {\n $(slideele).animate({\n left: '-=240'\n }, 458, 'swing', function () {});\n}\ntoggleStatemenu = !toggleStatemenu;\n});\n</code></pre>\n\n<p>you could try to make a helper function there.</p>\n\n<pre><code>var toggleStates = {};\n\nfunction createSlider( button, slider, animation1, animation2 ){\n toggleStates[button.id] = true;\n $(button).on(\"click\", function () {\n if (toggleStates[button.id]) {\n $(slider).animate(animation, 458, 'swing', function () {});\n } else {\n $(slider).animate(animation2, 458, 'swing', function () {});\n }\n toggleStates[button.id] = !toggleStates[button.id];\n }\n}\ncreateSlider(tblcontentstwo, slideele2, {top: '+=171'}, {top: '-=171'} );\ncreateSlider(tblcontents, slideele, {left: '+=240'}, {left: '-=240'} );\n</code></pre></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-01-11T20:42:24.830",
"Id": "152388",
"ParentId": "24739",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-04T23:52:57.337",
"Id": "24739",
"Score": "2",
"Tags": [
"javascript",
"jquery",
"animation",
"wordpress"
],
"Title": "jQuery eye candy for a WordPress site"
}
|
24739
|
<p>I wrote an HTTP server for the management of scores for users and levels.</p>
<p>It can return the highest score per level. It has a simple login with session-key.</p>
<p>What do you think could be improved in this code? What's wrong? And particularly, are there any multi-threading issues that I didn't take into account?</p>
<pre><code>//**********************************************************
//
// Http Server
//
// Author: Bombo Gongo
//
// Class purpose: demonstration of an http server
//
//*********************************************************
package org.bombo.server;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;
import com.sun.net.httpserver.HttpContext;
import com.sun.net.httpserver.HttpServer;
public class Main {
private static int port = 8009;
public static void main(String[] args) throws IOException {
// Create an http server
HttpServer server = HttpServer.create(new InetSocketAddress(port), 0);
// Create a context
HttpContext context = server.createContext("/", new RequestsHandler());
// Add a filter
context.getFilters().add(new ParamsFilter());
// Set an Executor for the multi-threading
server.setExecutor(Executors.newCachedThreadPool());
// Start the server
server.start();
System.out.println("The server is started!");
}
}
//**********************************************************
//
// Http Server
//
// Author: Bombo Gongo
//
// Class purpose: filter to set the request parameters
//
//*********************************************************
package org.bombo.server;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
import org.bombo.util.MiscUtils;
import com.sun.net.httpserver.*;
public class ParamsFilter extends Filter {
MiscUtils utils;
public ParamsFilter() {
utils = new MiscUtils();
}
/*
* Usage: filter the request before to be handled and prepare the
* parameters
*
* Input:
* exchange = request/response object
*
*/
@Override
public void doFilter(HttpExchange exchange, Chain chain)
throws IOException {
parseGetParameters(exchange);
parsePostParameters(exchange);
parseUrlEncodedParameters(exchange);
chain.doFilter(exchange);
}
/*
* Usage: retrieve the GET parameters
*
* Input:
* exchange = request/response object
*
*/
private void parseGetParameters(HttpExchange exchange)
throws UnsupportedEncodingException {
Map<String, Object> parameters = new HashMap<String, Object>();
URI requestedUri = exchange.getRequestURI();
String query = requestedUri.getRawQuery();
utils.parseQuery(query, parameters);
exchange.setAttribute("parameters", parameters);
}
/*
* Usage: retrieve the POST parameters
*
* Input:
* exchange = request/response object
*
*/
private void parsePostParameters(HttpExchange exchange)
throws IOException {
if ("post".equalsIgnoreCase(exchange.getRequestMethod())) {
@SuppressWarnings("unchecked")
Map<String, Object> parameters =
(Map<String, Object>)exchange.getAttribute("parameters");
InputStreamReader isr =
new InputStreamReader(exchange.getRequestBody(),"utf-8");
BufferedReader br = new BufferedReader(isr);
String query = br.readLine();
utils.parseQuery(query, parameters);
}
}
/*
* Usage: retrieve the URL encoded parameters
*
* Input:
* exchange = request/response object
*
*/
private void parseUrlEncodedParameters(HttpExchange exchange)
throws UnsupportedEncodingException {
@SuppressWarnings("unchecked")
Map<String, Object> parameters =
(Map<String, Object>)exchange.getAttribute("parameters");
String uri = exchange.getRequestURI().toString();
String[] tokens = uri.split("[/?=]");
if(tokens.length > 2) {
if(tokens[2].equals("score") || tokens[2].equals("highscorelist")) {
parameters.put("levelid", tokens[1]);
parameters.put("request",tokens[2]);
} else if(tokens[2].equals("login")) {
parameters.put("userid", tokens[1]);
parameters.put("request",tokens[2]);
}
else {
parameters.put("request","not supported");
}
}
else {
parameters.put("request","not supported");
}
}
@Override
public String description() {
return "Class to retrieve Get/Post parameters";
}
}
//**********************************************************
//
// Http Server
//
// Author: Bombo Gongo
//
// Class purpose: handler of a request (every handler instance is a thread)
//
//*********************************************************
package org.bombo.server;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;
import com.sun.net.httpserver.*;
import org.bombo.data.*;
class RequestsHandler implements HttpHandler {
/*
* Usage: handle a client request
*
* Input:
* exchange = request/response object
*
*/
public void handle(HttpExchange exchange) throws IOException {
String response = null;
int statusCode = 200;
try {
@SuppressWarnings("unchecked")
Map<String, Object> params = (Map<String, Object>)exchange.getAttribute("parameters");
if (params.get("request").equals("login")) {
// The user is logging-in, asking for a session key
System.out.println("New login request received for the user" +
(String)params.get("userid"));
response = SessionSingleton.getInstance().getSessionKey(
Integer.parseInt((String)params.get("userid")));
if(response == null) statusCode = 500; // Server error
}
else if (params.get("request").equals("score")) {
// A new store has been received to be stored
System.out.println("New request received to save the score" +
(String)params.get("score"));
int userId = SessionSingleton.getInstance().validateSessionKey(
(String)params.get("sessionkey"));
if (userId == -1)
statusCode = 401; // Unhautorized user
else if(ScoreSingleton.getInstance().insertScore(
userId, Integer.parseInt((String)params.get("levelid")),
Integer.parseInt((String)params.get("score"))) == -1)
statusCode = 500; // Server error
}
else if (params.get("request").equals("highscorelist")) {
// A list of the best scores has been requested
System.out.println("Received a new request for the highest scores" +
"the level " + (String)params.get("levelid"));
response = ScoreSingleton.getInstance().getHighestScores(
Integer.parseInt((String)params.get("levelid")));
// This is a header to permit the download of the csv
Headers headers = exchange.getResponseHeaders();
headers.add("Content-Type", "text/csv");
headers.add("Content-Disposition", "attachment;filename=myfilename.csv");
}
else {
response = "Method not implemented";
System.out.println(response);
statusCode = 400; // Request type not implemented
}
}
catch (NumberFormatException exception) {
statusCode = 400;
response = "Wrong number format";
System.out.println(response);
}
catch (Exception exception) {
statusCode = 400;
response = exception.getMessage().toString();
System.out.println(response);
}
// Send the header response
if (response != null)
exchange.sendResponseHeaders(statusCode, response.length());
else
exchange.sendResponseHeaders(statusCode, 0);
// Send the body response
OutputStream os = exchange.getResponseBody();
os.write(response.toString().getBytes());
os.close();
}
}
//**********************************************************
//
// Http Server
//
// Author: Bombo Gongo
//
// Class purpose: contain common math functionalities
//
//*********************************************************
package org.bombo.util;
import java.math.BigInteger;
import java.security.SecureRandom;
public class MathUtil {
/*
* SecureRandom guarantee secure random strings, very hard to hack, but
* the initialization is expensive and for this reason we are making
* it static.
*/
static private SecureRandom random = new SecureRandom();
/*
* Usage: create a new session key
*
* Returns:
* Session key
*/
public String createSessionKey() {
return new BigInteger(130, random).toString(32);
}
/*
* Usage: chek if a string is a positive integer and convert it
*
* Input:
* str = string containing a number
*
* Returns:
* -1 The string doesn't contain a valid positive integer
* n The converted number
*/
public int getPositiveInt(String str) {
int retInt = -1;
try {
retInt = Integer.parseInt(str);
if (retInt < 0) {
// Non positive integer
return -1;
}
}
catch(NumberFormatException nfe) {
// Exception because the input is not a number
System.out.println("Error: " + nfe.getMessage());
return -1;
}
return retInt;
}
}
//**********************************************************
//
// Http Server
//
// Author: Bombo Gongo
//
// Class purpose: contain common util functionalities
//
//*********************************************************
package org.bombo.util;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Map;
public class MiscUtils {
/*
* Usage: parse a query string in the format key=value&key=value and
* retrieve the values
*
* Input:
* query = query string
* parameters (out) = list of key-value parameters
*
*/
public void parseQuery(String query, Map<String, Object> parameters)
throws UnsupportedEncodingException {
if (query != null) {
String pairs[] = query.split("[&]");
for (String pair : pairs) {
String param[] = pair.split("[=]");
String key = null;
String value = null;
if (param.length > 0) {
// Retrieve the key
key = URLDecoder.decode(param[0],
System.getProperty("file.encoding"));
}
if (param.length > 1) {
// Retrieve the value
value = URLDecoder.decode(param[1],
System.getProperty("file.encoding"));
}
parameters.put(key.toLowerCase(), value);
}
}
}
}
//**********************************************************
//
// Http Server
//
// Author: Bombo Gongo
//
// Class purpose: Comparator implementation to order a score list
//
//*********************************************************
package org.bombo.util;
import java.util.Comparator;
import java.util.Map;
public class ScoreComparator implements Comparator<Integer> {
Map<Integer, Integer> base;
public ScoreComparator(Map<Integer, Integer> base) {
this.base = base;
}
public int compare(Integer a, Integer b) {
return -(base.get(a).compareTo(base.get(b)));
}
}
//**********************************************************
//
// Http Server
//
// Author: Bombo Gongo
//
// Class purpose: Store and manage scores by level and user
//
//*********************************************************
package org.bombo.data;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import org.bombo.util.ScoreComparator;;
public class ScoreSingleton
{
static private ScoreSingleton singletonInstance;
volatile private Map<Integer,Map<Integer,List<Integer>>> users;
final int numHighestScores;
private ScoreSingleton()
{
// Thread safe data structure to store user->Level->Score informations
users = new ConcurrentHashMap<Integer,Map<Integer,List<Integer>>>();
numHighestScores = 15; // Max num of high scores to be returned
}
/*
* Usage: return an instance of the singleton
*
* Returns:
* Singleton instance
*/
static public ScoreSingleton getInstance()
{
if ( singletonInstance == null )
singletonInstance = new ScoreSingleton();
return singletonInstance;
}
/*
* Usage: permit to insert a score for a user, in a specific level
*
* Input:
* user = user id
* level = level id
* score = last score
*
* Returns:
* -1 Error
* 0 Score added
*/
public int insertScore(int user, int level, int score) {
List<Integer> addScore = null;
if (user < 0 || level < 0 || score < 0) {
// The parameters are not valid
return -1;
}
synchronized(users) {
// this block is synchronized because this is not an atomic operation
if (users.containsKey(user)) {
// Existing user
Map<Integer,List<Integer>> storedUserLevels = users.get(user);
if (storedUserLevels.containsKey(level)) {
// Existing level
List<Integer> storedScores = storedUserLevels.get(level);
storedScores.add(score);
}
else {
// New level for existing user
addScore = Collections.synchronizedList(
new ArrayList<Integer>());
addScore.add(score);
storedUserLevels.put(level, addScore);
users.put(user, storedUserLevels);
}
} else {
// New user
Map<Integer,List<Integer>> addLevel =
new ConcurrentHashMap<Integer,List<Integer>>();
addScore = Collections.synchronizedList(new ArrayList<Integer>());
addScore.add(score);
addLevel.put(level, addScore);
users.put(user, addLevel);
}
}
return 0;
}
/*
* Usage: Get the n highest scores for a specific level (max 1 result per user)
*
* Input:
* level = level id
*
* Returns:
* null No score found
* String containing the list of scores
*/
public String getHighestScores(int level) {
Iterator<Integer> userIter = null;
Map<Integer,Integer> scoreResults = new TreeMap<Integer,Integer>();
int user = 0;
Integer userMaxScore = 0;
synchronized(users) {
// this block is synchronized because of the iterator
userIter = users.keySet().iterator();
while(userIter.hasNext()) { // Search the highest score for each user
user = userIter.next().intValue();
if (users.get(user) != null &&
users.get(user).get(level) != null &&
users.get(user).get(level).size() > 0) {
// I enter here if there is a score for this user at the requested level
userMaxScore = Collections.max(users.get(user).get(level));
scoreResults.put(user,userMaxScore); // Get only the highest score
}
}
}
return retrieveBestScores(scoreResults);
}
/*
* Usage: Order a list with the best scores and prepare a CSV string
*
* Input:
* scores = list of the best scores (not ordered)
*
* Returns:
* null No scores
* String containing the best scores (in inverse order)
* (format: user=score\r\nuser=score...)
*/
private String retrieveBestScores(Map<Integer,Integer> scores) {
int user = 0;
int contRes = 0;
String resScores = null;
// Map to order the scores by value (in desc order)
TreeMap<Integer,Integer> sortedScores =
new TreeMap<Integer,Integer>(new ScoreComparator(scores));
sortedScores.putAll(scores);
Iterator<Integer> scoreIter = sortedScores.keySet().iterator();
// I read all the scores starting from the highest
while(scoreIter.hasNext()) {
user = scoreIter.next();
if (resScores == null)
resScores = user + "=" + sortedScores.get(user).intValue() + "\r\n";
else
resScores += user + "=" + sortedScores.get(user).intValue() + "\r\n";
if (++contRes >= numHighestScores) break; // Once got the max num of scores, exits
}
return resScores;
}
}
//**********************************************************
//
// Http Server
//
// Author: Bombo Gongo
//
// Class purpose: java bean to store info related to a single session
//
//*********************************************************
package org.bombo.data;
public class Session {
long storedTime; // The time this session has been created
int user; // User associated to this session
public Session(long storedTime, int user) {
this.storedTime = storedTime;
this.user = user;
}
public long getStoredTime() {
return storedTime;
}
public void setStoredTime(long storedTime) {
this.storedTime = storedTime;
}
public int getUser() {
return user;
}
public void setUser(int user) {
this.user = user;
}
}
//**********************************************************
//
// Http Server
//
// Author: Bombo Gongo
//
// Class purpose: create and manage the session keys for the users
//
//*********************************************************
package org.bombo.data;
import java.util.Calendar;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.bombo.util.MathUtil;
public class SessionSingleton
{
static private SessionSingleton singletonInstance;
volatile private Map<String,Session> usedSessionKeys;
private MathUtil calc;
private long lastCleanup;
private final long cleanupEverySecs;
private final long maxSessionInSecs;
private SessionSingleton()
{
usedSessionKeys = new ConcurrentHashMap<String,Session>();
Calendar cal = Calendar.getInstance();
calc = new MathUtil();
lastCleanup = cal.getTimeInMillis();
cleanupEverySecs = 1000 * 60 * 15; // 15 minutes
maxSessionInSecs = 1000 * 60 * 10; // 10 minutes
}
/*
* Usage: return an instance of the singleton
*
* Returns:
* Singleton instance
*/
static public SessionSingleton getInstance()
{
if ( singletonInstance == null )
singletonInstance = new SessionSingleton();
return singletonInstance;
}
/*
* Usage: return a new session key
*
* Input:
* user = user id
*
* Returns:
* null Error
* String containing a new session key in base 32
*/
public String getSessionKey(int user)
{
if (user < 0) return null;
Calendar cal = Calendar.getInstance();
Session session = new Session(cal.getTimeInMillis(), user);
String sessionKey = calc.createSessionKey();
usedSessionKeys.put(sessionKey, session);
return sessionKey;
}
/*
* Usage: validate a session key and check if a session is still valid
*
* Input:
* sessionKey = base 32 session key string
*
* Returns:
* -1 Error
* user id associated to the session
*/
public int validateSessionKey(String sessionKey)
{
if (sessionKey == null || sessionKey == "")
return -1;
Calendar cal = Calendar.getInstance();
Session session = usedSessionKeys.get(sessionKey);
long currentTime = cal.getTimeInMillis();
if (session == null) {
// SessionKey not valid
return -1;
} else if (currentTime - session.getStoredTime() > maxSessionInSecs) {
// Session elapsed
return -1;
}
if (currentTime - lastCleanup > cleanupEverySecs)
doCleanup();
// Valid session
return session.getUser();
}
/*
* Usage: clean the list from unused session key
*/
private void doCleanup() {
Calendar cal = Calendar.getInstance();
lastCleanup = cal.getTimeInMillis();
Iterator<String> iter = usedSessionKeys.keySet().iterator();
String key = "";
while(iter.hasNext()) { // For each seassion...
key = iter.next();
if (lastCleanup - usedSessionKeys.get(key).getStoredTime() > maxSessionInSecs) {
usedSessionKeys.remove(key);
}
}
}
}
</code></pre>
<p>Oh, and here are some unit tests, if they help:</p>
<pre><code>package org.bombo.data;
import junit.framework.TestCase;
public class ScoreSingletonTest extends TestCase {
public void testGetHighestScores() {
ScoreSingleton.getInstance().insertScore(1, 14, 18);
ScoreSingleton.getInstance().insertScore(12, 3, 12455);
ScoreSingleton.getInstance().insertScore(18, 3, 3444);
assertEquals("12=12455\r\n18=3444\r\n", ScoreSingleton.getInstance().getHighestScores(3));
ScoreSingleton.getInstance().insertScore(12, 4, 88);
ScoreSingleton.getInstance().insertScore(18, 4, 99);
ScoreSingleton.getInstance().insertScore(18, 6, 34);
assertEquals("18=99\r\n12=88\r\n", ScoreSingleton.getInstance().getHighestScores(4));
ScoreSingleton.getInstance().insertScore(18, 44, 33);
ScoreSingleton.getInstance().insertScore(12, 5, 111);
ScoreSingleton.getInstance().insertScore(18, 5, 120);
assertEquals("18=120\r\n12=111\r\n", ScoreSingleton.getInstance().getHighestScores(5));
assertEquals(null, ScoreSingleton.getInstance().getHighestScores(88));
}
public void testInsertScore() {
assertEquals(0, ScoreSingleton.getInstance().insertScore(11, 12, 18));
assertEquals(-1, ScoreSingleton.getInstance().insertScore(-11, 10, 8));
assertEquals(-1, ScoreSingleton.getInstance().insertScore(11, -10, 8));
assertEquals(-1, ScoreSingleton.getInstance().insertScore(11, 10, -8));
}
}
package org.bombo.data;
import junit.framework.TestCase;
public class SessionsSingletonTest extends TestCase {
public void testGetSessionKey() {
for (int i=0; i < 100; ++i)
assertEquals(true, SessionSingleton.getInstance().getSessionKey(5).matches("[0-9a-z]+"));
}
public void testValidateSessionKey() {
String sessionKey = "";
for (int i=0; i < 100; ++i) {
sessionKey = SessionSingleton.getInstance().getSessionKey(6);
assertEquals(6, SessionSingleton.getInstance().validateSessionKey(sessionKey));
}
}
}
package org.bombo.util;
import org.bombo.util.MathUtil;
import junit.framework.TestCase;
public class MathUtilTest extends TestCase {
public void testCreateSessionKey() {
MathUtil mathUtil = new MathUtil();
for (int i=0; i < 100; ++i)
assertEquals(true, mathUtil.createSessionKey().matches("[0-9a-z]+"));
}
public void testGetPositiveInt() {
MathUtil mathUtil = new MathUtil();
assertEquals(15,mathUtil.getPositiveInt("15"));
assertEquals(18,mathUtil.getPositiveInt("18"));
assertEquals(1199,mathUtil.getPositiveInt("1199"));
assertEquals(0,mathUtil.getPositiveInt("0"));
assertEquals(-1,mathUtil.getPositiveInt("abc"));
assertEquals(-1,mathUtil.getPositiveInt("-188"));
assertEquals(-1,mathUtil.getPositiveInt("12.5"));
assertEquals(-1,mathUtil.getPositiveInt("0,33"));
}
}
package org.bombo.util;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import junit.framework.TestCase;
public class MiscUtilsTest extends TestCase {
public void testParseQuery() throws UnsupportedEncodingException {
MiscUtils utils = new MiscUtils();
Map<String, Object> parameters = new HashMap<String, Object>();
utils.parseQuery("name=Ale&surname=bobo", parameters);
assertEquals("Ale", parameters.get("name"));
utils.parseQuery("request=login&surname=bobo", parameters);
assertEquals("login", parameters.get("request"));
utils.parseQuery("name=Ron&levelid=15", parameters);
assertEquals("15", parameters.get("levelid"));
assertEquals("Ron", parameters.get("name"));
parameters.clear();
utils.parseQuery("", parameters);
assertEquals(null, parameters.get("name"));
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-06T18:08:29.677",
"Id": "38320",
"Score": "0",
"body": "Your singleton getInstance() method is not thread-safe. See double-check-locking pattern and so on"
}
] |
[
{
"body": "<h2>Volatile</h2>\n<p>I don't have time to write much here, but I did want to comment on the use of <code>volatile</code> members in both of your singletons.</p>\n<p>In my experience, <em>the majority</em> of the time that I see <code>volatile</code> in code, it's being misused. <code>volatile</code> does not make a member thread-safe, in the way that you want it to.</p>\n<p><a href=\"http://www.cs.umd.edu/%7Epugh/java/memoryModel/jsr-133-faq.html#volatile\" rel=\"noreferrer\">See more about Java volatile here</a></p>\n<p>In your case, if multiple threads are going to be reading and writing data from the <code>Map</code> at the same time, <code>ConcurrentHashMap</code> will probably help you. But, <code>volatile</code> does not.</p>\n<p>You are only assigning the <code>users</code> and <code>usedSessionKeys</code> map variables (e.g. <code>users =</code>) in the constructors of the classes that own them. So, there's no need to worry about whether or not one thread is <strong>assigning</strong> a new map to those members at (about) the same time that another thread is trying to <strong>access</strong> the member, where it might have to worry about having a stale value for the reference to the map.</p>\n<h2>Singleton</h2>\n<p>I haven't fully audited your code, but <strong>if</strong> you will have multiple threads calling <code>getInstance()</code> on your singleton classes, then as @Andrew said, you'll want to look into a thread-safe singleton pattern. There's tons online, so just search for <code>thread-safe Java Singleton pattern</code>. (<a href=\"https://stackoverflow.com/a/8297810/119114\">for example, this one</a>)</p>\n<h2>More</h2>\n<p><a href=\"https://stackoverflow.com/a/10357895/119114\">See this stack overflow answer for more related discussion</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-20T21:49:37.953",
"Id": "25297",
"ParentId": "24740",
"Score": "6"
}
},
{
"body": "<ol>\n<li>Please think twice before using your own http server. The better way is using Jetty or embed Tomcat - good way to get rid of defects and to save time for developing business logic.</li>\n<li><p>If you're going to use multithreading please look into java.util.concurrent.atomic package in order to start using AtomicInteger etc.</p></li>\n<li><p>Your multithreading is not actually multithreading as you've wrapped all logic into synchronized block. This will cause all threads to be executed one by one. </p></li>\n<li><p>Map<code><Integer,Map<Integer,List<Integer>>></code> is not a good way of handling variables. This might be an object. Probably you can make it thread safe inside</p></li>\n<li><p>volatile on Map is useless. It's like putting final on it. Anyway usage of these modifiers is not recommended as you can handle all types by concurrent package.</p></li>\n<li><p>This point is only my opinion but I do not like using TreeMap. As far as I see you are trying to return sorted String. But you can get values from scoreResults (<code>map.values()</code>) and sort them with <code>Collections.sort</code>. Also you should look into <code>StringUtils.join()</code> method (apache.commons package) in order to receive String. This will give you more readable code.</p></li>\n<li><p>Always close streams in try catch with finally block and always consume response body as you can receive memory leaks in your code:</p>\n\n<p><code>os.write(response.toString().getBytes())</code>;</p></li>\n</ol>\n\n<p>E.g. if the line above will cause an exception then os stream won't be closed. This will cause memory leak in your server. Please take a look in <code>IOUtils.closeQuitely()</code> method (apache.commons.io) as an example</p>\n\n<p>Hope this will help you</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-22T10:07:27.537",
"Id": "39262",
"Score": "0",
"body": "Nice first post. Please take the time to read your post twice and fix some typos :) Maybe some browser plugins can help you in spell checking."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-23T15:45:46.627",
"Id": "39335",
"Score": "0",
"body": "Thanks for the comment. Tried to fix findings - at least chrome is happy with spelling :). Hope now it looks better."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-22T09:10:11.717",
"Id": "25329",
"ParentId": "24740",
"Score": "10"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-05T00:02:57.733",
"Id": "24740",
"Score": "14",
"Tags": [
"java",
"multithreading",
"http"
],
"Title": "HTTP server and multi-threading optimization"
}
|
24740
|
<p>I've implemented a very simple in-memory "database" just as an exercise. I wanted to see if there's anything obvious I should be doing that fits more of the Haskell way of doing things.</p>
<pre><code>import qualified Data.Map as M
type History = [String]
data Result = Result (Maybe String) Bool DB
data Command = Command { name :: String
, key :: Maybe String
, value :: Maybe String
}
data DB = DB (M.Map String String)
cmdKey c = let Just s = key c in s
cmdValue c = let Just s = value c in s
runSetCmd :: Command -> DB -> IO (Maybe String, DB)
runSetCmd c db@(DB map) = do
let newMap = M.insert (cmdKey c) (cmdValue c) map
return $ (Nothing, DB newMap)
runGetCmd :: Command -> DB -> IO (Maybe String, DB)
runGetCmd c db@(DB map) = return $ (M.lookup (cmdKey c) map, db)
execCmd :: DB -> Command -> IO Result
execCmd db c@(Command name key value) = do
(output,newDB) <- case name of
"set" -> runSetCmd c db
"get" -> runGetCmd c db
_ -> return (Nothing, db)
return $ Result output end newDB
where
end = case name of
"end" -> True
_ -> False
getCmd = getLine >>= return . parseCmd
parseCmd :: String -> Command
parseCmd s =
case words s of
(name:key:value:_) -> Command name (Just key) (Just value)
(name:key:[]) -> Command name (Just key) Nothing
(name:[]) -> Command name Nothing Nothing
displayResult :: Result -> IO Result
displayResult r@(Result (Just s) _ _) = putStrLn s >> return r
displayResult r = return r
continue :: Result -> IO ()
continue (Result _ end db) = if end then return () else repl db
repl state = getCmd >>= execCmd state >>= displayResult >>= continue
main = repl (DB M.empty)
</code></pre>
|
[] |
[
{
"body": "<p><code>runSetCmd</code>, <code>runGetCmd</code>, and <code>execCmd</code> don't need to be in the IO monad.</p>\n\n<p>It feels a bit wrong to have <code>runGetCmd</code> returning a \"new DB\". Of course, it really returns the same DB, but the caller has no guarantee.</p>\n\n<p><code>cmdKey</code> and <code>cmdValue</code> are partial functions, which is dangerous. What you could do instead is have a unique data constructor in the <code>Command</code> type for each command, which has exactly the parameters that command needs.</p>\n\n<p>I'd recommend enabling all compiler warnings and making warnings into fatal errors. (That's <code>-Wall -Werror</code>.) It will probably catch some little things in here.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-05T06:14:34.607",
"Id": "24746",
"ParentId": "24741",
"Score": "2"
}
},
{
"body": "<p>First of all, as Karl said, you should minimize the code in IO monad and make sure most of your code is in pure functions</p>\n\n<p>Second your Command type is not properly designed</p>\n\n<pre><code>data Command = Command { name :: String\n , key :: Maybe String\n , value :: Maybe String\n }\n</code></pre>\n\n<p>Having the name as String is not cool. You could have a type something like </p>\n\n<pre><code>data CommandType = Get | Set\n</code></pre>\n\n<p>...but still your command type has too many invalid combinations which the type system cannot help you with (for example: name=\"get\", key=\"xyz\", value=\"asdfasdf\"). Your type should be designed such that you avoid these combinations and you make the type system work for you.</p>\n\n<p>Given this I would define the Command type like this:</p>\n\n<pre><code>data Command = Invalid | End | Get String | Set String String\n</code></pre>\n\n<p>if your type is like this then execCmd will become:</p>\n\n<pre><code>exec (Get key) = ....\nexec (Set key value) = ...\nexec Exit = ...\nexec Invalid = ...\n</code></pre>\n\n<p>If you only address these two issues you will see a lot of simplification in your code. Other things would be:</p>\n\n<p>Using the State monad will help you with the passing of the current db state between the functions operating on it. If you do this then passing the state will not be your concern and your result could be either a tuple or a record:</p>\n\n<pre><code>data Result = Result { output: String ; end:Bool} \n</code></pre>\n\n<p>Then your displayResult will look like this: </p>\n\n<h1>UPDATE</h1>\n\n<p>If you don't want the a command to output anything then the output field in Result could have the type \"Maybe String\" instead of String. \\</p>\n\n<pre><code>data Result = Result { output: Maybe String ; end:Bool} \n</code></pre>\n\n<p>Then you will have to choose only the Just outputs before you display the results. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-06-04T06:57:23.387",
"Id": "243465",
"Score": "0",
"body": "in the case of \"Set\", how would your proposed `displayResult` work ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-06-04T12:54:24.160",
"Id": "243477",
"Score": "0",
"body": "Good point. See the update"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-05T09:48:22.230",
"Id": "24751",
"ParentId": "24741",
"Score": "5"
}
},
{
"body": "<p>You have two important effects going on:</p>\n\n<ul>\n<li><p><code>IO</code>, to interact with the user</p></li>\n<li><p><code>State</code>, to store the map</p></li>\n</ul>\n\n<p>You can combine these using monad transformers, which let you layer <code>State</code> on top of <code>IO</code> by using <code>StateT</code>. When you do, the program becomes much more concise:</p>\n\n<pre><code>import Control.Monad (forever)\nimport Control.Monad.Trans.Class (lift)\nimport Control.Monad.Trans.State\nimport Data.Map as M\n\nloop :: StateT (Map String String) IO r\nloop = forever $ do\n l <- lift getLine\n case (words l) of\n [\"get\", key] -> do\n mval <- gets (M.lookup key)\n lift $ putStrLn $ case mval of\n Nothing -> \"Invalid key\"\n Just val -> val\n [\"set\", key, val] -> modify (M.insert key val)\n _ -> lift $ putStrLn \"Invalid command\"\n\nrepl :: IO r\nrepl = evalStateT loop M.empty\n</code></pre>\n\n<p>If you are new to monad transformers, I highly recommend you read <a href=\"http://www.cs.virginia.edu/~wh5a/personal/Transformers.pdf\" rel=\"nofollow\">Monad Transformers - Step by Step</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-06-04T17:16:29.073",
"Id": "243498",
"Score": "0",
"body": "I like this one, simple and neat. however the link is a bit `dry` to follow. I read the text, repo the code. but I barely understand how/when MonadTransformer shall be used."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-06-04T17:20:06.567",
"Id": "243499",
"Score": "0",
"body": "another question is: how will you handle `end` command here ?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-06T04:33:37.807",
"Id": "24790",
"ParentId": "24741",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "24751",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-05T01:44:01.833",
"Id": "24741",
"Score": "6",
"Tags": [
"beginner",
"haskell"
],
"Title": "Very simple in-memory database"
}
|
24741
|
<p>I am trying to simply present a table in HTML that is stored in a MySQL database. I would like to use Object Oriented PHP to access and fetch the data for the table. I have spent some time learning the different elements and have tried to put together a generic template I can use to access the tables in the database.</p>
<p>Questions:</p>
<ul>
<li>Is there anything wrong with the code below?</li>
<li>Is there a better way to do this?</li>
<li>Are there any redundancies in the code? Is a more generally preferred/standard way of doing this? I've seen <code>foreach</code> and <code>while</code> being used...</li>
</ul>
<p></p>
<pre><code><html>
<table>
<tr>
<th>field1</th>
<th>field2</th>
<th>field3</th>
<th>field4</th>
<th>field5</th>
</tr>
<?php
require_once 'db_config.php';
$dbh = new PDO($dsn, $dbuser, $dbpass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$sth = $dbh->prepare("SELECT * FROM a_temp");
$sth->execute();
$result = $sth->fetch(PDO::FETCH_ASSOC);
?>
<?php foreach($result as $index => $row) : ?>
<tr>
<td><?php echo $row[field1]; ?></td>
<td><?php echo $row[field2]; ?></td>
<td><?php echo $row[field3]; ?></td>
<td><?php echo $row[field4]; ?></td>
<td><?php echo $row[field5]; ?></td>
</tr>
<?php endforeach;?>
</table>
</body>
</html>
</code></pre>
|
[] |
[
{
"body": "<ol>\n<li>The <a href=\"http://php.net/manual/en/pdostatement.fetch.php\" rel=\"nofollow\"><code>fetch()</code></a> call only calls a single row from result set.</li>\n<li>Your <code>foreach</code> loop will, as a result, just go in the first result and do nothing. It may even produce an error/notice for undefined index in <code>$row</code>.</li>\n<li>While using a <code>SELECT</code> statement in PHP, always include the specific columns that you want to fetch. This is among good practices.</li>\n</ol>\n\n<hr>\n\n<pre><code>$sth = $dbh->prepare(\"SELECT `field1`, `field2`, `field3`, `field4`, `field5` FROM a_temp\");\n$sth->execute();\n?>\n<?php foreach($sth->fetch(PDO::FETCH_ASSOC) as $row) : ?>\n<tr>\n <td><?php echo $row['field1']; ?></td>\n <td><?php echo $row['field2']; ?></td>\n <td><?php echo $row['field3']; ?></td>\n <td><?php echo $row['field4']; ?></td>\n <td><?php echo $row['field5']; ?></td>\n</tr>\n<?php endforeach;?>\n</table>\n</code></pre>\n\n<hr>\n\n<p>Or, if you want to use a while loop:</p>\n\n<pre><code>$sth = $dbh->prepare(\"SELECT `field1`, `field2`, `field3`, `field4`, `field5` FROM a_temp\");\n$sth->execute();\n?>\n<?php while( $row = $sth->fetch(PDO::FETCH_ASSOC) ) { ?>\n<tr>\n <td><?php echo $row['field1']; ?></td>\n <td><?php echo $row['field2']; ?></td>\n <td><?php echo $row['field3']; ?></td>\n <td><?php echo $row['field4']; ?></td>\n <td><?php echo $row['field5']; ?></td>\n</tr>\n<?php } ?>\n</table>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-05T06:45:26.400",
"Id": "38217",
"Score": "0",
"body": "Thank you, that's really quite helpful as I am learning. I've posted a similar question (link below) in case you have any insight. Appreciate it!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-05T06:53:52.587",
"Id": "38218",
"Score": "0",
"body": "http://codereview.stackexchange.com/q/24748/23810"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-05T11:15:10.337",
"Id": "38225",
"Score": "0",
"body": "@BenJones You've used apostrophe character in that question. Use backticks in the `SELECT` statement."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-05T16:30:27.990",
"Id": "38267",
"Score": "0",
"body": "Pedantic moment: using backticks has no advantages, but has (minor) disadvantages. In particular, the only advantage that it has is that it allows you to use reserved keywords. You shouldn't be using reserved keywords anyway, so that's cancelled out. As for disadvantages though, it immediately kills any chance at SQL-interoptability. This is rarely going to be a problem since changing RDBMS is rarely a case of changing the driver anyway, but there's no reason to add an immediate barrier for 0 benefit."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-10-08T13:22:33.503",
"Id": "196090",
"Score": "1",
"body": "Just wondering, shouldn't it be `fetchAll` in the `foreach` example? As in `foreach($sth->fetchAll(PDO::FETCH_ASSOC) as $row):`?"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-05T05:46:46.890",
"Id": "24745",
"ParentId": "24743",
"Score": "4"
}
},
{
"body": "<pre><code> $result = $dbconn->query('SELECT * from accounts');\n $colcount = $result->columnCount();\n\n // Get coluumn headers\n echo ('<table><tr>');\n for ($i = 0; $i < $colcount; $i++){\n $meta = $result->getColumnMeta($i)[\"name\"];\n echo('<th>' . $meta . '</th>');\n }\n echo('</tr>');\n\n // Get row data\n while ($row = $result->fetch(PDO::FETCH_ASSOC)) {\n echo('<tr>');\n for ($i = 0; $i < $colcount; $i++){\n $meta = $result->getColumnMeta($i)[\"name\"];\n echo('<td>' . $row[$meta] . '</td>');\n }\n echo('</tr>');\n }\n\n echo ('</table>');\n</code></pre>\n\n<p>Note: There may be an issue with Boolean fields and this wont work on every PDO driver... Check out the php docs on getColumnMeta <a href=\"http://php.net/manual/en/pdostatement.getcolumnmeta.php\" rel=\"nofollow\">http://php.net/manual/en/pdostatement.getcolumnmeta.php</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-10-08T10:58:20.500",
"Id": "196059",
"Score": "4",
"body": "Welcome to Code Review! You have presented an alternative solution, but haven't reviewed the code. Please explain your reasoning (how your solution works and how it improves upon the original) so that the author can learn from your thought process."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-10-08T10:56:02.673",
"Id": "106931",
"ParentId": "24743",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-05T04:36:33.730",
"Id": "24743",
"Score": "6",
"Tags": [
"php",
"mysql",
"html",
"pdo"
],
"Title": "Create a table from MySQL using PHP PDO"
}
|
24743
|
<p>Only these formats are accepted.</p>
<ol>
<li>1.1.1</li>
<li>1.1.1-r</li>
<li>1.1.1-b</li>
<li>1.1.1-r1</li>
<li>1.1.1-b1</li>
</ol>
<p>I wrote this code. What don't I like in it? I used parentheses and now I have two groups. In fact, I don't need to do anything with groups. And there might be some bugs as well.</p>
<pre><code>package com.sandbox;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
checkVersion("10.22.5-r");
}
private static void checkVersion(String current) {
String regex = "([1-9]\\d*)\\.(\\d+)\\.(\\d+)-[b|r](?:[1-9]\\d*)*";
Pattern pattern = Pattern.compile(regex);
Matcher matcherCurrent = pattern.matcher(current);
System.out.println("Matches: " + matcherCurrent.matches());
System.out.println("The first digit: " + matcherCurrent.group(1));
System.out.println("The second digit: " + matcherCurrent.group(2));
System.out.println("The third digit: " + matcherCurrent.group(3));
// Compare and decide whether an update is necessary
}
</code></pre>
<p>}</p>
<p>Thank you for the answers you give me. I'll vote up as soon as I have enough reputation.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-06T07:05:01.233",
"Id": "38310",
"Score": "0",
"body": "Your last quantifier, `{0,1}` is the same as `?`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T10:29:05.993",
"Id": "38374",
"Score": "0",
"body": "@p.s.w.g, yes, I meant \"once or not at all.\""
}
] |
[
{
"body": "<p>It seems to me that you're using * when it looks like that's not the behaviour you want.</p>\n\n<p>i.e. this bit <code>-(b|r)*</code> do you really mean a dash followed by either a 'b' or an 'r' zero or more times? I think it's more likely that you meant more along the lines of: there can be a dash followed by a 'b' or an 'r' but there doesn't have to be.</p>\n\n<p>Do you want 1.1.1-brrrrrrrrrrr1 to match? What's the goal of the regex, is it just to see if it fits the pattern or do you want to use it to get the various numbers out?</p>\n\n<p>Btw: If you don't care about groups you can use <code>(?: )</code> instead of <code>()</code> to create non capturing groups.</p>\n\n<p><strong>Edit:</strong></p>\n\n<p>I think your regex needs to be more like: <code>^([1-9]\\\\d*)\\\\.(\\\\d+)\\\\.(\\\\d+)(?:-[br]{1}[0-9]?\\\\d*)?$</code> This makes everything following the first 3 numbers optional.</p>\n\n<p>I do wonder whether a regex is the right option though... If you know the strings you are comparing are definitely well formed version numbers just do normal string manipulation.</p>\n\n<pre><code>// Pseudocode\nString versionNumber = \"1.1.1-r1\";\nint indexOfDash = versionNumber.indexOf(\"-\");\nif (indexOfDash != -1) \n{\n versionNumber = versionNumber.substring(0, indexOfDash);\n}\nString[] numbers = versionNumber.split(\".\");\n\n// Now compare your numbers.\n</code></pre>\n\n<p>I generally like to avoid regular expressions as they are a lot more difficult to get right than people give them credit for. However, if you also need to check that it is a well formed version number you probably want to use the regex option.</p>\n\n<p>In fact, I got the regex wrong - edited now. I changed the matching for the final part of the version number and added in the anchors.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T10:33:37.253",
"Id": "38375",
"Score": "0",
"body": "I edited the question. The goal of the regex is to extract three digits from two string representations of a version: from a current one and from a new one. After that I'll return a `boolean` result (whether we need to update the current version). Now, I don't take into account `r` (release) and `b` (beta) symbols and any digits after them."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T15:34:39.340",
"Id": "38400",
"Score": "0",
"body": "@RedPlanet - I've responded based on your update."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-05T09:32:18.343",
"Id": "24750",
"ParentId": "24749",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "24750",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-05T09:07:24.250",
"Id": "24749",
"Score": "2",
"Tags": [
"java",
"regex"
],
"Title": "Regular expression for application version"
}
|
24749
|
<p>Each class of my project has several inputs and outputs. Each input, the same as output, depends on it's own set of value-datatype.</p>
<p>I need to provide a mechanism to forward data streams from one instance to another, with ability to split that streams and to combine several streams into one.</p>
<p>There are a lot of such classes, and they are hardly grouped by their input or output type. Splitting and combining (may be other operations like filtering or simple math) will provide this classes interaction. </p>
<p>I came out with <code>Table</code> class, which can store and manage two-dimensional array of objects and also can send rows to another <code>Table</code>, using maps on columns (that's how data streams splits). It could be one-dimensional, but data buffer avaibility is useful. Each class become a <code>Context</code> with a collection of that tables. Typical work algorythm for <code>Context</code> is to: 1. initialize tables, 2. handle input table inserts, 3. unbox and process data, 4. insert result to output table</p>
<p>Everything was OK with that <code>Table</code>, but one day, while coding a new <code>Context</code> I felt that data storage and transfering is not the only thing <code>Context</code> must do. When an external infrastructure is hiding behind the Context, it needs to be connected/disconnected/opened/loaded etc. And that looks like I need to add a <code>Procedure</code> or even <code>Function</code> to <code>Context</code>.</p>
<p>This is first huge project of mine and I have no person to help. Questions I care about:</p>
<ul>
<li><p>this design looks like implementing internal programming language, is that correct? Can you show examples?</p></li>
<li><p>this design looks like implementing in-memory database, is that correct? Can you show examples?</p></li>
<li><p>is that normal not to use interfaces on data types if there are a lot of them?</p></li>
<li><p>can you propose more effective and elegant design for my problem?</p></li>
<li><p>are there similiar design patterns?</p></li>
</ul>
<hr>
<p>May be some code will help to understand what I need. This is very simplified version. In real project there are a lot of Context realisations, more sugar to access and create Tables, more logic on managing internal collections.</p>
<pre><code>public abstract class Context
{
public Table this[string name] { get { /* ... */ } }
public IEnumerable<Table> Tables { get; }
protected void AddTable(Table t) { /* ... */ }
}
public class Table
{
object[][] rows; // Two-dimensional for buffering rows
public Table(string name /* + columns initialisation info */ ) { /* ... */ }
public void PushRow(params object[] row) { /* ... */ } // insert new row and send it to subscribers
public void AddSubscriber(Table dst, params int[] columnMap) { AddSubscriber(dst.PushRow, columnMap); }
public void AddSubscriber(Action<object[]> receiver, params int[] columnMap) { /* ... */ }
}
public class Function
{
// Do I need this in Context, if, for example, Mathematician must be Opened/Closed?
}
class Mathematician : Context
{
public Mathematician()
{
// input table
Table t = new Table("Numbers");
AddTable(t);
t.AddSubscriber(Count);
// output tables
AddTable(new Table("Average"));
AddTable(new Table("Variance"));
AddTable(new Table("StDev"));
}
void Count(object[] row)
{
double newNumber = (double)row[0]; // exception here if data streams connection is not correct
double avg = 0;
double variance = 0;
double stdev = 0;
/* ... computations begin ... */
/* Tables can be accessed, their buffer can be used */
// Finally, publish results
this["Average"].PushRow(avg);
this["Variance"].PushRow(variance);
this["StDev"].PushRow(stdev);
}
}
</code></pre>
<p>Possible usage. Imagine that we have another context <code>Secretary : Context</code> which will receive data from <code>Mathematician</code> to write it somewhere and <code>Device : Context</code> to provide <code>Mathematician</code> with new numbers. Note, they're independant of each other.</p>
<pre><code>static class Program
{
public static void Main(string[] args)
{
Context m = new Mathematician();
Context d = new Device();
Context s = new Secretary();
d["Sensor1"].AddSubscriber(m.Numbers, /* map must correspond to Device internals */)
m["StDev"].AddSubscriber(s.Console, /* ... */);
// Now each sensor1 signal in Device context will be sent to Mathematician, and the results of computations will be sent to Secretary, which can write it to console
// We can start this system manually like that
d["Sensor1"].PushRow( /* ... signal data ... */);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-05T11:57:32.443",
"Id": "38231",
"Score": "0",
"body": "my first question (more to come) is why do you have Context as `abstract` but have no abstract methods in it? abstraction layers help to combine same processes, or have a common method to call."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-05T12:05:00.660",
"Id": "38232",
"Score": "0",
"body": "It looks like you are trying to manually implement Tables and DataSet (the .Net versions) that do what you are trying to do, but with a lot of it taken out. Although this is not a bad idea, it can be hard for someone else to come in and review your code (even if that someone is you after a time has passed) Instead you would probably benefit to change the name of `Table` to say `ContextTable`. Now there is no ambiguity with `Table` and `System.Web.UI.WebControls.Table` or maybe even `System.Data.DataTable`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-05T12:09:23.817",
"Id": "38234",
"Score": "0",
"body": "As for having a `function` class if I was you I would change it to a `interface` and add one method called `Calculate()` or something similar. Then in your Table class implement `Function`. Then instead of having your different classes implement Context they would instead implement Table. In your math class move the `count` method over to `Calculate` Now you can just add Mathmetician to your array of Tables, and loop through them all calling Calculate."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-05T13:47:19.190",
"Id": "38244",
"Score": "0",
"body": "@RobertSnyder 1. Because I think about Context like something abstract, it must not be instantiated at any time. But it must have a lot of realisations. It could be an interface, but in this case I must refuse of nice indexer access and other features."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-05T13:57:27.097",
"Id": "38245",
"Score": "0",
"body": "2. Well, Table is really like System.Data.DataTable and it even can be replaced with it, but I think DataTable is quite complicated and not fit my tasks ideally. What about naming, I am not usually care about ambiguity with other namespaces. Anyway, thanks for idea with ContextTable"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-05T14:08:02.083",
"Id": "38246",
"Score": "0",
"body": "3. I agree that `Context` as a collection of tables is totally replacable by a `Table` itself. But it will make `Table` class more complicated, and make no big difference."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-05T14:11:30.880",
"Id": "38247",
"Score": "0",
"body": "I dont want to create a lot of Mathematicians and iterate them with calling their methods. I want to create many Context realisations (Mathematicians, Librarian, Administrator...) each having its own input/output, and able to connect with each other by simple data transformations in their data tables (mapping, filtering etc.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-05T14:14:25.783",
"Id": "38249",
"Score": "0",
"body": "And actually, I've already done it. But in the end it become looks like internal language or database with aspects, and that is confusing me. Future development is becoming more scientific and complicated. May be I am doing smthing wrong?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-05T14:21:07.563",
"Id": "38250",
"Score": "0",
"body": "@astef - I can't see how this is supposed to work. `Count()` is a callback from `PushRow()`, but `Count()` is also the only place that `PushRow()` is used. Can you take a step back and elaborate on the big picture goal?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-05T14:46:21.290",
"Id": "38257",
"Score": "0",
"body": "@Bobson I've added usage example. As always, it's not working, but the main idea must be clear... I hope )"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-05T15:14:23.993",
"Id": "38261",
"Score": "0",
"body": "Yep, I have a better idea for what you're tryng to do now. Do you want this to work asynchronously or should things happen as the data is updated? This feels very familiar, but I can't quite put my finger on the name of the pattern..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-05T15:23:50.917",
"Id": "38263",
"Score": "0",
"body": "I avoid asynchrony until performance issues are met"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-05T15:54:40.190",
"Id": "38266",
"Score": "0",
"body": "I remembered: It's called the [Observer Pattern](http://en.wikipedia.org/wiki/Observer_pattern). See [here](http://www.remondo.net/observer-pattern-example-csharp-iobservable/) for a good example of usage."
}
] |
[
{
"body": "<p>I think the single biggest issue with your design is that it's not type-safe and relies on strings a lot.</p>\n\n<p>C# is a statically-typed language, you should take advantage of that and let the compiler check for possible errors. This means:</p>\n\n<ol>\n<li>Making <code>Table</code> generic, so that a row is an object of a specific type, instead of <code>object[]</code>. If you need to “map” data between different types, you can use lambdas.</li>\n<li>Tables in a specific context should be properties, instead of accessing them by a string.</li>\n<li>You should separate input tables and output tables into separate types (at least on the outside). <code>Mathematician</code> should be able to read from the <code>Numbers</code> table, but others should only write to it. It's a good idea to enforce this by making <code>Numbers</code> something like <code>InputTable<T></code>.</li>\n</ol>\n\n<p>In general, your requirements are quite similar to <a href=\"http://msdn.microsoft.com/en-us/library/hh228603.aspx\" rel=\"nofollow\">TPL Dataflow</a>, you should consider looking at it for inspiration, or even use it in your implementation (though it's .Net 4.5 only).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-05T18:48:57.127",
"Id": "38284",
"Score": "0",
"body": "I agree that compile-time type-safety is lost and that smells bad. Though, this check can be made at run-time. Moreover, it will be performed at run-time anyway, because connecting different contexts will be performed by user at runtime, using UI.\n---\nI'm coming with next issues..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-05T19:02:58.307",
"Id": "38285",
"Score": "0",
"body": "Now, let's list disadvantages of type-safety in my case.\n1. If Table is generic, I must make: Table<T>, Table<T1,T2>, Table<T1,T2,T3>... At first time I would stop at 8. In nearest future I'm sure I'll need up to 14 columns. And that's nothing strange, tables sometime have a lot of columns.\n2. Accessing table by a string is neccessary, because I need to make context user (UI, for example) independant from context realisations. For user there is Context, not Mathematician.\n3. Actually, I'd like to have full access to read/write to any table. Arguments for this: easy testing, logging, sharing"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-05T19:06:17.700",
"Id": "38286",
"Score": "0",
"body": "About TPL Dataflow - thanks much, any external solutions on this topic is very useful for me now. If it will fit my needs, I'll accept this answer"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-05T19:44:58.070",
"Id": "38287",
"Score": "1",
"body": "@astef 1. That's not what I meant. `Table<T>` should be enough, since `T` can be any complex type. I don't see why the concept of columns would be useful here. 2. That's not making it actually independent, you still depend on the name of the table. If you meant that you want to be able to easily switch `Mathematician` for, say, `Calculator`, then use interfaces. E.g. you could have an interface that contains `Table<double> Numbers { get; }`. 3. Based on that argument, you should also make all your fields public. I think the advantages of proper encapsulation outweigh the disadvantages."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T15:00:07.123",
"Id": "38398",
"Score": "0",
"body": "Main application dependance on different context realisation is not an option. No sense to make Table generic because `Table<MathematicianResult>` will be external for the application the same as simply `MathematicianResult`. And I can't see a real problem with strings. Application asks for all table names, then links different tables, using column type checks. Where's the dependence?"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-05T17:17:17.623",
"Id": "24765",
"ParentId": "24753",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "24765",
"CommentCount": "13",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-05T11:10:07.957",
"Id": "24753",
"Score": "2",
"Tags": [
"c#",
"object-oriented",
"design-patterns"
],
"Title": "Design with Context, Table and Functions"
}
|
24753
|
<p>How would you write this?</p>
<pre><code>string halfADayOff = "Half a day off";
string oneDayOff = "One day off";
string days = "NoDaysOff";
if (typeOfDelegation)
{
if ((differenceInDays == 0) && (arrivalDay.TimeOfDay.Hours > 22))
days = halfADayOff;
else if ((differenceInDays == 1) && (arrivalDay.TimeOfDay.Hours > 22))
days = halfADayOff;
else if ((differenceInDays == 2) && (arrivalDay.TimeOfDay.Hours <= 22))
days = halfADayOff;
else if ((differenceInDays == 2) && (arrivalDay.TimeOfDay.Hours > 22))
days = oneDayOff;
else if (differenceInDays > 2)
days = oneDayOff;
else return days;
}
else
if (differenceInDays > 29)
days = oneDayOff;
else
return days;
return days;
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-05T13:00:19.257",
"Id": "38238",
"Score": "1",
"body": "Can `differenceInDays` be negative? Can `sosire.TimeOfDay.Hours` be greater than 23?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-05T13:03:26.263",
"Id": "38239",
"Score": "0",
"body": "No and No. It calculates de days off for a delegation. sosire = arrival, jumatateDeZiLbera = Half a day off, oZiLibera = one day off."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-05T13:08:27.313",
"Id": "38240",
"Score": "0",
"body": "The code returns only for last `else`'s, other cases just modify the (member? local?) variable `days`. Please describe whether `days` is a local variable, and what is **returned** in case of e.g. tipDelegatie==true and differenceInDays > 2. I can assume that at the and `days` value is a result of this method, but it is not reflected in your code"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-05T13:11:29.737",
"Id": "38241",
"Score": "0",
"body": "Is it a bug that when `differenceInDays == 2 && sosire.TimeOfDay.Hours == 22` you hit the final `else`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-05T13:15:04.930",
"Id": "38242",
"Score": "0",
"body": "I modified it and changed the variables in english. Now?"
}
] |
[
{
"body": "<p>You could change the logic so it is smaller, but in its current form, it looks more readable and readability has a value. However, I think a few more comments might make it even more readable. Especially comments that show some examples.</p>\n\n<pre><code>//for example: from 10pm to midnight\nif ((differenceInDays == 0) && (arrivalDay.TimeOfDay.Hours > 22))\n days = halfADayOff;\n//from 10pm to 4am or 10pm to 10am\nelse if ((differenceInDays == 1) && (arrivalDay.TimeOfDay.Hours > 22))\n days = halfADayOff;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-05T14:28:32.157",
"Id": "38252",
"Score": "4",
"body": "I disagree with using comments in this fashion. Your code should written in a way it conveys what it is accomplishing. Its easy to skip updating comments as the code changes, but the code will always be the source of truth."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-05T17:32:22.017",
"Id": "38272",
"Score": "1",
"body": "Absent more self-descriptive code, comments such as these are entirely desireable."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-05T13:35:16.210",
"Id": "24756",
"ParentId": "24755",
"Score": "0"
}
},
{
"body": "<p>In order to simplify nesting I reordered conditions so that you can deal with simplest cases first, and return result as soon as you know it instead of capturing it in <code>days</code> variable. Also ternary operator looks like a good choice here...</p>\n\n<pre><code>const string noDaysOff = \"NoDaysOff\";\nconst string halfADayOff = \"Half a day off\";\nconst string oneDayOff = \"One day off\";\nconst int lateNightCutoff = 22; //TODO: couldn't come up with better name, update if you find one\n\nif (!typeOfDelegation)\n return differenceInDays > 29 ? oneDayOff : noDaysOff;\n\nif (differenceInDays > 2)\n return oneDayOff;\n\nvar arrivalHour = arrivalDay.TimeOfDay.Hours;\n\nif (differenceInDays == 2)\n return arrivalHour > lateNightCutoff ? oneDayOff : halfADayOff;\n\nreturn arrivalHour > lateNightCutoff ? halfADayOff : noDaysOff;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-05T14:23:07.677",
"Id": "38251",
"Score": "7",
"body": "Excellent. The only thing I would change would be to give meaningful names to the constants 2, 29, and 22."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-05T14:00:24.633",
"Id": "24757",
"ParentId": "24755",
"Score": "18"
}
},
{
"body": "<p>I wouldn't shorten it and i don't like comments (seperate discussion but it usualyl means your code is hard to read) </p>\n\n<p>I would also try to see if you could avoid the daydifference and just pass in number of hours worked. \nIt would be easier to maintain and probably correspond directly to the law you are obeying.</p>\n\n<p>Anyway for example with the give restrictions and not 100% perfect but you get the point: </p>\n\n<pre><code> public class GiveTheManABreak\n {\n public enum DaysOff\n {\n HalfADayOff,\n OneDayOff,\n NoDaysOff,\n }\n\n public DaysOff CalculatesDaysOff(bool typeOfDelegation, int differenceInDays, DateTime arrivalDay)\n {\n if (typeOfDelegation)\n return DelgateCalculateDaysOff(differenceInDays, arrivalDay);\n\n if (BeenHereTooLong(differenceInDays))\n return DaysOff.OneDayOff;\n\n if (ArrivedAfterTenAndHasBeenHereZeroOrOneDay(differenceInDays, arrivalDay.TimeOfDay.Hours))\n return DaysOff.HalfADayOff;\n\n if (Arrived10pmOrEarlierTwoDaysAgo(differenceInDays, arrivalDay.TimeOfDay.Hours))\n return DaysOff.HalfADayOff;\n\n if (ArrivedAfter10pmTwoDaysAgo(differenceInDays, arrivalDay.TimeOfDay.Hours))\n return DaysOff.OneDayOff;\n\n return DaysOff.NoDaysOff;\n }\n\n private bool BeenHereTooLong(int differenceInDays)\n {\n return differenceInDays > 2;\n }\n\n private bool ArrivedAfter10pmTwoDaysAgo(int differenceInDays, int arrivalTime)\n {\n if (differenceInDays != 2)\n return false;\n\n return arrivalTime > 22;\n }\n\n private bool Arrived10pmOrEarlierTwoDaysAgo(int differenceInDays, int arrivalTime)\n {\n if (differenceInDays != 2)\n return false;\n\n return arrivalTime <= 22;\n }\n\n private bool ArrivedAfterTenAndHasBeenHereZeroOrOneDay(int differenceInDays, int arrivalTime)\n {\n if (differenceInDays > 2)\n return false;\n\n return arrivalTime > 22;\n }\n\n private DaysOff DelgateCalculateDaysOff(int differenceInDays, DateTime arrivalDay)\n {\n return differenceInDays > 29 ? DaysOff.OneDayOff : DaysOff.NoDaysOff;\n }\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-05T14:37:16.987",
"Id": "38253",
"Score": "0",
"body": "also string returns are usually a sign of ui and business together. have the ui transform the enum into a string (take for example the requirement to support multiple languages)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-05T15:17:06.550",
"Id": "38262",
"Score": "4",
"body": "I agree about strings, but I think your solution is over-architected. What you have done is produced 50 lines of highly structured code from 8 simple lines of business logic. Yes, your code is well-structured. But 8 lines are much easier to understand than 50 lines. It might be worth doing what you did if (when) business logic gets more complex, but as for current implementation that's too much (imho)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-05T17:20:46.360",
"Id": "38270",
"Score": "3",
"body": "You can't seriously think this is easier to understand than the original code, can you?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-07T13:50:46.120",
"Id": "38337",
"Score": "0",
"body": "@almaz good point with the over architecture. have removed it from the original post.\nStill I get worried when business is inlined to get shorter code. You may have smaller code but it takes a while to see all the business requirements being implemented, in this case its probably the law business and getting it wrong could be expensive."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-05T14:36:08.107",
"Id": "24759",
"ParentId": "24755",
"Score": "1"
}
},
{
"body": "<h2>considerations</h2>\n\n<ul>\n<li>Remove the <code>else return days</code> from both \"halves\" of the outer <code>if</code>. They are not needed.</li>\n<li>Use helpful names. What does <code>differenceInDays</code> <em>mean</em>?</li>\n<li>Initialize values near where they are used - a default value for <code>days</code>. That variable has class scope (I assume), so who knows what that value might if we hit the <code>if-else</code> default that didn't set it, but just returns it. We'd have to read LOTS of code to figure that out.</li>\n<li>Name boolean variables so they read well in the context of the <code>if</code> statement.</li>\n<li>Use enumerations instead of string literals when you have logical groupings.</li>\n<li>Use curly brackets in compound/complex <code>if-else</code> to avoid confusion and ambiguity.</li>\n<li>I don't understand what <code>typeOfDelegation</code> means, so I probably mis-re-named it below. That line essentially says \"If <em>something</em> is a kind of delegation ...\". How may types are there? If it either is or is not a \"delegation\" then \"isDelegation\" is better than \"typeOfDelegation\".</li>\n<li>I like what @almaz did in his answer to consolidate the logic, but too many <code>return</code>s makes code changes more error prone. In my opinion I'd re-structure the code if necessary to eliminate (most of) them. Yes, the code is short but that misses the point. I've seen short code like this re-written because multiple hard returns did not allow needed changes.</li>\n<li>encapsulate complex/long logic so the \"higher level\" code is clearer. The goal is not shorter code, but understanable and modular code.</li>\n</ul>\n\n<h2>considerations applied</h2>\n\n<pre><code>public enum DaysOff {none, one, half};\nprotected int oneMonth = 29; \n\n // let's assume the following was done earlier in code\n Timespan tripDuration = departureDay - arrivalDay;\n //end\n\n days = DaysOff.none;\n\n if(goneALongTime) {\n days = tripDuration.Days > oneMonth? DaysOff.one : days; \n } else {\n days = GoneShortTime( tripDuration.Days );\n }\n\n return days;\n } // method end\n\n protected DaysOff GoneShortTime( int daysGone, arrivalDay ) {\n DaysOff howMany; // defaults to \"none\" (the underlying zero value of the enum)\n int endOfDay = 22; // 10 pm \n int arrivalHour = arrivalDay.TimeOfDay.Hours;\n\n if (( daysGone == 0 ) && ( arrivalHour > endOfDay ))\n howMany = DaysOff.half;\n else if (( daysGone == 1 ) && ( arrivalHour > endOfDay ))\n howMany = DaysOff.half;\n else if (( daysGone == 2 ) && ( arrivalHour <= endOfDay ))\n howMany = DaysOff.half;\n else if (( daysGone == 2 ) && ( arrivalHour > endOfDay ))\n howMany = DaysOff.one;\n else if ( daysGone > 2 )\n howMany = DaysOff.one;\n\n return howMany;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-12T09:08:26.543",
"Id": "38709",
"Score": "0",
"body": "Relying on the zero value of the enum is somewhat brittle. Wouldn't you consider actually initialising howMany when you declare it more readable than a long comment explaining why you don't need to bother?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-16T02:42:59.170",
"Id": "38872",
"Score": "0",
"body": "Brittle? hmm.. It makes sense that the initial value of DaysOff would be \"none\". An int defaults to zero - same difference. The default value is what it is. The main point is defining/declaring \"undefined\"/\"none\" up front, the enum default just makes that particular value convenient to be defined as such. This is especially good when I'm converting text-based \"code\" values to enums. Helps trapping errors and keeps the enum-handling code from having to know about the \"raw\" code values. Also good when business rules do not specify a default value."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-05T19:18:59.837",
"Id": "24774",
"ParentId": "24755",
"Score": "6"
}
},
{
"body": "<p>The logic in the first case can be simplified by making two observations:</p>\n\n<ul>\n<li><code>differenceInDays == 0</code> behaves as <code>differenceInDays == 1</code></li>\n<li>For <code>d> 0</code>, <code>differenceInDays == d && arrivalDay.TimeOfDay.Hours > 22</code> behaves as <code>differenceInDays == d+1 && arrivalDay.TimeOfDay.Hours <= 22</code></li>\n</ul>\n\n<p>These observations give (following other answers in using an enum):</p>\n\n<pre><code>int halfDaysOff;\nif (typeOfDelegation) {\n if (differenceInDays == 0) differenceInDays++;\n if (arrivalDay.TimeOfDay.Hours > 22) differenceInDays++;\n halfDaysOff = differenceInDays - 1;\n}\nelse halfDaysOff = (differenceInDays > 29) ? 2 : 0;\nswitch (halfDaysOff) {\n case 0: return TimeOff.None;\n case 1: return TimeOff.HalfDay;\n default: return TimeOff.OneDay;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-12T09:21:56.243",
"Id": "25025",
"ParentId": "24755",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "24757",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-05T12:44:33.327",
"Id": "24755",
"Score": "11",
"Tags": [
"c#"
],
"Title": "Complex if else"
}
|
24755
|
<p>I develop my first async TCP socket server and client program in c# and would like to review the first parts of it. I like to get some information’s about smelly code that I missed and what I could improve in the program. I know it's a little bit much code, but it would awesome if you help me to improve my skills!</p>
<p>I have to classes <code>AsyncSocketListener</code> and <code>AsyncClient</code>. Both use events to tell the main program if messages sent or received. Here are the classes:</p>
<p><strong>AsyncSocketListener</strong></p>
<pre><code>static class AsyncSocketListener
{
private static ushort port = 8080;
private static ushort limit = 250;
private static ManualResetEvent mre = new ManualResetEvent(false);
private static Dictionary<int, StateObject> clients = new Dictionary<int, StateObject>();
#region Event handler
public delegate void MessageReceivedHandler(int id, String msg);
public static event MessageReceivedHandler MessageReceived;
public delegate void MessageSubmittedHandler(int id, bool close);
public static event MessageSubmittedHandler MessageSubmitted;
#endregion
/* Starts the AsyncSocketListener */
public static void StartListening()
{
IPHostEntry host = Dns.GetHostEntry(String.Empty);
IPAddress ip = host.AddressList[3];
IPEndPoint socket = new IPEndPoint(ip, port);
try
{
using (Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
listener.Bind(socket);
listener.Listen(limit);
while (true)
{
mre.Reset();
listener.BeginAccept(new AsyncCallback(OnClientConnect), listener);
mre.WaitOne();
}
}
}
catch (SocketException)
{
// TODO:
}
}
/* Gets a socket from the clients dictionary by his Id. */
private static StateObject getClient(int id)
{
StateObject state = new StateObject();
return clients.TryGetValue(id, out state) ? state : null;
}
/* Checks if the socket is connected. */
public static bool IsConnected(int id)
{
StateObject state = getClient(id);
return !(state.listener.Poll(1000, SelectMode.SelectRead) && state.listener.Available == 0);
}
/* Add a socket to the clients dictionary. Lock clients temporary to handle multiple access.
* ReceiveCallback raise a event, after the message receive complete. */
#region Receive data
public static void OnClientConnect(IAsyncResult result)
{
mre.Set();
StateObject state = new StateObject();
try
{
lock (clients)
{
state.Id = !clients.Any() ? 1 : clients.Keys.Max() + 1;
clients.Add(state.Id, state);
Console.WriteLine("Client connected. Get Id " + state.Id);
}
state.listener = (Socket)result.AsyncState;
state.listener = state.listener.EndAccept(result);
state.listener.BeginReceive(state.buffer, 0, StateObject.BufferSize, SocketFlags.None, new AsyncCallback(ReceiveCallback), state);
}
catch (SocketException)
{
// TODO:
}
}
public static void ReceiveCallback(IAsyncResult result)
{
StateObject state = (StateObject)result.AsyncState;
try
{
int receive = state.listener.EndReceive(result);
if (receive > 0)
state.sb.Append(Encoding.UTF8.GetString(state.buffer, 0, receive));
if (receive == StateObject.BufferSize)
state.listener.BeginReceive(state.buffer, 0, StateObject.BufferSize, SocketFlags.None, new AsyncCallback(ReceiveCallback), state);
else
{
MessageReceived(state.Id, state.sb.ToString());
state.sb = new StringBuilder();
}
}
catch (SocketException)
{
// TODO:
}
}
#endregion
/* Send(int id, String msg, bool close) use bool to close the connection after the message sent. */
#region Send data
public static void Send(int id, String msg, bool close)
{
StateObject state = getClient(id);
if (state == null)
throw new Exception("Client does not exist.");
if (!IsConnected(state.Id))
throw new Exception("Destination socket is not connected.");
try
{
byte[] send = Encoding.UTF8.GetBytes(msg);
state.Close = close;
state.listener.BeginSend(send, 0, send.Length, SocketFlags.None, new AsyncCallback(SendCallback), state);
}
catch (SocketException)
{
// TODO:
}
catch (ArgumentException)
{
// TODO:
}
}
private static void SendCallback(IAsyncResult result)
{
StateObject state = (StateObject)result.AsyncState;
try
{
state.listener.EndSend(result);
}
catch (SocketException)
{
// TODO:
}
catch (ObjectDisposedException)
{
// TODO:
}
finally
{
MessageSubmitted(state.Id, state.Close);
}
}
#endregion
public static void Close(int id)
{
StateObject state = getClient(id);
if (state == null)
throw new Exception("Client does not exist.");
try
{
state.listener.Shutdown(SocketShutdown.Both);
state.listener.Close();
}
catch (SocketException)
{
// TODO:
}
finally
{
lock (clients)
{
clients.Remove(state.Id);
Console.WriteLine("Client disconnected with Id {0}", state.Id);
}
}
}
}
</code></pre>
<p><strong>AsyncClient</strong></p>
<pre><code>class AsyncClient : IDisposable
{
private const ushort port = 8080;
private Socket listener = null;
private bool close = false;
public ManualResetEvent connected = new ManualResetEvent(false);
public ManualResetEvent sent = new ManualResetEvent(false);
public ManualResetEvent received = new ManualResetEvent(false);
#region Event handler
public delegate void ConnectedHandler(AsyncClient a);
public static event ConnectedHandler Connected;
public delegate void MessageReceivedHandler(AsyncClient a, String msg);
public static event MessageReceivedHandler MessageReceived;
public delegate void MessageSubmittedHandler(AsyncClient a, bool close);
public static event MessageSubmittedHandler MessageSubmitted;
#endregion
/* Starts the AsyncClient */
public AsyncClient()
{
}
public void StartClient()
{
IPHostEntry host = Dns.GetHostEntry(String.Empty);
IPAddress ip = host.AddressList[3];
IPEndPoint socket = new IPEndPoint(ip, port);
try
{
this.listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
this.listener.BeginConnect(socket, new AsyncCallback(OnConnectCallback), listener);
connected.WaitOne();
Connected(this);
}
catch (SocketException)
{
// TODO:
}
}
public bool IsConnected()
{
return !(this.listener.Poll(1000, SelectMode.SelectRead) && this.listener.Available == 0);
}
private void OnConnectCallback(IAsyncResult result)
{
Socket server = (Socket)result.AsyncState;
try
{
server.EndConnect(result);
connected.Set();
}
catch (SocketException)
{
}
}
#region Receive data
public void Receive()
{
StateObject state = new StateObject();
state.listener = this.listener;
state.listener.BeginReceive(state.buffer, 0, StateObject.BufferSize, SocketFlags.None, new AsyncCallback(ReceiveCallback), state);
}
private void ReceiveCallback(IAsyncResult result)
{
StateObject state = (StateObject)result.AsyncState;
int receive = state.listener.EndReceive(result);
if (receive > 0)
state.sb.Append(Encoding.UTF8.GetString(state.buffer, 0, receive));
if (receive == StateObject.BufferSize)
state.listener.BeginReceive(state.buffer, 0, StateObject.BufferSize, SocketFlags.None, new AsyncCallback(ReceiveCallback), state);
else
{
MessageReceived(this, state.sb.ToString());
state.sb = new StringBuilder();
received.Set();
}
}
#endregion
#region Send data
public void Send(String msg, bool close)
{
if (!IsConnected())
throw new Exception("Destination socket is not connected.");
byte[] response = Encoding.UTF8.GetBytes(msg);
this.close = close;
this.listener.BeginSend(response, 0, response.Length, SocketFlags.None, new AsyncCallback(SendCallback), this.listener);
}
private void SendCallback(IAsyncResult result)
{
try
{
Socket resceiver = (Socket)result.AsyncState;
resceiver.EndSend(result);
}
catch (SocketException)
{
// TODO:
}
catch (ObjectDisposedException)
{
// TODO;
}
MessageSubmitted(this, this.close);
sent.Set();
}
#endregion
private void Close()
{
try
{
if (IsConnected())
{
this.listener.Shutdown(SocketShutdown.Both);
this.listener.Close();
}
}
catch (SocketException)
{
// TODO:
}
}
public void Dispose()
{
connected.Close();
sent.Close();
received.Close();
Close();
}
}
</code></pre>
<p>I save the connection information in a third class called <code>StateObject</code>.</p>
<p><strong>StateObject</strong></p>
<pre><code>class StateObject
{
/* Contains the state information. */
private int id;
private bool close = false; // Used to close the socket after the message sent.
public Socket listener = null;
public const int BufferSize = 1024;
public byte[] buffer = new byte[BufferSize];
public StringBuilder sb = new StringBuilder();
public StateObject() { }
public int Id
{
get { return this.id; }
set { this.id = value; }
}
public bool Close
{
get { return this.close; }
set { this.close = value; }
}
}
</code></pre>
<p>With the following code I test the server and client:</p>
<pre><code>public Server()
{
InitializeComponent();
/* I use this to test my code on one machine. */
new Thread(new ThreadStart(AsyncSocketListener.StartListening)).Start();
AsyncSocketListener.MessageReceived += new AsyncSocketListener.MessageReceivedHandler(ClientMessageReceived);
AsyncSocketListener.MessageSubmitted += new AsyncSocketListener.MessageSubmittedHandler(ServerMessageSubmitted);
AsyncClient.Connected += new AsyncClient.ConnectedHandler(ConnectedToServer);
AsyncClient.MessageReceived += new AsyncClient.MessageReceivedHandler(ServerMessageReceived);
AsyncClient.MessageSubmitted += new AsyncClient.MessageSubmittedHandler(ClientMessageSubmitted);
for (int i = 0; i < 10; i++)
{
AsyncClient client = new AsyncClient();
Thread thread = new Thread(new ThreadStart(client.StartClient));
thread.Name = "Client" + i;
thread.Start();
}
}
/* Code to handle the events from AsyncSocketListener and AsyncClient. */
#region Server Code
private static void ClientMessageReceived(int id, String msg)
{
AsyncSocketListener.Send(id, msg.Replace("client", "server"), true);
Console.WriteLine("Server get Message from client. {0} ", msg);
}
private static void ServerMessageSubmitted(int id, bool close)
{
if (close)
AsyncSocketListener.Close(id);
}
#endregion
#region Client code
private static void ConnectedToServer(AsyncClient a)
{
a.Send("Hello, I'm the client.", false);
a.sent.WaitOne();
a.Receive();
a.received.WaitOne();
}
private static void ServerMessageReceived(AsyncClient a, String msg)
{
Console.WriteLine("Client get Message from server. {0} ", msg);
}
private static void ClientMessageSubmitted(AsyncClient a, bool close)
{
if (close)
a.Dispose();
}
#endregion
</code></pre>
<p>If the code is fine, I will use polymorphism for the <code>AsyncSocketListener</code> and <code>AsyncClient</code> because some parts are very similar. What do you think?</p>
<p><strong>Edit:</strong></p>
<p>At the moment the client could connect and send a message to the server. The server could reply on it. But it is not possible to exchange messages after this. I'm trying to fix this, but I can't find a solution. Any idea?</p>
|
[] |
[
{
"body": "<p>White space and Casing is good.</p>\n\n<p>Just a few things to think about:</p>\n\n<ol>\n<li><code>#region</code> is not very well accepted. If you have to use <code>#region</code>, then you should look at moving the code out into a method or its own class.</li>\n<li>Use var instead of explicit declarations for obvious variables. This makes the code much easier to scan over.</li>\n<li>If you insist on comments to explain what the method is doing, us the C# <code>///</code> syntax. This does a couple of things: it allows intellisense to pick up the description when using the library, and there are tools that can take the <code>///</code> comments and create API help documentation.</li>\n<li>General practice in C# is to use either m_ or _ at the beginning of class variables. This eliminates the need to use this., which clutters up the code a little.</li>\n<li>Be consistent with your use of <code>{ }</code> after if statements. It makes it eaasier to focus on the logic when it doesn't have to process changes in the formatting.</li>\n<li>In the line <code>thread.Name = \"Client\" + i;</code> I would make <code>\"Client\"</code> a constant.</li>\n<li>Separate concerns. For instance: <code>Console.WriteLine</code> does not belong in your server class.</li>\n<li>If the constructor doesn't do anything, get rid of it, it is only adding noise to your class.</li>\n<li>In my opinion, class variables should be initialized in the constructor, not on declaration.</li>\n<li>Use meaningful names for variables: <code>a</code> does not portray what the variable does. <code>tcpClient</code> on the other hand does. This makes your methods much easier to read.</li>\n<li><code>getClient</code> should be <code>GetClient</code>. C# naming conventions</li>\n</ol>\n\n<p>Most of these are minor, and don't affect the application, they just add that little bit to your code, and will make it easier to read and maintain in the future.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-05T15:00:30.420",
"Id": "38258",
"Score": "0",
"body": "Thanks for your reply! (1) I thought `#region` is just for structure and better reading. Why is it smelly? (3) The few commets are just for codereview :). (4) Nice to know. (7) `Console.WriteLine` is there just for testing. (9/10) Thanks, I will change. (11) Oh, yea you are right. What do you think about the events, to pass the messages to the main program?Is there a other, better way?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-05T15:08:19.760",
"Id": "38259",
"Score": "0",
"body": "Code smell might of been the wrong term, but it is bad practice to use it. There is a post on [Programmers.StackExchange](http://programmers.stackexchange.com/questions/53086/are-regions-an-antipattern-or-code-smell) that has a good discussion on it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-05T17:25:46.413",
"Id": "38271",
"Score": "0",
"body": "I don't see any `#region`s inside a method in the code, so I don't understand what do you mean by “pulling the code out into a method”."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-05T17:37:31.310",
"Id": "38273",
"Score": "0",
"body": "Changed bullet on `#region`. I hope its more clear now."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-05T14:48:13.497",
"Id": "24760",
"ParentId": "24758",
"Score": "5"
}
},
{
"body": "<p>0: Keep class members <code>private</code> unless there is a darn good reason to expose them. And then, if you have to, use properties.</p>\n\n<p>1: Use <code>readonly</code> on class declarations which are considered unmodifiable after construction. Example:</p>\n\n<pre><code>public readonly ManualResetEvent connected = new ManualResetEvent(false);\n</code></pre>\n\n<p>This declares intent and keeps other code from accidentally modifying an invariant. Plus, the runtime can sometimes perform certain optimizations knowing a field is <code>readonly</code>.</p>\n\n<p>2: Develop to interfaces. This allows for decoupling of implementation plus ease of testing/mocking.</p>\n\n<p>So this being said, here's how I refactored it:</p>\n\n<blockquote>\n <p>IStateObject:</p>\n</blockquote>\n\n<pre><code>public interface IStateObject\n{\n int BufferSize { get; }\n\n int Id { get; }\n\n bool Close { get; set; }\n\n byte[] Buffer { get; }\n\n Socket Listener { get; }\n\n string Text { get; }\n\n void Append(string text);\n\n void Reset();\n}\n</code></pre>\n\n<blockquote>\n <p>StateObject:</p>\n</blockquote>\n\n<pre><code>public sealed class StateObject : IStateObject\n{\n /* Contains the state information. */\n\n private const int Buffer_Size = 1024;\n private readonly byte[] buffer = new byte[Buffer_Size];\n private readonly Socket listener;\n private readonly int id;\n private StringBuilder sb;\n\n public StateObject(Socket listener, int id = -1)\n {\n this.listener = listener;\n this.id = id;\n this.Close = false;\n this.Reset();\n }\n\n public int Id\n {\n get\n {\n return this.id;\n }\n }\n\n public bool Close { get; set; }\n\n public int BufferSize\n {\n get\n {\n return Buffer_Size;\n }\n }\n\n public byte[] Buffer\n {\n get\n {\n return this.buffer;\n }\n }\n\n public Socket Listener\n {\n get\n {\n return this.listener;\n }\n }\n\n public string Text\n {\n get\n {\n return this.sb.ToString();\n }\n }\n\n public void Append(string text)\n {\n this.sb.Append(text);\n }\n\n public void Reset()\n {\n this.sb = new StringBuilder();\n }\n}\n</code></pre>\n\n<blockquote>\n <p>IAsyncSocketListener:</p>\n</blockquote>\n\n<pre><code>public interface IAsyncSocketListener : IDisposable\n{\n event MessageReceivedHandler MessageReceived;\n\n event MessageSubmittedHandler MessageSubmitted;\n\n void StartListening();\n\n bool IsConnected(int id);\n\n void OnClientConnect(IAsyncResult result);\n\n void ReceiveCallback(IAsyncResult result);\n\n void Send(int id, string msg, bool close);\n\n void Close(int id);\n}\n</code></pre>\n\n<blockquote>\n <p>AsyncSocketListener:</p>\n</blockquote>\n\n<pre><code>public delegate void MessageReceivedHandler(int id, string msg);\npublic delegate void MessageSubmittedHandler(int id, bool close);\n\npublic sealed class AsyncSocketListener : IAsyncSocketListener\n{\n private const ushort Port = 8080;\n private const ushort Limit = 250;\n\n private static readonly IAsyncSocketListener instance = new AsyncSocketListener();\n\n private readonly ManualResetEvent mre = new ManualResetEvent(false);\n private readonly IDictionary<int, IStateObject> clients = new Dictionary<int, IStateObject>();\n\n public event MessageReceivedHandler MessageReceived;\n\n public event MessageSubmittedHandler MessageSubmitted;\n\n private AsyncSocketListener()\n {\n }\n\n public static IAsyncSocketListener Instance\n {\n get\n {\n return instance;\n }\n }\n\n /* Starts the AsyncSocketListener */\n public void StartListening()\n {\n var host = Dns.GetHostEntry(string.Empty);\n var ip = host.AddressList[3];\n var endpoint = new IPEndPoint(ip, Port);\n\n try\n {\n using (var listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))\n {\n listener.Bind(endpoint);\n listener.Listen(Limit);\n while (true)\n {\n this.mre.Reset();\n listener.BeginAccept(this.OnClientConnect, listener);\n this.mre.WaitOne();\n }\n }\n }\n catch (SocketException)\n {\n // TODO:\n }\n }\n\n /* Gets a socket from the clients dictionary by his Id. */\n private IStateObject GetClient(int id)\n {\n IStateObject state;\n\n return this.clients.TryGetValue(id, out state) ? state : null;\n }\n\n /* Checks if the socket is connected. */\n public bool IsConnected(int id)\n {\n var state = this.GetClient(id);\n\n return !(state.Listener.Poll(1000, SelectMode.SelectRead) && state.Listener.Available == 0);\n }\n\n /* Add a socket to the clients dictionary. Lock clients temporary to handle multiple access.\n * ReceiveCallback raise a event, after the message receive complete. */\n #region Receive data\n public void OnClientConnect(IAsyncResult result)\n {\n this.mre.Set();\n\n try\n {\n IStateObject state;\n\n lock (this.clients)\n {\n var id = !this.clients.Any() ? 1 : this.clients.Keys.Max() + 1;\n\n state = new StateObject(((Socket)result.AsyncState).EndAccept(result), id);\n this.clients.Add(id, state);\n Console.WriteLine(\"Client connected. Get Id \" + id);\n }\n\n state.Listener.BeginReceive(state.Buffer, 0, state.BufferSize, SocketFlags.None, this.ReceiveCallback, state);\n }\n catch (SocketException)\n {\n // TODO:\n }\n }\n\n public void ReceiveCallback(IAsyncResult result)\n {\n var state = (IStateObject)result.AsyncState;\n\n try\n {\n var receive = state.Listener.EndReceive(result);\n\n if (receive > 0)\n {\n state.Append(Encoding.UTF8.GetString(state.Buffer, 0, receive));\n }\n\n if (receive == state.BufferSize)\n {\n state.Listener.BeginReceive(state.Buffer, 0, state.BufferSize, SocketFlags.None, this.ReceiveCallback, state);\n }\n else\n {\n var messageReceived = this.MessageReceived;\n\n if (messageReceived != null)\n {\n messageReceived(state.Id, state.Text);\n }\n\n state.Reset();\n }\n }\n catch (SocketException)\n {\n // TODO:\n }\n }\n #endregion\n\n /* Send(int id, String msg, bool close) use bool to close the connection after the message sent. */\n #region Send data\n public void Send(int id, string msg, bool close)\n {\n var state = this.GetClient(id);\n\n if (state == null)\n {\n throw new Exception(\"Client does not exist.\");\n }\n\n if (!this.IsConnected(state.Id))\n {\n throw new Exception(\"Destination socket is not connected.\");\n }\n\n try\n {\n var send = Encoding.UTF8.GetBytes(msg);\n\n state.Close = close;\n state.Listener.BeginSend(send, 0, send.Length, SocketFlags.None, this.SendCallback, state);\n }\n catch (SocketException)\n {\n // TODO:\n }\n catch (ArgumentException)\n {\n // TODO:\n }\n }\n\n private void SendCallback(IAsyncResult result)\n {\n var state = (IStateObject)result.AsyncState;\n\n try\n {\n state.Listener.EndSend(result);\n }\n catch (SocketException)\n {\n // TODO:\n }\n catch (ObjectDisposedException)\n {\n // TODO:\n }\n finally\n {\n var messageSubmitted = this.MessageSubmitted;\n\n if (messageSubmitted != null)\n {\n messageSubmitted(state.Id, state.Close);\n }\n }\n }\n #endregion\n\n public void Close(int id)\n {\n var state = this.GetClient(id);\n\n if (state == null)\n {\n throw new Exception(\"Client does not exist.\");\n }\n\n try\n {\n state.Listener.Shutdown(SocketShutdown.Both);\n state.Listener.Close();\n }\n catch (SocketException)\n {\n // TODO:\n }\n finally\n {\n lock (this.clients)\n {\n this.clients.Remove(state.Id);\n Console.WriteLine(\"Client disconnected with Id {0}\", state.Id);\n }\n }\n }\n\n public void Dispose()\n {\n foreach (var id in this.clients.Keys)\n {\n this.Close(id);\n }\n\n this.mre.Dispose();\n }\n}\n</code></pre>\n\n<blockquote>\n <p>IAsyncClient:</p>\n</blockquote>\n\n<pre><code>public interface IAsyncClient : IDisposable\n{\n event ConnectedHandler Connected;\n\n event ClientMessageReceivedHandler MessageReceived;\n\n event ClientMessageSubmittedHandler MessageSubmitted;\n\n void StartClient();\n\n bool IsConnected();\n\n void Receive();\n\n void Send(string msg, bool close);\n}\n</code></pre>\n\n<blockquote>\n <p>AsyncClient:</p>\n</blockquote>\n\n<pre><code>public delegate void ConnectedHandler(IAsyncClient a);\npublic delegate void ClientMessageReceivedHandler(IAsyncClient a, string msg);\npublic delegate void ClientMessageSubmittedHandler(IAsyncClient a, bool close);\n\npublic sealed class AsyncClient : IAsyncClient\n{\n private const ushort Port = 8080;\n\n private Socket listener;\n private bool close;\n\n private readonly ManualResetEvent connected = new ManualResetEvent(false);\n private readonly ManualResetEvent sent = new ManualResetEvent(false);\n private readonly ManualResetEvent received = new ManualResetEvent(false);\n\n public event ConnectedHandler Connected;\n\n public event ClientMessageReceivedHandler MessageReceived;\n\n public event ClientMessageSubmittedHandler MessageSubmitted;\n\n public void StartClient()\n {\n var host = Dns.GetHostEntry(string.Empty);\n var ip = host.AddressList[3];\n var endpoint = new IPEndPoint(ip, Port);\n\n try\n {\n this.listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);\n this.listener.BeginConnect(endpoint, this.OnConnectCallback, this.listener);\n this.connected.WaitOne();\n\n var connectedHandler = this.Connected;\n\n if (connectedHandler != null)\n {\n connectedHandler(this);\n }\n }\n catch (SocketException)\n {\n // TODO:\n }\n }\n\n public bool IsConnected()\n {\n return !(this.listener.Poll(1000, SelectMode.SelectRead) && this.listener.Available == 0);\n }\n\n private void OnConnectCallback(IAsyncResult result)\n {\n var server = (Socket)result.AsyncState;\n\n try\n {\n server.EndConnect(result);\n this.connected.Set();\n }\n catch (SocketException)\n {\n }\n }\n\n #region Receive data\n public void Receive()\n {\n var state = new StateObject(this.listener);\n\n state.Listener.BeginReceive(state.Buffer, 0, state.BufferSize, SocketFlags.None, this.ReceiveCallback, state);\n }\n\n private void ReceiveCallback(IAsyncResult result)\n {\n var state = (IStateObject)result.AsyncState;\n var receive = state.Listener.EndReceive(result);\n\n if (receive > 0)\n {\n state.Append(Encoding.UTF8.GetString(state.Buffer, 0, receive));\n }\n\n if (receive == state.BufferSize)\n {\n state.Listener.BeginReceive(state.Buffer, 0, state.BufferSize, SocketFlags.None, this.ReceiveCallback, state);\n }\n else\n {\n var messageReceived = this.MessageReceived;\n\n if (messageReceived != null)\n {\n messageReceived(this, state.Text);\n }\n\n state.Reset();\n this.received.Set();\n }\n }\n #endregion\n\n #region Send data\n public void Send(string msg, bool close)\n {\n if (!this.IsConnected())\n {\n throw new Exception(\"Destination socket is not connected.\");\n }\n\n var response = Encoding.UTF8.GetBytes(msg);\n\n this.close = close;\n this.listener.BeginSend(response, 0, response.Length, SocketFlags.None, this.SendCallback, this.listener);\n }\n\n private void SendCallback(IAsyncResult result)\n {\n try\n {\n var resceiver = (Socket)result.AsyncState;\n\n resceiver.EndSend(result);\n }\n catch (SocketException)\n {\n // TODO:\n }\n catch (ObjectDisposedException)\n {\n // TODO;\n }\n\n var messageSubmitted = this.MessageSubmitted;\n\n if (messageSubmitted != null)\n {\n messageSubmitted(this, this.close);\n }\n\n this.sent.Set();\n }\n #endregion\n\n private void Close()\n {\n try\n {\n if (!this.IsConnected())\n {\n return;\n }\n\n this.listener.Shutdown(SocketShutdown.Both);\n this.listener.Close();\n }\n catch (SocketException)\n {\n // TODO:\n }\n }\n\n public void Dispose()\n {\n this.connected.Dispose();\n this.sent.Dispose();\n this.received.Dispose();\n this.Close();\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-05T17:50:43.913",
"Id": "38278",
"Score": "0",
"body": "Thanks, looks great :) Is there a different if I use `IStateObject state` or `StateObject state`? Would you use polymorphism for AsyncSocketListener and AsyncClient? My Idea was to make one Interface for example for Send(), Start(), Close(), ..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-05T17:54:58.517",
"Id": "38279",
"Score": "0",
"body": "The reason I factored out `IStateObject` is twofold: first, it could be that sometime in the future you want to alternate between implementations - for example `StateObject` vs. `LoggingStateObject` where the latter dumps client/server conversations to storage. The second reason is, as I alluded to, Mocking frameworks can create fake implementations of the interface for unit testing your other classes independently."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-05T17:58:19.183",
"Id": "38280",
"Score": "0",
"body": "You could define an additional interface, `IConnection` or something that each has to implement as those operations you mention are common between servers and clients. I don't see that as a bad thing at all."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T06:11:21.527",
"Id": "38364",
"Score": "0",
"body": "Ok. Thank you very much! What do you think about the events to get the received messages and so on..? Is there a better way?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T12:21:06.693",
"Id": "38385",
"Score": "0",
"body": "It's pretty canonical the way you have it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-03-20T07:48:12.540",
"Id": "152171",
"Score": "0",
"body": "Thanks for solution. Can I use this code for base of highload client/server application? And what about interact with UI in WinForms and WPF? Thanks you."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-05T17:22:15.240",
"Id": "24766",
"ParentId": "24758",
"Score": "9"
}
}
] |
{
"AcceptedAnswerId": "24766",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-05T14:04:38.687",
"Id": "24758",
"Score": "10",
"Tags": [
"c#",
"asynchronous",
"socket",
"server",
"client"
],
"Title": "TCP async socket server client communication"
}
|
24758
|
<p>I am writing a CSV file generator that's filtering through about seven million database entries (MySQL backend). This part is especially slow and I was wondering if there is a way to make it much faster. I was thinking of wiring to a temp file first before serving it and then deleting the file.</p>
<p>The <code>Station.header()</code> returns a list with header names <code>['a','b','c']</code>, etc.</p>
<p>Is there an advantage to this? Is there a better way?</p>
<pre><code>def metadata_file(request):
"""Gets metadata for sensors"""
if request.GET.has_key('all'):
s101 = Station.objects.all().filter(fwy='101', dir='S',
abs_pm__gte=420.80, abs_pm__lte=431.63)
s280 = Station.objects.all().filter(fwy='280', dir='S',
abs_pm__gte=41.16, abs_pm__lte=56.49)
q = s101|s280
response = HttpResponse(mimetype='text/csv')
response['Content-Disposition'] = 'attachment; filename="all_stations.csv"'
writer = csv.writer(response)
writer.writerow(Station().header())
for x in q:
writer.writerow(x.line())
return response
</code></pre>
|
[] |
[
{
"body": "<h3>1. Introduction</h3>\n\n<p>By coincidence, I'm working on a similar problem right now, so here's a chance for me to write up an experiment I ran today, in the hope that it might prove useful. However, the solution presented below is far from ideal (see section 3).</p>\n\n<h3>2. The idea</h3>\n\n<p>Processing your query results through Django's ORM and then through <a href=\"http://docs.python.org/2/library/csv.html#csv.writer\"><code>csv.writer</code></a> is time-consuming. You can speed things up by getting the database to write the query output directly to a file and then serving that file.</p>\n\n<p>First, your database user needs to have <a href=\"http://dev.mysql.com/doc/refman/5.1/en/privileges-provided.html#priv_file\"><code>FILE</code> privilege</a> in order to be able to write files:</p>\n\n<pre><code>mysql> GRANT FILE ON *.* TO 'user'@'host';\n</code></pre>\n\n<p>Then you need to run your query with MySQL's <a href=\"http://dev.mysql.com/doc/refman/5.0/en/select-into.html\"><code>INTO OUTFILE</code></a> clause. You can get the query you need from Django by calling <code>.query.sql_with_params()</code>:</p>\n\n<pre><code>from django.db.models import Q\ns101 = Q(fwy='101', dir='S', abs_pm__gte=420.80, abs_pm__lte=431.63)\ns280 = Q(fwy='280', dir='S', abs_pm__gte=41.16, abs_pm__lte=56.49)\nsql, params = Station.objects.filter(s101|s280).query.sql_with_params()\n</code></pre>\n\n<p>Add the <code>INTO OUTFILE</code> clause:</p>\n\n<pre><code>sql += ''' INTO OUTFILE %s\n FIELDS TERMINATED BY ','\n OPTIONALLY ENCLOSED BY '\"'\n LINES TERMINATED BY '\\n' '''\n</code></pre>\n\n<p>Pick a place to put the CSV:</p>\n\n<pre><code>import os.path\ncsv_path = os.path.join(csv_directory, csv_filename)\n</code></pre>\n\n<p>Run the query:</p>\n\n<pre><code>from django.db import connection\ncursor = connection.cursor()\ncursor.execute(sql, params + (csv_path,))\n</code></pre>\n\n<p>Send the file (using <a href=\"https://docs.djangoproject.com/en/1.5/ref/request-response/#django.http.StreamingHttpResponse\"><code>StreamingHttpResponse</code></a> which is new in Django 1.5):</p>\n\n<pre><code>from django.http import StreamingHttpResponse\nresponse = StreamingHttpResponse(open(csv_path), content_type='text/csv')\nresponse['Content-Disposition'] = 'attachment; filename=' + csv_filename\nreturn response\n</code></pre>\n\n<h3>3. Analysis</h3>\n\n<p>In my test cases (about a million records) this is around ten times as fast as processing the data through <code>csv.writer</code> in Python.</p>\n\n<p>But there are several problems, mostly related to security:</p>\n\n<ol>\n<li><p>This depends on the MySQL server being on the same machine as the Django web server. You can imagine working around this by some kind of reverse proxying but it all gets rather complicated.</p></li>\n<li><p>Granting <code>FILE</code> access to your MySQL user is dangerous because it means that a SQL injection attacker can read and write files on your disk. You might want to create a separate MySQL user just to generate these CSV files, and you'll definitely want to set MySQL's <a href=\"http://dev.mysql.com/doc/refman/5.1/en/server-system-variables.html#sysvar_secure_file_priv\"><code>secure_file_priv</code></a> variable.</p></li>\n<li><p>Even if the attacker can't inject SQL, they may be able to cause your disk to fill up with these temporary files. You need a plan for how they are going to be deleted. (Maybe using the <a href=\"https://docs.djangoproject.com/en/dev/ref/signals/#django.core.signals.request_finished\"><code>request_finished</code> signal</a>?)</p></li>\n<li><p>You need to find somewhere safe to put them (a directory to which the MySQL database user has write access).</p></li>\n</ol>\n\n<h3>4. Update</h3>\n\n<p>I did some more timing experiments today, trying out five different ways of generating and downloading the CSV, summarized in the table below:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>+------+-----------------------+-------+\n| | through Django |Direct |\n| |Streaming|Not streaming|from DB|\n+------+---------+-------------+-------+\n|ORM | 630| 370| N/A| \n+------+---------+-------------+-------+\n|No ORM| 190| 125| 58| \n+------+---------+-------------+-------+\n</code></pre>\n\n<p>Notes on the table:</p>\n\n<ul>\n<li>Times are in seconds.</li>\n<li>This is for a query with a million rows that generates 150 MiB of CSV.</li>\n<li>\"ORM\" means that I passed the query results through Django's object-relational mapping system before generating the CSV.</li>\n<li>\"No ORM\" means that I avoided this by running a custom SQL query.</li>\n<li>\"Streaming\" means that I used a <code>StreamingHttpResponse</code> and generated the CSV one line at a time using a technique I'll describe below.</li>\n<li>\"Not streaming\" means that I used the <a href=\"https://docs.djangoproject.com/en/dev/howto/outputting-csv/\">technique described in the Django documentation</a> to generate the CSV. (This involves reading the entire CSV output into memory, which is a bit painful for other processes running on the server.)</li>\n<li>\"Direct\" is the technique described in section 2 above, using MySQL's <code>INTO OUTFILE</code> clause.</li>\n</ul>\n\n<p>Clearly Django's ORM and Python's <code>csv.writer</code> are both significant bottlenecks. If only the <code>INTO OUTFILE</code> approach weren't so painful!</p>\n\n<p>So I would still be interested to see other suggestions for speeding up this operation.</p>\n\n<h3>5. Appendix: streaming CSV download</h3>\n\n<p>Python's <code>csv</code> module doesn't provide an easy way to generate one record at a time, but you can coerce it into doing so like this, using <a href=\"http://docs.python.org/2/library/io.html#io.BytesIO\"><code>io.BytesIO</code></a> to capture the output:</p>\n\n<pre><code>from io import BytesIO\n\ndef writerow(row):\n \"\"\"Format row in CSV format and return it as a byte string.\"\"\"\n bio = BytesIO()\n csv.writer(bio).writerow([unicode(r).encode('utf-8') for r in row])\n return bio.getvalue()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-05T20:08:09.103",
"Id": "38288",
"Score": "0",
"body": "Awesome! I didn't know about the **StreamingHttpResponse**. Thanks a lot for this comprehensive write up as well. Let's see if anyone else will contribute so we can both implement the best."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-05T16:54:16.380",
"Id": "24763",
"ParentId": "24761",
"Score": "11"
}
}
] |
{
"AcceptedAnswerId": "24763",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-05T14:50:29.263",
"Id": "24761",
"Score": "10",
"Tags": [
"python",
"performance",
"csv",
"http",
"django"
],
"Title": "Faster Django CSV generation for several million database entries"
}
|
24761
|
<p>I've been playing around with 8051 assembly lately and thought I would make a little project of implementing RC4, since it is pretty interesting and the algorithm doesn't seem too hard. Plus, taking <code>mod 256</code> is REALLY easy when you're only working with single bytes.</p>
<p>Below I've included my (hopefully well-commented) code. I based my algorithm on the description given on Wikipedia <a href="http://en.wikipedia.org/wiki/RC4" rel="nofollow noreferrer">here</a> and use the same naming conventions (<code>i</code>, <code>j</code>, <code>S[i]</code>). I am new to the 8051 and assembly in general and am just looking for any optimization advice. Do my uses of subroutines and the way I assigned i-l make sense? Am I failing to use important standard conventions?</p>
<p>(BTW, I have simulated the key schedule algorithm and the keystream matches the test vector <a href="https://datatracker.ietf.org/doc/html/draft-josefsson-rc4-test-vectors-02" rel="nofollow noreferrer">here</a> for a 5-byte key 0x0102030405, so I am at least mostly confident in my code's math.)</p>
<pre><code>$NOSYMBOLS
$INCLUDE (C:\RIDE\INC\51\REG51.INC)
$INCLUDE (C:\RIDE\INC\51\VECTORS51.INC)
i DATA 06h;
j DATA 07h;
k DATA 08h;
l DATA 09h;
ORG 0;
LJMP STARTUP;
ORG 600h;
STARTUP: MOV SP, #6Fh; move stack pointer to a safely high address
ACALL READ_KEY;
ACALL FILL_S;
ACALL KSA;
ACALL INIT_INDICIES; clear i and j for the last time before encryption begins. from here on out, they change only when the PRNG cycles
MOV k, #03h; run DROP 3 times = 768 cycles
ACALL DROP;
ACALL ENCRYPT;
SJMP STOP; finished, loop forever
; read the key from 3100h to R1-R5
READ_KEY: MOV DPTR, #3100h; set DPTR to address of first byte of key
MOVX A, @DPTR; move first byte of key into A
MOV R1, A; copy first byte of key to R1
INC DPTR; set DPTR to address of second byte of key
MOVX A, @DPTR; etc
MOV R2, A; etc
INC DPTR; etc
MOVX A, @DPTR;
MOV R3, A;
INC DPTR;
MOVX A, @DPTR;
MOV R4, A;
INC DPTR;
MOVX A, @DPTR;
MOV R5, A;
RET;
; place the identity permutation (0, 1, 2, ..., FF) at 3000h-30FFh
FILL_S: MOV DPTR #3000h; S array begins at 3000h
CLR A; known startup state
LOOP_S: MOVX @DPTR, A; fill S
INC A; get ready for the next number...
INC DPTR; ...and the next address
CJNE A, #0FFh, LOOP_S; jump back until all 256 values are written
RET;
KSA: ACALL INIT_INDICIES; zero i and j
MOV DPTR, #3000h; head back to the start of the S array
KSA_SHUFFLE: MOVX A, @DPTR; grab S[i] and bring it to A
ADD A, j; get S[i] + j
PUSH ACC; store S[i] + j for later
;time to get (i mod 5) +1
MOV A, i;
MOV B, #05h; prepare for division
DIV AB; B will contain the remainder which is i mod 5
MOV A, B; get the remainder into a more convenient register
ADD A, #01h; add 1 b/c we start at R1, not R0
MOV R0, A; put address of key[i mod 5] in R0
MOV A, @R0; get the chosen key byte
POP 0; get S[i] + j back, this time into R0
ADD A, R0; finally, S[i] + j + key[i mod 5]
MOV j, A; store the new j
; and now the actual shuffle (swap S[i] and S[j])
; the top byte of DPTR is still 30h
MOV DPL, i; set DPTR to location of S[i]
MOVX A, @DPTR; read in S[i]...
PUSH R0; ...and save it for later
MOV DPL, j; now go to location of S[j]
MOVX A, @DPTR; read in S[j]...
XCH A, R0; ...save S[j] for later, get S[i] back in A
MOVX @DPTR, A; put the old value of S[i] at S[j]
MOV DPL, i; head on back to the location of S[i]
MOV A, R0; put the old S[j] value in A
MOVX @DPTR, A; and finally write old S[j] to its new home in S[i]
INC i; we did it once
MOV DPL, i; set address of the next S[i] to grab
CJNE R6, #0FFh, KSA_SHUFFLE; lather, rinse, and repeat (R6 = i)
RET;
; "warm up" the prng by running a multiple of 256 times based on the value of k
DROP: CLR 20.1; clear the "output keystream" flag
DROP_LOOP: ACALL PRNG_CYCLE; cycle the PRNG
CJNE R6, #FFh DROP_LOOP; go back 256 times
DJNZ 08, DROP_LOOP; decrement k (at address 8) and jump back if not zero
RET;
; encrypt the message stored at 3200h-32FFh;
ENCRYPT: MOV DPH, #32h; head over to where the message is stored
MOV l, #0h; known starting state
SETB 20.1; we want to get the keystream!
MOV DPL, l; get the right byte of the message
ENCRYPT_LOOP: MOVX A, @DPTR; get the first byte of the message
MOV DPH, #30h; get ready for PRNG_CYCLE--it expects to be around 0x30xx
ACALL PRNG_CYCLE; gets the next byte of the keystream, store it in k
XRL A, 08; (08 = k) perform the encryption!
MOV DPH, #32h; move to where we need to be to write the ciphertext
MOVX @DPTR, A; write back the encrypted byte
INC l; get ready for the next byte
CJNE 09, #0FFh, ENCRYPT_LOOP; do it again, unless we've finished the message (09 = l)
RET;
PRNG_CYCLE: INC i;
MOV DPL, i; set DPTR to location of S[i]
MOVX A, @DPTR; get S[i]
PUSH ACC; save S[i] for a moment
ADD A, j; get S[i] + j
MOV j, A; store the new j
POP ACC; get S[i] back
MOV R1, A; ...and save it for later
MOV DPL, j; now go to location of S[j]
MOVX A, @DPTR; read in S[j]...
XCH A, R0; save S[j] for later, get back S[i]
MOVX @DPTR, A; put the old value of S[i] at S[j]
MOV DPL, i; head on back to the location of S[i]
MOV A, R0; put the old S[j] value in A
MOVX @DPTR, A; and finally write old S[j] to its new home in S[i]
JNB 20.1, END_PRNG_CYCLE; don't output the keystream value if we're just warming up the PRNG
ADD A, R1; S[i] + S[j]
MOV DPL, A; put address of S[S[i] + S[j] mod 256] in DPTR
MOVX A, @DPTR; read in S[S[i] + S[j] mod 256]
MOV k, A; store they keystream value in k for use by ENCRYPT
END_PRNG_CYCLE: RET;
; zero my indicies i and j
INIT_INDICIES: MOV i, #00h; zero i (R6)
MOV j, #00h; zero j (R7)
RET;
STOP: NOP;
SJMP STOP;
END
</code></pre>
|
[] |
[
{
"body": "<p>I'm not familiar with 8051 assembly in particular, but there are some readability things I want to point out.</p>\n\n<p><strong>Commenting</strong></p>\n\n<p>It would be more readable to vertically-align all the comments provided for the individual lines. With the code and comments condensed like this, it's hard to distinguish them from the code. Both should easily be able to stand out from each other.</p>\n\n<p>It may also be beneficial to have a description and register usage given at the top of each procedure.</p>\n\n<p>Consider something in this form:</p>\n\n<pre><code>; procedure name\n; procedure description\n;\n; register 1 - what it stores, if used\n; ...\n; register n - what it stores, if used\n</code></pre>\n\n<p><strong>Procedures</strong></p>\n\n<p>I like that there are breaks between the procedures, which allows me to tell apart the separate procedures. However, you can do more here for readability.</p>\n\n<p>I'd recommend keeping the procedure labels on their own lines. The accompanying commands, arguments, and comments could also be vertically-aligned with each other.</p>\n\n<p>Here's an example:</p>\n\n<pre><code>procedure:\n; command arguments comments\n; command arguments comments\n; command arguments comments\n</code></pre>\n\n<p>This would especially be useful with your jump commands, as you should clearly be able to tell which labels are used in your program.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T10:35:44.873",
"Id": "75575",
"Score": "0",
"body": "IMO it's not a bad idea to comment every line of assembly; but it would be more readable if the comments were vertically aligned. Vertical alignment is a bore to write and maintain, but then again it is assembly. [See e.g. here for an example of comments.](http://codereview.stackexchange.com/q/23245/34757)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T14:57:36.627",
"Id": "75611",
"Score": "0",
"body": "@ChrisW: Oh yeah. I was thinking about that, but I forgot about vertically-aligned. I'll make the changes."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T00:32:48.737",
"Id": "43662",
"ParentId": "24762",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-05T16:09:15.203",
"Id": "24762",
"Score": "7",
"Tags": [
"optimization",
"beginner",
"cryptography",
"assembly"
],
"Title": "RC4 in 8051 assembly optimization"
}
|
24762
|
<p>I am writing Python code for a Tic Tac Toe game. I need to write a function that takes in three inputs: board, x, and y. Board being the current display of the board and then x and y being values of 0, 1, or 2. The game is set up to ask the user for coordinates.</p>
<pre><code>def CheckVictory(board, x, y):
#check if previous move was on vertical line and caused a win
if board[0][y] == ('X') and board[1][y] == ('X') and board [2][y] == ('X'):
return True
if board[0][y] == ('O') and board[1][y] == ('O') and board [2][y] == ('O'):
return True
#check if previous move was on horizontal line and caused a win
if board[x][0] == ('X') and board[x][1] == ('X') and board [x][2] == ('X'):
return True
if board[x][0] == ('O') and board[x][1] == ('O') and board [x][2] == ('O'):
return True
#check if previous move was on the main diagonal and caused a win
if board[0][0] == ('X') and board[1][1] == ('X') and board [2][2] == ('X'):
return True
if board[0][0] == ('O') and board[1][1] == ('O') and board [2][2] == ('O'):
return True
#check if previous move was on the secondary diagonal and caused a win
if board[0][2] == ('X') and board[1][1] == ('X') and board [2][0] == ('X'):
return True
if board[0][2] == ('O') and board[1][1] == ('O') and board [2][0] == ('O'):
return True
return False
#end of CheckVictory function
</code></pre>
<p>The function is called in the game loop like so:</p>
<pre><code>p_x, p_y = playerTurn(board) #let player take turn
displayBoard(board) #show board after move has been made
if CheckVictory(board, p_x, p_y): #see if user has won
print("CONGRATULATIONS, you win!")
newGame(board) #game over start new one
continue
</code></pre>
<p>and it's similar for the computer turn.</p>
<p>I feel like there is a better way to write this function. I feel like I should be using x and y more or there is a better way to check rather than writing all the possibilities. What's a better way to write this to make it short and concise?</p>
|
[] |
[
{
"body": "<p>I would start by removing duplication. If you pass in the mark that the player being checked is using, then you can eliminate 1/2 your code.</p>\n\n<pre><code>def CheckVictory(board, x, y, mark):\n\n if board[x][0] == (mark) and board[x][1] == (mark) and board [x][2] == (mark):\n return True\n\n if board[0][y] == (mark) and board[1][y] == (mark) and board [2][y] == (mark):\n return True\n\n #check if previous move was on the main diagonal and caused a win\n if board[0][0] == (mark) and board[1][1] == (mark) and board [2][2] == (mark):\n return True\n\n #check if previous move was on the secondary diagonal and caused a win\n if board[0][2] == (mark) and board[1][1] == (mark) and board [2][0] == (mark):\n return True \n\n return False \n\n#end of CheckVictory function\n</code></pre>\n\n<p>Please excuse me if I have syntax wrong, I've never used python before.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-09T07:08:10.583",
"Id": "38459",
"Score": "0",
"body": "...or set `mark = board[x][y]` inside the function."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-05T17:33:29.717",
"Id": "24768",
"ParentId": "24764",
"Score": "2"
}
},
{
"body": "<p>For a start you could make your code twice smaller by removing the logic common to 'X' and to 'O'.\nThen, you can perform all the comparisons in one go.</p>\n\n<pre><code>def CheckVictory(board, x, y):\n playerSymbols=['X','O']\n\n #check if previous move was on vertical line and caused a win\n if (board[0][y] in playerSymbols) and board[0][y] == board[1][y] == board[2][y]:\n\n #check if previous move was on horizontal line and caused a win\n if (board[x][0] in playerSymbols) and board[x][0] == board[x][1] == board [x][2]:\n return True\n\n #check if previous move was on the main diagonal and caused a win\n if (board[0][0] in playerSymbols) and board[0][0] == board[1][1] == board [2][2]:\n\n #check if previous move was on the secondary diagonal and caused a win\n if (board[0][2] in playerSymbols) and board[0][2] == board[1][1] == board [2][0]:\n return True\n\n return False \n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-05T17:43:37.657",
"Id": "24770",
"ParentId": "24764",
"Score": "0"
}
},
{
"body": "<p>Notes:</p>\n\n<ul>\n<li><p><code>CheckVictory</code>: Idiomatic in Python is <code>check_victory</code>.</p></li>\n<li><p><code>CheckVictory(board, x, y)</code>: I think you are mixing two things here, putting a value in the board and checking if someone won. Your function should be doing only one thing, checking if someone won on a given <code>board</code>. </p></li>\n<li><p>A standard approach is to prepare all the data you need (here, the positions/coordinates to check) and leave the code as simple as possible. </p></li>\n</ul>\n\n<p>I'd write:</p>\n\n<pre><code>positions_groups = (\n [[(x, y) for y in range(3)] for x in range(3)] + # horizontals\n [[(x, y) for x in range(3)] for y in range(3)] + # verticals\n [[(d, d) for d in range(3)]] + # diagonal from top-left to bottom-right\n [[(2-d, d) for d in range(3)]] # diagonal from top-right to bottom-left\n)\n\ndef get_winner(board):\n \"\"\"Return winner piece in board (None if no winner).\"\"\"\n for positions in positions_groups:\n values = [board[x][y] for (x, y) in positions]\n if len(set(values)) == 1 and values[0]:\n return values[0]\n\nboard = [\n [\"X\", \"X\", \"O\"],\n [\"O\", \"X\", \"X\"],\n [\"O\", \"X\", \"O\"],\n]\n\nprint(get_winner(board)) # \"X\"\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-09-16T19:35:47.273",
"Id": "115214",
"Score": "0",
"body": "\"I think you are mixing two things here\" - no, it's just using the location of the last move (which must be part of any newly-created victory) to narrow down the scope of the search."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-05T20:37:28.810",
"Id": "24775",
"ParentId": "24764",
"Score": "0"
}
},
{
"body": "<p>You know that a mark has been placed at <code>board[x][y]</code>. Then you only need this to check for a win on vertical line <code>y</code>:</p>\n\n<pre><code>if board[0][y] == board[1][y] == board [2][y]\n</code></pre>\n\n<p>Your comments state \"check if previous move was on the main/secondary diagonal\", but you don't actually check. You can use the expressions <code>x == y</code> and <code>x + y == 2</code> to check that.</p>\n\n<p>Simplified code:</p>\n\n<pre><code>def CheckVictory(board, x, y):\n\n #check if previous move caused a win on vertical line \n if board[0][y] == board[1][y] == board [2][y]:\n return True\n\n #check if previous move caused a win on horizontal line \n if board[x][0] == board[x][1] == board [x][2]:\n return True\n\n #check if previous move was on the main diagonal and caused a win\n if x == y and board[0][0] == board[1][1] == board [2][2]:\n return True\n\n #check if previous move was on the secondary diagonal and caused a win\n if x + y == 2 and board[0][2] == board[1][1] == board [2][0]:\n return True\n\n return False \n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-09T07:24:36.103",
"Id": "24890",
"ParentId": "24764",
"Score": "5"
}
},
{
"body": "<p>This solution will check horizontal lines, vertical lines and diagonal lines for a winner and return the player number. I just used player numbers 1, 2 instead of 'x', 'o' to avoid numpy array conversions.</p>\n\n<pre><code>board = np.empty((BOARD_SIZE,BOARD_SIZE))\nwinner_line = [\n np.array([1, 1, 1]),\n np.array([2, 2, 2])\n]\n\ndef CheckVictory(board):\n for idx in range(BOARD_SIZE):\n row = board[idx, :]\n col = board[:, idx]\n diagonal_1 = np.diagonal(board)\n diagonal_2 = np.diagonal(np.fliplr(board))\n\n # Check for each player\n for player in range(1,3):\n if np.all(row == winner_line[player-1]) \\\n or np.all(col == winner_line[player-1]) \\\n or np.all(diagonal_1 == winner_line[player-1]) \\\n or np.all(diagonal_2 == winner_line[player-1]):\n return player # There is a winner\n return False # No winner\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-11-08T11:10:10.873",
"Id": "179899",
"ParentId": "24764",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "24890",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-05T16:58:50.477",
"Id": "24764",
"Score": "4",
"Tags": [
"python",
"tic-tac-toe"
],
"Title": "Tic Tac Toe victory check"
}
|
24764
|
<p>I'm trying to get the most out of this code, so I would understand what should I look for in the future. The code below, works fine, I just want to make it more efficient. </p>
<p>Any suggestions?</p>
<pre><code>from mrjob.job import MRJob
import operator
import re
# append result from each reducer
output_words = []
class MRSudo(MRJob):
def init_mapper(self):
# move list of tuples across mapper
self.words = []
def mapper(self, _, line):
command = line.split()[-1]
self.words.append((command, 1))
def final_mapper(self):
for word_pair in self.words:
yield word_pair
def reducer(self, command, count):
# append tuples to the list
output_words.append((command, sum(count)))
def final_reducer(self):
# Sort tuples in the list by occurence
map(operator.itemgetter(1), output_words)
sorted_words = sorted(output_words, key=operator.itemgetter(1), reverse=True)
for result in sorted_words:
yield result
def steps(self):
return [self.mr(mapper_init=self.init_mapper,
mapper=self.mapper,
mapper_final=self.final_mapper,
reducer=self.reducer,
reducer_final=self.final_reducer)]
if __name__ == '__main__':
MRSudo.run()
</code></pre>
|
[] |
[
{
"body": "<p>Since the reduce function in this case is commutative and associative you can use a combiner to pre-aggregate values.</p>\n\n<pre><code>def combiner_count_words(self, word, counts):\n # sum the words we've seen so far\n yield (word, sum(counts))\n\ndef steps(self):\n return [self.mr(mapper_init=self.init_mapper,\n mapper=self.mapper,\n mapper_final=self.final_mapper,\n combiner= self.combiner_count_words,\n reducer=self.reducer,\n reducer_final=self.final_reducer)]\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-08-19T09:31:24.787",
"Id": "101347",
"ParentId": "24776",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-05T20:40:26.903",
"Id": "24776",
"Score": "3",
"Tags": [
"python"
],
"Title": "How to improve performace of this Map Reduce function, Python mrjob"
}
|
24776
|
<p>Looking for a review of my first published jQuery Plugin. It's for TreeViews, very basic example demo can be seen at: <a href="http://goodcodeguy.github.io/demos/goodtree/index.html" rel="nofollow noreferrer">Demo</a></p>
<p>Everything works fine, just looking to see if I can get some feedback on things that I may be doing wrong best practices wise and/or things I could be doing better.</p>
<pre><code>(function ( $ ) {
var methods = {
init : function(options) {
// Default Settings
var settings = $.extend({
'expandIconClass' : 'closed',
'contractIconClass' : 'open',
'setFocus' : undefined,
'classPrefix' : 'goodtree_',
}, options);
return this.each(function() {
// Hide all of the children Elements
$(this).find('ul').hide();
// Add the plus minus buttons
$(this).find('li').each(function() {
if($(this).children('ul').length > 0)
$(this).prepend($('<div />', {'class': settings.classPrefix + "toggle " + settings.expandIconClass}));
});
// Events
$('.' + settings.classPrefix + 'toggle').click(function() {
$(this).parent().children('ul').toggle();
$(this).hasClass('open')
? $(this).removeClass(settings.contractIconClass).addClass(settings.expandIconClass)
: $(this).removeClass(settings.expandIconClass).addClass(settings.contractIconClass);
});
if(undefined !== settings.setFocus)
{
$(this).goodtree('setFocus', settings.setFocus);
}
});
},
setFocus : function(obj) {
return this.each(function() {
var tree_parent = this;
$(obj).parents('ul').each(function() {
if($(this) === this)
return;
else
$(this).show();
});
});
}
}
$.fn.goodtree = function( method ) {
if ( methods[method] ) {
return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof method === 'object' || ! method ) {
return methods.init.apply( this, arguments );
} else {
$.error( 'Method ' + method + ' does not exist on jQuery.goodtree' );
}
};
}) ( jQuery );
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-05T21:30:49.827",
"Id": "38289",
"Score": "0",
"body": "Just a question why are you doing ` var tree_parent = this;` if you do not use the var tree parent after!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T13:10:11.220",
"Id": "38387",
"Score": "0",
"body": "because it was a bug...I need to be comparing to tree_parent in the comparison"
}
] |
[
{
"body": "<p>First off it'd be good to run the code through <a href=\"http://jslint.org\" rel=\"nofollow\">jslint</a> or <a href=\"http://jshint.org\" rel=\"nofollow\">jshint</a>. It identifies a few issues, such as an extra comma in the default options list; that'll break the code in older IE versions. Also, it flags some things like the block-less <code>if</code>, which - while allowed - it's best to avoid for the sake of consistency and maintainability.</p>\n\n<p>As for the code itself, here are the things I noticed:</p>\n\n<ul>\n<li>jQuery objects should be cached whenever possible</li>\n<li>The code only handles unordered lists (<code>UL</code>s), not ordered lists (<code>OL</code>) although it might as well</li>\n<li>The event handling is added document-wide every time the code is run. If you use the plugin twice in a document, the first tree gets double event handlers. That spells trouble.</li>\n<li>The <code>setFocus</code> function might misbehave if the tree list is itself inside a list element, as it loops through <em>all</em> list-type parents up to the document root.</li>\n<li>The <code>classPrefix</code> option is confusing: It's not used for the expand/contract classes, only for the toggle button's \"main\" class. But since that's the only one, why not just let the user define that as well? Basically, if a prefix is used only once, it's not necessary.</li>\n<li>Comparing against <code>undefined</code> is a no-no. <code>undefined</code> is not a reserved word, and can (in some runtimes) <em>be defined</em>. In this case, a simple boolean works just as well.</li>\n</ul>\n\n<p>Here's what I arrived at</p>\n\n<pre><code>(function ($) {\n var methods = {\n init: function(options) {\n // Default Settings\n var settings = $.extend({\n expandIconClass: 'closed',\n contractIconClass: 'open',\n toggleButtonClass: 'toggle',\n setFocus: false // just use a boolean here\n }, options);\n\n return this.each(function() {\n var target = $(this);\n\n // walk the tree\n target.find('li').each(function() {\n var node = $(this),\n branches = node.children('ul, ol'),\n button;\n\n if(branches.length > 0) {\n branches.hide();\n button = $('<div />', {\n 'class': settings.toggleButtonClass + \" \" + settings.expandIconClass,\n on: {\n click: function (event) {\n // we already have the correct elements here\n branches.toggle();\n button.toggleClass(settings.expandIconClass + \" \" + settings.contractIconClass);\n }\n }\n });\n\n node.prepend(button);\n }\n });\n\n if(settings.setFocus === true) {\n target.goodtree('setFocus');\n }\n });\n },\n\n setFocus: function(element) {\n return this.each(function() {\n $(element).parents('ul, ol').each(function() {\n var ancestor = $(this);\n if( this.is(ancestor) ) { // better check\n return false; // stop the each-loop\n }\n ancestor.show();\n });\n });\n }\n };\n\n $.fn.goodtree = function(method) {\n if(typeof methods[method] === 'function') { // stronger conditional\n return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));\n } else if(typeof method === 'object' || !method) {\n return methods.init.apply(this, arguments);\n } else {\n $.error('Method ' + method + ' does not exist on jQuery.goodtree');\n }\n };\n}(jQuery));\n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/Fh4eY/1/\" rel=\"nofollow\">Here's a demo</a> (I reused your demo markup and styling, minus the open/close icons)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T13:15:12.527",
"Id": "38388",
"Score": "0",
"body": "this makes a lot of sense, thanks tons for the advice!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T19:30:38.320",
"Id": "38418",
"Score": "0",
"body": "@goodcodeguy No prob; glad it's useful. By the way, I might rename `setFocus` to `reveal` or `expand` or similar. Seems more descriptive, and \"focus\" is usually used to refer to selected input elements. Just a thought."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-09T00:31:09.670",
"Id": "38448",
"Score": "0",
"body": "actually that's what it's used for. It's used to focus on a single element no matter where it is in the trees and opens up all the parents so it can be exposed (can also be used to set focus on multiple elements). Very useful for search filters which is the primary reason I generally use this type of layout."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-09T08:56:14.467",
"Id": "38465",
"Score": "0",
"body": "@goodcodeguy Exactly my point. It's used to _expose_ or _reveal_ an item, whereas \"focus\" typically refers to the form element that's receiving keyboard input. I.e. there is a `focus()` method in the native DOM already, but its purpose is different and is only used in connection with form elements. Hence why I'd suggest not using the word \"focus\" unless you're dealing with input elements."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-07T05:29:34.383",
"Id": "24812",
"ParentId": "24778",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "24812",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2013-04-05T21:10:39.197",
"Id": "24778",
"Score": "1",
"Tags": [
"javascript",
"jquery",
"plugin"
],
"Title": "Is this jQuery Plugin for TreeView correct?"
}
|
24778
|
<pre><code>public static void listPrimesThree(int maxNum){
long startTime = System.currentTimeMillis();
boolean[] booleanArray = new boolean[maxNum+1];
int root = (int)Math.sqrt(maxNum);
for (int m = 2; m <= root; m++){
for (int k = m*m; k <= maxNum; k+=m){
booleanArray[k] = true;
}
}
for (int m = 3; m <= maxNum; m+=2){
if(!booleanArray[m]){
System.out.println(m);
}
}
long endTime = System.currentTimeMillis();
System.err.println(endTime - startTime+"ms");
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-06T00:54:31.833",
"Id": "38291",
"Score": "1",
"body": "You can improve the efficiency by skipping sieving numbers that are already known to be composite. For example, inside your first outer for loop, you could do `if (booleanArray[m]) continue;` to skip composite numbers. I'm seeing 4-5x speed improvement with that one change for large values."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-09T17:43:09.887",
"Id": "38497",
"Score": "0",
"body": "You can use a BitSieve. The one from java or better a custom one, because you know the number of primes inside the Integer range."
}
] |
[
{
"body": "<p>In your second, output loop, <code>m</code> enumerates only odd numbers: <code>m = 3, 5, 7, 9, ...</code>. So we don't need to mark any evens in the first loop, as we skip them over anyway:</p>\n\n<pre><code>for (int m = 3; m <= root; m+=2) {\n if (!booleanArray[m]) { // if not marked as a composite:\n for (int k = m*m; k <= maxNum; k+=2*m) { // mark only _odd_ multiples\n booleanArray[k] = true; // as composite\n }\n }\n}\n</code></pre>\n\n<p>(also incorporating the advice you got in the comments, about only marking the multiples of <em>non</em>-composites). Incrementing <strong>in steps of <code>2*m</code></strong> (going through <em>odds</em> only) cuts the overall amount of work in half.</p>\n\n<hr>\n\n<p>Loop unrolling turns it into</p>\n\n<pre><code>if ((m=3) <= root) break; // m = 3 .\nif (!booleanArray[m]) { \n for (int k = m*m; k <= maxNum; k+=2*m) { \n booleanArray[k] = true; // k = 9, 15, 21, 27, ... \n } // all are composite, multiples of 3,\n} // k = m*(m..+=2) = 3*i, i=3,5,7,9,11...\n\nfor (int i = 5; ; i+=6) {\n\n if ((m=i) <= root) break; // m = 5, 11, 17, 23, ...\n if (!booleanArray[m]) { // m%6==5 for all m\n for (int k = m*m; k <= maxNum; k+=2*m) { // (m==6x+5)\n booleanArray[k] = true; \n }\n }\n\n if ((m=i+2) <= root) break; // m = 7, 13, 19, 25, ...\n if (!booleanArray[m]) { // m%6==1 for all m\n for (int k = m*m; k <= maxNum; k+=2*m) { // (m==6x+1)\n booleanArray[k] = true; \n }\n }\n\n if ((m=i+4) <= root) break; // m = 9, 15, 21, 27, ... \n if (!booleanArray[m]) { // m%6==3 for all m\n for (int k = m*m; k <= maxNum; k+=2*m) { // (m==6x+3)\n booleanArray[k] = true; \n } // all k's are composite, multiples of 3,\n } // all are already marked in the (m==3) loop\n}\n</code></pre>\n\n<p>It is clear now that the third sub-loop is totally superfluous. The first (<code>m==3</code>) loop marks all multiples of 3; we can skip this step also, if we'll skip over the multiples of 3 in the output stage. This saves 1/3rd of the remaining work, which makes it 3x speedup overall.</p>\n\n<hr>\n\n<p>We can fold the remaining two sub-loops back into one loop:</p>\n\n<pre><code>for (int m = 5, n=6, k=4; m <= root; m += (k=n-k)) {\n if (!booleanArray[m]){ // if prime - mark its multiples\n int j = m*m, l=6*m, i=4*m; // that are not mults of 2 nor 3\n if ( (m%6) == 1 ) { i=2*m; } // (be at the correct phase)\n for ( ; j <= maxNum; j += (i=l-i)) { \n booleanArray[j] = true; \n } // k = 2, 4, 2, 4, 2, 4, 2, ...\n } // m = 5, 7, 11, 13, 17, 19, 23, 25, ...\n} // skipped: 9, 15, 21, 27, ...\n</code></pre>\n\n<p>This uses the fact that for any even number <code>n</code> the value <code>n%6</code> is either 0, 2, or 4; and for any multiple <code>m</code> of 3, <code>m%6</code> is either 0 or 3. Which leaves only 1 and 5 for all the rest of the numbers. </p>\n\n<p>Next, augment the output loop to work only with the {2,3}-coprimes as well:</p>\n\n<pre><code>System.out.println(3); // print 3 unconditionally\nfor (int m = 5, n=6, k=4; m <= maxNum; m += (k = n-k)) {\n if(!booleanArray[m]) {\n System.out.println(m);\n } \n} \n</code></pre>\n\n<hr>\n\n<p>The next step of improvement is to condense the array. Right now it hosts a lot of unused entries which we skip over. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T18:47:16.177",
"Id": "38596",
"Score": "0",
"body": "Ah, sneaky, very sneaky."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T18:47:55.063",
"Id": "38597",
"Score": "0",
"body": "@DanielFischer I'm still reading your reply there; thanks BTW. I wish there was a simple way in Haskell to have arrays that are guaranteed to be mutable in-place."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T18:51:40.240",
"Id": "38599",
"Score": "0",
"body": "No, no problem, I was just curious. Re the previous comment, `ST(U)Array`s are about as simple as it gets. But I suppose you think rather of a way to annotate \"this one is used sequentially, don't bother copying, mutate in place\" and write `nextStep (arr // updateList)`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T18:53:01.260",
"Id": "38600",
"Score": "0",
"body": "@DanielFischer yes, that would be great, thank you. ;) I'll take STUArrays, but I see you still had to tweak it even after you used unsafeThaw ... (still reading)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T18:53:59.343",
"Id": "38601",
"Score": "0",
"body": "@Daniel (and I think, ultimately Haskell ought to compile into simple loops, in C, where possible) ... both test3 and test4 can be represented in C with simple loop on two register variables. And they *ought to*. (that's not mentioning the SuperSmart Compiler which would recognize that the 10 million swaps are equivalent to just 1 swap (or is it 0?))."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T18:58:21.573",
"Id": "38603",
"Score": "0",
"body": "Will, `unsafeThaw` is minor there because the `ByteArray#` is only eight bytes, the constructor and the bounds/size components take far more. It would have made a far bigger impact if the array had, say 1000 elements. 0 swaps, `testN . testN = id`, and 10000000 is even."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T19:12:50.267",
"Id": "38607",
"Score": "0",
"body": "ah, yes, thanks; *you are* like the super smart compiler. ;) but 10 mil is an arg to apply; what apply does with it is not immediately apparent. there's an (n-1) there... maybe it stops 1 short of the given n times? does it call a function one extra time before starting a loop? (so many opportunities to screw up...) (what I'm saying is I'm too lazy to check it up too closely... but now I did. hmm.)"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-07T16:11:02.597",
"Id": "24822",
"ParentId": "24781",
"Score": "0"
}
},
{
"body": "<p>This is a great example of memory bound problem. If you manage to reduce the number of cache misses you can have quite a speedup.\nI am providing almost identical code, only instead of boolean array I am using BitSet. Running on Server machinve, on my quite dated hardware I observe about 30% speedup without any other optimizations. Hand-optimizing the bit set functionality may speed things a little more, although I am not too much an optimist.</p>\n\n<p>I am providing this example only to show how important memory (micro) management can be. I do not suggest that the original algorithm can not be optimized.</p>\n\n<pre><code>public void listPrimesThree(int maxNum) {\n long startTime = System.currentTimeMillis();\n\n int root = (int) Math.sqrt(maxNum);\n\n BitSet bs = new BitSet(maxNum+1);\n for (int m = 2; m <= root; m++) {\n for (int k = m * m; k <= maxNum; k += m) {\n bs.set(k);\n }\n }\n long endTime = System.currentTimeMillis();\n System.err.println((endTime - startTime) / 1000 + \" s\");\n for (int m = 3; m <= maxNum; m += 2) {\n if (!bs.get(m)) {\n System.out.println(m);\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-12T12:11:35.043",
"Id": "38715",
"Score": "0",
"body": "if you change it to work by segments, such that each segment fits into your cache entirely, you're supposed to get even more speedup."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-12T13:35:25.690",
"Id": "38718",
"Score": "0",
"body": "Absolutely agree. Unfortunately cache sizes may vary wildly on different architectures. I am curious to see a cache oblivious https://en.wikipedia.org/wiki/Cache-oblivious_algorithm implementation of this problem (again, without adding too much complexity)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-11T12:34:28.743",
"Id": "24993",
"ParentId": "24781",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-06T00:36:56.157",
"Id": "24781",
"Score": "4",
"Tags": [
"java",
"algorithm",
"primes"
],
"Title": "Prime sieve: improve efficiency while keeping it reasonably simple?"
}
|
24781
|
<p>There may not be a "right" way to do it, but I'm inexperienced in functional programming. I'd like some feedback on how the code can be written in a more idiomatic way.</p>
<p>Here it is:</p>
<pre><code>import Data.Maybe (fromJust, isJust)
sepInt n = if n >= 10
then ( sepInt ( n `div` 10 ) ) ++ ((n `mod` 10):[])
else n `mod` 10 : []
getStuff (x:xs) = if isJust x || null xs
then fromJust x
else getStuff xs
base10IntTOstring num =
let chars = [ (1, '1'), (2, '2'), (3, '3'), (4, '4'), (5, '5'), (6, '6'), (7, '7'), (8, '8'), (9, '9'), (0, '0') ]
numbahs = sepInt num in
map getStuff ( map (\a -> (map (\(x,y) -> if a == x then Just y else Nothing ) chars ) ) numbahs )
charTOBase10Int char =
let chars = [ ('1', 1), ('2', 2), ('3', 3), ('4', 4), ('5', 5), ('6', 6), ('7', 7), ('8', 8), ('9', 9), ('0', 0) ] in
let charslist = ( map (\(a,x) -> if char == a then Just x else Nothing) chars ) in
getStuff charslist
stringTOBase10Int string =
let integers = ( map charTOBase10Int string ) in
let multByBase i (x:xs) = if null xs
then (10^i)*x
else (10^i)*x + multByBase ( i-1 ) xs
in multByBase ( (length integers)-1 ) integers
</code></pre>
<p>It also reverses integers.</p>
<pre><code>sepInt n = if n >= 10
then ( sepInt ( n `div` 10 ) ) ++ ((n `mod` 10):[])
else n `mod` 10 : []
reverseInteger string =
let integers = sepInt string in
let multByBase i (x:xs) = if null xs
then (10^i)*x
else (10^i)*x + multByBase ( i-1 ) xs
in multByBase ( (length integers) - 1 ) integers
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-06T03:29:07.693",
"Id": "38294",
"Score": "0",
"body": "Also, I highly recommend that when you share code with other people, whether on Stack Overflow or otherwise, that you annotate your functions with types. It makes it much easier for other people to review your code."
}
] |
[
{
"body": "<p>Ok, so here are some comments while I'm fixing up your code:</p>\n\n<ul>\n<li><p>In <code>sepInt</code>, you can combine <code>div</code> and <code>mod</code> into one computation using <code>quotRem</code></p></li>\n<li><p>An efficient trick for building up a list in the \"wrong order\" is to build it up in reverse and then <code>reverse</code> it.</p></li>\n<li><p>Don't write partial functions like <code>getStuff</code>. That usually indicates a flaw in your code. <code>getStuff</code> is partial because the list could be empty or full of <code>Nothing</code>s, in which case there is no way you could possibly retrieve an <code>a</code> from it. Idiomatic Haskell code should never need partial functions.</p></li>\n<li><p>You can replace <code>base10IntTOstring</code> with the <code>show</code> function, which converts any integer to its <code>String</code> representation. However, if you still want to write the function yourself without using <code>show</code>, then it's much more efficient to use the <code>ord</code> and <code>chr</code> functions from <code>Data.Char</code> and do simple arithmetic to convert them to to the equivalent ASCII characters.</p></li>\n<li><p>You shouldn't check things using functions like <code>null</code> or <code>isJust</code>. Use <code>case</code> statements to pattern match on them.</p></li>\n</ul>\n\n<p>For example, this is NOT idiomatic Haskell:</p>\n\n<pre><code>foo :: Maybe Int -> Int\nfoo m = if (isJust m)\n then fromJust m\n else 0\n</code></pre>\n\n<p>Instead you would do:</p>\n\n<pre><code>foo = case m of\n Just n -> n\n Nothing -> 0\n</code></pre>\n\n<p>Same thing with list operations. You do NOT do this:</p>\n\n<pre><code>bar :: [Int] -> Int\nbar xs = if (null xs)\n then head xs\n else 0\n</code></pre>\n\n<p>Instead you do this:</p>\n\n<pre><code>bar xs = case xs of\n x:_ -> x\n [] -> 0\n</code></pre>\n\n<p><code>case</code> statements are more efficient, safer, and they are statically checked by the compiler to make sure you don't extract a variable on the wrong branch.</p>\n\n<ul>\n<li>When you combine a list into a single value, you probably want a strict left fold like <code>foldl'</code>.</li>\n</ul>\n\n<p>When I combine all of those fixes, I get this:</p>\n\n<pre><code>import Data.Char (chr, ord)\nimport Data.List (foldl')\n\nsepInt :: Int -> [Int]\nsepInt n = reverse (go n)\n where\n go n = if n >= 10\n then let (q, r) = quotRem n 10 in r:go q\n else [n]\n\nbase10IntTOstring :: Int -> [Char]\nbase10IntTOstring = map (\\n -> chr (ord '0' + n)) . sepInt\n\ncharTOBase10Int :: Char -> Int\ncharTOBase10Int c = ord c - ord '0'\n\nstringTOBase10Int :: [Char] -> Int\nstringTOBase10Int cs = foldl' step 0 (map charTOBase10Int cs)\n where\n step acc elem = 10 * acc + elem\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-06T04:02:38.007",
"Id": "24788",
"ParentId": "24782",
"Score": "5"
}
},
{
"body": "<p>Let's take one function at a time, until we're all done.</p>\n\n<p><strong>sepInt</strong></p>\n\n<pre><code>sepInt n = if n >= 10\n then ( sepInt ( n `div` 10 ) ) ++ ((n `mod` 10):[])\n else n `mod` 10 : []\n</code></pre>\n\n<p>First things first: you'll definitely want to learn a bit about precedence! Normally I'm in favor of adding some unnecessary parentheses if it helps disambiguate a strange situation or if the operators involved aren't often mixed, but too many of them can get in the way of readability. Also, take advantage of that sweet syntactic sugar for lists that the language provides! So iteration one of this function is</p>\n\n<pre><code>sepInt n = if n >= 10\n then sepInt (n `div` 10) ++ [n `mod` 10]\n else [n `mod` 10]\n</code></pre>\n\n<p>Now, as we all know, building up a linked list by repeatedly appending to the end is a bit inefficient. Probably for such small lists as you'll be using in test cases here it won't matter, but it's a good idea to get in the habit of paying attention to some of the easiest stuff, so let's try to improve this a bit. We have a choice here: either we can keep the interface of this function as-is, that is, always output a list in the right order, or we can choose to change the interface, and change all the call-sites of this function. I think for this case we can keep the interface. The idea we'll take is to build up the list backwards, then reverse it at the very end. The name <code>go</code> is traditional for local workers.</p>\n\n<pre><code>sepInt = reverse . go where\n go n = if n >= 10\n then [n `mod` 10] ++ go (n `div` 10)\n else [n `mod` 10]\n</code></pre>\n\n<p>There's something a bit funny about this base case to me. It seems like it's not the most basic one you could choose. If we let the \"loop\" run one more time...</p>\n\n<pre><code>sepInt = reverse . go where\n go n = if n > 0\n then [n `mod` 10] ++ go (n `div` 10)\n else []\n</code></pre>\n\n<p>There's a few things I find more satisfying about this: our base-case input is <code>0</code>, a common base for <code>Integer</code>s; our base-case output is <code>[]</code>, a common base for <code>[]</code>s; and there's no duplicated code in the two branches of the <code>if</code>. Finally, I think I'd choose to replace the <code>if</code>-<code>then</code>-<code>else</code> with a pattern match, noting however that this function has a slightly different behavior for negative numbers. Since we were never really doing the right thing for negative numbers, this doesn't bother me too much.</p>\n\n<pre><code>sepInt = reverse . go where\n go 0 = []\n go n = [n `mod` 10] ++ go (n `div` 10)\n</code></pre>\n\n<p>If we're feeling fancy, we can choose to use <code>divMod</code> instead of two separate calls to <code>div</code> and <code>mod</code>; and we can unroll the definition of <code>(++)</code>; but I think neither of these is terribly important. Nevertheless, they're idiomatic, so:</p>\n\n<pre><code>sepInt = reverse . go where\n go 0 = []\n go n = let (d, m) = n `divMod` 10 in m : go d\n</code></pre>\n\n<p>Okay, let's check our work. We already know that the final thing works differently for negative numbers, so let's only check non-negative ones.</p>\n\n<pre><code>*Main Test.QuickCheck> quickCheck (\\(NonNegative n) -> sepInt n == sepInt' n)\n*** Failed! Falsifiable (after 2 tests): \nNonNegative {getNonNegative = 0}\n</code></pre>\n\n<p>Whoa, whoops! Can you figure out which refactoring above was the culprit? =)</p>\n\n<p>Now we have to decide whether we like the old behavior better or the new one. I think in this particular case we should like the old behavior better, since the goal is to show a number, and we'd like <code>0</code> to show up as <code>\"0\"</code> rather than as <code>\"\"</code>. It's a bit ugly, but we can special-case it. Since we like our future selves, we'll leave ourselves a note about this, too.</p>\n\n<pre><code>-- special case for a human-readable 0\nsepInt 0 = [0]\nsepInt n = reverse . go $ n where\n go 0 = []\n go n = let (d, m) = n `divMod` 10 in m : go d\n</code></pre>\n\n<p>Now the test passes:</p>\n\n<pre><code>*Main Test.QuickCheck> quickCheck (\\(NonNegative n) -> sepInt n == sepInt' n)\n+++ OK, passed 100 tests.\n</code></pre>\n\n<p><strong>getStuff</strong></p>\n\n<pre><code>getStuff (x:xs) = if isJust x || null xs\n then fromJust x\n else getStuff xs\n</code></pre>\n\n<p>This name sure leaves something to be desired! And it leaves another important thing to be desired, too: there's lots of inputs where it just crashes. Nasty! It turns out that you never call it on inputs of that form later, but totality is another good habit that you should get yourself into. It's just another tool in the mature programmer's defensive programming toolbelt. In our case, we'll want to handle cases like <code>[]</code>, or <code>[Nothing]</code>, or <code>[Nothing, Nothing]</code>, etc. where there's no good answer to return. What should we return if that happens?</p>\n\n<p>One simple and quite common choice is to change our type from</p>\n\n<pre><code>getStuff :: [Maybe a] -> a\n</code></pre>\n\n<p>to</p>\n\n<pre><code>getStuff :: [Maybe a] -> Maybe a\n</code></pre>\n\n<p>but I think that's a bit short-sighted. Ignoring for the moment the inputs we know we're going to call this thing on, we've observed already that there's times when there's no good answer to return, and there's times when there <em>is</em> a good answer to return, so <code>Maybe a</code> seems like a good start, but there's also times when there are <em>two</em> good answers -- or more! So let's use a type that reflects this scenario instead:</p>\n\n<pre><code>getStuff :: [Maybe a] -> [a]\n</code></pre>\n\n<p>It's not too hard to fix up the code. First we'll just fix the type errors:</p>\n\n<pre><code>getStuff (x:xs) = if isJust x || null xs\n then [fromJust x]\n else getStuff xs\n</code></pre>\n\n<p>This isn't obviously better, since it still fails in all the same situations it used to fail, and it never returns multiple answers. So we should differentiate the two cases that lead us to the <code>then</code> branch:</p>\n\n<pre><code>getStuff (x:xs) = if isJust x\n then fromJust x : if null xs\n then []\n else getStuff xs\n else getStuff xs\n</code></pre>\n\n<p>Now, we have this <code>if null xs</code> branch primarily because <code>getStuff</code> still isn't total (it can't handle an empty input list). Instead of protecting ourselves from calling <code>getStuff</code> in this case, we should just let <code>getStuff</code> deal with empty lists correctly. So:</p>\n\n<pre><code>getStuff [] = []\ngetStuff (x:xs) = if isJust x\n then fromJust x : getStuff xs\n else getStuff xs\n</code></pre>\n\n<p>Actually, using <code>isJust</code> and <code>fromJust</code> is also a code smell, for the same reason as the rest of the changes so far: <code>fromJust</code> is partial. Instead of protecting ourselves from calling <code>fromJust</code> on inputs it can't handle, we should write our code in a way that avoids partial functions. Here's how:</p>\n\n<pre><code>getStuff [] = []\ngetStuff (Just x : xs) = x : getStuff xs\ngetStuff (Nothing : xs) = getStuff xs\n</code></pre>\n\n<p>(I've added a little creative whitespace to show parallels between the branches.) The only thing I'd change now is to pick a better name. For example, <code>catMaybes</code> might be an okay name for this. I'll mention one more thing, which is that this can also be implemented quite beautifully as a list comprehension:</p>\n\n<pre><code>catMaybes xs = [x | Just x <- xs]\n</code></pre>\n\n<p>By the way, this function is available from <code>Data.Maybe</code>.</p>\n\n<p><strong>base10IntTOstring</strong></p>\n\n<pre><code>base10IntTOstring num =\n let chars = [ (1, '1'), (2, '2'), (3, '3'), (4, '4'), (5, '5'), (6, '6'), (7, '7'), (8, '8'), (9, '9'), (0, '0') ]\n numbahs = sepInt num in\n map getStuff ( map (\\a -> (map (\\(x,y) -> if a == x then Just y else Nothing ) chars ) ) numbahs )\n</code></pre>\n\n<p>There are better ways to construct that lookup table! For example, I might choose</p>\n\n<pre><code>chars = zip [0..9] ['0'..'9']\n</code></pre>\n\n<p>(If you haven't seen <code>zip</code> before, I encourage you to try to code it up yourself! Then check the Report and compare answers.) Additionally, we're going to have to change things up a little, since we've changed how <code>getStuff</code> works and <code>base10IntTOstring</code> calls <code>getStuff</code>. Before, we had <code>getStuff :: [Maybe a] -> a</code> and hence <code>map getStuff :: [[Maybe a]] -> [a]</code>. Now, we have <code>catMaybes :: [Maybe a] -> [a]</code> and hence <code>map catMaybes :: [[Maybe a]] -> [[a]]</code>. Since we expect each of the lists in the output of that to be singleton lists, we can smash them all together with <code>concat</code>:</p>\n\n<pre><code>base10IntTOstring num =\n let chars = zip [0..9] ['0'..'9']\n numbahs = sepInt num in\n concat (map catMaybes ( map (\\a -> (map (\\(x,y) -> if a == x then Just y else Nothing ) chars ) ) numbahs ))\n</code></pre>\n\n<p>Actually, this whole process at the very end is quite roundabout! If you squint, it looks like what we're really trying to implement here is a little function</p>\n\n<pre><code>lookupList :: Eq k => [(k, v)] -> k -> [v]\n</code></pre>\n\n<p>which we can use to index into our lookup table with the digits of our integer. So let's try to write this directly! Taking a cue from the final implementation of <code>catMaybes</code> above, we can write</p>\n\n<pre><code>lookupList table k = [v | (k', v) <- table, k == k']\n</code></pre>\n\n<p>Now our implementation can look like this:</p>\n\n<pre><code>base10IntTOstring num =\n let chars = zip [0..9] ['0'..'9']\n numbahs = sepInt num in\n concat (map (lookupList chars) numbahs)\n</code></pre>\n\n<p>In fact, there's even a function <code>concatMap</code> that squashes those two things together. Veteran Haskellers will prefer to spell this function in its infix, polymorphic form as <code>(>>=)</code></p>\n\n<pre><code>base10IntTOstring num =\n let chars = zip [0..9] ['0'..'9']\n numbahs = sepInt num in\n numbahs >>= lookupList chars\n</code></pre>\n\n<p>though this spelling is optional. In fact, everything is short enough now that I would even feel comfortable inlining the definitions:</p>\n\n<pre><code>base10IntTOstring num = sepInt num >>= lookupList (zip [0..9] ['0'..'9'])\n</code></pre>\n\n<p>My only complaint now is the name, for two reasons. The first is that <code>string</code> isn't capitalized, which is inconsistent with the naming of the remainder of the file. The other one is more of a philosophical one: our input is an integer, not a base-ten integer. If anything, the base-ten-ness is being imposed on the <em>output</em>. So:</p>\n\n<pre><code>intTOBase10String num = sepInt num >>= lookupList (zip [0..9] ['0'..'9'])\n</code></pre>\n\n<p>Let's test it:</p>\n\n<pre><code>*Main Test.QuickCheck> quickCheck (\\n -> base10IntTOstring n == intTOBase10String n)\n+++ OK, passed 100 tests.\n</code></pre>\n\n<p>(By the way, a variant of <code>lookupList</code> that I have always felt has the wrong type, <code>lookup</code>, is available from <code>Prelude</code>.)</p>\n\n<p>Finally, I would be remiss without pointing out that there are several good functions that already exist for doing conversions like this:</p>\n\n<pre><code>*Main Test.QuickCheck> let checkPosBase10 f = quickCheck (\\(NonNegative n) -> f n == intTOBase10String n)\n*Main Test.QuickCheck> checkPosBase10 show\n+++ OK, passed 100 tests.\n*Main Test.QuickCheck Numeric Data.Char> checkPosBase10 (\\n -> showIntAtBase 10 intToDigit n \"\")\n+++ OK, passed 100 tests.\n</code></pre>\n\n<p>The difference here is that <code>showIntAtBase</code> can be used for any base, and <code>show</code> is specific to base 10.</p>\n\n<p><strong>charTOBase10Int</strong></p>\n\n<pre><code>charTOBase10Int char =\n let chars = [ ('1', 1), ('2', 2), ('3', 3), ('4', 4), ('5', 5), ('6', 6), ('7', 7), ('8', 8), ('9', 9), ('0', 0) ] in\n let charslist = ( map (\\(a,x) -> if char == a then Just x else Nothing) chars ) in\n getStuff charslist\n</code></pre>\n\n<p>Actually, most of the changes we made to <code>base10IntTOstring</code> can be done here, as well. In the interest of totality, we'll change the type, too; it will return a <code>[Char]</code> (which we happen to know will be a singleton list, if anything) instead of a <code>Char</code>.</p>\n\n<pre><code>base10CharTOInt char = lookupList (zip ['0'..'9'] [0..9]) char\n</code></pre>\n\n<p>It's common in cases like this where the trailing arguments to the function you're defining are also trailing arguments to a function in the definition to omit the arguments entirely. The technical term for this is <code>eta reduction</code>, I think. Whether you choose to do this yourself is primarily a stylistic choice.</p>\n\n<pre><code>base10CharTOInt = lookupList (zip ['0'..'9'] [0..9])\n</code></pre>\n\n<p>The test for this one is a bit complicated; since the old implementation is partial, we have to restrict ourselves to those inputs that work.</p>\n\n<pre><code>*Main Test.QuickCheck> quickCheck (\\n -> n >= '0' && n <= '9' ==> [charTOBase10Int n] == base10CharTOInt n)\n*** Gave up! Passed only 67 tests.\n</code></pre>\n\n<p>The report here says that it passed the test, but that QuickCheck didn't run as many tests as it wanted to because most of the random inputs it generated weren't in the desired range. (In fact, perhaps it's questionable to use QuickCheck at all for this, since there's only ten inputs of interest anyway!)</p>\n\n<p>By the way, this function (a partial version! boooo) exists also in <code>Data.Char</code>:</p>\n\n<pre><code>*Main Test.QuickCheck Data.Char> quickCheck (\\n -> n >= '0' && n <= '9' ==> charTOBase10Int n == digitToInt n)\n*** Gave up! Passed only 54 tests.\n</code></pre>\n\n<p><strong>stringTOBase10Int</strong></p>\n\n<pre><code>stringTOBase10Int string =\n let integers = ( map charTOBase10Int string ) in\n let multByBase i (x:xs) = if null xs\n then (10^i)*x\n else (10^i)*x + multByBase ( i-1 ) xs\n in multByBase ( (length integers)-1 ) integers\n</code></pre>\n\n<p>We first need to fix up some typing issues, since we've changed the interface to <code>base10CharTOInt</code> and this is a caller. As before, we can do that just by putting in a <code>concat</code>; as before, we'll spell the combination of <code>concat</code> and <code>map</code> as <code>(>>=)</code>.</p>\n\n<pre><code>stringTOBase10Int string =\n let integers = string >>= base10CharTOInt in\n let multByBase i (x:xs) = if null xs\n then (10^i)*x\n else (10^i)*x + multByBase ( i-1 ) xs\n in multByBase ( (length integers)-1 ) integers\n</code></pre>\n\n<p>As with <code>sepInt</code> waaaay back at the beginning, I find the choice of base case a bit odd. Let's try the trick from before of letting the \"loop\" run one more iteration (and this time hopefully the refactoring isn't wrong!).</p>\n\n<pre><code>stringTOBase10Int string =\n let integers = string >>= base10CharTOInt in\n let multByBase i [] = 0\n multByBase i (x:xs) = (10^i)*x + multByBase ( i-1 ) xs\n in multByBase ( (length integers)-1 ) integers\n</code></pre>\n\n<p>Also, let's eliminate unnecessary parentheses.</p>\n\n<pre><code>stringTOBase10Int string =\n let integers = string >>= base10CharTOInt in\n let multByBase i [] = 0\n multByBase i (x:xs) = 10^i*x + multByBase (i-1) xs\n in multByBase (length integers-1) integers\n</code></pre>\n\n<p>Now, I wonder whether recomputing the power of ten each time is really the right thing to do. One thing we could do is to use <code>10^(length integers - 1)</code> and divide by 10 in each recursion. But division is slow, so let's take another plan: instead of computing the length of the list explicitly, let's do it implicitly by having <code>multByBase</code> also compute the appropriate power of ten.</p>\n\n<pre><code>stringTOBase10Int string =\n let integers = string >>= base10CharTOInt in\n let multByBase [] = (1, 0)\n multByBase (x:xs) = let (pow, n) = multByBase xs in (pow*10, pow*x+n)\n in snd (multByBase integers)\n</code></pre>\n\n<p>This now has the magical special form of recursion that can be turned into a <code>foldr</code>. Let's do so! See if you can spot where each piece of code from the above ends up in the below.</p>\n\n<pre><code>stringTOBase10Int string =\n let integers = string >>= base10CharTOInt in\n snd (foldr (\\x (pow, n) -> (pow*10, pow*x+n)) (1, 0) integers)\n</code></pre>\n\n<p>Personally, I often prefer <code>where</code> to <code>let</code>, and the <code>foldr</code> is complicated enough that I feel like it should be named, so I'd write it as follows. But this is an aesthetic choice that you may or may not agree with.</p>\n\n<pre><code>stringTOBase10Int string = snd (go integers) where\n integers = string >>= base10CharTOInt\n go = foldr (\\x (pow, n) -> (pow*10, pow*x+n)) (1, 0)\n</code></pre>\n\n<p>And finally, fix up the name:</p>\n\n<pre><code>base10StringTOInt string = snd (go integers) where\n integers = string >>= base10CharTOInt\n go = foldr (\\x (pow, n) -> (pow*10, pow*x+n)) (1, 0)\n</code></pre>\n\n<p>As usual, the tests. Since the old function was pretty partial, we'll arrange to have inputs it knows how to handle, though our new one tries to give an answer even when you feed it garbage.</p>\n\n<pre><code>*Main Test.QuickCheck> quickCheck (\\(NonNegative n) -> base10StringTOInt (show n) == stringTOBase10Int (show n))\n+++ OK, passed 100 tests.\n</code></pre>\n\n<p>By the way, there are functions for this available, too; take a look at <code>reads</code> from <code>Prelude</code> (base-10 specific) and <code>readInt</code> from <code>Numeric</code> (pick your favorite base). I won't try to write tests here, because the types of these functions are more informative (and more correct in many ways).</p>\n\n<p><strong>Final result</strong></p>\n\n<p>Barring the reuse of already-written functions, here's the final versions of all the functions.</p>\n\n<pre><code>sepInt 0 = [0]\nsepInt n = reverse . go $ n where\n go 0 = []\n go n = let (d, m) = n `divMod` 10 in m : go d\n\nlookupList table k = [v | (k', v) <- table, k == k']\nintTOBase10String num = sepInt num >>= lookupList (zip [0..9] ['0'..'9'])\n\nbase10CharTOInt = lookupList (zip ['0'..'9'] [0..9]) \nbase10StringTOInt string = snd (go integers) where\n integers = string >>= base10CharTOInt\n go = foldr (\\x (pow, n) -> (pow*10, pow*x+n)) (1, 0)\n</code></pre>\n\n<p>Keep at it; I look forward to many more questions from you!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-06T04:32:37.687",
"Id": "24789",
"ParentId": "24782",
"Score": "26"
}
},
{
"body": "<p>The other answers are excellent, I just want to point out a handy way to split positive numbers to digits:</p>\n\n<pre><code>sepInt = reverse . map (`mod` 10) . takeWhile (> 0) . iterate (`div` 10)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-11T09:08:42.980",
"Id": "24984",
"ParentId": "24782",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2013-04-06T01:10:55.277",
"Id": "24782",
"Score": "5",
"Tags": [
"strings",
"haskell",
"integer"
],
"Title": "Haskell functions to extract and reverse integers hiding in strings"
}
|
24782
|
<p>I have completed my homework with directions as follows:</p>
<blockquote>
<p>Declare and implement a class named Binary. This class will have a
method named printB(int n) that prints all binary strings of length n.
For n = 3, it will print</p>
</blockquote>
<pre><code>000
001
010
011
100
101
110
111
</code></pre>
<blockquote>
<p>in this order.</p>
</blockquote>
<p>Here is my code:</p>
<pre><code>import java.util.Scanner;
class Binary
{
String B;
int temp;
void printB(int n)
{
for(int i = 0; i < Math.pow(2,n); i++)
{
B = "";
int temp = i;
for (int j = 0; j < n; j++)
{
if (temp%2 == 1)
B = '1'+B;
else
B = '0'+B;
temp = temp/2;
}
System.out.println(B);
}
}
}
class Runner
{
public static void main(String [] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Enter n:");
int n = in.nextInt();
Binary myB = new Binary();
myB.printB(n);
}
}
</code></pre>
<p>My question is...is there anyway to make this shorter or more efficient?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-04T01:51:43.883",
"Id": "38296",
"Score": "1",
"body": "+1 for posting your code and not just the assignment. Nice to see someone actually trying to do the work before asking here. :-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-04T02:18:43.180",
"Id": "38297",
"Score": "0",
"body": "Taking `Math.pow()` out of the header will give an optimization when `n` starts to get large."
}
] |
[
{
"body": "<p>Speaking from a straight Java perspective, one thing you can do is change your loop header. You evaluate the power every iteration and could do something like:</p>\n\n<pre><code>for (int i = 0, end = Math.pow(2, n); i < end; i++)\n</code></pre>\n\n<p>You also use standard String concatenation which is slow because once compiled, when you concatenate two strings a <code>StringBuffer</code> is created, and both strings are added to it, and then resulting string is returned. You save a step by using a <code>StringBuffer</code> from the get go which would you replace <code>B = \"\";</code> with <code>B = new StringBuffer();</code> (of course changing it's type accordingly). Instead of adding strings to you call <code>insert</code> (which can be chained) like <code>B.insert(0, \"1\")</code></p>\n\n<p>You're appending a char (<code>'0'</code> or <code>'1'</code>) which you evaluate with modular division, you can just prepend it like <code>B.insert(0, (temp % 2))</code> and save that entire if.</p>\n\n<p>I probably said more than I should have for homework, but you appear to have already solved your problem and so I was just giving advice in addition to that.</p>\n\n<p><strong>EDIT</strong></p>\n\n<p>My solution would be as follows:</p>\n\n<pre><code>import java.util.Scanner;\n\npublic class Main {\n public static void main(String[] args) {\n Scanner in = new Scanner(System.in);\n System.out.print(\"Enter number >> \");\n int value = in.nextInt();\n in.close();\n Binary binary = new Binary(value);\n System.out.println(binary.getResult());\n }\n}\n\nclass Binary {\n private int value = 0;\n private StringBuilder binaryValues;\n\n public Binary(int value) {\n this.value = value;\n this.binaryValues = new StringBuilder();\n this.process();\n }\n\n private void process() {\n for (int i = 0, end = (1 << this.value); i < end; i++) {\n StringBuilder binary = new StringBuilder(Integer.toString(i, 2));\n while (binary.length() < this.value)\n binary.insert(0, 0);\n this.binaryValues.append(binary).append(\"\\n\");\n }\n }\n\n public String getResult() {\n return this.binaryValues.toString();\n }\n}\n</code></pre>\n\n<p>Maybe not shorter but no need to rewrite binary number generation when it's built in.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-04T01:56:47.567",
"Id": "38298",
"Score": "0",
"body": "Actually, it may be a good idea to take `Math.pow()` out of the header. I'm not sure if this is true in Java, but in some languages, having something like this in the header will be evaluated after *every* loop iteration. Assigning it to a variable and then placing the variable in the loop header may be an optimization."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-04T01:58:37.770",
"Id": "38299",
"Score": "1",
"body": "@DougRamsey Last I checked the initialization step is only executed once, at loop start. From then the conditional is evaluated each loop and upon completion the increment step is executed."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-04T01:58:38.677",
"Id": "38300",
"Score": "2",
"body": "You can use `1 << n` instead."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-04T02:14:32.380",
"Id": "38302",
"Score": "0",
"body": "@izuriel: `Math.pow()` is being evaluated on every loop iteration. This can become drastically inefficient (in general terms, but for specifically relatively large `n` the pow function can take a while to return)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-04T02:34:17.970",
"Id": "38303",
"Score": "1",
"body": "@DougRamsey As I said before (and in the post) moving that to the initialization steps it is only executed once. You check [here](http://www.tutorialspoint.com/java/java_loop_control.htm) to see when and how often each phase is executed. I do not evaluate `Math.pow` every step (and I warned against that in the post itself)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-04T02:34:46.707",
"Id": "38304",
"Score": "0",
"body": "@A.R.S. Yes you can, I was just commenting on changes to his immediate code but I used that method in my \"solution.\" Thanks for the suggestion."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-09T09:14:59.070",
"Id": "38469",
"Score": "0",
"body": "Since the access to your StringBuffer is clearly single threaded, you should use a StringBuilder instead."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-09T14:27:01.310",
"Id": "38486",
"Score": "0",
"body": "@assylias You're right, I should have used that. Updated my answer."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-04T01:33:22.337",
"Id": "24784",
"ParentId": "24783",
"Score": "4"
}
},
{
"body": "<p>There's a couple of things you could do to make it shorter (not more efficient). One thing is you could make</p>\n\n<pre><code> String B;\n\n int temp;\n</code></pre>\n\n<p>non-global in the class. Also, you declared temp twice, once above the function and once in the function. Another thing to shorten it is, when you create the object \"myB\", you could exempt the creation of the variable.</p>\n\n<pre><code> new Binary().printB(n);\n</code></pre>\n\n<p>Finally, you could shorten up the for loop with a tertiary operator like so:</p>\n\n<pre><code> B = temp % 2 == 1 ? '1' + B : '0' + B; //instead of using if : else\n</code></pre>\n\n<p>I also wanted to point out that you didn't close the scanner. It's a good habit to build to always close your scanner objects. This is all just shortening code; I'm not sure if it's more efficient or not.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-04T01:46:06.820",
"Id": "24785",
"ParentId": "24783",
"Score": "1"
}
},
{
"body": "<p>This is how I would do it personally:</p>\n\n<pre><code>public static void printB(int n) {\n StringBuilder bin = new StringBuilder(n); // represents our binary number\n\n for (int i = 0; i < n; i++) // initialize to all 0s\n bin.append('0');\n\n int r = (1 << n); // number of times we will iterate (2^n)\n for (int i = 0; i < r; i++) { // iterate 2^n times\n System.out.println(bin);\n increment(bin, n - 1);\n }\n}\n\nprivate static void increment(StringBuilder bin, int loc) {\n if (loc < 0) // avoids StringIndexOutOfBoundsException\n return;\n if (bin.charAt(loc) == '1') { // bit at loc is already 1\n bin.setCharAt(loc, '0'); // set bit to 0\n increment(bin, loc - 1); // increment at loc-1\n } else { // bit at loc is 0, all we have to do is set it to 1\n bin.setCharAt(loc, '1');\n }\n}\n</code></pre>\n\n<p>The <code>increment</code> method takes a <code>StringBuilder</code> representing a binary string and 'increments' it starting at <code>loc</code>. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-04T01:59:41.977",
"Id": "38306",
"Score": "0",
"body": "Your binary shift is happening each iteration, probably meaningless gain but as far as efficiency goes it's not as efficient as it could be."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-04T01:51:34.667",
"Id": "24786",
"ParentId": "24783",
"Score": "0"
}
},
{
"body": "<p>This is pretty fast and concise:</p>\n\n<pre><code>void printB(int n) \n{\n int len = (int) Math.pow(2, n);\n for(int count = 0; count < len; count++)\n System.out.println(Integer.toBinaryString(count));\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-09T09:15:52.917",
"Id": "38470",
"Score": "0",
"body": "Nice and clean."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-05T15:51:38.457",
"Id": "24787",
"ParentId": "24783",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-04T01:20:54.573",
"Id": "24783",
"Score": "7",
"Tags": [
"java",
"homework",
"combinatorics",
"formatting",
"number-systems"
],
"Title": "Printing all binary strings of length n"
}
|
24783
|
<p>I'm new to Haskell, and here is my first not-totally-trivial program. It's the first program I tend to write in any language -- a Markov text generator. I'm wondering what I can change to make it more idiomatic, or what language features I could make better use of.</p>
<pre><code>import Data.List
import System.Environment
import qualified Data.Map as Map
import Control.Monad.State
import System.Random
type MarkovMap = Map.Map String String
type MarkovState = (MarkovMap, StdGen, String)
transition :: State MarkovState Char
transition = do
(m, gen, sofar) <- get
let options = m Map.! sofar
(index, newGen) = randomR (0, length options - 1) gen
next = options !! index
put (m, newGen, tail sofar ++ [next])
return next
generateText :: State MarkovState Char -> State MarkovState String
generateText s = do
x <- s
xs <- generateText s
return (x:xs)
getWords :: MarkovMap -> Int -> [String]
getWords m n =
let keys = filter ((==) ' ' . last) $ Map.keys m
(r, gen) = randomR (0, length keys - 1) $ mkStdGen 137
startState = keys !! r
markovChars = evalState (generateText transition) (m, gen, startState)
in take n . words $ markovChars
printWords :: [String] -> IO ()
printWords ws = mapM_ putStrLn $ makeLines ws
where makeLines [] = []
makeLines ws = unwords (take 10 ws) : makeLines (drop 10 ws)
main :: IO ()
main = do
(n:nwords:fileName:[]) <- getArgs
contents <- readFile fileName
let chainMap = chain (read n :: Int) . unwords . words $ contents
printWords $ getWords chainMap (read nwords :: Int)
chain :: Int -> String -> Map.Map String String
chain n xs =
let from = map (take n) . tails $ xs ++ " " ++ xs
to = drop n . map (:[]) $ xs ++ " " ++ take n xs
in Map.fromListWith (++) $ zip from to
</code></pre>
<p>Example usage:</p>
<p>Keep track of the last 3 characters, take 100 words from tobeornottobe.txt</p>
<pre><code>> runhaskell markov.hs 3 100 tobeornottobe.txt
delay, the law's count with who would bear things all;
and that make and sweary life; fortal shocks the hue
of returns tural consience of somethis againsolution. To die, thers
the he law's the have, or nobler retus resolence to
troublesh is noblesh is sicklied of regards of some will,
and arrows of? To beary from who would by a
life; for inst give spurns, and, but to sleep: perchan
flesh is heir thing afterprises us for no mortal shocks
turns of action devoutly to dreathe sleep: perchance thance the
ills we hue of time, to suffled of great pith
</code></pre>
|
[] |
[
{
"body": "<p>First of all, it seems like you never change the MarkovMap in your States. So, why don't you take it out of MarkovState and change the type of, say, transition, to MarkovMap -> State MarkovState Char?</p>\n\n<p>Try to use more combinators and less pattern-matching. For example, the generate function is something like sequence . repeat.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-06T19:18:54.380",
"Id": "24803",
"ParentId": "24791",
"Score": "3"
}
},
{
"body": "<p>The code is already quite Haskell-ish. I might have used <code>unfoldr</code> on plain functions instead of 'sequence' on the state monad, but that's just a matter of taste. Nevertheless, your implementation could be more efficient, as it looks up an entry of the <code>MarkovMap</code> for every character that is emitted. The Haskell way would be to exploit laziness, so that at most one lookup per map entry is performed. Define the map as</p>\n\n<pre><code>type MarkovMap = Map.Map String (StdGen -> String)\n</code></pre>\n\n<p>and you can move the map lookup <em>into</em> the map entries by \"tying the knot\". It's a bit tricky if you try to re-implement this from scratch, but you can get there by small-step refactorings of your code.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-09T22:35:41.433",
"Id": "24926",
"ParentId": "24791",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-06T04:58:15.190",
"Id": "24791",
"Score": "4",
"Tags": [
"beginner",
"haskell",
"markov-chain"
],
"Title": "Haskell markov text generator"
}
|
24791
|
<p>Please review and recommend improvements. It looks horrible to me, difficult to read, too lengthy, and just plain old inelegant. But I don't see the potential improvements.</p>
<pre><code>private boolean useCachedReportBean(BeanReport cachedReportBean, String strRequestedReportID)
throws ExceptionInvalidReportRequest
{
/* There may or may not be a cached report
* bean, and their may or may not be a requested
* report ID. If both exist, and they match, use
* the cached report bean. If only one of
* the two exist, use it. Finally if neither exist,
* throw an Exception.
*/
if (strRequestedReportID == null || "".equals(strRequestedReportID)) {
if (cachedReportBean == null) {
throw new ExceptionInvalidReportRequest(
"The request ID is invalid and no cached report exists.");
} else {
/* There was no requested ID but there is a cached bean.
* Returning true causes the cache to be used. */
return true;
}
}
/* If we are here, we know that there is a requested ID.
* If there is no cached bean, use the request id. */
if (cachedReportBean == null) {
return false;
}
/* There is a requested ID and cached bean. If they match, use the cached bean. */
if (strRequestedReportID.equalsIgnoreCase(cachedReportBean.getConfigBean().getReportID())) {
return true;
} else {
return false;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-07T22:05:11.287",
"Id": "38351",
"Score": "0",
"body": "If you `throw` in an `if`, there is no need for an `else`"
}
] |
[
{
"body": "<p>This is not really very different from what you had, but here goes.</p>\n\n<pre><code>private boolean useCachedReportBean(BeanReport cachedReportBean, String strRequestedReportID) \n throws ExceptionInvalidReportRequest \n{\n if (isEmpty(strRequestedReportID)) {\n if (cachedReportBean == null) {\n throw new ExceptionInvalidReportRequest(\n \"The request ID is invalid and no cached report exists.\");\n } else {\n return true;\n }\n }\n else if (cachedReportBean == null) {\n return false;\n }\n else {\n return strRequestedReportID.equalsIgnoreCase(cachedReportBean.getConfigBean().getReportID());\n }\n}\n</code></pre>\n\n<p>I think the if/else if structure provides some symmetry with the 3 primary conditions (no requested report id, no cached report bean, both present), and more clearly demonstrates that it can only be one of those 3.</p>\n\n<p>Note: I am also assuming the existence of a string utility function <code>isEmpty</code>.</p>\n\n<pre><code>boolean isEmpty(String s) {...}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-06T13:29:24.673",
"Id": "24798",
"ParentId": "24793",
"Score": "3"
}
},
{
"body": "<p>Rather than nesting if-else blocks it sometimes helps to cut the problem into independent slices and deal with them one by one, starting with the fairly exceptional ones:</p>\n\n<pre><code>private boolean useCachedReportBeanRefact(BeanReport cachedReportBean,\n String strRequestedReportID) throws ExceptionInvalidReportRequest {\n // validate input arguments\n if (cachedReportBean == null\n && StringUtils.isBlank(strRequestedReportID)) {\n throw new ExceptionInvalidReportRequest(\n \"The request ID is invalid and no cached report exists.\");\n }\n\n // corner case #1\n if (cachedReportBean == null) {\n return false;\n }\n\n // corner case #2\n if (StringUtils.isBlank(strRequestedReportID)) {\n return true;\n }\n\n // after all corner cases are dealt with, just go ahead and compare the id\n return strRequestedReportID.equalsIgnoreCase(cachedReportBean\n .getConfigBean().getReportID());\n}\n</code></pre>\n\n<p>I think the real problem is that this function does too much and is poorly named (it doesn't really <strong>use</strong> the cached report, it only checks if... a bean, if not null, has a config object whose ID is same as the other input parameter... on the condition that this other parameter is not blank either... I think?). It's not immediately obvious where it would be used and what the returned boolean would mean, it doesn't seem to translate to any real-life concept.</p>\n\n<p>Making <code>ExceptionInvalidReportRequest</code> a checked exception feels like a bad idea, too (difficult to say without knowing the context); wouldn't unchecked <code>IllegalArgumentException</code> do?</p>\n\n<hr>\n\n<p>Working code including unit tests: <a href=\"http://pastebin.com/pCXQXLee\" rel=\"noreferrer\">http://pastebin.com/pCXQXLee</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-06T20:04:42.147",
"Id": "24805",
"ParentId": "24793",
"Score": "5"
}
},
{
"body": "<h1>Unified representation of ONE semantic</h1>\n<p>If "strRequestedReportID == null" and "".equals(strRequestedReportID) have the same semantic this should be unified as early as possible in previous code (maybe where the request occured) so the provided method and maybe all other methods need only to handle one case. I suggest to use an empty String that is the neutral element for String operations.</p>\n<h1>Responsibilities</h1>\n<p>Throwing an ExceptionInvalidReportRequest is not the responsibility of this method. Why ask for the usage of a cached ReportBean when it is not even passed in as a parameter? This should be handled before this method is called.</p>\n<h1>Multiple return statements</h1>\n<p>Try to avoid multiple returns. Breaking the control flow can hinder you to apply refactorings like extract method. So you should be sure that your code does not violate SRP or it will never change again when using multiple return statements, break or continue.</p>\n<h1>Code in guessed environment</h1>\n<p>As only one method for review is provided I can only guess how the environment looks like. So I made up a setup to include the method with the semantic I analyzed.</p>\n<p>The point is: The method as provided is effectively one line. For me it makes perfect sense that "A cached report bean should only be used if it is the requested one". All other stuff I think does not belong to this method. Therefore it must be located in the environment I made up.</p>\n<pre><code>private BeanReport cachedReportBean;\n\n\nprivate BeanReport getBeanReport(String strRequestedReportID) throws ExceptionInvalidReportRequest {\n \n // this should be done as early as possible \n String normalizedRequestedReportID = strRequestedReportID == null ? "": strRequestedReportID;\n \n BeanReport reportBean = null;\n \n if ("".equals(normalizedRequestedReportID) && cachedReportBean == null) {\n throw new ExceptionInvalidReportRequest(\n "The request ID is invalid and no cached report exists.");\n }\n \n if (cachedReportBean != null && useCachedReportBean(cachedReportBean, normalizedRequestedReportID)) {\n ...\n reportBean = cachedReportBean;\n ...\n } else {\n ...\n reportBean = loadReportBean(normalizedRequestedReportID);\n ...\n }\n \n ...\n \n return reportBean;\n}\n\nprivate boolean useCachedReportBean(BeanReport cachedReportBean, String normalizedRequestedReportID) {\n return normalizedRequestedReportID.equalsIgnoreCase(cachedReportBean.getConfigBean().getReportID())\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-02-17T00:29:40.060",
"Id": "155557",
"ParentId": "24793",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "24805",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-06T10:54:00.133",
"Id": "24793",
"Score": "2",
"Tags": [
"java",
"cache",
"null"
],
"Title": "Checking for a cache hit"
}
|
24793
|
<p>I'm implementing <a href="http://en.wikipedia.org/wiki/Kruskal%27s_algorithm" rel="nofollow">Kruskal's algorithm</a> in C++11 and would like feedback on style and performance on my graph data structure and algorithm for educational purposes (for production code, I'd use a pre-existing library). The main design questions I have are:</p>
<p>Is there a better way to implement the handle class for the graph structure?
Did I implement path compression correctly in the <code>UnionFind</code> data structure?</p>
<p>I also have a couple of C++11 specific questions:</p>
<ol>
<li>Am I applying move semantics in a useful way when I add vertices and edges?</li>
<li>Am I taking full advantage of return value optimization and copy elision?</li>
</ol>
<p><strong>AdjacencyList.h</strong></p>
<pre><code>#include <vector>
#include <memory>
#include <algorithm>
#include <string>
#include "FwdDecl.h"
#include "Handle.h"
#include "Vertex.h"
#include "Edge.h"
class AdjacencyList
{
public:
typedef Vertex vertex_type;
typedef std::string vertex_id_type;
typedef std::vector<std::shared_ptr<vertex_type>> vertex_container;
typedef Handle<vertex_type> vertex_handle;
typedef Edge<vertex_handle> edge_type;
typedef std::vector<std::shared_ptr<edge_type>> edge_container;
typedef Handle<edge_type> edge_handle;
vertex_container getVertexList() const
{
return m_vertices;
}
edge_container getEdgeList() const
{
return m_edges;
}
size_t getNumVerts() const
{
return m_vertices.size();
}
size_t getNumEdges() const
{
return m_edges.size();
}
vertex_handle findVertex(const vertex_type& v) const
{
return findVertexById(v.m_id);
}
vertex_handle findVertexById(const vertex_id_type& id) const
{
const auto vertexIt(std::find_if(begin(m_vertices),
end(m_vertices),
[id](const std::shared_ptr<vertex_type>& v) { return v->m_id == id; } ));
vertex_handle result(std::shared_ptr<vertex_type>(nullptr), 0);
if (vertexIt != end(m_vertices))
{
result = vertex_handle(*vertexIt, std::distance(begin(m_vertices), vertexIt));
}
return result;
}
edge_handle findEdge(const edge_type& e) const
{
return findEdge(e.getStart(), e.getEnd(), e.getWeight());
}
edge_handle findEdge(const vertex_handle& startVertex, const vertex_handle& endVertex, size_t weight) const
{
return findEdge(startVertex->m_id, endVertex->m_id, weight);
}
edge_handle findEdge(const vertex_id_type& startId, const vertex_id_type& endId, size_t weight) const
{
const auto edgeIt(std::find_if(begin(m_edges),
end(m_edges),
[startId, endId, weight](const std::shared_ptr<edge_type>& e)
{ return weight == e->getWeight() &&
startId == e->getStart()->m_id &&
endId == e->getEnd()->m_id;
} ));
edge_handle result(std::shared_ptr<edge_type>(nullptr), 0);
if (edgeIt != end(m_edges))
{
result = edge_handle(*edgeIt, std::distance(begin(m_edges), edgeIt));
}
return result;
}
vertex_handle addVertex(const vertex_type& v)
{
auto existingVertex(findVertex(v));
if (!existingVertex.isValid())
{
m_vertices.push_back(std::make_shared<vertex_type>(v));
existingVertex = vertex_handle(m_vertices.back(), m_vertices.size() - 1);
}
return existingVertex;
}
vertex_handle addVertex(vertex_type&& v)
{
auto existingVertex(findVertex(v));
if (!existingVertex.isValid())
{
m_vertices.push_back(std::make_shared<vertex_type>(std::move(v)));
existingVertex = vertex_handle(m_vertices.back(), m_vertices.size() - 1);
}
return existingVertex;
}
edge_handle addEdge(const edge_type& e)
{
auto existingEdge(findEdge(e));
if (!existingEdge.isValid())
{
m_edges.push_back(std::make_shared<edge_type>(e));
existingEdge = edge_handle(m_edges.back(), m_edges.size() - 1);
}
return existingEdge;
}
edge_handle addEdge(edge_type&& e)
{
auto existingEdge(findEdge(e));
if (!existingEdge.isValid())
{
m_edges.push_back(std::make_shared<edge_type>(std::move(e)));
existingEdge = edge_handle(m_edges.back(), m_edges.size() - 1);
}
return existingEdge;
}
private:
vertex_container m_vertices;
edge_container m_edges;
};
</code></pre>
<p><strong>Handle.h</strong></p>
<pre><code>#include <memory>
#include <exception>
template <typename T>
class Handle
{
public:
Handle(const std::shared_ptr<T>& ptr, size_t index)
: m_ptr(ptr)
, m_index(index)
{
}
bool isValid() const
{
return !m_ptr.expired();
}
size_t getIndex() const
{
if (isValid())
{
return m_index;
}
throw std::logic_error("Attempt to get index from invalid handle.");
}
T& operator*()
{
const auto ptr = m_ptr.lock();
if (ptr)
{
return *ptr;
}
throw std::logic_error("Attempt to dereference invalid handle.");
}
const T& operator*() const
{
const auto ptr = m_ptr.lock();
if (ptr)
{
return *ptr;
}
throw std::logic_error("Attempt to dereference invalid handle.");
}
T* operator->()
{
const auto ptr = m_ptr.lock();
if (ptr)
{
return ptr.get();
}
return nullptr;
}
const T* operator->() const
{
const auto ptr = m_ptr.lock();
if (ptr)
{
return ptr.get();
}
return nullptr;
}
private:
std::weak_ptr<T> m_ptr;
size_t m_index;
};
</code></pre>
<p><strong>Kruskal.cpp</strong></p>
<pre><code>#include "Kruskal.h"
#include "AdjacencyList.h"
#include "UnionFind.h"
AdjacencyList kruskal(const AdjacencyList& graph)
{
auto edges(graph.getEdgeList());
std::sort(begin(edges),
end(edges),
[](const AdjacencyList::edge_container::value_type& lhs,
const AdjacencyList::edge_container::value_type& rhs)
{
return *lhs < *rhs;
});
UnionFind components(graph.getNumVerts());
AdjacencyList minimumSpanningTree;
for (const auto edgePtr : edges)
{
const auto* edge = edgePtr.get();
const auto startIndex = edge->getStart().getIndex();
const auto endIndex = edge->getEnd().getIndex();
if (!components.sameComponent(startIndex, endIndex))
{
const auto startVertex(minimumSpanningTree.addVertex(*edge->getStart()));
const auto endVertex(minimumSpanningTree.addVertex(*edge->getEnd()));
minimumSpanningTree.addEdge(AdjacencyList::edge_type(startVertex,
endVertex,
edge->getWeight()));
components.merge(startIndex, endIndex);
}
}
return minimumSpanningTree;
}
</code></pre>
<p><strong>UnionFind.h</strong></p>
<pre><code>#include <vector>
#include <algorithm>
#include <iterator>
#include <exception>
#include <sstream>
class UnionFind
{
public:
explicit UnionFind(size_t numVerts)
{
m_components.reserve(numVerts);
size_t parentIdx = 0;
std::generate_n(std::back_inserter(m_components),
numVerts,
[&]() { return UnionFindNode(parentIdx++); });
}
bool sameComponent(size_t start, size_t end) const
{
return findRoot(start) == findRoot(end);
}
size_t findRoot(size_t elem) const
{
if (elem < m_components.size())
{
auto prevParent = elem;
auto parentIdx = m_components[prevParent].parentIdx;
while (parentIdx != prevParent)
{
prevParent = parentIdx;
parentIdx = m_components[parentIdx].parentIdx;
}
return parentIdx;
}
std::ostringstream oss;
oss << "Element index " << elem << " is out of range of components buffer (size " << m_components.size() << ").";
throw std::out_of_range(oss.str());
}
void merge(size_t start, size_t end)
{
const auto startRoot(findRoot(start));
const auto endRoot(findRoot(end));
if (startRoot == endRoot)
{
return;
}
const auto startTreeSize = m_components[startRoot].subtreeSize;
const auto endTreeSize = m_components[endRoot].subtreeSize;
if (startTreeSize < endTreeSize)
{
m_components[startRoot].parentIdx = m_components[endRoot].parentIdx;
}
else
{
m_components[endRoot].parentIdx = m_components[startRoot].parentIdx;
}
if (startTreeSize == endTreeSize)
{
m_components[startRoot].subtreeSize += 1;
}
}
private:
struct UnionFindNode
{
explicit UnionFindNode(size_t parent)
: parentIdx(parent)
, subtreeSize(1)
{
}
size_t parentIdx;
size_t subtreeSize;
};
std::vector<UnionFindNode> m_components;
};
</code></pre>
|
[] |
[
{
"body": "<p>To be honest I am having a hard time following your code.<br>\nSo I can't comment on the efficiency.</p>\n\n<p>But as an engineer I will make comments on maintainability (which I think is much more important (because if you understand the code you can optimize the slow parts once you have measured it))</p>\n\n<p>I am not sure I understand the difference between \"vertex_type\" and \"edge_type\"?. </p>\n\n<pre><code>typedef Vertex vertex_type;\ntypedef std::string vertex_id_type;\ntypedef std::vector<std::shared_ptr<vertex_type>> vertex_container;\ntypedef Handle<vertex_type> vertex_handle;\n\ntypedef Edge<vertex_handle> edge_type;\ntypedef std::vector<std::shared_ptr<edge_type>> edge_container;\ntypedef Handle<edge_type> edge_handle;\n</code></pre>\n\n<p>Getters are bad OO design. They expose and thus bind your implementation to specific types.</p>\n\n<pre><code>vertex_container getVertexList() const\nedge_container getEdgeList() const\nsize_t getNumVerts() const\nsize_t getNumEdges() const\n</code></pre>\n\n<p>Also you are returning the result by value (and thus copying) when you could return a const reference achieving the same affect without copying.</p>\n\n<p>I am not sure what <code>Handle</code> is.<br>\nIn computer science terms a Handle is named resource (thus allowing the resource to be moved and the handle to still refer to the same thing (commonly implemented as a pointer to a pointer to the resource)).</p>\n\n<p>I handle you violate the \"DRY\" principle:</p>\n\n<p>this code (or simple variations of it) are reeated multiple times.:</p>\n\n<pre><code> const auto ptr = m_ptr.lock();\n if (ptr)\n {\n return <SIMPLE ACTION>;\n }\n\n throw std::logic_error(<ERROR MESSAGE>);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-07T17:52:16.123",
"Id": "38340",
"Score": "0",
"body": "why would vertex be a synonym for edge?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-07T18:03:39.007",
"Id": "38341",
"Score": "0",
"body": "@Ysangkok: Ops. Long time since I did geometry."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-07T17:40:50.837",
"Id": "24827",
"ParentId": "24801",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "24827",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-06T17:02:55.640",
"Id": "24801",
"Score": "2",
"Tags": [
"c++",
"algorithm",
"c++11",
"graph"
],
"Title": "Is this implementation of Kruskal's algorithm maintainable and efficient?"
}
|
24801
|
<p>Lets imagine we have an <code>Article</code> entity, with data imported from a legacy database. It contains an <code>appendix</code> column with type <code>integer</code>. This column is always filled with values <code>0</code>, <code>1</code> or <code>nil</code>, so we decide to call it <code>in_appendix</code> with type <code>boolean</code>. We want to preserve all existent data so we convert the data like this:</p>
<pre><code>class ChangeTypeAppendixColumn < ActiveRecord::Migration
def up
add_column :article, :in_appendix, :boolean
f = Article.update_all({ in_appendix: false }, { appendix: nil })
f += Article.update_all({ in_appendix: false }, { appendix: 0 })
t = Article.update_all({ in_appendix: true }, { appendix: 1 })
remove_column :article, :appendix
end
def down
...
end
end
</code></pre>
<p>The problem is, if someday the <code>Article</code> model changes radically or ceases to exist, these migrations won't run anymore. My current solution is to create an <code>AuxArticle</code> class like this:</p>
<pre><code>class AuxArticle < ActiveRecord::Base
self.table_name = :article
end
class ChangeTypeAppendixColumn < ActiveRecord::Migration
def up
add_column :article, :in_appendix, :boolean
f = AuxArticle.update_all({ in_appendix: false }, { appendix: nil })
f += AuxArticle.update_all({ in_appendix: false }, { appendix: 0 })
t = AuxArticle.update_all({ in_appendix: true }, { appendix: 1 })
remove_column :article, :appendix
end
def down
...
end
end
</code></pre>
<p>It works but I would like to know about more elegant ways to keep existing data and at the same time prevent coupling between migrations and models.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-29T17:40:10.047",
"Id": "39683",
"Score": "0",
"body": "hmmm... why not do this in raw sql or Arel then ? as a side note, you have to call `Article.reset_column_information` before using the model or your operations will fail."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-06T21:47:08.990",
"Id": "24808",
"Score": "2",
"Tags": [
"ruby",
"ruby-on-rails"
],
"Title": "Converting data in a Rails Migration using the model"
}
|
24808
|
<p>I am happy to receive all recommendations for improvement. But below I am mostly interested in a review of my handling of the exception thrown by the <code>close()</code> method of <code>RandomAccessFile</code>.</p>
<p>The <code>FileNotFoundException</code> thrown by the opening of a file (in the constructor of <code>RandomAccessFile</code>) is declared as thrown by my method, because the caller can act on it. </p>
<p>But the exception thrown by the close() method on that file cannot be handled the caller, so I repackage it in a <code>RuntimeException</code>.</p>
<pre><code>private boolean includeArticle(File articleFile, Map<String, String> conditionMap)
throws FileNotFoundException
{
if (doesFileQualifyAsArticle(articleFile)) {
/* This can throw a FileNotFoundException, which the caller should know about. */
RandomAccessFile raFile = new RandomAccessFile(articleFile, "r");
if (this.isToInclude(raFile, conditionMap)) {
return true;
}
try {
raFile.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return false;
}
</code></pre>
|
[] |
[
{
"body": "<p>At least in code that I've seen, it is very common to ignore exceptions when closing a resource. In fact Apache Commons IO has a number of <a href=\"http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/IOUtils.html#closeQuietly%28java.io.Closeable%29\"><code>closeQuietly</code></a> functions just for this purpose.</p>\n\n<p>Also, the work being done with <code>raFile</code> should be wrapped in a <code>try</code>, with the <code>close/closeQuietly</code> being called in the <code>finally</code>. This ensures that <code>close/closeQuietly</code> is called even if an exception occurs while working with the file.</p>\n\n<pre><code>RandomAccessFile raFile = new RandomAccessFile(articleFile, \"r\");\ntry {\n if (this.isToInclude(raFile, conditionMap)) {\n return true;\n }\n}\nfinally {\n IOUtils.closeQuietly(raFile);\n}\n</code></pre>\n\n<p>Also, if you are using Java 7, you might want to check out the new <a href=\"http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html\">try-with-resources</a> statement.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-07T05:48:04.900",
"Id": "38326",
"Score": "0",
"body": "I am using Java 7. So I will use try-with-resources. Please correct me if I'm wrong, but even with that I need a `finally` and a `closeQuietly()` if I don't want to propogate the `IOException` from the `close()`, correct?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-07T13:28:59.943",
"Id": "38336",
"Score": "0",
"body": "In general, it is not a good idea to ignore close exceptions for/after writing. You could get the same exceptions for the same reasons there as for a normal write call. Which can lead to unexpected behavior then. This could happen only very rarely or never in good environments, but does not make it that better. To the question about try-with: You have to catch it."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-06T22:54:08.723",
"Id": "24810",
"ParentId": "24809",
"Score": "7"
}
},
{
"body": "<p>From your description, I assume you only do reading. At least, you only mention FileNotFoundException, no write exceptions. If you do only reading, you can most likely do it in this way, with a small improvement:</p>\n\n<pre><code>....\nfinally {\n try {\n if (raFile != null)\n raFile.close();\n } catch (IOException e) {\n log.warn(e); // not interesting, we are in read only mode\n }\n}\n</code></pre>\n\n<p>Otherwise, you could throw an additional NullPointerException.</p>\n\n<p>If you need it several times, you could use a static utility method:</p>\n\n<pre><code>public static void closeQuietly(Closeable closeable) {\n try {\n if (closeable != null)\n closeable.close();\n } catch (IOException e) {\n log.warn(e); // we do not care\n }\n}\n</code></pre>\n\n<p>(which is the same implementation as for apache commonsio)</p>\n\n<p>If you do writing, you should throw the exception. Because the final close can lead to the same exceptions as every write (remember, we do probably a last flush before the close and write unwritten data). I would suggest to do only:</p>\n\n<pre><code>finally {\n if (closeable != null)\n closeable.close();\n}\n</code></pre>\n\n<p>or rethrow the exception. This is exactly the same what happens with try-with, see for example here: <a href=\"http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html\" rel=\"nofollow\">http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html</a></p>\n\n<p>And do not use abbreviations.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-07T13:25:01.960",
"Id": "24820",
"ParentId": "24809",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-06T22:09:47.660",
"Id": "24809",
"Score": "2",
"Tags": [
"java",
"exception-handling"
],
"Title": "What to do with the Exception when you fail to close() a resource?"
}
|
24809
|
<p>Consider this simplified code which successively permutes array elements:</p>
<pre><code>import Data.Word
import Data.Bits
import Data.Array.Unboxed
import Data.Array.Base
import Data.Array.ST
test3 :: UArray Int Word32 -> UArray Int Word32
test3 arr = arr `seq` runSTUArray (change arr) where
change a' = do
a <- thaw a'
x0 <- unsafeRead a 0
x1 <- unsafeRead a 1
unsafeWrite a 0 (x1 + 1)
unsafeWrite a 1 (x0 - 1)
return a
test4 :: (Word32, Word32) -> (Word32, Word32)
test4 (x, y) = x `seq` y `seq` (y + 1, x - 1)
apply :: Int -> (Int -> a -> a) -> a -> a
apply n f v0 = n `seq` v0 `seq` applyLoop 0 v0 where
applyLoop i v
| i == n - 1 = res
| otherwise = applyLoop (i + 1) res
where res = f i v
main :: IO ()
main = let arr = listArray (0, 1) [0, 1] :: UArray Int Word32
in print $ apply 10000000 (\_ x -> x `seq` test3 x) arr
</code></pre>
<p>On my machine, with <code>ghc 7.4.2</code> and <code>-O3</code> flag the version with <code>test4</code> (plain tuples) shows ~10 times better performance then the version with <code>UArray</code> (also, according to the profiler, <code>UArray</code> version has total allocation of ~1.5 Gb). Are there any other optimizations I could do? I'd prefer to use the array version, because it will be more convenient in the real application.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T01:43:14.720",
"Id": "38357",
"Score": "0",
"body": "`applyLoop` is not strict in either of its accumulators. You might just be getting lucky with the strictness analyzer when using `test4`. Also, `-O2` is the highest optimization level, although `ghc` seems to silently accept any optimization level."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T02:57:09.207",
"Id": "38360",
"Score": "0",
"body": "Will writing ``where res = i `seq` v `seq` f i v`` make ``applyLoop`` strict (I know I have ``seq``s all over the place, I still have little intuition about strictness analyzer abilities)? It does not seem to have any effect on the performance."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T03:16:03.577",
"Id": "38361",
"Score": "0",
"body": "Actually, what I had in mind was something like ``i `seq` v `seq` applyLoop (i + 1) res``, but that doesn't help either. I'll post more details in an answer."
}
] |
[
{
"body": "<p>So I profiled your code using the <code>-prof -auto-all -caf-all</code> options at first and then ran it with <code>./arr +RTS -p</code>, which generates the <code>arr.prof</code> file. It gave me the following measurements:</p>\n\n<pre><code> Sun Apr 7 20:16 2013 Time and Allocation Profiling Report (Final)\n\n arr +RTS -p -RTS\n\n total time = 10.42 secs (10419 ticks @ 1000 us, 1 processor)\n total alloc = 14,400,052,608 bytes (excludes profiling overheads)\n\nCOST CENTRE MODULE %time %alloc\n\napply.applyLoop Main 32.9 0.0\ntest3 Main 30.7 55.6\ntest3.change Main 21.3 44.4\nmain.\\ Main 7.7 0.0\napply.applyLoop.res Main 7.5 0.0\n</code></pre>\n\n<p>All the allocation is occurring in <code>test3</code>. I thought it was because you keep <code>thaw</code>ing array, which makes a new copy, but that was not the case. Replacing <code>thaw</code> with <code>unsafeThaw</code> and <code>runSTArray</code> with the <code>unsafeFreeze</code> equivalent did nothing:</p>\n\n<pre><code>{-# LANGUAGE RankNTypes #-}\n\nimport Data.Word\nimport Data.Bits\nimport Data.Array.Unboxed\nimport Data.Array.Base hiding (unsafeThaw, unsafeFreeze)\nimport Data.Array.ST\nimport Control.Monad.ST (ST, runST)\n\ntest3 :: UArray Int Word32 -> UArray Int Word32\ntest3 arr = runST $ change arr where\n change a' = do\n a <- unsafeThaw a' :: forall s . ST s (STUArray s Int Word32)\n x0 <- unsafeRead a 0\n x1 <- unsafeRead a 1\n unsafeWrite a 0 (x1 + 1)\n unsafeWrite a 1 (x0 - 1)\n unsafeFreeze a\n\ntest4 :: (Word32, Word32) -> (Word32, Word32)\ntest4 (x, y) = x `seq` y `seq` (y + 1, x - 1)\n\napply :: Int -> (Int -> a -> a) -> a -> a\napply n f v0 = n `seq` v0 `seq` applyLoop 0 v0 where\n applyLoop i v\n | i == n - 1 = res\n | otherwise = (applyLoop $! i + 1) $! res\n where res = f i v\n\nmain :: IO ()\nmain = let arr = listArray (0, 1) [0, 1] :: UArray Int Word32\n in print $ apply 100000000 (\\_ x -> x `seq` test3 x) arr\n</code></pre>\n\n<p>So I added more fine grained cost centers to zoom in on which part was the trouble-maker:</p>\n\n<pre><code>{-# LANGUAGE RankNTypes #-}\n\nimport Data.Word\nimport Data.Bits\nimport Data.Array.Unboxed\nimport Data.Array.Base hiding (unsafeThaw, unsafeFreeze)\nimport Data.Array.ST\nimport Control.Monad.ST (ST, runST)\n\ntest3 :: UArray Int Word32 -> UArray Int Word32\ntest3 arr = {-# SCC \"runST\" #-} runST $ {-# SCC \"change\" #-} change arr where\n change a' = do\n a <- {-# SCC \"unsafeThaw\" #-} unsafeThaw a' :: forall s . ST s (STUArray s Int Word32)\n x0 <- {-# SCC \"unsafeRead1\" #-} unsafeRead a 0\n x1 <- {-# SCC \"unsafeRead2\" #-} unsafeRead a 1\n {-# SCC \"unsafeWrite1\" #-} unsafeWrite a 0 (x1 + 1)\n {-# SCC \"unsafeWrite2\" #-} unsafeWrite a 1 (x0 - 1)\n {-# SCC \"unsafeFreeze\" #-} unsafeFreeze a\n\ntest4 :: (Word32, Word32) -> (Word32, Word32)\ntest4 (x, y) = x `seq` y `seq` (y + 1, x - 1)\n\napply :: Int -> (Int -> a -> a) -> a -> a\napply n f v0 = n `seq` v0 `seq` applyLoop 0 v0 where\n applyLoop i v\n | i == n - 1 = res\n | otherwise = (applyLoop $! i + 1) $! res\n where res = f i v\n\nmain :: IO ()\nmain = let arr = listArray (0, 1) [0, 1] :: UArray Int Word32\n in print $ apply 100000000 (\\_ x -> x `seq` test3 x) arr\n</code></pre>\n\n<p>... but that just gave even more confusing results. It says that <code>change</code> is the bottle-neck, but as far as I can tell, <code>change</code> is just the bind for <code>ST</code>, which should be just as fast as the <code>IO</code> monad's bind (which is fast).</p>\n\n<pre><code> Sun Apr 7 20:39 2013 Time and Allocation Profiling Report (Final)\n\n arr +RTS -p -RTS\n\n total time = 29.24 secs (29237 ticks @ 1000 us, 1 processor)\n total alloc = 26,400,052,608 bytes (excludes profiling overheads)\n\nCOST CENTRE MODULE %time %alloc\n\ntest3.change Main 45.4 15.2\napply.applyLoop Main 12.1 0.0\nchange Main 6.8 15.2\nunsafeFreeze Main 6.3 24.2\nunsafeThaw Main 6.2 24.2\nunsafeRead1 Main 5.0 12.1\nrunST Main 4.9 0.0\nunsafeWrite2 Main 4.3 9.1\napply.applyLoop.res Main 2.9 0.0\ntest3 Main 2.7 0.0\nmain.\\ Main 2.7 0.0\n</code></pre>\n\n<p>So I'm sort of at a loss at this point for how to optimize it further, but perhaps somebody else can build off of this.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T03:45:16.090",
"Id": "24840",
"ParentId": "24811",
"Score": "1"
}
},
{
"body": "<p>Okay, first let's establish a baseline. I'm on a 32-bit system now, so the allocation figures and also the timings are somewhat different than on a 64-bit system, but the trends are mostly the same. To see what we deal with, let's not compile for profiling, but just plain with optimisations (<code>-O2</code>).</p>\n\n<p>I have created <a href=\"https://bitbucket.org/dafis/arrayswaps\" rel=\"noreferrer\">a repository</a> with all versions of the code I ran. I took the liberty and removed all superfluous <code>seq</code>s, and slightly changed <code>applyLoop</code>, to</p>\n\n<pre><code>applyLoop i v\n | i == n = v\n | otherwise = applyLoop (i + 1) $ f i v\n</code></pre>\n\n<p>which changes the result if <code>apply</code> is initially called with a zero argument (the new one immediately returns the original argument, while the old looped until <code>i</code> reaches <code>-1</code> after wrap-around of the counter), but for positive arguments the semantics remain unchanged. For very small positive <code>n</code>, the one extra comparison the new version does <em>might</em> make a measurable difference if <code>f</code> is inlined and trivial, but for nontrivial <code>n</code> or <code>f</code>, the extra comparison is negligible, and the new version avoids code duplication that happens with the old.</p>\n\n<p>That gives</p>\n\n<pre><code>$ ./test3 +RTS -s\narray (0,1) [(0,0),(1,1)]\n 560,049,112 bytes allocated in the heap\n 32,160 bytes copied during GC\n 42,632 bytes maximum residency (2 sample(s))\n 22,904 bytes maximum slop\n 1 MB total memory in use (0 MB lost due to fragmentation)\n\n Tot time (elapsed) Avg pause Max pause\nGen 0 1083 colls, 0 par 0.02s 0.02s 0.0000s 0.0001s\nGen 1 2 colls, 0 par 0.00s 0.00s 0.0002s 0.0002s\n\nINIT time 0.00s ( 0.00s elapsed)\nMUT time 1.35s ( 1.35s elapsed)\nGC time 0.02s ( 0.02s elapsed)\nEXIT time 0.00s ( 0.00s elapsed)\nTotal time 1.37s ( 1.37s elapsed)\n\n%GC time 1.3% (1.3% elapsed)\n\nAlloc rate 415,944,041 bytes per MUT second\n\nProductivity 98.6% of total user, 98.4% of total elapsed\n</code></pre>\n\n<p>in contrast to</p>\n\n<pre><code>$ ./test4 +RTS -s\n(0,1)\n 47,492 bytes allocated in the heap\n 1,756 bytes copied during GC\n 42,632 bytes maximum residency (1 sample(s))\n 18,808 bytes maximum slop\n 1 MB total memory in use (0 MB lost due to fragmentation)\n\n Tot time (elapsed) Avg pause Max pause\nGen 0 0 colls, 0 par 0.00s 0.00s 0.0000s 0.0000s\nGen 1 1 colls, 0 par 0.00s 0.00s 0.0002s 0.0002s\n\nINIT time 0.00s ( 0.00s elapsed)\nMUT time 0.04s ( 0.04s elapsed)\nGC time 0.00s ( 0.00s elapsed)\nEXIT time 0.00s ( 0.00s elapsed)\nTotal time 0.04s ( 0.04s elapsed)\n\n%GC time 0.5% (0.6% elapsed)\n\nAlloc rate 1,182,455 bytes per MUT second\n\nProductivity 98.9% of total user, 103.1% of total elapsed\n</code></pre>\n\n<p>from <code>test4</code>. The difference is enormous. Well, let's look at the core to find out why, and how we can reduce it.</p>\n\n<p>First, the core for using <code>test4</code>:</p>\n\n<pre><code>Rec {\nMain.main_$s$wapplyLoop [Occ=LoopBreaker]\n :: GHC.Prim.Int#\n -> GHC.Prim.Word#\n -> GHC.Prim.Word#\n -> (# GHC.Word.Word32, GHC.Word.Word32 #)\n[GblId, Arity=3, Caf=NoCafRefs, Str=DmdType LLL]\nMain.main_$s$wapplyLoop =\n \\ (sc :: GHC.Prim.Int#)\n (sc1 :: GHC.Prim.Word#)\n (sc2 :: GHC.Prim.Word#) ->\n case sc of wild {\n __DEFAULT ->\n Main.main_$s$wapplyLoop\n (GHC.Prim.+# wild 1)\n (GHC.Prim.plusWord# sc2 (__word 1))\n (GHC.Prim.minusWord# sc1 (__word 1));\n 10000000 -> (# GHC.Word.W32# sc1, GHC.Word.W32# sc2 #)\n }\nend Rec }\n</code></pre>\n\n<p>You can't beat that without short-cutting. You get a tight loop using only unboxed values in registers, it does no allocation. But note that <code>seq</code>ing <code>x</code> and <code>y</code> in <code>test4</code> is necessary here to aid the strictness analyser. Without it, you get a loop using boxed <code>Word32</code>s building up huge thunks. The <code>seq</code>s that originally were in <code>apply</code> resp. in the function <code>(\\_ x -> x `seq` testN x)</code> passed to it make no difference whatsoever.</p>\n\n<p>So, we have a lean and mean unboxed loop to aim for, and a sluggish alternative allocating tons. What is allocating so much, and taking so much time there?</p>\n\n<p>The <code>applyLoop</code> worker in this case begins with</p>\n\n<pre><code>case GHC.ST.runSTRep\n @ (Data.Array.Base.UArray GHC.Types.Int GHC.Word.Word32)\n (\\ (@ s) (s :: GHC.Prim.State# s) ->\n let {\n n# [Dmd=Just L] :: GHC.Prim.Int#\n [LclId, Str=DmdType]\n n# = GHC.Prim.sizeofByteArray# ww4 } in\n case GHC.Prim.newByteArray# @ s n# s of _ { (# ipv, ipv1 #) ->\n case {__pkg_ccall array-0.4.0.1 memcpy forall s.\n GHC.Prim.MutableByteArray# s\n -> GHC.Prim.ByteArray#\n -> GHC.Prim.Word#\n -> GHC.Prim.State# GHC.Prim.RealWorld\n -> (# GHC.Prim.State# GHC.Prim.RealWorld, GHC.Prim.Addr# #)}\n</code></pre>\n\n<p>allocating a new <code>ByteArray#</code> - which is pretty fast, GHC's runtime is very good at such things, but nevertheless, 10 million allocations sum up to non-negligible time - and copying the contents of the old array over. The <code>__pkg_ccall</code> is a quite fast C call, but it is considerably slower than a Haskell call, and calling over to C for copying 8 bytes is wasteful (the call takes much longer than the copying). I think - though I can't verify at the moment - that on a 64-bit system that is done without calling out to C, which would be much faster. Replacing the <code>thaw</code> with a manual copying loop for an <code>unsafeNewArray_</code> of the appropriate size (manual_copy.hs) brings down the time to 0.65 seconds - but increases the allocation figures:</p>\n\n<pre><code>$ ./manual_copy +RTS -s\narray (0,1) [(0,0),(1,1)]\n 760,049,112 bytes allocated in the heap\n 41,424 bytes copied during GC\n 42,632 bytes maximum residency (2 sample(s))\n 22,904 bytes maximum slop\n 1 MB total memory in use (0 MB lost due to fragmentation)\n\n Tot time (elapsed) Avg pause Max pause\nGen 0 1469 colls, 0 par 0.02s 0.02s 0.0000s 0.0001s\nGen 1 2 colls, 0 par 0.00s 0.00s 0.0003s 0.0003s\n\nINIT time 0.00s ( 0.00s elapsed)\nMUT time 0.62s ( 0.63s elapsed)\nGC time 0.02s ( 0.02s elapsed)\nEXIT time 0.00s ( 0.00s elapsed)\nTotal time 0.64s ( 0.65s elapsed)\n\n%GC time 3.3% (3.2% elapsed)\n\nAlloc rate 1,226,997,169 bytes per MUT second\n\nProductivity 96.6% of total user, 95.3% of total elapsed\n</code></pre>\n\n<p>Note that it would be different for a large array, then calling to <code>memcpy</code> of the C standard library would pay off.</p>\n\n<p>Using <code>unsafeThaw</code> here (unsafeThaw.hs) avoids allocating new <code>ByteArray#</code>s (the underlying raw arrays that carry the payload of <code>UArray</code>s) each iteration, and the involved copying, so it unsurprisingly speeds up the program, and reduces allocation:</p>\n\n<pre><code>$ ./unsafeThaw +RTS -s\narray (0,1) [(0,0),(1,1)]\n 400,049,112 bytes allocated in the heap\n 27,596 bytes copied during GC\n 42,632 bytes maximum residency (2 sample(s))\n 22,904 bytes maximum slop\n 1 MB total memory in use (0 MB lost due to fragmentation)\n\n Tot time (elapsed) Avg pause Max pause\nGen 0 764 colls, 0 par 0.01s 0.01s 0.0000s 0.0001s\nGen 1 2 colls, 0 par 0.00s 0.00s 0.0003s 0.0003s\n\nINIT time 0.00s ( 0.00s elapsed)\nMUT time 0.28s ( 0.28s elapsed)\nGC time 0.01s ( 0.01s elapsed)\nEXIT time 0.00s ( 0.00s elapsed)\nTotal time 0.29s ( 0.29s elapsed)\n\n%GC time 4.4% (4.3% elapsed)\n\nAlloc rate 1,448,146,787 bytes per MUT second\n\nProductivity 95.5% of total user, 95.6% of total elapsed\n</code></pre>\n\n<p>So the speedup is about 4.5× compared to the original - not bad, but still a <em>far</em> cry from the <code>test4</code> time - and the allocation is reduced by 160 million bytes (10 million times 8 bytes for the two <code>Word32</code> plus 8 for bookkeeping [size] of the <code>ByteArray#</code>), but it is still huge.</p>\n\n<p>That is because</p>\n\n<pre><code>of _ { (# ipv4, ipv5 #) ->\n(# ipv4,\n Data.Array.Base.UArray\n @ GHC.Types.Int @ GHC.Word.Word32 ww1 ww2 ww3 ipv5 #)\n}\n</code></pre>\n\n<p>in each iteration it creates a new <code>UArray Int Word32</code>. It allocates a new <code>UArray</code> constructor, and pointers to the components, lower bound, upper bound, number of elements and the <code>ByteArray#</code>. We can avoid that by returning the argument array - after we sneakily changed the contents of its <code>ByteArray#</code> (unsafeThaw2.hs):</p>\n\n<pre><code>test3 :: UArray Int Word32 -> UArray Int Word32\ntest3 arr = runST (change arr) where\n change a' = do\n a <- Data.Array.Unsafe.unsafeThaw a' :: ST s (STUArray s Int Word32)\n x0 <- unsafeRead a 0\n x1 <- unsafeRead a 1\n unsafeWrite a 0 (x1 + 1)\n unsafeWrite a 1 (x0 - 1)\n return a'\n</code></pre>\n\n<p>which results in</p>\n\n<pre><code>$ ./unsafeThaw2 +RTS -s\narray (0,1) [(0,0),(1,1)]\n 80,049,100 bytes allocated in the heap\n 6,828 bytes copied during GC\n 42,632 bytes maximum residency (2 sample(s))\n 22,904 bytes maximum slop\n 1 MB total memory in use (0 MB lost due to fragmentation)\n\n Tot time (elapsed) Avg pause Max pause\nGen 0 151 colls, 0 par 0.00s 0.00s 0.0000s 0.0001s\nGen 1 2 colls, 0 par 0.00s 0.00s 0.0003s 0.0003s\n\nINIT time 0.00s ( 0.00s elapsed)\nMUT time 0.17s ( 0.17s elapsed)\nGC time 0.00s ( 0.00s elapsed)\nEXIT time 0.00s ( 0.00s elapsed)\nTotal time 0.17s ( 0.17s elapsed)\n\n%GC time 1.7% (1.7% elapsed)\n\nAlloc rate 480,150,792 bytes per MUT second\n\nProductivity 98.1% of total user, 98.0% of total elapsed\n</code></pre>\n\n<p>another nearly twofold speedup and allocation figures reduced by 80%.</p>\n\n<p>It takes so much longer and allocates so much more than the tight loop mostly because each iteration costs a <code>GHC.ST.runSTRep</code>, which is <code>NOINLINE</code> and inhibits a worker-wrapper transform of <code>test3</code> that would allow cheaper access to the <code>ByteArray#</code>.</p>\n\n<p>You can get much better performance if you change the type of <code>apply</code> to be monadic, and use a monadic version of <code>test3</code>, e.g. (cleanST.hs)</p>\n\n<pre><code>import Data.Word\nimport Data.Array.Unboxed\nimport Data.Array.ST\nimport Data.Array.Base\nimport Control.Monad.ST\n\ntest0 :: STUArray s Int Word32 -> ST s (STUArray s Int Word32)\ntest0 arr = do\n x0 <- unsafeRead arr 0\n x1 <- unsafeRead arr 1\n unsafeWrite arr 0 (x1+1)\n unsafeWrite arr 1 (x0 - 1)\n return arr\n\napplyM :: Monad m => Int -> (Int -> a -> m a) -> a -> m a\napplyM n f v0 = do\n let loop i v\n | i < n = do\n v' <- f i v\n loop (i+1) v'\n | otherwise = return v\n loop 0 v0\n\nmain :: IO ()\nmain = let arr = listArray (0,1) [0,1] :: UArray Int Word32\n in print $ runSTUArray $ do\n marr <- thaw arr\n applyM 10000000 (\\_ a -> test0 a) marr\n</code></pre>\n\n<p>that comes close to the tight loop:</p>\n\n<pre><code>$ ./cleanST +RTS -s\narray (0,1) [(0,0),(1,1)]\n 49,148 bytes allocated in the heap\n 1,756 bytes copied during GC\n 42,632 bytes maximum residency (1 sample(s))\n 18,808 bytes maximum slop\n 1 MB total memory in use (0 MB lost due to fragmentation)\n\n Tot time (elapsed) Avg pause Max pause\nGen 0 0 colls, 0 par 0.00s 0.00s 0.0000s 0.0000s\nGen 1 1 colls, 0 par 0.00s 0.00s 0.0002s 0.0002s\n\nINIT time 0.00s ( 0.00s elapsed)\nMUT time 0.05s ( 0.06s elapsed)\nGC time 0.00s ( 0.00s elapsed)\nEXIT time 0.00s ( 0.00s elapsed)\nTotal time 0.06s ( 0.06s elapsed)\n\n%GC time 0.4% (0.4% elapsed)\n\nAlloc rate 905,470 bytes per MUT second\n\nProductivity 99.2% of total user, 97.3% of total elapsed\n</code></pre>\n\n<p>but is of course still slower because the array reads and writes go to the L1 cache, while <code>test4</code> operated completely in registers.</p>\n\n<p>If you don't want to change the type of <code>apply</code>, I know no clean way of coming close to the performance of the tight loop.</p>\n\n<p>If you are prepared to get your hands really dirty, you can use low-level primitives (low_level.hs),</p>\n\n<pre><code>{-# LANGUAGE MagicHash, UnboxedTuples, BangPatterns #-}\n\nimport Data.Word\nimport Data.Array.Unboxed\nimport Data.Array.Base\nimport GHC.Base\n\ntest3 :: UArray Int Word32 -> UArray Int Word32\ntest3 arr = change arr where\n swp mbarr s =\n case readWord32Array# mbarr 0# s of\n (# s1, w0 #) ->\n case readWord32Array# mbarr 1# s1 of\n (# s2, w1 #) ->\n case writeWord32Array# mbarr 0# (w1 `plusWord#` 1##) s2 of\n s3 -> writeWord32Array# mbarr 1# (w0 `minusWord#` 1##) s3\n change arr@(UArray _ _ _ ba)\n = case swp (unsafeCoerce# ba) realWorld# of\n !s -> arr\n</code></pre>\n\n<p>which gives more or less the same figures as <code>cleanST</code>,</p>\n\n<pre><code>$ ./low_level +RTS -s\narray (0,1) [(0,0),(1,1)]\n 49,112 bytes allocated in the heap\n 1,756 bytes copied during GC\n 42,632 bytes maximum residency (1 sample(s))\n 18,808 bytes maximum slop\n 1 MB total memory in use (0 MB lost due to fragmentation)\n\n Tot time (elapsed) Avg pause Max pause\nGen 0 0 colls, 0 par 0.00s 0.00s 0.0000s 0.0000s\nGen 1 1 colls, 0 par 0.00s 0.00s 0.0002s 0.0002s\n\nINIT time 0.00s ( 0.00s elapsed)\nMUT time 0.05s ( 0.06s elapsed)\nGC time 0.00s ( 0.00s elapsed)\nEXIT time 0.00s ( 0.00s elapsed)\nTotal time 0.06s ( 0.06s elapsed)\n\n%GC time 0.4% (0.4% elapsed)\n\nAlloc rate 928,001 bytes per MUT second\n\nProductivity 99.0% of total user, 95.1% of total elapsed\n</code></pre>\n\n<p>and more-or-less equivalent core (<code>cleanST</code>'s is cleaner), but is really as dirty as it looks. I cannot recommend going down that route except in extreme circumstances.</p>\n\n<hr>\n\n<p>Note: new (better) timings, the machine was busier when the original runs were made</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T19:03:29.437",
"Id": "38605",
"Score": "0",
"body": "I'm having trouble following your steps, Daniel. If you could hpaste each code variant used on each step, it would probably help a great deal. If you still have them. :) If not, no matter."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T19:06:51.590",
"Id": "38606",
"Score": "0",
"body": "Urk. I'll try to reconstruct as good as possible. Will take a bit."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T19:23:57.383",
"Id": "38609",
"Score": "0",
"body": "and you say you changed it to `ByteArray#`, but the `test3` that follows is tagged with `test3 :: UArray Int Word32 -> UArray Int Word32`... ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T19:38:01.487",
"Id": "38611",
"Score": "0",
"body": "so is it correct to say that while the original function did 10 million thaws and freezes, your monadic version does just one thaw (and doesn't even bother with unsafeThaw) and then does a 10 million loop *inside* the ST monad? It does make perfect sense for it to perform that much better! :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T20:11:53.687",
"Id": "38613",
"Score": "0",
"body": "@Will [here is a repo](https://bitbucket.org/dafis/arrayswaps) with as far as I remember all versions. I'll reply to the following comments in a moment."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T20:16:01.077",
"Id": "38615",
"Score": "0",
"body": "@Will No, I didn't change it to `ByteArray#`, nor did I say so, I think. A `ByteArray#` is what bears a `UArray`'s payload. In the second `unsafeThaw` version, we return the `UArray` we got as argument, but in the meantime changed the contents of its (typo there in the answer) `ByteArray#`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T20:22:46.977",
"Id": "38617",
"Score": "0",
"body": "@Will Yes, `test0` does just one `thaw` (and that I allow to copy, in case something wants to retain the original, for one `thaw` it doesn't make much of a difference). And since we then only have one `runST(UArray)`, we don't run into the `runSTRep` fence on every iteration, so GHC can inline and optimise it better. The reduction from 400 M to 80 M alloc between the two `unsafeThaw` versions is because the first (with `return a`) allocates a new `UArray` constructor (plus the three pointers to the two bounds and the element count), which the second (with `return a'`) doesn't."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T20:23:53.450",
"Id": "38618",
"Score": "0",
"body": "got it! Thanks a lot for all the code and explanations!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T21:02:51.997",
"Id": "38623",
"Score": "0",
"body": "two more (last!) questions (remarks, really) at http://chat.stackexchange.com/rooms/8284/discussion-between-will-ness-and-daniel-fischer"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-11T00:02:29.807",
"Id": "38638",
"Score": "0",
"body": "Wow, thank you for such detailed explanation! Especially for the step with moving the loop inside the monad; I'll be aware of this possibility in the future."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-07-23T14:13:48.750",
"Id": "323947",
"Score": "0",
"body": "This answer is underrated!"
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T15:21:55.823",
"Id": "24968",
"ParentId": "24811",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "24968",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-07T01:22:59.870",
"Id": "24811",
"Score": "3",
"Tags": [
"optimization",
"performance",
"array",
"haskell"
],
"Title": "Optimizing unboxed array operations in Haskell"
}
|
24811
|
<p>I have just picked up Scala like 2 hours ago, and I am thinking of printing a series like 1 to 10 but in a recursive fashion. I do not understand what is wrong with this:</p>
<pre><code>def printSeries(x:Int):Int = {
if(x==0) doNothing() else doSomething()
def doNothing() = {}
def doSomething() = {
println(x)
printSeries(x-1)
}
}
</code></pre>
<p>Sorry, this might be very basic. Please point out my mistakes or any alternative and simpler implementation. (I do not want to use loops).</p>
<p>Thanks,</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-06T19:01:42.353",
"Id": "38328",
"Score": "3",
"body": "Unrelated but maybe of interest to you, Coursera just started a class on Scala last week taught by Martin Odersky (the creator of Scala): [link](https://class.coursera.org/progfun-002/auth/welcome)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-06T19:03:51.640",
"Id": "38329",
"Score": "1",
"body": "^ And I just finished the lecture videos for Week 2. Such an awesome instructor he is."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-06T19:16:04.060",
"Id": "38330",
"Score": "0",
"body": "Thanks Nathan for the coursera link. Will definitely check it out."
}
] |
[
{
"body": "<p>First of all, you are promising to return Int from <code>printSeries</code>. Why? If method is printing, isn't much more natural* to make it return Unit (aka void). This is usually can be done either explicitly </p>\n\n<pre><code>def printSeries(upTo: Int): Unit = { .... } \n</code></pre>\n\n<p>or implicitly: </p>\n\n<pre><code>def printSeries(upTo: Int) { .... } \n</code></pre>\n\n<p>(see, no equals sign in code above).</p>\n\n<p>Next, why do you have explicit doNothing method? I think it would be better to write something like: </p>\n\n<pre><code>def printSeries(upTo: Int) {\n if(upTo > 0) {\n println(upTo)\n printSeries(upTo - 1)\n }\n}\n</code></pre>\n\n<p>You also might want to place @tailrec annotation to ensure that code will be optimized and won't fail with Stackoverflow at big <code>upTo</code> numbers (if it will and function is annotated compiler will yell on you).</p>\n\n<pre><code>@annotation.tailrec\ndef printSeries(upTo: Int) {\n if(upTo > 0) {\n println(upTo)\n printSeries(upTo - 1)\n }\n}\n</code></pre>\n\n<p>Finally, generally, it is better to produce sequences and only then make something with them.</p>\n\n<p>P.S. you might better to post questions like this on <a href=\"https://codereview.stackexchange.com/\">code review site</a>, not on stackoverlow itself</p>\n\n<p>* there is a good rule in programming to make functions <em>do one thing and be good at it</em> so getXandMakeY usually is bad idea.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-06T19:14:59.337",
"Id": "38331",
"Score": "0",
"body": "Thanks @om-nom-nom, I did not know about Unit. Also thanks for the code review web site link. I did not know about that."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-06T19:03:27.747",
"Id": "24816",
"ParentId": "24815",
"Score": "5"
}
},
{
"body": "<p>Because your method signature is <code>Int => Int</code>, your method expects to return an Int. You might have wanted to define it like <code>def printSeries(x:Int):Unit = {</code> sot that it does not need to return something.</p>\n\n<p>Besides, you can do it with the following shorter function</p>\n\n<pre><code>def printSeries(x:Int):Unit= {\n if(x>0) {\n println(x)\n printSeries(x-1)\n }\n}\n</code></pre>\n\n<p>Other alternatives using val and pattern matching at the same time.</p>\n\n<pre><code>val printSeries: (Int)=> Unit = _ match {\n case x if x>0 =>\n println(x)\n printSeries(x-1)\n case _ =>\n}\n</code></pre>\n\n<p>Another alternative using anonymous function</p>\n\n<pre><code>val printSeries: (Int)=> Unit = { x =>\n if(x>0) {\n println(x)\n printSeries(x-1)\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-06T19:06:27.803",
"Id": "38332",
"Score": "0",
"body": "I think pattern matching here is kinda harmfull."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-06T19:08:40.517",
"Id": "38333",
"Score": "0",
"body": "Because it concerns integers, yes, But this can be generalized for other cases."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-06T19:09:34.130",
"Id": "38334",
"Score": "0",
"body": "[...can be generalized for other cases](https://en.wikipedia.org/wiki/YAGNI)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-06T19:05:10.957",
"Id": "24817",
"ParentId": "24815",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "24816",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-06T18:56:59.493",
"Id": "24815",
"Score": "1",
"Tags": [
"scala",
"recursion"
],
"Title": "Recursively print in scala"
}
|
24815
|
<p>I am learning C from K.N. King and at ch-17, I covered linked list and wrote a code to add data in the ascending order in the linked list which is opposite to found in the book (In the book, it store in reverse order). Here's the code:</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
typedef struct NODE {
int value;
struct NODE *next;
} Node;
int main(void) {
Node *root = NULL;
Node *connector;
int n;
for(n = 1; n < 5; n++) {
if(root == NULL) {
connector = malloc(sizeof(Node));
connector->value = n;
connector->next = NULL;
root = connector;
}
else {
connector->next = malloc(sizeof(Node));
connector->next->value = n;
connector = connector->next;
connector->next = NULL;
}
}
while(root != NULL) {
printf("%d\n", root->value);
root = root->next;
}
return 0;
}
</code></pre>
<p>Can this code be improved. I know it's very basic and I just write for testing only. However I can make a function for it and loop is not necessary also. What I want to know is that, can I reduce the if-else to single if statement.</p>
|
[] |
[
{
"body": "<p>Well you can get rid of the if-else by avoiding a malloc of the root node like this:</p>\n\n<pre><code>Node root = {0, NULL};\nNode *tail = &root;\n\nfor (int n = 1; n < 5; n++) {\n Node *node = malloc(sizeof(Node));\n node->value = n;\n node->next = NULL;\n tail->next = node;\n tail = node;\n}\n\nfor (const Node *node = &root; node != NULL; node = node->next) {\n printf(\"%d\\n\", node->value);\n}\n</code></pre>\n\n<p>This avoids the if-else, as you asked, but means you must be careful never to free the root node (as that will fail). Note that the printing loop changes accordingly. </p>\n\n<p>Alternatively, you could extract the common code from the if-else and keep the root node as a pointer. This doesn't get rid of the if-else, but simplifies it for the reader.</p>\n\n<pre><code>Node *root = NULL;\nNode *tail = NULL;\n\nfor (int n = 1; n < 5; n++) {\n Node *node = malloc(sizeof(Node));\n node->value = n;\n node->next = NULL;\n\n if (root == NULL) {\n root = node;\n } else {\n tail->next = node;\n }\n tail = node;\n}\n</code></pre>\n\n<p>Note that in both cases I used the variable <code>tail</code> rather than <code>connector</code>, as it seems more descriptive, and a temporary variable <code>node</code>. I also defined the loop variables within the loop, which is preferable.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-07T16:48:44.797",
"Id": "24825",
"ParentId": "24823",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "24825",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-07T16:24:45.633",
"Id": "24823",
"Score": "1",
"Tags": [
"c",
"linked-list"
],
"Title": "Basic Linked list"
}
|
24823
|
<p>I am writing a basic image upload script in PHP, and am looking for critiques. The script below is the result of various suggestions I have found online... for now I am running it locally and it works fine, but I would love for someone more experienced to look over it.</p>
<p>Is this secure? Poorly implemented? Too redundant? Not redundant enough? What am I missing and/or doing incorrectly? Any suggestions/help/advice is GREATLY appreciated. Thank you.</p>
<p>PHP:</p>
<pre><code>if (isset($_FILES['image']))
{
$files_array = $_FILES['image'];
$num_of_image_uploads = count($files_array['name']);
// Loop through array of file uploads
for ($i = 0; $i < $num_of_image_uploads; $i++)
{
// Check if there is a file to upload
// If so -> define, validate, and upload
if ($files_array['tmp_name'][$i] != "")
{
$errors = false; // Flag for errors
$allowed_ext = array('jpg', 'jpeg', 'png', 'gif');
$file_name = $files_array['name'][$i];
$file_ext = strtolower(end(explode('.', $file_name)));
$file_size = $files_array['size'][$i];
$file_tmp = $files_array['tmp_name'][$i];
// Extension check 1
if (in_array($file_ext, $allowed_ext) === false)
{
echo "Extension not allowed. <br/>";
$errors = true;
}
// Extension check 2 - if file is not empty
if ($file_size == 0)
{
echo "File is empty. <br/>";
$errors = true;
}
else if (!getimagesize($file_tmp))
{
echo "Not an image. <br/>";
$errors = true;
}
// Extension check 3
$blacklist = array(".php", ".phtml", ".php3", ".php4");
foreach ($blacklist as $item)
{
if(preg_match("/$item\$/i", $file_name))
{
echo "File not allowed. <br/>";
$errors = true;
}
}
// File size check
if ($file_size > 4718592)
{
echo "File size must be under 4.5MB. <br/>";
$errors = true;
}
// Rename file
$file_name = preg_replace("/[^A-Z0-9_]/i", "_", $file_name);
$file_name = md5($i.$file_name.time());
// Insert if no errors
if ($errors == false)
{
if (move_uploaded_file($file_tmp, 'uploads/'.$file_name.'.'.$file_ext))
{
echo "Success! File uploaded. <br/>";
}
}
}
}
}
</code></pre>
<p>HTML:</p>
<pre><code><body>
<form enctype="multipart/form-data" action="" method="post">
<input name="image[]" type="file" />
<input name="image[]" type="file" />
<input name="image[]" type="file" />
<input name="image[]" type="file" />
<input type="submit" value="Upload" />
</form>
</body>
</code></pre>
|
[] |
[
{
"body": "<p>Why are you using <code>preg_match</code> if you don't need it? The unescaped dot in a regex will match any char. Even if the dot wasn't there, your code is still vulnerable to regex injection.</p>\n\n<p>Also, why are you sanitizing the filename if you're hashing it anyway? Why use hashing at all? Is it so important that the original filename is lost? What about hash collisions? Why not just base-16 it?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-07T22:21:27.550",
"Id": "38352",
"Score": "0",
"body": "Thanks for the response. I am a beginner when it comes to security, and I am not really sure what I'm doing. I tried to implement security measures I have found in various forums/tutorials, but I don't fully understand all the threats I need to protect against. Sanitizing and hashing the name was just my attempt to rename the file something safe, unique, and random. It sounds like I am going about that wrong. Any suggestions on a better solution? Also, can you elaborate on regex injection, why I am vulnerable, and how I can prevent it? Thanks!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T13:38:44.270",
"Id": "38391",
"Score": "0",
"body": "just use http://php.net/preg_quote and hex (base-16) the user supplied data instead of hashing it. and if the file already exists, refuse the upload."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-07T17:09:34.163",
"Id": "24826",
"ParentId": "24824",
"Score": "0"
}
},
{
"body": "<p>Your script has one underlying assumption that invalidates the whole set of security checks: That the value of <code>$files_array['name']</code> is safe - it is not. This value is user supplied, and can very easily be spoofed to pass malicious data into your server that would get through all your security checks.</p>\n\n<p>Neither <code>$_FILES['control']['name']</code> nor <code>$_FILES['control']['type']</code> are safe and you should not use either value for anything, ever.</p>\n\n<p>In order to make your image uploads as safe as possible you must do all of the following:</p>\n\n<ul>\n<li>Verify that the data you are working with is an uploaded file (<code>move_uploaded_file()</code> / <code>is_uploaded_file()</code> will take care of this for you)</li>\n<li>Create the file name used to store the file on the file system entirely dynamically. You cannot use user input in any way to generate this. If your application requires that you store the original file name, you should keep this association in an external data store such as a database.</li>\n<li>Verify that the image really is an image. The <a href=\"http://www.php.net/manual/en/book.image.php\" rel=\"nofollow noreferrer\">GD</a> extension can verify the headers for you (use the <a href=\"http://www.php.net/manual/en/function.getimagesize.php\" rel=\"nofollow noreferrer\"><code>getimagesize()</code></a> function).</li>\n<li>Copy the pixel data out of the image into a new one. Again, GD can do this for you (<code>imagecopyresampled()</code>). It is important to do this - it is possible to hide malicious code inside something with headers that make it appear to be a valid image. Resampling the image will destroy such malicious code.</li>\n<li>I recommend that if you store the image on the file system, store it outside the document root and proxy the retrieval process with a script, so it cannot be directly accessed via the web server. The above measures <em>should</em> mitigate the implied security risk here, but better safe than sorry ;-)</li>\n<li><strong>Never</strong> <code>include</code>/<code>require</code> a file uploaded by a user. If you want to provide a file download, always use filesystem functions. <code>readfile()</code> is often the most appropriate choice.</li>\n</ul>\n\n<p>Unfortunately, in order to comply with all these requirements you are basically going to need to throw your code out and start again.</p>\n\n<p>If you want something for reference, <a href=\"https://gist.github.com/DaveRandom/4708126\" rel=\"nofollow noreferrer\">this Gist</a> contains something that's not a million miles away from the code I use in my real-life applications, and contains a basic usage example.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T13:39:12.133",
"Id": "38392",
"Score": "0",
"body": "i disagree that you need to resample the picture, if you always serve it with a safe content-type, the risk is minimal. even big sites like imgur do not resample your images."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T13:46:02.290",
"Id": "38394",
"Score": "1",
"body": "@Ysangkok It's not about how you serve it, it's about what's theoretically possible. If you can trick another script on the server into `include`ing the file, and you can manage to hide (the classic example) `<?php exec('rm -rf /'); ?>` in the pixel data, you're screwed. Never trust anyone, not even yourself ;-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T21:08:07.727",
"Id": "38427",
"Score": "0",
"body": "if they can execute arbitrary stuff from the filesystem, why wouldn't they be able to execute arbitrary stuff from the database? i'd rather just use a langauge without eval if you're this paranoid."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T21:13:28.367",
"Id": "38430",
"Score": "1",
"body": "@Ysangkok Big difference between `include` and `eval()` though. Probably 99.9% of PHP apps ever made use an `include` statement somewhere, but I know I'm not in the habit of `eval()`ing data from the database. It's quite feasible that somewhere on the server (may not even be my app) there is a script with an `include` hole in it. The most dangerous and harmful attacks often utilise more than one attack vector, via multiple routes into the server."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T21:22:19.493",
"Id": "38432",
"Score": "3",
"body": "The \"oh, it'll probably be fine\" approach to security has historically not worked out well for most people..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T22:00:23.263",
"Id": "38435",
"Score": "0",
"body": "Fantastic, thank you for the feedback. I will redo the script and try to implement the measures you suggested."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T23:29:42.610",
"Id": "38443",
"Score": "0",
"body": "@DaveRandom: Nobody said that. The \"let's avoid all useful but potentially dangerous features so we don't get anything done at all\" doesn't work either. I don't see much of a difference between eval and include, it's basically just reading+evalling. If you can't trust data in your file system, I don't see why you'd trust it in database. More exploits have been based on SQL injection than include-holes. Especially since SQL is something you usually write yourself, while application structure and module loading is hopefully something your framework/language does for you."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T23:47:42.070",
"Id": "38444",
"Score": "0",
"body": "@Ysangkok Functionally there's almost no difference between `eval()` and `include`, the point is that people use `include` all the time, they very rarely use `eval()`. I don't trust data in a database, but I do trust that in order to execute malicious code stored in a database you'd need to know some way of getting that data passed through the PHP (or whatever) interpreter. One badly sanitised `include` statement can be a free gift to hackers in this respect, but how often do you ever see `eval()` in the real world, let alone user-supplied and/or database data being passed to it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T23:50:58.350",
"Id": "38445",
"Score": "1",
"body": "The argument here seems to be against taking an inexpensive one-shot security measure simply because the exploit it avoids is complex and difficult to achieve. That argument just doesn't hold water for me - it costs me maybe 1/10 of a second of CPU cycles to resample the image, to make it impossible for a known attack vector to be exploited. I cannot see the sense in *not* doing it."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T12:38:38.220",
"Id": "24857",
"ParentId": "24824",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "24857",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-07T16:39:48.357",
"Id": "24824",
"Score": "4",
"Tags": [
"php",
"security"
],
"Title": "Check the security of my image upload script"
}
|
24824
|
<p>I have a collection of <code>PlaylistItem</code> objects. They are linked together such that each item knows the ID of its next/previous item. I am iterating over this collection of objects, starting at a known position and working with each object once. I'm not a big fan of how I do this, but I am not seeing an obvious way of rewriting it.</p>
<pre><code>var firstItemId = activePlaylist.get('firstItemId');
var currentItem = activePlaylist.get('items').get(firstItemId);
// Build up the ul of li's representing each playlistItem.
do {
var listItem = $('<li/>', {
'data-itemid': currentItem.get('id'),
contextmenu: function (e) {
var clickedItemId = $(this).data('itemid');
var clickedItem = activePlaylist.get('items').get(clickedItemId);
contextMenu.initialize(clickedItem);
// +1 offset because if contextmenu appears directly under mouse, hover css will be removed from element.
contextMenu.show(e.pageY, e.pageX + 1);
// Prevent default context menu display.
return false;
}
}).appendTo(playlistItemList);
$('<img>', {
'class': 'playlistItemVideoImage',
src: 'http://img.youtube.com/vi/' + currentItem.get('video').get('id') + '/default.jpg',
}).appendTo(listItem);
$('<a/>', {
text: currentItem.get('title')
}).appendTo(listItem);
currentItem = activePlaylist.get('items').get(currentItem.get('nextItemId'));
} while (currentItem && currentItem.get('id') !== firstItemId)
</code></pre>
<p>How would you write this?</p>
<p>Note that it is a <code>do-while</code> because I want to ensure I always render that <code>firstItem</code>. If there's only one item in the list, the loop will immediately terminate. Thus the need for the <code>do-while</code>.</p>
|
[] |
[
{
"body": "<p>Here's a bit of \"light\" refactoring. I've basically moved the element constructing into its own function to keep the while-block less crowded.</p>\n\n<p>I'm also using some closure magic for the contextmenu, so it doesn't have to re-get the clicked item.</p>\n\n<p>Lastly, I'm going more by the current <em>ID</em> rather than the current <em>object</em> when looping. This was to avoid the \"get the id to get the object to get its id again\" code that I see a few places in your version.</p>\n\n<pre><code>function buildListItem(item) {\n var listItem = $('<li/>', {\n contextmenu: function (event) {\n contextMenu.initialize(item); // available via closure\n contextMenu.show(e.pageY, e.pageX + 1);\n return false;\n }\n });\n\n listItem.append($('<img>', {\n 'class': 'playlistItemVideoImage',\n 'src': 'http://img.youtube.com/vi/' + item.get('video').get('id') + '/default.jpg'\n }));\n\n listItem.append($('<a/>', {\n text: item.get('title')\n }));\n\n return listItem;\n}\n\nvar firstItemId = activePlaylist.get('firstItemId'),\n allItems = activePlaylist.get('items'),\n currentItemId = firstItemId,\n currentItem;\n\ndo {\n currentItem = allItems.get(currentItemId); // get the obj\n if(!currentItem) {\n break; // stop if it ain't there\n }\n playlistItemList.append(buildListItem(currentItem)); // build the list item element\n currentItemId = currentItem.get('nextItemId'); // get the next ID\n} while(currentItemId && currentItemId !== firstItemId); // I'm assuming that valid IDs are thruth'y\n</code></pre>\n\n<p>Another thing to consider would be to use rawer HTML <a href=\"http://www.learningjquery.com/2009/03/43439-reasons-to-use-append-correctly\" rel=\"nofollow\">because it can be faster</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-07T23:55:07.457",
"Id": "24832",
"ParentId": "24829",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "24832",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-07T18:41:41.253",
"Id": "24829",
"Score": "4",
"Tags": [
"javascript",
"linked-list"
],
"Title": "Iterating through a linked-list in a cleaner manner"
}
|
24829
|
<p>For my display functions in my Blackjack game, I want to control each player's stats output based on whether a turn is in progress or has ended. Normally, you could only see one card that your opponent(s) hold, while the rest are only revealed at the end of each turn. My code does that well, but I'm having trouble making it more concise.</p>
<p>The display function in <code>Game</code> is called to display each player's stats (name, chips, and hand). It takes a Boolean argument to determine if it should display each CPU's partial stats (during each turn) or full stats (after each turn). At the function call in <code>Game</code>, the <code>bool</code> argument is passed to the respective display function in Player, where the human player and CPU player have individual display procedures. The display functions in <code>Player</code> primarily display the chip amounts and card rank totals. They also call respective <code>Hand</code> display functions which, again, solely depend on the Boolean argument for displaying the CPUs' stats.</p>
<p>How could I simplify this code to achieve the same output (shown below the code)?</p>
<p><strong>Game.cpp</strong></p>
<pre><code>displayStats(false); // function call elsewhere in Game
void Game::displayStats(bool showCPUResults) const
{
players[0].displayPlayerStats(); // displays player stats
for (int i = 1; i < numPlrs; i++)
players[i].displayCPUStats(showCPUResults); // displays CPU stats
}
</code></pre>
<p><strong>Player.cpp</strong></p>
<pre><code>void Player::displayPlayerStats() const
{
// always shown
std::stringstream ss;
std::cout << "\n* " << name << ": ";
std::cout << "($" << chips << ") ";
// displays two-digit card rank total (always shown)
if (totalCardsValue <= 9)
ss << "(0" << totalCardsValue << ") ";
else
ss << "(" << totalCardsValue << ") ";
std::cout << ss.str();
// displays human player's hand
playerHand[0].displayPlayerHand();
}
void Player::displayCPUStats(bool showResults) const
{
// always shown
std::stringstream ss;
std::cout << "\n* " << name << ": ";
std::cout << "($" << chips << ") ";
if (!showResults)
{
std::cout << " ";
playerHand[0].displayCPUHand(showResults);
}
else
{
// only shown after each turn
if (totalCardsValue <= 9)
ss << "(0" << totalCardsValue << ") ";
else
ss << "(" << totalCardsValue << ") ";
std::cout << ss.str();
// displays CPU's hand
playerHand[0].displayCPUHand(showResults);
}
}
</code></pre>
<p><strong>Hand.cpp</strong></p>
<pre><code>void Hand::displayPlayerHand() const
{
// displays player's full hand (always)
for (unsigned i = 0; i < cards.size(); i++)
std::cout << cards[i] << " ";
}
void Hand::displayCPUHand(bool showCPUHand) const
{
// displays CPU's first card (always)
std::cout << cards[0] << " ";
// displays the rest of the CPU's cards (only after each turn)
if (showCPUHand)
{
for (unsigned i = 1; i < cards.size(); i++)
std::cout << cards[i] << " ";
}
}
</code></pre>
<p><strong>Output <em>during</em> a turn...</strong></p>
<blockquote>
<p>Jamal: ($1000) (23) [8C] [6H] [9C]</p>
<p>CPU1: ($1000) [AD]</p>
</blockquote>
<p><strong>...and <em>after</em> a turn...</strong></p>
<blockquote>
<p>Jamal: ($1000) (23) [8C] [6H] [9C]</p>
<p>CPU1: ($1000) (21) [AD] [KH]</p>
</blockquote>
|
[] |
[
{
"body": "<p>If you want to make things more consice, you could change a few things:</p>\n\n<ul>\n<li><p>Number of card printed on 2 digits:</p>\n\n<pre><code>if (totalCardsValue <= 9)\n ss << \"(0\" << totalCardsValue << \") \";\nelse\n ss << \"(\" << totalCardsValue << \") \";\n</code></pre>\n\n<p>could be written</p>\n\n<pre><code>ss << ((totalCardsValue <= 9) ? \"(0\" : \"(\") << totalCardsValue << \") \";\n</code></pre>\n\n<p>or </p>\n\n<pre><code>ss << \"(\" << std::setw(2) << std::setfill('0') << totalCardsValue << \") \";\n</code></pre></li>\n<li><p>No need for temporary <code>std::stringstream</code>.\nI think you could just <code>std::cout</code> directly without using <code>std::stringstream ss</code>.</p></li>\n<li><p>Removing duplicated code: <code>void Hand::displayPlayerHand()</code> does the same as <code>void Hand::displayCPUHand(true)</code>. This would probably better if you were naming this method <code>display</code> and calling the parameter <code>displayAllCards</code> or <code>displayOnlyFirst</code>. Also, you might want to give it a default value. </p>\n\n<p>Corresponding code for Hand.cpp is:</p>\n\n<pre><code>void Hand::display(bool displayAllCards) const \n{\n // displays the first card\n std::cout << cards[0] << \" \";\n\n // displays the rest of the cards if required\n if (displayAllCards)\n {\n for (unsigned i = 1; i < cards.size(); i++)\n std::cout << cards[i] << \" \";\n }\n}\n</code></pre></li>\n<li><p>Removing duplicated code: things can be changed in Player.cpp too as <code>Player::displayCPUStats</code> and <code>Player::displayPlayerStats</code> really look alike.</p>\n\n<p><strong>Edited to finish my answer:</strong> Indeed, <code>displayPlayerStats()</code> is nothing but <code>displayCPUStats(true)</code>. Here again, it might be worth changing the names of methods and variables.</p>\n\n<p>Corresponding code for Player.cpp is:</p>\n\n<pre><code>void Player::displayStats(bool displayAllCards) const\n{\n std::cout << \"\\n* \" << name << \": \";\n std::cout << \"($\" << chips << \") \";\n\n if (displayAllCards)\n {\n std::cout << ((totalCardsValue <= 9) ? \"(0\" : \"(\") << totalCardsValue << \") \";\n }\n playerHand[0].displayHand(displayAllCards);\n}\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T21:22:14.993",
"Id": "38431",
"Score": "0",
"body": "Yes, I too am looking at `Player::displayPlayerStats` and `Player::displayCPUStats` and trying to \"merge\" them. As for `Hand::displayCompHand`, it's actually `Hand::displayCPUHand`. I changed that part of the name but must've missed that instance. Sorry about that! Knowing that, you may continue what you were about to do (and I'll change that bit in the code now)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T22:32:17.767",
"Id": "38438",
"Score": "0",
"body": "I've just finished."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T22:34:57.100",
"Id": "38439",
"Score": "0",
"body": "And I was just about to answer my question (alongside yours) since I've already found an answer. :-) Who should post it, then?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T22:46:52.830",
"Id": "38441",
"Score": "0",
"body": "Okay, I take back my answer; yours is more concise than mine. I really need to start practicing this. Thanks again!"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T20:12:44.513",
"Id": "24872",
"ParentId": "24831",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "24872",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-07T22:02:24.853",
"Id": "24831",
"Score": "5",
"Tags": [
"c++",
"game",
"classes",
"playing-cards"
],
"Title": "Simplifying member functions in Blackjack game"
}
|
24831
|
<p>My program has to decrypt ciphertext. It has to try all possible 26 shifts and store each in an array so that I calculate the frequencies of each array and find the highest frequency, in which that would result in the plain text.</p>
<pre><code>#include <stdio.h>
#define CIPHERSIZE 42
char decryptCiphertext(char data[], double data2[]);
char likelyPlaintext (char decrypt[], double data2[]);
int main (void)
{
char cipher[43];
printf("\t===========================\n");
printf(" \t DECRYPTING CIPHERTEXT\n");
printf("\t===========================\n");
FILE *ciphertext;
ciphertext = fopen("ciphertext.txt", "r");
if (ciphertext != NULL)
{
while (!feof(ciphertext))
fscanf(ciphertext, "%s", cipher);
fclose(ciphertext);
}
else
printf("Error opening file\n");
printf("Ciphertext : %s\n", cipher);
FILE *frequency;
double freq[26];
double num;
int i;
frequency = fopen("frequencies.dat", "r");
if (frequency == NULL)
printf("Error opening file\n");
for (i=0; i < 26; i++)
{
fscanf(frequency, "%lf", &freq[i]);
//printf("%lf\n", freq[i]);
}
fclose(frequency);
decryptCiphertext(cipher, freq);
}
char decryptCiphertext(char data[], double data2[])
{
int i, convert, shiftingLetter;
char decrypted26[42], decrypted1[42], decrypted2[42], decrypted3[42], decrypted4[42],
decrypted5[42], decrypted6[42], decrypted7[42], decrypted8[42], decrypted9[42], decrypted10[42],
decrypted11[42], decrypted12[42], decrypted13[42], decrypted14[42], decrypted15[42], decrypted16[42],
decrypted17[42], decrypted18[42], decrypted19[42], decrypted20[42], decrypted21[42], decrypted22[42],
decrypted23[42], decrypted24[42], decrypted25[42];
//Try all possible shifts from 1-25 and store each in an array
for (i = 0; data[i] != '\0'; i++)
{
convert = data[i] - 'A'; //convert letters to equal 0-26 ex:A=0,B=1,C=2,etc
convert = (convert + 1); //add shift
shiftingLetter = convert % 26; //cycle around
decrypted1[i] = 'A' + shiftingLetter; //store new letter in array
}
decrypted1[i] = '\0';
likelyPlaintext(decrypted1, data2);
//printf(" 1. %s\n", decrypted1);
for (i = 0; data[i] != '\0'; i++)
{
convert = data[i] - 'A';
convert = (convert + 2);
shiftingLetter = convert % 26;
decrypted2[i] = 'A' + shiftingLetter;
}
decrypted2[i] = '\0';
//printf(" 2. %s\n", decrypted2);
for (i = 0; data[i] != '\0'; i++)
{
convert = data[i] - 'A';
convert = (convert + 3);
shiftingLetter = convert % 26;
decrypted3[i] = 'A' + shiftingLetter;
}
decrypted3[i] = '\0';
//printf(" 3. %s\n", decrypted3);
for (i = 0; data[i] != '\0'; i++)
{
convert = data[i] - 'A';
convert = (convert + 4);
shiftingLetter = convert % 26;
decrypted4[i] = 'A' + shiftingLetter;
}
decrypted4[i] = '\0';
//printf(" 4. %s\n", decrypted4);
for (i = 0; data[i] != '\0'; i++)
{
convert = data[i] - 'A';
convert = (convert + 5);
shiftingLetter = convert % 26;
decrypted5[i] = 'A' + shiftingLetter;
}
decrypted5[i] = '\0';
//printf(" 5. %s\n", decrypted5);
for (i = 0; data[i] != '\0'; i++)
{
convert = data[i] - 'A';
convert = (convert + 6);
shiftingLetter = convert % 26;
decrypted6[i] = 'A' + shiftingLetter;
}
decrypted6[i] = '\0';
//printf(" 6. %s\n", decrypted6);
for (i = 0; data[i] != '\0'; i++)
{
convert = data[i] - 'A';
convert = (convert + 7);
shiftingLetter = convert % 26;
decrypted7[i] = 'A' + shiftingLetter;
}
decrypted7[i] = '\0';
//printf(" 7. %s\n", decrypted7);
for (i = 0; data[i] != '\0'; i++)
{
convert = data[i] - 'A';
convert = (convert + 8);
shiftingLetter = convert % 26;
decrypted8[i] = 'A' + shiftingLetter;
}
decrypted8[i] = '\0';
//printf(" 8. %s\n", decrypted8);
for (i = 0; data[i] != '\0'; i++)
{
convert = data[i] - 'A';
convert = (convert + 9);
shiftingLetter = convert % 26;
decrypted9[i] = 'A' + shiftingLetter;
}
decrypted9[i] = '\0';
//printf(" 9. %s\n", decrypted9);
for (i = 0; data[i] != '\0'; i++)
{
convert = data[i] - 'A';
convert = (convert + 10);
shiftingLetter = convert % 26;
decrypted10[i] = 'A' + shiftingLetter;
}
decrypted10[i] = '\0';
//printf(" 10. %s\n", decrypted10);
for (i = 0; data[i] != '\0'; i++)
{
convert = data[i] - 'A';
convert = (convert + 11);
shiftingLetter = convert % 26;
decrypted11[i] = 'A' + shiftingLetter;
}
decrypted11[i] = '\0';
//printf(" 11. %s\n", decrypted11);
for (i = 0; data[i] != '\0'; i++)
{
convert = data[i] - 'A';
convert = (convert + 12);
shiftingLetter = convert % 26;
decrypted12[i] = 'A' + shiftingLetter;
}
decrypted12[i] = '\0';
//printf(" 12. %s\n", decrypted12);
for (i = 0; data[i] != '\0'; i++)
{
convert = data[i] - 'A';
convert = (convert + 13);
shiftingLetter = convert % 26;
decrypted13[i] = 'A' + shiftingLetter;
}
decrypted13[i] = '\0';
//printf(" 13. %s\n", decrypted13);
for (i = 0; data[i] != '\0'; i++)
{
convert = data[i] - 'A';
convert = (convert + 14);
shiftingLetter = convert % 26;
decrypted14[i] = 'A' + shiftingLetter;
}
decrypted14[i] = '\0';
//printf(" 14. %s\n", decrypted14);
for (i = 0; data[i] != '\0'; i++)
{
convert = data[i] - 'A';
convert = (convert + 15);
shiftingLetter = convert % 26;
decrypted15[i] = 'A' + shiftingLetter;
}
decrypted15[i] = '\0';
//printf(" 15. %s\n", decrypted15);
for (i = 0; data[i] != '\0'; i++)
{
convert = data[i] - 'A';
convert = (convert + 16);
shiftingLetter = convert % 26;
decrypted16[i] = 'A' + shiftingLetter;
}
decrypted16[i] = '\0';
//printf(" 16. %s\n", decrypted16);
for (i = 0; data[i] != '\0'; i++)
{
convert = data[i] - 'A';
convert = (convert + 17);
shiftingLetter = convert % 26;
decrypted17[i] = 'A' + shiftingLetter;
}
decrypted17[i] = '\0';
//printf(" 17. %s\n", decrypted17);
for (i = 0; data[i] != '\0'; i++)
{
convert = data[i] - 'A';
convert = (convert + 18);
shiftingLetter = convert % 26;
decrypted18[i] = 'A' + shiftingLetter;
}
decrypted18[i] = '\0';
//printf(" 18. %s\n", decrypted18);
for (i = 0; data[i] != '\0'; i++)
{
convert = data[i] - 'A';
convert = (convert + 19);
shiftingLetter = convert % 26;
decrypted19[i] = 'A' + shiftingLetter;
}
decrypted19[i] = '\0';
//printf(" 19. %s\n", decrypted19);
for (i = 0; data[i] != '\0'; i++)
{
convert = data[i] - 'A';
convert = (convert + 20);
shiftingLetter = convert % 26;
decrypted20[i] = 'A' + shiftingLetter;
}
decrypted20[i] = '\0';
//printf(" 20. %s\n", decrypted20);
for (i = 0; data[i] != '\0'; i++)
{
convert = data[i] - 'A';
convert = (convert + 21);
shiftingLetter = convert % 26;
decrypted21[i] = 'A' + shiftingLetter;
}
decrypted21[i] = '\0';
//printf(" 21. %s\n", decrypted21);
for (i = 0; data[i] != '\0'; i++)
{
convert = data[i] - 'A';
convert = (convert + 22);
shiftingLetter = convert % 26;
decrypted22[i] = 'A' + shiftingLetter;
}
decrypted22[i] = '\0';
//printf(" 22. %s\n", decrypted22);
for (i = 0; data[i] != '\0'; i++)
{
convert = data[i] - 'A';
convert = (convert + 23);
shiftingLetter = convert % 26;
decrypted23[i] = 'A' + shiftingLetter;
}
decrypted23[i] = '\0';
//printf(" 23. %s\n", decrypted23);
for (i = 0; data[i] != '\0'; i++)
{
convert = data[i] - 'A';
convert = (convert + 24);
shiftingLetter = convert % 26;
decrypted24[i] = 'A' + shiftingLetter;
}
decrypted24[i] = '\0';
//printf(" 24. %s\n", decrypted24);
for (i = 0; data[i] != '\0'; i++)
{
convert = data[i] - 'A';
convert = (convert + 25);
shiftingLetter = convert % 26;
decrypted25[i] = 'A' + shiftingLetter;
}
decrypted25[i] = '\0';
//printf(" 25. %s\n", decrypted25);
}
char likelyPlaintext (char decrypt[], double frequencies[])
{
int i;
for (i = 0; i < 26; i++)
printf("%lf\n", frequencies[i]);
printf("First shift : %s\n", decrypt);
for (i = 0; i <
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T00:29:53.410",
"Id": "38353",
"Score": "0",
"body": "Create a structure for `decrypted<i>[]`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T00:44:35.210",
"Id": "38354",
"Score": "0",
"body": "I don't understand how to finish the last function likelyPlaintext it has to take all the arrays in the decryptCiphertext function and find the frequency for each after that it has to see the greatest frequency and that results in being the plaintext."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T02:26:49.403",
"Id": "38358",
"Score": "2",
"body": "Write a function containing the for-loop and call it 26 times instead of repeating the for loop."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-05T21:12:48.153",
"Id": "54355",
"Score": "1",
"body": "You don't have to create all 26 \"decryptions\" of the string! Only create ONE (or use the ciphertext itself)! Then do the distribution of letters array - then shift THAT array to find your \"target\" distribution..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-05T21:21:31.980",
"Id": "54359",
"Score": "1",
"body": "You have figured out loops. Why can't you put a loop inside a loop."
}
] |
[
{
"body": "<p>decryptCiphertext can be reduced to</p>\n\n<pre><code>char decryptCiphertext(char data[], double data2[])\n{\n int i, shift, convert, shiftingLetter;\n char decrypted[26][CIPHERSIZE];\n\n for (shift = 1; shift < 26; shift++)\n {\n //Try all possible shifts from 1-25 and store each in an array\n for (i = 0; data[i] != '\\0'; i++) \n {\n convert = data[i] - 'A'; //convert letters to equal 0-26 ex:A=0,B=1,C=2,etc\n convert = (convert + shift); //add shift\n shiftingLetter = convert % 26; //cycle around\n decrypted[shift][i] = 'A' + shiftingLetter; //store new letter in array\n }\n decrypted[shift][i] = '\\0';\n likelyPlaintext(decrypted[shift], data2);\n }\n} \n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T17:24:22.760",
"Id": "38407",
"Score": "2",
"body": "Note that you could just `decrypted[shift][i] = 'A' + (data[i] - 'A' + shift) % 26;`"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T16:33:47.473",
"Id": "24865",
"ParentId": "24833",
"Score": "5"
}
},
{
"body": "<p>In fact, my comment up there is basically saying don't use the algorithm you're using now, instead use the normal \"CryptoQuiz\" algorithm your grandma has been using for 100 years to solve crypto-quiz puzzles in the newspaper (those were a printed version of the news, typically delivered to your door).</p>\n\n<p>So, I'm saying, implement #2 in this tutorial on crypto-grams: <a href=\"http://www.cryptograms.org/tutorial.php\" rel=\"nofollow\">http://www.cryptograms.org/tutorial.php</a></p>\n\n<p>This method works on ANY substitution ciphers, not just the \"simple\" type you are dealing with.</p>\n\n<p>IF your assignment requires you to use the algorithm given, just let me know and I'll change this answer.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-05T21:20:31.533",
"Id": "33887",
"ParentId": "24833",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T00:08:24.600",
"Id": "24833",
"Score": "3",
"Tags": [
"c",
"caesar-cipher"
],
"Title": "Shorten this Caesar Cipher cracker"
}
|
24833
|
<p>A socket; in network computing; is an endpoint of a bidirectional inter-process communication flow across an Internet Protocol-based computer network, such as the Internet.</p>
<p>An internet socket address is the combination of an IP address (the location of the computer) and a port (which is mapped to the application program process) into a single identity, much like one end of a telephone connection is the combination of a phone number and a particular extension.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T01:31:08.897",
"Id": "24834",
"Score": "0",
"Tags": null,
"Title": null
}
|
24834
|
An endpoint of a bidirectional inter-process communication flow. This often refers to a process flow over a network connection, but by no means is limited to such.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T01:31:08.897",
"Id": "24835",
"Score": "0",
"Tags": null,
"Title": null
}
|
24835
|
<p>I have been working on a project where I needed to analyze multiple, large datasets contained inside many CSV files at the same time. I am not a programmer but an engineer, so I did a lot of searching and reading. Python's stock CSV module provides the basic functionality, but I had a lot of trouble getting the methods to run quickly on 50k-500k rows since many strategies were simply appending. I had lots of problems getting what I wanted and I saw the same questions asked over and over again. I decided to spend some time and write a class that performed these functions and would be portable. If nothing else, myself and other people I work with could use it.</p>
<p>I would like some input on the class and any suggestions you may have. I am not a programmer and don't have any formal background so this has been a good OOP intro for me. The end result is in two lines you can read all CSV files in a folder into memory as either pure Python lists or, as lists of NumPy arrays. I have tested it in many scenarios and hopefully found most of the bugs. I'd like to think this is good enough that other people can just copy and paste into their code and move on to the more important stuff. I am open to all critiques and suggestions. Is this something you could use? If not, why?</p>
<p>You can try it with generic CSV data. The standard Python lists are flexible in size and data type. NumPy will only work with numeric (float specifically) data that is rectangular in format:</p>
<pre><code>x, y, z,
1, 2, 3,
4, 5, 6,
...
import numpy as np
import csv
import os
import sys
class EasyCSV(object):
"""Easily open from and save CSV files using lists or numpy arrays.
Initiating and using the class is as easy as CSV = EasyCSV('location').
The class takes the following arguements:
EasyCSV(location, width=None, np_array='false', skip_rows=0)
location is the only mandatory field and is string of the folder location
containing .CSV file(s).
width is optional and specifies a constant width. The default value None
will return a list of lists with variable width. When used with numpy the
array will have the dimensions of the first valid numeric row of data.
np_array will create a fixed-width numpy array of only float values.
skip_rows will skip the specified rows at the top of the file.
"""
def __init__(self, location, width=None, np_array='false', skip_rows=0):
# Initialize default vairables
self.np_array = np_array
self.skip_rows = skip_rows
self.loc = str(location)
os.chdir(self.loc)
self.dataFiles = []
self.width = width
self.i = 0
#Find all CSV files in chosen directory.
for files in os.listdir(loc):
if files.endswith('CSV') or files.endswith('csv'):
self.dataFiles.append(files)
#Preallocate array to hold csv data later
self.allData = [0] * len(self.dataFiles)
def read(self,):
'''Reads all files contained in the folder into memory.
'''
self.Dict = {} #Stores names of files for later lookup
#Main processig loop
for files in self.dataFiles:
self.trim = 0
self.j = 0
with open(files,'rb') as self.rawFile:
print files
#Read in CSV object
self.newData = csv.reader(self.rawFile)
self.dataList = []
#Extend iterates through CSV object and passes to datalist
self.dataList.extend(self.newData)
#Trims off pre specified lines at the top
if self.skip_rows != 0:
self.dataList = self.dataList[self.skip_rows:]
#Numpy route, requires all numeric input
if self.np_array == 'true':
#Finds width if not specified
if self.width is None:
self.width = len(self.dataList[self.skip_rows])
self.CSVdata = np.zeros((len(self.dataList),self.width))
#Iterate through data and adds it to numpy array
self.k = 0
for data in self.dataList:
try:
self.CSVdata[self.j,:] = data
self.j+=1
except ValueError: #non numeric data
if self.width < len(data):
sys.exit('Numpy array too narrow. Choose another width')
self.trim+=1
pass
self.k+=1
#trims off excess
if not self.trim == 0:
self.CSVdata = self.CSVdata[:-self.trim]
#Python nested lists route; tolerates multiple data types
else:
#Declare required empty str arrays
self.CSVdata = [0]*len(self.dataList)
for rows in self.dataList:
self.k = 0
self.rows = rows
#Handle no width imput, flexible width
if self.width is None:
self.numrow = [0]*len(self.rows)
else:
self.numrow = [0]*self.width
#Try to convert to float, fall back on string.
for data in self.rows:
try:
self.numrow[self.k] = float(data)
except ValueError:
try:
self.numrow[self.k] = data
except IndexError:
pass
except IndexError:
pass
self.k+=1
self.CSVdata[self.j] = self.numrow
self.j+=1
#append file to allData which contains all files
self.allData[self.i] = self.CSVdata
#trim CSV off filename and store in Dict for indexing of allData
self.dataFiles[self.i] = self.dataFiles[self.i][:-4]
self.Dict[self.dataFiles[self.i]] = self.i
self.i+=1
def write(self, array, name, destination=None):
'''Writes array in memory to file.
EasyCSV.write(array, name, destination=None)
array is a pointer to the array you want written to CSV
name will be the name of said file
destination is optional and will change the directory to the location
specified. Leaving it at the default value None will overwrite any CSVs
that may have been read in by the class earlier.
'''
self.array = array
self.name = name
self.dest = destination
#Optional change directory
if self.dest is not None:
os.chdir(self.dest)
#Dict does not hold CSV, check to see if present and trim
if not self.name[-4:] == '.CSV' or self.name[-4:] == '.csv':
self.name = name + '.CSV'
#Create files and write data, 'wb' binary req'd for Win compatibility
with open(self.name,'wb') as self.newCSV:
self.CSVwrite = csv.writer(self.newCSV,dialect='excel')
for data in self.array:
self.CSVwrite.writerow(data)
os.chdir(self.loc) #Change back to original __init__.loc
def lookup(self, key=None):
'''Prints a preview of data to the console window with just a key input
'''
self.key = key
#Dict does not hold CSV, check to see if present and trim
if self.key[-4:] == '.CSV' or self.key[-4:] == '.csv':
self.key = key[:-4]
#Print None case
elif self.key is None:
print self.allData[0]
print self.allData[0]
print '... ' * len(self.allData[0][-2])
print self.allData[0][-2]
print self.allData[0]
#Print everything else
else:
self.index = self.Dict[self.key]
print self.allData[self.index][0]
print self.allData[self.index][1]
print '... ' * len(self.allData[self.index][-2])
print self.allData[self.index][-2]
print self.allData[self.index][-1]
def output(self, key=None):
'''Returns the array for assignment to a var with just a key input
'''
self.key = key
#Dict does not hold CSV, check to see if present and trim
if self.key is None:
return self.allData[0]
elif self.key[-4:] == '.CSV' or self.key[-4:] == '.csv':
self.key = key[:-4]
#Return file requested
self.index = self.Dict[self.key]
return self.allData[self.Dict[self.key]]
################################################
loc = 'C:\Users\Me\Desktop'
CSV = EasyCSV(loc, np_array='false', width=None, skip_rows=0)
CSV.read()
target = 'somecsv' #with or without .csv/.CSV
CSV.lookup(target)
A = CSV.output(target)
loc2 = 'C:\Users\Me\Desktop\New folder'
for keys in CSV.Dict:
print keys
CSV.write(CSV.output(keys),keys,destination=loc2)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-07T20:28:50.570",
"Id": "38355",
"Score": "1",
"body": "Also you should investigate [`csvkit`](http://csvkit.readthedocs.org/en/latest/) and [`pandas`](http://pandas.pydata.org), or maybe import CSVs into a relational or key-value database instead of using them directly."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-07T21:26:51.837",
"Id": "38356",
"Score": "0",
"body": "Pandas is interesting but not very light weight. I wish I saw a suggestion for it before. Can't use CSV kit because I'm primarily on Win. Thanks for the useful info."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T14:55:04.897",
"Id": "38397",
"Score": "0",
"body": "csvkit is supported on all platforms."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T19:11:41.003",
"Id": "38416",
"Score": "0",
"body": "Please use comments to respond to people rather than editing your question."
}
] |
[
{
"body": "<p>Some observations:</p>\n\n<ul>\n<li>You expect <code>read</code> to be called exactly once (otherwise it reads the same files again, right?). You might as well call it from <code>__init__</code> directly. Alternatively, <code>read</code> could take <code>location</code> as parameter, so one could read multiple directories into the object.</li>\n<li>You use strings <code>'true', 'false'</code> where you should use actual <code>bool</code> values <code>True, False</code></li>\n<li>You set instance variables such as <code>self.key = key</code> that you use only locally inside the function, where you could simply use the local variable <code>key</code>.</li>\n<li>The <code>read</code> method is very long. Divide the work into smaller functions and call them from <code>read</code>.</li>\n<li>You have docstrings and a fair amount of comments, good. But then you have really cryptic statements such as <code>self.i = 0</code>.</li>\n<li>Some variable names are misleading, such as <code>files</code> which is actually a single filename.</li>\n<li>Don't change the working directory (<code>os.chdir</code>). Use <code>os.path.join(loc, filename)</code> to construct paths. (If you think it's OK to change it, think what happens if you combine this module with some other module that <em>also</em> thinks it's OK)</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T15:05:13.380",
"Id": "38399",
"Score": "0",
"body": "This was exactly the sort of stuff I was looking for. Thanks for taking the time to look through it. You hit on a lot of the issues that came up during. Allowing for separate read paths would be really helpful. Also I need to research more on the local vars for a function. I was having problems getting them to work and found it easier to declare a self.xyz. Tan"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T11:31:51.730",
"Id": "24852",
"ParentId": "24836",
"Score": "6"
}
},
{
"body": "<p><a href=\"https://codereview.stackexchange.com/a/24852/11728\">Janne's points</a> are good. In addition:</p>\n\n<ol>\n<li><p>When I try running this code, it fails:</p>\n\n<pre><code>>>> e = EasyCSV('.')\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\n File \"cr24836.py\", line 37, in __init__\n for files in os.listdir(loc):\nNameError: global name 'loc' is not defined\n</code></pre>\n\n<p>I presume that <code>loc</code> is a typo for <code>self.loc</code>. This makes me suspicious. Have you actually used or tested this code?</p></li>\n<li><p>The <code>width</code> and <code>skip_rows</code> arguments to the constructor apply to <em>all</em> CSV files in the directory. But isn't it likely that different CSV files will have different widths and need different numbers of rows to be skipped?</p></li>\n<li><p>Your class requires NumPy to be installed (otherwise the line <code>import numpy as np</code> will fail). But since it has a mode of operation that doesn't require NumPy (return lists instead), it would be nice if it worked even if NumPy is not installed. Wait until you're just about to call <code>np.zeros</code> before importing NumPy.</p></li>\n<li><p><code>location</code> is supposed to be the name of a directory, so name it <code>directory</code>.</p></li>\n<li><p>You write <code>self.key[-4:] == '.CSV'</code> but why not use <code>.endswith</code> like you did earlier in the program? Or better still, since you are testing this twice, write a function:</p>\n\n<pre><code>def filename_is_csv(filename):\n \"\"\"Return True if filename has the .csv extension.\"\"\"\n _, ext = os.path.splitext(filename)\n return ext.lower() == '.csv'\n</code></pre>\n\n<p>But having said that, do you really want to insist that this can only read CSV files whose names end with <code>.csv</code>? What if someone has CSV stored in a file named <code>foo.data</code>? They'd never be able to read it with your class.</p></li>\n<li><p>There's nothing in the documentation for the class that explains that I am supposed to call the <code>read()</code> method. (If I don't, nothing happens.)</p></li>\n<li><p>There's nothing in the documentation for the class that explains how I am supposed to access the data that has been loaded into memory.</p></li>\n<li><p>If I want to access the data for a filename, I have look up the filename in the <code>Dict</code> attribute to get the index, and then I could look up the index in the <code>allData</code> attribute to get the data. Why this double lookup? Why not have a dictionary that maps filename to data instead of going via an index?</p></li>\n<li><p>There is no need to preallocate arrays in Python. Wait to create the array until you have some data to put in it, and then <code>append</code> each entry to it. Python is not Fortran!</p></li>\n<li><p>In your <code>read()</code> method, you read all the CSV files into memory. This seems wasteful. What if I had hundreds of files but only wanted to read one of them? Why not wait to read a file until the caller needs it?</p></li>\n<li><p>You convert numeric elements to floating-point numbers. This might not be what I want. For example, if I have a file containing:</p>\n\n<pre><code>Apollo,Launch\n7,19681011\n8,19681221\n9,19690303\n10,19690518\n11,19690716\n12,19691114\n13,19700411\n14,19710131\n15,19710726\n16,19720416\n17,19721207\n</code></pre>\n\n<p>and then I try to read it, all the data has been wrongly converted to floating-point:</p>\n\n<pre><code>>>> e = EasyCSV('.')\n>>> e.read()\napollo.csv\n>>> from pprint import pprint\n>>> pprint(e.allData[e.Dict['apollo']])\n[['Apollo', 'Launch'],\n [7.0, 19681011.0],\n [8.0, 19681221.0],\n [9.0, 19690303.0],\n [10.0, 19690518.0],\n [11.0, 19690716.0],\n [12.0, 19691114.0],\n [13.0, 19700411.0],\n [14.0, 19710131.0],\n [15.0, 19710726.0],\n [16.0, 19720416.0],\n [17.0, 19721207.0]]\n</code></pre>\n\n<p>This can go wrong in other ways. For example, suppose I have a CSV file like this:</p>\n\n<pre><code>product code,inventory\n1a0,81\n7b4,61\n9c2,32\n8d3,90\n1e9,95\n2f4,71\n</code></pre>\n\n<p>When I read it with your class, look at what happens to the sixth row:</p>\n\n<pre><code>>>> e = EasyCSV('.')\n>>> e.read()\ninventory.csv\n>>> pprint(e.allData[e.Dict['inventory']])\n[['product code', 'inventory'],\n ['1a0', 81.0],\n ['7b4', 61.0],\n ['9c2', 32.0],\n ['8d3', 90.0],\n [1000000000.0, 95.0],\n ['2f4', 71.0]]\n</code></pre></li>\n<li><p>You suggest that \"other people can just copy and paste into their code\" but this is never a good idea. How would you distribute bug fixes and other improvements? If you plan for other people to use your code, you should aim to make a package that can be distributed through the <a href=\"https://pypi.python.org/pypi\" rel=\"nofollow noreferrer\">Python Package Index</a>.</p></li>\n</ol>\n\n<p>In summary, your class is misnamed: it does not seem to me as if it would be easy to use in practice.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T15:56:02.063",
"Id": "24860",
"ParentId": "24836",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-07T20:15:44.593",
"Id": "24836",
"Score": "5",
"Tags": [
"python",
"parsing",
"csv",
"numpy",
"portability"
],
"Title": "Portable Python CSV class"
}
|
24836
|
<p>I am hoping to streamline this bit of code better. This snippet does not cause my any slow downs <strong>in relation</strong> to other parts of the algorithm(?). I would just like guidance on making it better.</p>
<p>Some variables not given by code:</p>
<pre><code>regionDimensions = whatever you want. (256)
hexagonArray[,] = new Hexagon[regionDimensions, regionDimensions];
</code></pre>
<p><strong>The Struct:</strong></p>
<pre><code>public struct Hexagon
{
private float height;
private bool[] hasSides;
public Hexagon(float height)
{
this.height = height;
hasSides = new bool[] { true, true, true, true, true, true };
}
public float Height
{
get { return height; }
}
public bool[] HasSides
{
get { return hasSides; }
set { hasSides = value; }
}
public bool this[int i]
{
get { return hasSides[i]; }
set { hasSides[i] = value; }
}
}
</code></pre>
<p><strong>The Iterator:</strong></p>
<pre><code> // Evaluate heights of hexagons and cull sides
for (var x = 0; x < regionDimensions; x++)
for (var y = 0; y < regionDimensions; y++)
{
var neighborHexes = new Dictionary<Hexagon, int>();
// If it's not in bounds it doesn't need its side no matter what.
if (y % 2 == 0)
{
if (CheckBounds(x, y + 1)) // 0
neighborHexes.Add(hexagonArray[x, y + 1], 0);
else
hexagonArray[x, y].HasSides[0] = false;
if (CheckBounds(x + 1, y)) // 1
neighborHexes.Add(hexagonArray[x + 1, y], 1);
else
hexagonArray[x, y].HasSides[1] = false;
if (CheckBounds(x, y - 1)) // 2
neighborHexes.Add(hexagonArray[x, y - 1], 2);
else
hexagonArray[x, y].HasSides[2] = false;
if (CheckBounds(x - 1, y - 1)) // 3
neighborHexes.Add(hexagonArray[x - 1, y - 1], 3);
else
hexagonArray[x, y].HasSides[3] = false;
if (CheckBounds(x - 1, y)) // 4
neighborHexes.Add(hexagonArray[x - 1, y], 4);
else
hexagonArray[x, y].HasSides[4] = false;
if (CheckBounds(x - 1, y + 1)) // 5
neighborHexes.Add(hexagonArray[x - 1, y + 1], 5);
else
hexagonArray[x, y].HasSides[5] = false;
}
else
{
if (CheckBounds(x + 1, y + 1)) // 0
neighborHexes.Add(hexagonArray[x + 1, y + 1], 0);
else
hexagonArray[x, y].HasSides[0] = false;
if (CheckBounds(x + 1, y)) // 1
neighborHexes.Add(hexagonArray[x + 1, y], 1);
else
hexagonArray[x, y].HasSides[1] = false;
if (CheckBounds(x + 1, y - 1)) // 2
neighborHexes.Add(hexagonArray[x + 1, y - 1], 2);
else
hexagonArray[x, y].HasSides[2] = false;
if (CheckBounds(x, y - 1)) // 3
neighborHexes.Add(hexagonArray[x, y - 1], 3);
else
hexagonArray[x, y].HasSides[3] = false;
if (CheckBounds(x - 1, y)) // 4
neighborHexes.Add(hexagonArray[x - 1, y], 4);
else
hexagonArray[x, y].HasSides[4] = false;
if (CheckBounds(x, y + 1)) // 5
neighborHexes.Add(hexagonArray[x, y + 1], 5);
else
hexagonArray[x, y].HasSides[5] = false;
}
EvaluateNeighbors(neighborHexes, ref hexagonArray[x, y]);
}
</code></pre>
<p><strong>Check Bounds:</strong></p>
<pre><code> private bool CheckBounds(int x, int y)
{
if ((x >= 0) && (x < regionDimensions) &&
(y >= 0) && (y < regionDimensions))
return true;
else
return false;
}
</code></pre>
<p><strong>Evaluate Neighbors:</strong></p>
<pre><code> private void EvaluateNeighbors(Dictionary<Hexagon, int> neighbors, ref Hexagon currentHexagon)
{
foreach (var neighbor in neighbors)
{
if (currentHexagon.Height < neighbor.Key.Height)
currentHexagon.HasSides[neighbor.Value] = false;
else if (MathExtensions.NearlyEqual(currentHexagon.Height, neighbor.Key.Height))
currentHexagon.HasSides[neighbor.Value] = false;
}
}
</code></pre>
<p><strong>Fix To Struct:</strong>
Object is built once and is no longer mutable.</p>
<pre><code>[Serializable]
public struct Hexagon
{
private readonly float height;
private readonly bool[] hasSides;
public Hexagon(float height, bool[] sides)
: this()
{
this.height = height;
this.hasSides = (bool[])sides.Clone();
}
public float Height
{
get { return height; }
}
public bool[] HasSides
{
get { return hasSides; }
}
public bool this[int i]
{
get { return hasSides[i]; }
}
}
</code></pre>
|
[] |
[
{
"body": "<p>You will see a big improvement in performance if you swap the key/value types of your <code>neighborHexes</code> dictionary around..</p>\n\n<pre><code>var neighbourHexes = new Dictionary<int, Hexagon>();\n\nneighborHexes.Add(0, hexagonArray[x, y + 1]); // etc...\n\nprivate void EvaluateNeighbors(Dictionary<int, Hexagon> neighbors, ref Hexagon currentHexagon)\n{\n foreach (var neighbor in neighbors)\n {\n if (currentHexagon.Height < neighbor.Value.Height)\n currentHexagon[neighbor.Key] = false;\n else if (NearlyEqual(currentHexagon.Height, neighbor.Value.Height))\n currentHexagon[neighbor.Key] = false;\n }\n}\n</code></pre>\n\n<p>I also moved the dictionary construction <code>var neighborHexes = new Dictionary<int, Hexagon>();</code> outside of the loop, and replaced it with <code>neighbourHexes.Clear()</code> inside the loop (we don't need 65536 individual dictionaries, we can just create one and re-use it).</p>\n\n<p>In my tests that small change resulted in about a 72% improvement.</p>\n\n<p>Here are my test results (regionDimensions = 256, 100 iterations)</p>\n\n<pre><code>Unoptimized Average \n0.091637207 \n\nOptimized Average \n0.025620268 \n</code></pre>\n\n<p>And here is <a href=\"https://dl.dropbox.com/u/39213941/24848.linq\" rel=\"nofollow\">the code in Linqpad</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T10:24:39.003",
"Id": "24848",
"ParentId": "24839",
"Score": "2"
}
},
{
"body": "<p>First off, <a href=\"https://stackoverflow.com/a/441323/3312\">mutable <code>structs</code> are evil</a>. Next, why expose the array via a property <strong>and</strong> have an iterator when one or the other will do? And since exposing array fields directly via a property leaks the implementation, let's expose the iterator only instead:</p>\n\n<pre><code>public struct Hexagon\n{\n private readonly float height;\n\n private readonly bool[] hasSides;\n\n public Hexagon(float height)\n {\n this.height = height;\n this.hasSides = new[] { true, true, true, true, true, true };\n }\n\n public float Height\n {\n get\n {\n return this.height;\n }\n }\n\n public bool this[int i]\n {\n get\n {\n if ((i < 0) || (i >= this.hasSides.Length))\n {\n throw new IndexOutOfRangeException(\"Index is out of bounds for the array.\");\n }\n\n return this.hasSides[i];\n }\n\n set\n {\n if ((i < 0) || (i >= this.hasSides.Length))\n {\n throw new IndexOutOfRangeException(\"Index is out of bounds for the array.\");\n }\n\n this.hasSides[i] = value;\n }\n }\n</code></pre>\n\n<p>So now with that, we can also simplify the <code>CheckBounds</code> method into a more succinct, yet still wholly readable single-line (also made <code>static</code> as I don't see instance variables in play):</p>\n\n<pre><code>private static bool CheckBounds(int x, int y)\n{\n return (x >= 0) && (x < RegionDimensions)\n && (y >= 0) && (y < RegionDimensions);\n}\n</code></pre>\n\n<p>Throw in <a href=\"https://codereview.stackexchange.com/users/7697/mattdavey\">MattDavey</a>'s dictionary switcher-arounder (oh, yes, note that there is zero reason for you to be using the <code>ref</code> keyword anywhere in your code):</p>\n\n<pre><code>private static void EvaluateNeighbors(IEnumerable<KeyValuePair<int, Hexagon>> neighbors, Hexagon currentHexagon)\n{\n foreach (var neighbor in neighbors)\n {\n if (currentHexagon.Height < neighbor.Value.Height)\n {\n currentHexagon[neighbor.Key] = false;\n }\n else if (MathExtensions.NearlyEqual(currentHexagon.Height, neighbor.Value.Height))\n {\n currentHexagon[neighbor.Key] = false;\n }\n }\n}\n</code></pre>\n\n<p>Finally, the driver looks like this:</p>\n\n<pre><code>var hexagonArray = new Hexagon[RegionDimensions, RegionDimensions];\n\n// Make sure the hexagonArray is filled with valid Hexagons here.\n\nvar neighborHexes = new Dictionary<int, Hexagon>();\n\n// Evaluate heights of hexagons and cull sides\nfor (var x = 0; x < RegionDimensions; x++)\n{\n for (var y = 0; y < RegionDimensions; y++)\n {\n // If it's not in bounds it doesn't need its side no matter what.\n if (y % 2 == 0)\n {\n // 0\n if (CheckBounds(x, y + 1))\n {\n neighborHexes.Add(0, hexagonArray[x, y + 1]);\n }\n else\n {\n hexagonArray[x, y][0] = false;\n }\n\n // 1\n if (CheckBounds(x + 1, y))\n {\n neighborHexes.Add(1, hexagonArray[x + 1, y]);\n }\n else\n {\n hexagonArray[x, y][1] = false;\n }\n\n // 2\n if (CheckBounds(x, y - 1))\n {\n neighborHexes.Add(2, hexagonArray[x, y - 1]);\n }\n else\n {\n hexagonArray[x, y][2] = false;\n }\n\n // 3\n if (CheckBounds(x - 1, y - 1))\n {\n neighborHexes.Add(3, hexagonArray[x - 1, y - 1]);\n }\n else\n {\n hexagonArray[x, y][3] = false;\n }\n\n // 4\n if (CheckBounds(x - 1, y))\n {\n neighborHexes.Add(4, hexagonArray[x - 1, y]);\n }\n else\n {\n hexagonArray[x, y][4] = false;\n }\n\n // 5\n if (CheckBounds(x - 1, y + 1))\n {\n neighborHexes.Add(5, hexagonArray[x - 1, y + 1]);\n }\n else\n {\n hexagonArray[x, y][5] = false;\n }\n }\n else\n {\n // 0\n if (CheckBounds(x + 1, y + 1))\n {\n neighborHexes.Add(0, hexagonArray[x + 1, y + 1]);\n }\n else\n {\n hexagonArray[x, y][0] = false;\n }\n\n // 1\n if (CheckBounds(x + 1, y))\n {\n neighborHexes.Add(1, hexagonArray[x + 1, y]);\n }\n else\n {\n hexagonArray[x, y][1] = false;\n }\n\n // 2\n if (CheckBounds(x + 1, y - 1))\n {\n neighborHexes.Add(2, hexagonArray[x + 1, y - 1]);\n }\n else\n {\n hexagonArray[x, y][2] = false;\n }\n\n // 3\n if (CheckBounds(x, y - 1))\n {\n neighborHexes.Add(3, hexagonArray[x, y - 1]);\n }\n else\n {\n hexagonArray[x, y][3] = false;\n }\n\n // 4\n if (CheckBounds(x - 1, y))\n {\n neighborHexes.Add(4, hexagonArray[x - 1, y]);\n }\n else\n {\n hexagonArray[x, y][4] = false;\n }\n\n // 5\n if (CheckBounds(x, y + 1))\n {\n neighborHexes.Add(5, hexagonArray[x, y + 1]);\n }\n else\n {\n hexagonArray[x, y][5] = false;\n }\n }\n\n EvaluateNeighbors(neighborHexes, hexagonArray[x, y]);\n neighborHexes.Clear();\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T16:37:35.683",
"Id": "38402",
"Score": "0",
"body": "I find range checking in indexing property quite useless here... `this.hasSides[i]` will throw the same exception anyway, it's like throwing `NullReferenceException`..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T16:38:28.490",
"Id": "38403",
"Score": "0",
"body": "I'm a stickler on getting Pex to shut the heck up."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T14:55:31.740",
"Id": "24858",
"ParentId": "24839",
"Score": "1"
}
},
{
"body": "<ol>\n<li>Completely agree with <a href=\"https://codereview.stackexchange.com/users/6172/jesse-c-slicer\">Jesse</a> concerning mutable structs - it's hard to always remember to mutate proper variable. </li>\n<li>If you're very concerned about memory consumption (if that's the main reason for using mutable structs) I would rather use a bitmap for storing hasSides.</li>\n<li>I'll also use simplification of <code>CheckBounds</code> proposed by <a href=\"https://codereview.stackexchange.com/users/6172/jesse-c-slicer\">Jesse</a> (and ReSharper :)).</li>\n<li><code>Dictionary</code> (that <a href=\"https://codereview.stackexchange.com/users/7697/mattdavey\">MattDavey</a> suggested to improve) is not needed at all... I don't see the reason for creating collection of hexagons just to iterate on it later, it's better to do the \"EvaluateNeighbor\" inline.</li>\n<li>And the last simplification that will reduce most of the code: all your <code>CheckBounds</code> can be combined in a simple loop if you extract the definition of \"neighbors\" in a separate array.</li>\n</ol>\n\n<p>As a result I've got the following code:</p>\n\n<pre><code>static readonly Tuple<int, int>[][] _neighbors = new[] //TODO: rename to whatever you find appropriate\n{\n new[] \n {\n Tuple.Create(0,1),\n Tuple.Create(1,0),\n Tuple.Create(0,-1),\n Tuple.Create(-1,-1),\n Tuple.Create(-1,0),\n Tuple.Create(-1,+1)\n },\n new[]\n {\n Tuple.Create(1,1),\n Tuple.Create(1,0),\n Tuple.Create(1,-1),\n Tuple.Create(0,-1),\n Tuple.Create(-1,0),\n Tuple.Create(0,+1)\n }\n};\n\nprivate static bool HasSide(Hexagon neighbor, Hexagon currentHexagon)\n{\n return currentHexagon.Height >= neighbor.Height &&\n !MathExtensions.NearlyEqual(currentHexagon.Height, neighbor.Height);\n}\n\nprivate static bool CheckBounds(int x, int y)\n{\n return (x >= 0) && (x < regionDimensions) &&\n (y >= 0) && (y < regionDimensions);\n}\n</code></pre>\n\n<p>And the main <strong>iterator</strong>:</p>\n\n<pre><code>// Evaluate heights of hexagons and cull sides\nfor (var x = 0; x < regionDimensions; x++)\n for (var y = 0; y < regionDimensions; y++)\n {\n var activeMapping = _neighbors[y % 2]; //TODO: rename to whatever you find more appropriate\n\n for (int i = 0; i < activeMapping.Length; i++)\n {\n var shiftFromCurrentCell = activeMapping[i];\n var neighborX = x + shiftToCurrentCell.Item1;\n var neighborY = y + shiftToCurrentCell.Item2;\n\n hexagonArray[x, y].HasSides[i] = CheckBounds(neighborX, neighborY) &&\n HasSide(hexagonArray[neighborX, neighborY], hexagonArray[x, y]);\n }\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T16:26:38.487",
"Id": "24864",
"ParentId": "24839",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "24864",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T03:04:29.503",
"Id": "24839",
"Score": "3",
"Tags": [
"c#",
".net"
],
"Title": "Quickly Iterate through 2D array manipulating contained structs"
}
|
24839
|
<p>The goal of my assignment is simple:</p>
<blockquote>
<p>Write a program that converts a given text to "Pig Latin". Pig Latin
consists of removing the first letter of each word in a sentence and
placing that letter at the end of the word. This is followed by
appending the word with letters "ay".</p>
<p>Example</p>
<p>Input: THIS IS A TEST
Output: HISTAY SIAY AAY ESTTAY</p>
</blockquote>
<p>I want to know if there is any way to write this part of the code in a different/better way:</p>
<blockquote>
<pre><code>foreach (string word in engword.Split())
</code></pre>
</blockquote>
<p><strong>Here is my full code:</strong></p>
<pre><code>string engword = textBox1.Text; //english word
string pig1 = ""; //pig latin
string pig2 = ""; //first letter
string space = " ";
string extra = ""; //extra letters
int pos = 0; //position
foreach (string word in engword.Split())
{
if (pos != 0)
{
pig1 = pig1 + space;
}
else
{
pos = 1;
}
pig2 = word.Substring(0,1);
extra = word.Substring(1, word.Length - 1);
pig1 = pig1 + extra + pig2 + "ay";
}
MessageBox.Show(pig1.ToString());
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T05:40:44.170",
"Id": "38363",
"Score": "1",
"body": "`string.Empty` is generally preferred to the empty string literal, `\"\"`. Also if `pos` only ever equals `1` or `0`, why not use a `bool`?"
}
] |
[
{
"body": "<p>This looks pretty decent for a beginner. Some suggestions:</p>\n\n<ul>\n<li><p>Making a variable <code>space</code> instead of using the literal directly is actually a kind of nice idea. You can improve the code by marking the local <code>const</code>.</p></li>\n<li><p>Why is pos an integer? it only has two values, and you are using it to test a condition. Use a bool instead.</p></li>\n<li><p>For that matter, why have pos in the first place? Pos tells you the same thing as <code>pig1.Length == 0</code>.</p></li>\n<li><p>Any time you write a comment, ask yourself <em>did I add this comment because the code was unclear?</em> and then <em>can I write the code so clearly that I don't need the comment?</em> You say </p>\n\n<pre><code>string pig2 = \"\"; // First letter\n</code></pre>\n\n<p>Dude. If the name of the variable is <code>firstLetter</code> then <em>you don't need the comment</em>.</p></li>\n<li><p>pig2 is just one letter, so it can be a <code>char</code> instead of a <code>string</code>. You can say:</p>\n\n<pre><code>char firstLetter;\n...\nfirstLetter = word[0];\n</code></pre></li>\n<li><p>You're using <code>pig1</code> as an <em>accumulator</em>; you're accumulating the final result piece by piece. This is totally fine for small strings. If that string was really big then this is not an efficient technique; you should use <code>StringBuilder</code> instead if you want to make an accumulator for a large string.</p></li>\n<li><p>Finally, like I said, this is fine for a beginner, walk before you run, and so on. To give you a sense of how an expert would write this code, I'd write it like this:</p>\n\n<pre><code>string pigLatin = string.Join(\" \", \n engword.Split()\n .Select(word => word.Substring(1, word.Length - 1) + word[0] + \"ay\"));\n</code></pre>\n\n<p>Which is nicely compact.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T13:29:36.907",
"Id": "38389",
"Score": "2",
"body": "Unless I'm wildly mistaken, there is no overload on `String.Split` which takes zero arguments, which may be what lead to the question in the first place? Also, you can just say `word.SubString(1)`. There's no need to specify the length. Also, unless I'm wrong, this will fail if the sentence includes a single letter word. There should be a check on the word length before assuming that `word.SubString(1)` is a valid index. Other than that, great answer, you covered everything I was going to say."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T14:07:11.117",
"Id": "38396",
"Score": "2",
"body": "+1 simply for mentioning the oft-overlooked value of self-documenting code and forgoing redundant comments."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T19:23:19.243",
"Id": "38417",
"Score": "4",
"body": "@StevenDoggart, `Split()` with 0 arguments is basically equivalent to passing `new char[0]` to fill the `params char[]` parameter. Pointing it out in case you were asking. If you were not asking, then forget I said anything."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T20:59:13.390",
"Id": "38425",
"Score": "0",
"body": "`string.Join` needs an array, doesn't it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T21:13:12.310",
"Id": "38429",
"Score": "4",
"body": "@Blorgbeard, as of .NET 4, string.Join is overloaded to support IEnumerable<string> specifically and IEnumerable<T> generically."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T02:09:37.593",
"Id": "76182",
"Score": "2",
"body": "As @StevenDoggart has pointed out, it is best practise to verify that input you receive is as you expect before operating on it. Given Eric's example, after the call to `.Split()`, I would add `.Where( word => !string.IsNullOrWhiteSpace( word ) )` so that strings made up of spaces, or having many spaces next to one another, do not cause your program to crash. I would probably also check that `textBox1.Text` was not null before starting, but it maybe that it can be guaranteed to be not-null."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T05:23:26.960",
"Id": "24842",
"ParentId": "24841",
"Score": "20"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T04:32:14.243",
"Id": "24841",
"Score": "7",
"Tags": [
"c#",
"homework",
"pig-latin"
],
"Title": "Simple Pig Latin Translator"
}
|
24841
|
<p>I have a dropdownbox, <code>ActiviteitAardItems</code>, where <code>ActiviteitAard</code> items can be checked (checkbox). If one (or more) are checked the property Opacity will be changed, and the code beneath will be executed. The <code>Tijdblok</code> mentioned below also has a property <code>Activiteit</code> and <code>ActiviteitAard</code>.</p>
<pre><code>public double Opacity
{
get
{
if (Planning.ActiviteitAardItems.Where(aa => aa.IsChecked == true).Count() > 0)
{
if (this.Tijdblokken.Where(t => t.Activiteit != null && t.Activiteit.ActiviteitAard != null).Count() > 0)
{
Tijdblok tijdblok;
var tijdblokken = new List<Tijdblok>();
foreach (var item in Planning.ActiviteitAardItems.Where(aa => aa.IsChecked == true))
{
tijdblok = this.Tijdblokken.Where(t => t.Activiteit != null && t.Activiteit.ActiviteitAard != null && t.Activiteit.ActiviteitAard.Code == item.Code).FirstOrDefault();
if (tijdblok != null)
tijdblokken.Add(tijdblok);
}
tijdblok = tijdblokken.OrderByDescending(tb => tb.Activiteit.RoosterKleurPrioriteit).FirstOrDefault();
if (tijdblok != null && tijdblok.Activiteit != null && tijdblok.Activiteit.ActiviteitAard != null)
{
if (Planning.ActiviteitAardItems.Where(aa => aa.IsChecked).Select(x => x.Code).Contains(tijdblok.Activiteit.ActiviteitAard.Code))
{
return 1.0;
}
else
{
return 0.1;
}
}
else
{
return 0.1;
}
}
else
{
return 0.1;
}
}
return 1.0;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T01:45:21.293",
"Id": "38508",
"Score": "3",
"body": "I think a getter that does that much, deserves to be a full-fledged method."
}
] |
[
{
"body": "<p>I think there is probably more that could be offered as the code like something that could do with a makeover, but here's a couple of minor points for consideration.</p>\n\n<ol>\n<li><p>To avoid any potential full enumeration of the items to retrieve the count of items in the list use either the <code>.Count</code> property or the option I prefer <code>.Any()</code>. e.g. <code>Planning.ActiviteitAardItems.Where(aa => aa.IsChecked == true).Any()</code></p></li>\n<li><p>I personally think lines like aa.Checked == true is unecessary noise. You can achieve the same result by just going <code>.Where(aa => aa.IsChecked)</code>.</p></li>\n<li><p>If you are using the same IEnumerable multiple times consider first assigning it to a local variable and doing a ToList() on it. This means that you will avoid any potential multiple enumerations of the dataset as ToList() will force it all back into memory.</p>\n\n<p>For example</p>\n\n<pre><code>var ardCheckedItems = Planning.ActiviteitAardItems.Where(aa => aa.IsChecked).ToList();\n</code></pre>\n\n<p>You can now use this same variable in a couple of places in your code.</p></li>\n<li><p>Does 1.0 and 0.1 mean anything? You could perhaps convert them to constants to avoid any repetition. See example below.</p></li>\n<li><p>Here is an attempt to reduce the <a href=\"http://www.codinghorror.com/blog/2006/01/flattening-arrow-code.html\" rel=\"nofollow noreferrer\">Arrow code effect</a> we sometimes find ourselves writing and seems evident in this case.</p></li>\n</ol>\n\n\n\n<pre><code>public double Opacity\n{\n get\n {\n const double returnOne = 1.0; // for lack of better names\n const double returnTwo = 0.1;\n\n var ardCheckedItems = Planning.ActiviteitAardItems.Where(aa => aa.IsChecked).ToList();\n\n if(!ardCheckedItems.Any()) return returnOne; \n\n tijdBlokkenItems = this.Tijdblokken.Where(t => t.Activiteit != null && t.Activiteit.ActiviteitAard != null).ToList();\n\n if(!tijdBlokkenItems.Any()) return returnTwo;\n\n Tijdblok tijdblok;\n var tijdblokken = new List<Tijdblok>();\n\n // See Edit below for an example of how to possibly re-write this\n foreach (var item in ardCheckedItems)\n {\n tijdblok = tijdBlokkenItems.Where(t => t.Activiteit.ActiviteitAard.Code == item.Code).FirstOrDefault();\n if (tijdblok != null)\n tijdblokken.Add(tijdblok);\n }\n\n tijdblok = tijdblokken.OrderByDescending(tb => tb.Activiteit.RoosterKleurPrioriteit).FirstOrDefault();\n\n var objectsNotNull = tijdblok != null && tijdblok.Activiteit != null && tijdblok.Activiteit.ActiviteitAard != null;\n var anyCheckedItems = ardCheckedItems.Any(x => x.Code == tijdblok.Activiteit.ActiviteitAard.Code);\n\n return objectsNotNull && anyCheckedItems ? returnOne : returnTwo;\n }\n}\n</code></pre>\n\n<p>EDIT: After Trevor pointed me in the right direction in order to improve the foreach statement I did a quick search on if it would be easy enough to do an extension method to return items that are not Null. Stack overflow to the rescue <a href=\"https://stackoverflow.com/questions/14469159/linq-selectmany-and-where-extension-method-ignoring-nulls\">https://stackoverflow.com/questions/14469159/linq-selectmany-and-where-extension-method-ignoring-nulls</a>. So altering that slighty I came up with and extension method like so:</p>\n\n<pre><code>public static IEnumerable<TResult> WhereNotNull<TSource, TResult>(\n this IEnumerable<TSource> source, Func<TSource, TResult> selector)\n where TResult : class\n{\n return source.Select(selector).Where(sequence => sequence != null);\n}\n</code></pre>\n\n<p>which means I believe we can re-write the foreach like so:</p>\n\n<pre><code>var tijdblokken = ardCheckedItems.WhereNotNull(ard => tijdBlokkenItems.FirstOrDefault(t.Activiteit.ActiviteitAard.Code == ard.Code)).ToList();\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T09:58:05.880",
"Id": "38369",
"Score": "0",
"body": "Thanks for your comment, some nice 'tips' in there :) \nI am actually wondering about the part you also commented on.\n \nI want to know if there is an easier (cleaner) way of checking if an ActiviteitAard is also checked in the list."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T10:13:55.517",
"Id": "38373",
"Score": "0",
"body": "The code is inside a get method of a property, and is responsible for calculating the opacity value based on the checked items."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T11:50:24.653",
"Id": "38383",
"Score": "0",
"body": "@dreza - something like this: `var tijdblokken = ardCheckedItems.SelectMany(ard => tijdBlokkenItems.Where(t => t.Activiteit.ActiviteitAard.Code == ard.Code).FirstOrDefault()).Where(t => t != null).ToList();`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T13:36:23.697",
"Id": "38390",
"Score": "0",
"body": "@TrevorPilley only logical occasion where `FirstOrDefault`s can be chained are when we know that underlying `IEnumerable` cannot have more than one element. If @frG can confirm that `t.Activiteit.ActiviteitAard.Code == item.Code` cannot be true for more than one `t` (which is reasonable), then your snippet could be rewritten\n`var tijdblokken = ardCheckedItems.SelectMany(ard => tijdBlokkenItems.Where(t => t.Activiteit.ActiviteitAard.Code == ard.Code)).ToList();`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T13:41:09.607",
"Id": "38393",
"Score": "0",
"body": "@TrevorPilley I think you should not have the `firstOrDefault()` in the the `SelectMany`, anyways. Am i missing something? I can't try it right now."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T13:58:37.743",
"Id": "38395",
"Score": "0",
"body": "@abuzittingillifirca I used `FirstOrDefault()` as that is what the OP used, I think it might be necessary, the `.SelectMany` does the outer `for each` over `ardCheckedItems`, the `.Where().FirstOrDefault()` covers the inner lookup. The `FirstOrDefault()` may be unnecessary depending on the object model and uniqueness of `.Code` but the OP would have to confirm."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T20:52:49.947",
"Id": "38423",
"Score": "0",
"body": "@TrevorPilley Cheers Trevor. I've added an update on doing something like your suggestion"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T09:32:53.110",
"Id": "24846",
"ParentId": "24843",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T07:14:04.063",
"Id": "24843",
"Score": "3",
"Tags": [
"c#",
".net",
"linq"
],
"Title": "Changing the opacity property"
}
|
24843
|
<p>The new <a href="http://www.haskell.org/ghc/docs/7.6.2/html/users_guide/syntax-extns.html#multi-way-if" rel="nofollow"><code>MultiWayIf</code></a> extension (available with GHC 7.6) allows guard syntax in an <code>if</code>:</p>
<pre><code>{-# LANGUAGE MultiWayIf #-}
fn :: Int -> String
fn x y = if | x == 1 -> "a"
| y < 2 -> "b"
| otherwise -> "c"
</code></pre>
<p>But I don't find it better than the old way:</p>
<pre><code>fn :: Int -> String
fn x y | x == 1 = "a"
| y < 2 = "b"
| otherwise = "c"
</code></pre>
<p>Has it sense in other cases?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T10:00:52.913",
"Id": "38370",
"Score": "0",
"body": "I am not sure if this question is suited for Code Review, maybe it should get migrated to SO."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T10:06:29.307",
"Id": "38371",
"Score": "0",
"body": "Flow, I put in codereview because is probably more subjective that a question in SO. It, IMHO, is a \"Best practices and design pattern usage\" question"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T10:09:30.050",
"Id": "38372",
"Score": "0",
"body": "Good point, seems reasonable."
}
] |
[
{
"body": "<p>Unsurprisingly, it's mainly useful when the <code>if</code> is <em>not</em> the top-level expression. Say:</p>\n\n<pre><code>forM_ [1..100] $ \\i ->\n putStrLn $ if | i `mod` 15 == 0 -> \"FizzBuzz\"\n | i `mod` 3 == 0 -> \"Fizz\"\n | i `mod` 5 == 0 -> \"Buzz\"\n | otherwise -> show i\n</code></pre>\n\n<p>I happen across similar cases quite often - up to this point this required either deep <code>if</code> trees or mis-using <code>case</code> in some way.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T12:00:36.970",
"Id": "24856",
"ParentId": "24844",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "24856",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T08:40:50.163",
"Id": "24844",
"Score": "1",
"Tags": [
"haskell",
"formatting"
],
"Title": "Haskell MultiWayIf extension: When is it considered useful syntactic sugar?"
}
|
24844
|
<p>I really like using the new <a href="http://msdn.microsoft.com/en-us/library/hh873175.aspx" rel="noreferrer">TAP</a> pattern in .Net 4.5. and I am updating some of my older projects to use it.</p>
<p>One of my old patterns was to use <a href="http://msdn.microsoft.com/en-us/library/wewwczdw.aspx" rel="noreferrer">EAP</a> with WCF so I could have functions that could take longer than 60 seconds (the default timeout for WCF) to complete without doing custom setup on the client side App.Conifg.</p>
<p>Here is a simple example of what I would do.</p>
<pre><code>[ServiceContract(CallbackContract = typeof(ICallback))]
public interface IService1
{
[OperationContract(IsOneWay = true)]
void Test(int arg);
}
[ServiceContract]
interface ICallback
{
[OperationContract(IsOneWay=true)]
void Callback(int arg);
}
public class Service1 : IService1
{
public void Test(int arg)
{
var callback = OperationContext.Current.GetCallbackChannel<ICallback>();
Thread.Sleep(61000); //Sleep for 61 sec.
callback.Callback(arg + 1);
}
}
</code></pre>
<p>Now I want to put a wrapper around my EAP pattern and turn it in to a TAP pattern (as an aside, just returning a TAP pattern like <code>public Task<int> Test(int arg)</code> will still have the 60 second time limit but it does work)</p>
<p>Here is the solution I came up with, this code would be run on the client.</p>
<pre><code>static class ProxyClient
{
private delegate void CallbackDelegate(int arg);
private class CallbackClass : IService1Callback
{
public event CallbackDelegate CallbackEvent;
void IService1Callback.Callback(int arg)
{
var tmp = CallbackEvent;
if (tmp != null)
tmp(arg);
}
}
public static async Task<int> Test(int arg)
{
var callback = new CallbackClass();
var client = new Service1Client(new InstanceContext(callback));
TaskCompletionSource<int> tcs = new TaskCompletionSource<int>();
//start listening for the completion event
callback.CallbackEvent += (resultArg) => tcs.TrySetResult(resultArg);
client.Test(arg);
//wait for the result
var result = await tcs.Task;
//close the connection
client.Close();
return result;
}
}
</code></pre>
<p>The main concern I had was receiving the completion callback for another invocation if a connection was used more than once. So I create and breakdown the connection from inside the function entirely.</p>
<p>I would love to hear input if this is a good idea, or is there a better way to accomplish long running tasks in WCF without having to modify timeout values client-side at the time of proxy creation.</p>
|
[] |
[
{
"body": "<h2>Design Trigger</h2>\n\n<p>I don't understand why you implement a duplex wcf operation to emulate a simplex operation, just to avoid configuring the timeout. Let's assume you have a really good reason why you don't want to change the default timeouts, then your solution can still time out on being idle (after 10 minutes), because you changed from timing out on <code>SendTimeout</code> to <code>ReceiveTimeout</code>. </p>\n\n<p>As explained <a href=\"https://codereview.stackexchange.com/questions/24845/wcf-using-tap-without-worrying-about-timeouts\">here</a> the following timeouts have an impact on your code:</p>\n\n<ul>\n<li><strong>SendTimeout</strong>:\nmaximum threshold to expire an ongoing simplex operation. -> The timeout you don't like to configure (default: 1 minute)</li>\n<li><strong>ReceiveTimeout</strong>: \nmaximum idle time on a session. -> The timeout between the one-way message and the callback fired back. (default: 10 minutes)</li>\n</ul>\n\n<hr>\n\n<h2>Review</h2>\n\n<ul>\n<li><p>Your concern about using a single instance for multiple calls is valid. Using a single instance with a single callback is the simplest solution. Otherwise, you would need to implement a matching system with correlation ids in the request and callback contracts.</p></li>\n<li><p>The lifetime management is not robust enough. Use a try-finally block to close the connection. Also, distinguish between <code>Abort</code> (when connection is <code>Faulted</code>) and <code>Close</code> (graceful disconnect) (<a href=\"https://blog.rsuter.com/correctly-handle-wcf-clients-life-cycle-simple-way/\" rel=\"nofollow noreferrer\">Close Connection</a>).</p>\n\n<blockquote>\n<pre><code>//wait for the result\nvar result = await tcs.Task; // <- if this throws an exception\n\n//close the connection\nclient.Close(); // <- this won't be called\n</code></pre>\n</blockquote></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-02T21:55:45.103",
"Id": "437718",
"Score": "1",
"body": "You understand wcf :-o I have never met anybody who whould know how this _crap_ works :-P the first paragraph is like black magic."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-03T07:18:07.443",
"Id": "437743",
"Score": "1",
"body": "I used to work on a project where we used duplex tcp connections in wcf. I had to find out the hard way what all the timeouts actually are meant for."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-02T17:10:14.560",
"Id": "225426",
"ParentId": "24845",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T08:43:54.543",
"Id": "24845",
"Score": "9",
"Tags": [
"c#",
"asynchronous",
"wcf",
"async-await"
],
"Title": "WCF using TAP without worrying about timeouts"
}
|
24845
|
<p><em>Coding to the interface, rather than the implementation</em>. Here is what I'm doing in simple terms.</p>
<p><em>Note: Although written using PHP, this is more of a general design / abstraction question that developers using any language could help answer.</em></p>
<p>I'm writing an application that can handle different types of connection to gather it's data. The connection could be:</p>
<ul>
<li>A server somewhere abroad</li>
<li>Localhost</li>
<li>On a local network</li>
</ul>
<p>All connections <strong>must handle their data retrieval using SFTP</strong> as the data may be sensitive.</p>
<p>Therefore, I coded an interface as follows:</p>
<h2>The Interface</h2>
<pre><code>interface ConnectionInterface
{
/**
* __construct instantiates connection object with settings
*/
/**
* connect() attempts connection using settings set up within constructor
*/
public function connect();
/**
* runCommand() executes a cmd and retrieves a string using the connection resource
*/
public function runCommand($command);
/**
* ping() checks that the actual host exists, before trying to connect
*/
public function ping($ip);
}
</code></pre>
<p>Above is the interface I created before coding anything else.</p>
<p>Here is one concrete implementation that <strong>requires SSH2 via PECL</strong> to be installed.</p>
<h2>SSH2 Implementation</h2>
<pre><code>class SSHConnection implements ConnectionInterface
{
public $config;
public $conn;
/**
* Instantiates SSHConnection Object with settings
*/
public function __construct($ip, $port, $username, $password)
{
// Check SSH2 extension loaded. If not, throw exception / exit
// Set class variables to that of those passed into constructor
}
/**
* Attempt SSH connection using settings set up within constructor
*
* @return mixed True on success, false on exception
* @throws \Exception if can't find server or can't connect
*/
public function connect()
{
extract($this->config);
if (!$this->ping($ip))
{
return false;
}
if (@!$conn = ssh2_connect($ip, $port))
{
throw new \Exception('Unable to connect to the server');
return false;
}
if (@!ssh2_auth_password($conn, $username, $password))
{
throw new \Exception('Incorrect server login username / password');
return false;
}
$this->conn = $conn;
return true;
}
/**
* Simple server ping using exec(), used in $this connect()
*/
public function ping($ip)
{
// Ping.. obviously..
}
/**
* Execute a command and retrieve a string using the connection resource
*
* @param string $command The command to run (example: 'ln -s')
* @return mixed An object containing arrays data
*/
public function runCommand($command)
{
// Use $this->conn to run a shell command
}
/**
* If there is a connection, runs exit on it then unset
*/
public function __destruct()
{
// If connection, ssh_exec 'exit' then unset($this->conn)
}
}
</code></pre>
<h2>My questions</h2>
<p>Apart from giving a load of general suggestions about why and how to improve this code, I have a few more specific questions that I hope could be added to your answer:</p>
<ol>
<li><p><em>Is it wrong to perform any sort of calculations within the constructor?</em> For example, if the SSH2 extension isn't loaded, isn't the constructor the clearest place to put the check for this? Someone suggested creating a "test if you can run this class" command line script, but... honestly I think that someone trying to create this object should not be allowed to if they don't have the required dependency.</p></li>
<li><p><em>Should the <code>ping()</code> function be here?</em> Ping is only required when using a server abroad, not really if on localhost. Should there be a check here? Should this be moved somewhere else entirely? How should I go about it?</p></li>
<li><p><em>What about the actual data retrieval?</em> This is just the connection. Should I insert the data retrieval within this class? Or create a new <code>DataRetrieval</code> object which uses the connection object?</p></li>
</ol>
<p>Your help will be greatly appreciated. This is not a work project, just a personal one and I asked this question to learn - I know it'll work, but I <strong>want it to work well</strong>. So what would you do and why?</p>
|
[] |
[
{
"body": "<p><em><strong>Is it wrong to perform any sort of calculations within the constructor?</em></strong></p>\n\n<p>Opinion is somewhat divided on this matter. I think it is generally accepted that a constructor should not contain business logic because it makes your code much more difficult to mock for testing, however this particular case you show comes down to how you define that term \"business logic\".</p>\n\n<p>Personally I believe that checking for global dependencies (in this case, checking for the existence of the SSH2 extension) is acceptable. Ideally you would not need to be checking for any global environmental state, you would simply inject a state object, but because of the way PHP's extension system works that's not really possible. Obviously injecting state object is possible, but that would still need to check global state, so you haven't really gained anything, except possibly in terms of SRP - but this would require an added layer of abstraction to separate the protocol from the connection. It's up to you whether you think this is worthwhile.</p>\n\n<p>The alternative is to put this check in a separate method and require that the consumer call it explicitly. However, to me this is at odds with the idea of the interface and is defining and exposing the underlying implementation.</p>\n\n<p>There are only two cases that need to be mocked: the dependencies exist, or they don't. There's no real logic that needs to be tested here. What you definitely should <em>not</em> do is automatically connect in the constructor, but I think that dependency validation in the constructor is harmless.</p>\n\n<p>However, I know there are others who would disagree with me on this point.</p>\n\n<p><em><strong>Should the <code>ping()</code> function be here?</em></strong></p>\n\n<p>No, the ping function should not be there. We have already had a <a href=\"http://chat.stackoverflow.com/rooms/11/conversation/jimbos-ssh2-code-review\">conversation about this in chat</a>, but sum it up in a sentence: The ping function is there to validate that the host is connectable, this should be done internally by the <code>connect()</code> method and not by a separate external API call. This is exposing part of your implementation in your interface, exactly what you are trying to avoid.</p>\n\n<p><em><strong>What about the actual data retrieval?</em></strong></p>\n\n<p>It depends. If the class contains a <code>send()</code> mechanism, it should also contain the <code>retrieve()</code> mechanism. But it may be that this should be divided up a bit more:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>/**\n * Value object that just holds the connection parameters like host, port, protocol\n *\n * It may be that this is simply a concrete implementation and an interface isn't required\n */\ninterface ConnectionParameters\n{\n // ...\n}\n\ninterface Connector\n{\n /**\n * Uses a parameters object to create a connection object\n *\n * @param ConnectionParameters $parameters The parameters to use\n *\n * @return Connection The created connection\n *\n * @throws \\RuntimeException When the connect operation fails\n */\n public function connect(ConnectionParameters $parameters);\n}\n\n/**\n * Represents an active connection\n */\ninterface Connection\n{\n\n /**\n * Get the connection parameters used to create the connection\n *\n * This is optional, but personally I believe it makes sense to carry this\n * information with the connection. Obviously in order for this to be implemented\n * the object will need to be passed in by the Connector.\n *\n * Some may say this is inviting LoD violations and that the association, if\n * required, should be carried by the consumer.\n *\n * @return ConnectionParameters Parameters used to create the connection\n */\n public function getParameters();\n\n /**\n * Send data from a buffer\n *\n * @param DataBuffer $buffer Buffer that holds data to send\n * @param int $length Number of bytes to send (<0: drain buffer)\n *\n * @return int Number of bytes sent\n */\n public function send(DataBuffer $buffer, $length = -1);\n\n /**\n * Receive data into a buffer\n *\n * @param DataBuffer $buffer Buffer to populate with received data\n * @param int $length Number of bytes to receive (<0: all pending data)\n *\n * @return int Number of bytes received\n */\n public function recv(DataBuffer $buffer, $length = -1);\n\n /**\n * Close the connection\n */\n public function close();\n}\n\n/**\n * Represents a store of data that can be transmitted via the connection\n *\n * You may wish to add other methods to this interface, for example an fgets()\n * equivalent. Arguably though, that might be a case for extending this interface:\n * This assumes all data is binary, you might want to have TextBuffer extends DataBuffer\n */\ninterface DataBuffer\n{\n /**\n * Read some data from the buffer\n *\n * @param int $length Number of bytes to read (<0: drain buffer)\n *\n * @return string Data from buffer\n */\n public function read($length = -1);\n\n /**\n * Write some data to the buffer\n *\n * @param string $data Data to write\n * @param int $length Number of bytes to write (<0: all pending data)\n *\n * @return int Number of bytes written\n */\n public function write($data, $length = -1);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-09T09:09:24.233",
"Id": "38467",
"Score": "0",
"body": "Quick question Dave - Is the intent here to create the `Connector` Object, then *pass it via dependency injection* into the constructor of the `Connection` object?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-09T09:13:56.690",
"Id": "38468",
"Score": "0",
"body": "@Jimbo The idea of the connector is to act as a service creator. So you could have a `SSH2ExtnConnector` and a `cURLSSH2Connector`, which would perform their relevant connection tasks and instantiate different implementations of `Connection`. Which one you would use would depend on what is available on the current platform. By doing it this way you can simply inject the correct `Connector` implementation into the code that consumes the SSH2 service, and the underlying implementation is effectively abstracted."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T11:58:11.000",
"Id": "24855",
"ParentId": "24847",
"Score": "2"
}
},
{
"body": "<p>Consider creating a static method within the class that performs all requirement checks and either returns the constructed object or NULL to indicate there was a failure in meeting all requirements.</p>\n\n<pre><code>class SSHConnection implements ConnectionInterface\n{\n //.... your class functions\n public static function SSHConnection GetInstanceIfRequirementsMatched(/*...args*/)\n {\n $myObj = NULL;\n $bIsAllGood = TRUE;\n\n //run checks for installed features, example:\n if(!isset($_SERVER['SSH'])) { $bIsAllGood = FALSE; }\n\n if($bIsAllGood)\n {\n //initialize object, run connection obj, etc.\n $myObj = new SSHConnection(/*...args*/);\n $response = $myObj->InitConnection();\n\n if(!$response) \n { \n /*throw new Exception(\"Could not connect...!\");*/ \n $myObj = NULL; \n }\n }\n\n return $myObj;\n }\n\n protected function __construct(/*...args*/) { }\n\n /*Basically your connection() method*/\n protected function InitConnection() { return 0; }\n}\n</code></pre>\n\n<p>Note: for this, I'd also suggest making your constructor <em>protected</em> instead of <em>public</em> to enforce usage of your static method outside the class.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-21T13:22:56.227",
"Id": "222707",
"ParentId": "24847",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "24855",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T09:45:56.653",
"Id": "24847",
"Score": "3",
"Tags": [
"php",
"object-oriented"
],
"Title": "Abstraction for multiple connection methods"
}
|
24847
|
<p>I have to run a python script that enters data into MySQL database table.</p>
<p>My below query runs and inserts data into MySQL database. But I want to optimize it and I have 2 requests:</p>
<ol>
<li><p>I want to use try except error handling inside the for loop. Probably before insertstmt or where it would be more efficient.
If there is bug while executing nSql, program should not terminate, rather continue in other nSql tests.
nSql has complex SQL queries with multiple joins, below shown is for simplicity. If any one of the nSql fails during quering, I want the error
message to be displayed. </p></li>
<li><p>If the data already exists for yesterday, I want to be deleted it as well.
As the loop iterates, I want data to be deleted if it exists for yesterday as loop iterates through the nSql.</p></li>
</ol>
<p>I have: </p>
<pre><code>#! /usr/bin/env python
import mysql.connector
con=mysql.connector.connect(user='root', password ='root', database='test')
cur=con.cursor()
sel=("select id, custName, nSql from TBLA")
cur.execute(sel)
res1=cur.fetchall()
for outrow in res1:
print 'Customer ID : ', outrow[0], ': ', outrow[1]
nSql = outrow[2]
cur.execute(nSql)
res2=cur.fetchall()
for inrow in res2:
dateK =inrow[0]
id= inrow[1]
name= inrow[2]
city=inrow[3]
insertstmt=("insert into TBLB (dateK, id, name, city) values ('%s', '%s', '%s', '%s')" % (dateK, id, name, city))
cur.execute(insertstmt)
con.commit()
con.close()
</code></pre>
<p>Database schema is:</p>
<pre><code>create table TBLA (id int, custName varchar(20), nSql text);
insert into TBLA values ( 101, 'cust1', "select date_sub(curdate(), interval 1 day) as dateK, id, 'name', 'city' from t1"), ( 102, 'cust2', "select date_sub(curdate(), interval 1 day) as dateK, id, 'name', 'city' from t2"), ( 103, 'cust3', "select date_sub(curdate(), interval 1 day) as dateK, id, 'name', 'city' from t3");
create table t1 (id int, name varchar(20), city varchar(20));
create table t2 (id int, name varchar(20), city varchar(20));
create table t3 (id int, name varchar(20), city varchar(20));
insert into t1 values( 101, 'bob', 'dallas'), ( 102, 'boby', 'dallas');
insert into t2 values( 101, 'bob', 'dallas'), ( 102, 'boby', 'dallas');
insert into t3 values( 101, 'bob', 'dallas'), ( 102, 'boby', 'dallas');
create table TBLB (dateK date, id int, name varchar(20), city varchar (20));
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-07T21:13:02.947",
"Id": "38377",
"Score": "0",
"body": "You seem to know what you want and how to do it, so... where's the question?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-07T21:15:33.127",
"Id": "38378",
"Score": "0",
"body": "I want to use try except inside the code and would like to delete data if exists as said in 1 in 2. Btw, I am a new to Python World !"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-07T21:16:22.840",
"Id": "38379",
"Score": "0",
"body": "I know what you want, but where's the problem? You know how to use `try:except:` right? You know how to make delete query, right? So where's the problem?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-07T21:18:22.703",
"Id": "38380",
"Score": "0",
"body": "I am sorry, but I am stuck in using try except and delete."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-07T21:34:17.113",
"Id": "38381",
"Score": "1",
"body": "just one tip: it's never a good idea to create sql statements like you do. mysql.connector supports python format style parameter expansion, so if you change your query to `cur.execute(\"insert into TBLB (dateK, id, name, city) values (%s, %s, %s, %s)\", (dateK, id, name, city))` you won't have to worry about sql injection. It's best to get used to this as early as possible."
}
] |
[
{
"body": "<p>OK, here's the simpliest version of <code>try:except:</code> block for your case:</p>\n\n<pre><code># some code\nfor inrow in res2:\n # some code\n try:\n cur.execute(insertstmt)\n except MySQLdb.ProgrammingError:\n pass\n</code></pre>\n\n<p>That's pretty much it. You probably want to know which queries failed, so you should use for example that version:</p>\n\n<pre><code> try:\n cur.execute(insertstmt)\n except MySQLdb.ProgrammingError:\n print \"The following query failed:\"\n print insertstmt\n</code></pre>\n\n<p>Now as for the other question. You have to use a delete query. For example:</p>\n\n<pre><code>DELETE FROM TBLB WHERE dateK < CURDATE();\n</code></pre>\n\n<p>or something like that (note that <code>CURDATE</code> is a built-in MySQL function). Read more about delete queries here:</p>\n\n<p><a href=\"http://dev.mysql.com/doc/refman/5.0/en/delete.html\" rel=\"nofollow\">http://dev.mysql.com/doc/refman/5.0/en/delete.html</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-07T22:18:32.057",
"Id": "38382",
"Score": "0",
"body": "@ freakish thank you for the response. During the nSql execution, if one of the SQL execution fails, how can I continue with other SQL execution without getting interrupted."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T12:00:07.893",
"Id": "38384",
"Score": "1",
"body": "I would suggest writing `except MySQLdb.ProgrammingError:` and not `except Exception:`. You should always catch the most specific error class that makes sense. See [PEP 249](http://www.python.org/dev/peps/pep-0249/#exceptions) for the exceptions that can be generated by DB-API methods."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T23:13:20.850",
"Id": "38442",
"Score": "0",
"body": "`ProgrammingError` might not be the right one (or the only one) you need to catch here: it all depends on the OP's purpose in catching these errors."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-07T21:24:48.040",
"Id": "24854",
"ParentId": "24853",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-07T21:07:54.810",
"Id": "24853",
"Score": "4",
"Tags": [
"python",
"mysql"
],
"Title": "Inserting data into database by Python"
}
|
24853
|
<p>To work around the <a href="http://blogs.msdn.com/b/tess/archive/2006/02/15/net-memory-leak-xmlserializing-your-way-to-a-memory-leak.aspx" rel="nofollow">XmlSerializer memory leak thing</a> I created this:</p>
<pre><code>public static class XmlSerializerCache
{
public static XmlSerializer GetXmlSerializer(Type type, XmlRootAttribute xmlRoot)
{
var cache = System.AppDomain.CurrentDomain;
var key = String.Format(CultureInfo.InvariantCulture, "CachedXmlSerializer:{0}:{1}", type, xmlRoot.ElementName);
var serializer = cache.GetData(key) as XmlSerializer;
if (serializer == null)
{
serializer = new XmlSerializer(type, xmlRoot);
cache.SetData(key, serializer);
}
return serializer;
}
}
</code></pre>
<p>As far as I understood, the generated assemblies get unloaded as soon as the AppDomain gets unloaded. So I thought I can use the AppDomain Cache to cache my serializers. </p>
<p>Is this approach a good one? Or at least a "Leak-Safe" one? </p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T16:32:46.513",
"Id": "38401",
"Score": "0",
"body": "Gotta be honest, I've never actually used that particular `XmlSerializer` constructor overload that doesn't cache."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T20:35:51.963",
"Id": "38421",
"Score": "0",
"body": "Do you actually have multiple AppDomains in your application? If not, this code doesn't make much sense."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T22:07:47.967",
"Id": "38437",
"Score": "0",
"body": "I'd say I have only one AppDomain. (I don't explicitly use more than one.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-04-08T09:39:41.317",
"Id": "155464",
"Score": "0",
"body": "Can this be used in a WCF generated client reference?"
}
] |
[
{
"body": "<p>According the work around section in the <a href=\"https://web.archive.org/web/20070102071100/http://support.microsoft.com:80/kb/886385/en-us\" rel=\"nofollow noreferrer\">kb article</a> mentioned in the <a href=\"http://blogs.msdn.com/b/tess/archive/2006/02/15/net-memory-leak-xmlserializing-your-way-to-a-memory-leak.aspx\" rel=\"nofollow noreferrer\">blog</a> entry, your solution looks correct.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2013-04-08T16:12:27.797",
"Id": "24862",
"ParentId": "24861",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T16:01:47.643",
"Id": "24861",
"Score": "1",
"Tags": [
"c#",
".net"
],
"Title": "Caching XmlSerializer in AppDomain"
}
|
24861
|
<p>I have the following code:</p>
<pre><code>const String sqlSelect = "SELECT * FROM UserPasswords WHERE username='System Administrator';";
const String sqlInsert = "INSERT INTO UserPasswords VALUES (@username,@Password,@startDate,@Expired,@UserPasswordsID)";
using (var con1 = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["dataConnectionString"].ConnectionString))
using (var con2 = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["utilConnectionString"].ConnectionString))
{
con1.Open();
con2.Open();
using (var selectCommand = new SqlCommand(sqlSelect, con1))
{
using (var reader = selectCommand.ExecuteReader())
{
if (reader.Read())
{
using (var insertCommand = new SqlCommand(sqlInsert, con2))
{
insertCommand.Parameters.Add(new SqlParameter("@username", reader.GetString(0)));
insertCommand.Parameters.Add(new SqlParameter("@Password", reader.GetString(1)));
insertCommand.Parameters.Add(new SqlParameter("@startDate", reader.GetDateTime(2)));
insertCommand.Parameters.Add(new SqlParameter("@Expired", reader.GetBoolean(3)));
insertCommand.Parameters.Add(new SqlParameter("@UserPasswordsID", reader.GetInt32(4)));
insertCommand.ExecuteNonQuery();
}
}
}
}
</code></pre>
<p>All I need to do is copy the row with the 'System Administrator' info into another table as a backup. Though this code works is there someway to do this more elegantly?</p>
|
[] |
[
{
"body": "<p><a href=\"http://www.codeproject.com/Articles/18418/Transferring-Data-Using-SqlBulkCopy\" rel=\"nofollow\">Transferring Data Using SqlBulkCopy</a></p>\n\n<pre><code>private static void PerformBulkCopy()\n{\n string connectionString =\n @\"Server=localhost;Database=Northwind;Trusted_Connection=true\";\n // get the source data\n using (SqlConnection sourceConnection = \n new SqlConnection(connectionString))\n {\n SqlCommand myCommand =\n new SqlCommand(\"SELECT * FROM Products_Archive\", sourceConnection);\n sourceConnection.Open();\n SqlDataReader reader = myCommand.ExecuteReader();\n\n // open the destination data\n using (SqlConnection destinationConnection =\n new SqlConnection(connectionString))\n {\n // open the connection\n destinationConnection.Open();\n\n using (SqlBulkCopy bulkCopy =\n new SqlBulkCopy(destinationConnection.ConnectionString))\n {\n bulkCopy.BatchSize = 500;\n bulkCopy.NotifyAfter = 1000;\n bulkCopy.SqlRowsCopied +=\n new SqlRowsCopiedEventHandler(bulkCopy_SqlRowsCopied);\n bulkCopy.DestinationTableName = \"Products_Latest\";\n bulkCopy.WriteToServer(reader);\n }\n }\n reader.Close();\n }\n}\n</code></pre>\n\n<p><strong>Solution #2: stored procedure</strong></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T17:22:53.837",
"Id": "38406",
"Score": "0",
"body": "Excellent, thanks! This is much easier. I didn't look into SqlBulkCopy because I'm only dealing with one row, but it seems this is the way to do it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T17:31:42.350",
"Id": "38408",
"Score": "0",
"body": "You could also try a stored procedure."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T17:03:09.453",
"Id": "24867",
"ParentId": "24866",
"Score": "4"
}
},
{
"body": "<p>Why not just <code>INSERT INTO newtable (SELECT * FROM UserPasswords WHERE username='System Administrator');</code>?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T02:07:33.597",
"Id": "24931",
"ParentId": "24866",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "24867",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T16:57:14.390",
"Id": "24866",
"Score": "1",
"Tags": [
"c#",
"sql",
"asp.net"
],
"Title": "Is there a simpler way to write a row from one table to another?"
}
|
24866
|
<p>I have a simple two-class hierarchy to represent U.S. ZIP (12345) and ZIP+4 (12345-1234) codes. To allow clients to allow both types for a field/parameter or restrict it to one type or the other, the specific types inherit from a common generic <code>ZipCode</code> interface.</p>
<p><strong>Update:</strong> A ZIP code is five digits. A ZIP+4 code consists of the primary five-digit ZIP code plus a four-digit plus-4 (+4) code. You can create a ZIP+4 from a regular ZIP and get the primary ZIP from a ZIP+4. Thus, the interface which the two classes implement knows about the two classes, and they know about each other.</p>
<pre><code>interface ZipCode
boolean isPlusFour()
ZipPlusFour plusFour(String code)
Zip primary()
boolean hasSamePrimary(ZipCode other)
class Zip implements ZipCode
String code
class ZipPlusFour implements ZipCode
Zip primary
String plusFourCode
</code></pre>
<p><strong>Introducing Null Object Pattern</strong></p>
<p>To avoid duplicating code that checks for null values throughout the application, I would like to introduce the <a href="http://en.wikipedia.org/wiki/Null_Object_pattern" rel="nofollow">Null Object pattern</a>. However, I'm afraid the only way to do so that supports the features above is to add three new classes instead of just one:</p>
<pre><code>class NullZipCode implements ZipCode
class NullZip extends Zip
class NullZipPlusFour extends ZipPlusFour
</code></pre>
<p>Worse, since the last two extend concrete classes they will need to pass special values to their superclass that will pass validation but not block the possibility of using real values. For example, <code>NullZip</code> would call <code>super("00000")</code>.</p>
<p>Here are my main questions, though please don't hesitate to throw out any suggestions you have.</p>
<ol>
<li>Is there a way to solve this with just one new class to cover all bases?</li>
<li><p>Is it worth extracting interfaces from <code>Zip</code> and <code>ZipPlusFour</code> so that <code>NullZip</code> won't extend the concrete <code>Zip</code> implementation (same for <code>ZipPlusFour</code>)?</p>
<pre><code>ZipCode
Zip
NullZip
RealZip
</code></pre></li>
<li><p>Another option is to forego separate classes altogether and check for a special value in <code>Zip</code> and <code>ZipPlusFour</code> to signify a missing ZIP code.</p>
<pre><code>class Zip
boolean isNone() {
return code.equals("00000");
}
boolean hasSamePrimary(ZipCode other) {
if (isNone() || other.isNone())
return false;
else
return code.equals(other.primary().code);
}
</code></pre>
<p>At least the complicated checks are encapsulated in these classes which is the whole point of introducing the pattern. The downside is that this logic can be more fragile than inheritance. Is this a good trade-off?</p></li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T20:02:01.273",
"Id": "38420",
"Score": "0",
"body": "I'm not sure I understand your interface. Why does the interface know about the concrete objects that implement it, and have functions that return both? Who is using this that they'll be able to differentiate between the two classes - other developers? This might be a place to use composition instead of inheritance. Is there ever a scenario where you would want to allow a base zipcode and *not* allow a Zip+4?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T20:36:15.333",
"Id": "38422",
"Score": "0",
"body": "@Bobson - `ZipPlusFour` is composed of a `Zip` (the *primary*) and a four-digit +4 code. You can get a ZIP+4 from a ZIP by adding a +4 code, and you can get the primary ZIP from a full ZIP+4. I'll explain this more in the question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T20:53:38.633",
"Id": "38424",
"Score": "1",
"body": "If you can always transform one into another, then why have them be separate in the first place? Just have one class, and provide a `HasPlusFour()` function to differentiate them, and a `ToString()` which returns the appropriate string representation depending on whether the +4 is there or not."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T21:01:19.803",
"Id": "38426",
"Score": "0",
"body": "@Bobson - I want clients to be able to declare via the parameter type that they accept or return a single form. A `Customer` has a `Zip` since we do not store the +4 if provided when parsing, but `Dealer` has a `ZipCode` because it may be either a ZIP or ZIP+4 code. `Phone`, on the other hand, accepts an optional extension using a single class as you describe."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T21:42:51.627",
"Id": "38433",
"Score": "0",
"body": "@DavidHarkness where are you using `boolean isPlusFour()`? Can we see some example code?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T21:58:58.060",
"Id": "38434",
"Score": "0",
"body": "@abuzittingillifirca - Only in test code. The production code places constraints on which types it accepts (sometimes) but lets the behavior be decided by the implementation. Thus it never needs to ask a ZIP code which type it is. If we merged the classes as we did with `Phone`, it would be required to perform validation checks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T22:00:27.223",
"Id": "38436",
"Score": "0",
"body": "Clearly this question is simplified with a single-class \"hierarchy\" as we have with `Phone`. Assume for the sake of this question that going that route isn't practical."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-09T07:12:43.243",
"Id": "38460",
"Score": "0",
"body": "@DavidHarkness You stated a `Customer` has a ZIP and `Dealer` has a ZIP+4, so to speak. Do you have another class, say `Address`, that has 'either' a ZIP or a ZIP+4?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-09T07:48:47.760",
"Id": "38461",
"Score": "0",
"body": "@abuzittingillifirca - Yes, as I said above, `Dealer` has a `ZipCode` to allow either a `Zip` or `ZipPlusFour`. Just take it as a given that the separate classes are required along with the interface."
}
] |
[
{
"body": "<p>This is a preliminary answer:</p>\n\n<blockquote>\n <p>Assume for the sake of this question that going that route isn't\n practical.</p>\n</blockquote>\n\n<p>Assuming this is about some group of similar value objects.\nEverything is meaningful in a context. So we need to determine what are the use cases for this object. Suppose we have the following use cases (I'm trying to guess how you could end up with the provided interfaces.):</p>\n\n<ol>\n<li>We need to display a ZipCode on screen</li>\n<li>We need to print ZipCode on envelopes</li>\n<li>We also need to lookup some external service for demographic data using the 5-digit ZIP as a key.</li>\n</ol>\n\n<p>Simplest thing that could work would then be something like:</p>\n\n<pre><code>interface ZipCode\n Zip primary() // for service lookup\n String getScreenRepresentation()\n String getPrintRepresentation()\n // you may one to use Visitor pattern \n // if you have much more different formats\n</code></pre>\n\n<p>Now we may try to design a Null Object that could work for all these situations.\nfor ZIP and ZIP+4 their implementations are straight forward.\nFor <code>NullZipCode</code> we can have <code>getScreenRepresentation</code> to return <code>\"No ZIP provided\"</code> and \n<code>getPrintRepresentation</code> to return empty string. You definitely would not want \"00000\" or some other invalid value on the label. (Unless in the improbable case that US postal service requires people put it to designate unknown ZIP, but you get what I mean)</p>\n\n<p>My criticism of the below code</p>\n\n<pre><code>interface ZipCode\n boolean isPlusFour()\n ZipPlusFour plusFour(String code)\n Zip primary()\n boolean hasSamePrimary(ZipCode other)\n\nclass Zip implements ZipCode\n String code\n\nclass ZipPlusFour implements ZipCode\n Zip primary\n String plusFourCode\n</code></pre>\n\n<p><code>isPlusFour</code> is the back door where all the null checks sneak back in.</p>\n\n<p><code>plusFour(code)</code> does not belong in the interface. It is a factory method. One sign it does not belong there is <code>Zip</code> and <code>ZipPlusFour</code> should not be able to provide different versions. </p>\n\n<p><code>hasSamePrimary</code> is unnecessary. Value objects should provide their equality, comparison, hash, display string etc. by overriding equals, hashCode etc in Java, (or deriving Show, Eq in Haskell and so on). By value object semantics; <code>zipCode1.hasSamePrimary(zipCode2)</code> <strong>should</strong> be equivalent to <code>zipCode1.primary().equals(zipCode2.primary())</code>, it is not an overridable behavior (Closed for modification principle). If it is there for brevity, it can be placed in an abstract base class or as a static method in a Utility class (or extension method if you are using C#, etc.)</p>\n\n<p>What you should do for <code>Dealer</code> class cannot be a simple interface, if it is to be a value object also.</p>\n\n<pre><code>class ZipOrZipPlusFour implements ZipCode\n //fields depend on what sort of persistence you use\n // factory methods:\n newNullZipCode()\n newZip(String code)\n newZipPlusFour(Zip primary, String ext)\n\nclass Dealer\n ZipOrZipPlusFour zipCode\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-09T08:27:40.217",
"Id": "24893",
"ParentId": "24869",
"Score": "2"
}
},
{
"body": "<p>I still don't really understand why they have to be separate classes, but here's my take on it:</p>\n\n<pre><code>interface ZipCode\n boolean isPlusFour()\n boolean hasSamePrimary(ZipCode other)\n String code\n String display\n\ninterface ZipCodePlusFour extends ZipCode\n String plusFourCode\n override String display\n boolean hasSamePlusFour(ZipCodePlusFour other)\n\nclass ZipCode implements ZipCode\n // Nothing here that isn't in the interface\nclass ZipPlusFour extends ZipCode implements ZipCodePlusFour\n // Nothing here that isn't in the interface\n\nclass NullZip implements ZipCode\n // Null responses for everything\nclass NullZipPlusFour extends NullZip implements ZipCodePlusFour\n // Null responses for everything that NullZip doesn't already do.\n</code></pre>\n\n<p>Everything in your code should either require the <code>ZipCode</code> interface or the <code>ZipCodePlusFour</code> interface. If the former, it can accept any of the four classes. If the latter, it requires the plus four bit. Since a plus four can always be downgraded to a pure zipcode, this set of inheritance will let you pass a +4 wherever you are looking for a <code>ZipCode</code>.</p>\n\n<p>Also, by always requiring the interface, rather than the concrete type, you can trivially implement the null object pattern you asked about.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T05:07:20.860",
"Id": "70320",
"Score": "0",
"body": "They are separate so I can specify that one parameter allows a +4 code while another does not. When both are acceptable, use the interface. Certainly I could use a single class and perform validation checks as you would with `nonNegativeLength`. However, compile-time checks are les prone to error than runtime validation."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T14:29:21.413",
"Id": "70400",
"Score": "0",
"body": "@DavidHarkness - It's been a long time, but I think what I meant by \"separate\" is \"not inheriting\". Having the +4 version inherit from the base one still allows you to have compile-time checking, but allows you to reuse some functionality."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-09T12:59:45.920",
"Id": "24901",
"ParentId": "24869",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T18:50:47.257",
"Id": "24869",
"Score": "3",
"Tags": [
"java",
"design-patterns",
"polymorphism",
"null"
],
"Title": "Null Object pattern with simple class hierarchy"
}
|
24869
|
<p>The goal of this was to be able to enter any number and print out the prime factors of that number. Are there any shorter ways of writing this code? I'm not very familiar with low-level syntax and was hoping somebody could give it a look. </p>
<pre><code>.text
.align 2
.globl main
main:
# compute and display the first prime numbers up to n where n is given. Set n to be 19 but the program should work of any value of n.
li $v0, 4
la $a0, prompt
syscall # call operating sys
li $v0, 5 # read keyboard into $v0 (number n is the limit)
syscall # call operating sys
move $t0,$v0 # store n in $t0
li $v0, 4 # display message to user
la $a0, message
syscall
# call operating sys
li $v0, 4
la $a0, space
syscall # call operating sys
# Load variables into registers
lw $t1, i # $t1 = i
lw $t2, k # $t2 = k
lw $t3, p # $t3 = p
lw $t5, c # $t5 = c
lw $t6, d # $t6 = d
blt $t0,$t1 L2
li $v0, 1 # print integer function call 1
move $a0, $t1 # integer to print
syscall
# call operating sys
li $v0, 4 # print new line
la $a0, space
syscall # call operating sys
#Outer loop
L2: move $t3, $zero
# Inner loop
L1: remu $t4, $t1, $t2
bne $t4, $zero, I
move $t3, $t5
I: add $t2, $t2, $t5 # increment k
blt $t2, $t1 L1
bne $t3, $zero, P
li $v0, 1 # print integer function call 1
move $a0, $t1 # integer to print
syscall
li $v0, 4 # print new line
la $a0, space
syscall # call operating sys
P: add $t1, $t1, $t5 # increment i
move $t2, $t6
bgt $t1, $t0, E
j L2
E: li $v0, 10 # system call code for exit = 10
syscall # call operating sys
end: jr $ra
.data
prompt:
.asciiz "Please enter the number you wish to find the prime numbers of : "
message:
.asciiz "The Prime Numbers are : "
space: .asciiz "\n "
#initialization of registers
i:
.word 2
p:
.word 0
k:
.word 2
c:
.word 1
d:
.word 2
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T21:11:16.633",
"Id": "38428",
"Score": "0",
"body": "does it run in MARS or what?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T22:39:07.067",
"Id": "38440",
"Score": "0",
"body": "I used PCSpim to test this"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-21T23:03:24.307",
"Id": "66721",
"Score": "0",
"body": "I'm not familiar with `remu` - is that a macro, or is it an instruction that was added more recently than I've seen MIPS?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-09T20:52:50.060",
"Id": "525193",
"Score": "0",
"body": "I'd like to know how to you keep track of the PC (program counter)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-09T21:05:59.817",
"Id": "525194",
"Score": "0",
"body": "Why did you iniatialize registers like that, and not with move instruction?"
}
] |
[
{
"body": "<p><strong>Procedures</strong></p>\n\n<ul>\n<li><p>You appear to be doing everything in <code>main</code> while just branching into single-character procedures. Consider renaming them to specify their purpose, while separating them from <code>main</code> with proper indentation and such. I cannot tell what <code>main</code> should be doing by itself. I can just see that it prompts for user input <em>and</em> operates the two loops with its procedures.</p></li>\n<li><p>Since <code>prompt</code> is done first, consider defining it above <code>main</code> instead. The end of the program should just display the result(s).</p></li>\n</ul>\n\n<p><strong>Structure</strong></p>\n\n<ul>\n<li><p>The register initializations should be placed above <code>main</code> for better visibility and maintainability.</p></li>\n<li><p>The loop labels barely stand out, and this really hurts structure. The loop procedures are all crammed together and <code>L1</code> looks like just another procedure. You could <em>at least</em> rename <code>L1</code> and <code>L2</code> to <code>Loop1</code> and <code>Loop2</code> respectively.</p></li>\n<li><p>The procedures should be properly indented to help them stay isolated.</p>\n\n<p><code>P:</code>, for instance, hardly stands out:</p>\n\n<pre><code>P: add $t1, $t1, $t5 # increment i\n\nmove $t2, $t6\n\nbgt $t1, $t0, E \nj L2\n</code></pre>\n\n<p>All of that could should be indented together and with <code>P:</code> on its own line:</p>\n\n<pre><code>P: \n add $t1, $t1, $t5 # increment i\n\n move $t2, $t6\n\n bgt $t1, $t0, E \n j L2\n</code></pre></li>\n</ul>\n\n<p><strong>Comments</strong></p>\n\n<ul>\n<li><p>The side comments here seem redundant:</p>\n\n<pre><code># Load variables into registers\nlw $t1, i # $t1 = i\nlw $t2, k # $t2 = k\nlw $t3, p # $t3 = p\nlw $t5, c # $t5 = c\nlw $t6, d # $t6 = d\n</code></pre>\n\n<p>The top comment describes this block clearly enough, whether or not the reader already knows that <code>lw</code> means <code>load word</code>. The side comments don't add anything else here.</p></li>\n<li><p>This comment is also redundant:</p>\n\n<pre><code>syscall # call operating sys\n</code></pre>\n\n<p>Unless there are some special circumstances to note, such comments do not add anything important. Readers familiar with MIPS commands will already know what this means. You <em>may</em> just mention this at the top of the program if you'd like for anyone to know what this means. Putting it with <em>every</em> call just clutters your code.</p>\n\n<p>This, on the other hand, <em>doesn't</em> state the obvious:</p>\n\n<pre><code>add $t2, $t2, $t5 # increment k\n</code></pre>\n\n<p>Without the comment, all I can tell is that this is equivalent to <code>$t2 += $t5</code>, and not that it increments <code>k</code>. These are situations where commenting on separate commands is helpful.</p></li>\n</ul>\n\n<p>Overall, this is just very hard to follow. If there are bugs in here, it would be difficult to isolate them. This, in turn, hurts maintainability. Comments alone can't help with this, either. The overall structure must be sound, otherwise fixing problems is just a matter of picking apart separate lines, one-by-one.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-03T01:55:59.483",
"Id": "40709",
"ParentId": "24874",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "40709",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T21:00:55.927",
"Id": "24874",
"Score": "6",
"Tags": [
"primes",
"assembly"
],
"Title": "Calculating prime factors in MIPS assembly"
}
|
24874
|
<p>The class does some database abstraction operations. And while I could have just used an ORM, I prefer to get my hands dirty when learning something new. There are no bugs (not as far as I know anyway) and the code is working as intended. But, since I'm learning Python, I want to make sure I'm thinking and working in the most "pythonic" way possible.</p>
<pre><code>from Singleton import Singleton;
#Singleton class implements static methods and variable required for the
#singleton design pattern
class Database(Singleton):
def __init__(self, **kwargs):
self._con = None;
self._host = kwargs['host'] if kwargs.has_key('host') else 'localhost';
self._username = kwargs['username'];
self._password = kwargs['password'];
self._dbname = kwargs['database'];
self._driver = kwargs['driver'];
#encloser characters for system identifiers(key_delim) and strings(str_delim)
self._key_delim = '"';
self._str_delim = "'";
if self._driver == 'mysql':
self._module = __import__('MySQLdb');
self._key_delim = '`';
elif self._driver == 'pgsql':
self._module = __import__('psycopg2');
else:
raise Exception("Unknown database driver");
self._affected_rows = None;
self._last_query = None;
self._insert_id = None;
self._error = None;
self._autocommit = False;
self.connect();
def __del__(self):
self.disconnect();
def connect(self):
kwargs = {'host': self._host, 'user': self._username};
if self._driver == 'mysql':
kwargs['passwd'] = self._password;
kwargs['db'] = self._dbname;
elif self._driver == 'pgsql':
kwargs['database'] = self._dbname;
kwargs['password'] = self._password;
self._con = self._module.connect(**kwargs);
def disconnect(self):
if self._con:
self._con.commit();
self._con.close();
def reconnect(self):
self.disconnect();
self.connect();
#fake connecting to the database. Useful when trying out connection parameters, e.g. during install
@staticmethod
def mock(**kwargs):
try:
d = Database(kwargs);
return true;
except Exception:
return false;
#queries the database, returning the result as a list of dicts or None, if no row found or on commands
def _query(self, s, params = None):
if isinstance(params, list):
params = tuple(params);
#need this for compatibility with manual queries using MySQL format, where the backtick is used for enclosing column names
#instead of the standard double quote. Will be removed soon
if self._driver != 'mysql':
s = self.__replace_backticks(s);
try:
cur = self._con.cursor();
cur.execute(s, params);
self._insert_id = cur.lastrowid;
self._affected_rows = cur.rowcount;
try:
results = cur.fetchall();
n = len(results);
cols = self.table_columns(None, cur);
except self._module.DatabaseError:
#INSERT/UPDATE or similar
return None;
finally:
cur.close();
retval = [];
for i in range(0,n):
aux = results[i];
row = {};
for j in range(0,len(cols)):
#elem = aux[j].decode('UTF-8') if isinstance(aux[j], basestring) else aux[j];
row[cols[j]] = aux[j];
if len(row):
retval.append(row);
return retval;
except self._module.DatabaseError as e:
#Error. Reset insert id and affected rows to None
self._insert_id = None;
self._affected_rows = None;
raise Exception("Database Error: %s" % str(e));
return retval;
#escape a variable/tuple/list
def escape(self, s):
if isinstance(s, basestring):
return self._con.escape_string(s);
elif isinstance(s, list):
return map(lambda x: self.escape(x), s);
elif isinstance(s, tuple):
return tuple(self.escape(list(s)));
else:
raise TypeException("Unknown parameter given for escaping");
#never get here
return None;
#encloses a string with single quotes
def enclose_str(self, s):
if isinstance(s, basestring):
return ''.join([self._str_delim,str(s),self._str_delim]);
elif isinstance(s, list):
return map(self.enclose_str, s);
elif isinstance(s, tuple):
return tuple(map(self.enclose_str, s));
else:
raise TypeError("Unknown argument type to enclose_str");
#encloses an identifier in the appropriate double quotes/backticks
def enclose_sys(self,s):
#we do not enclose variable containing spaces because we assume them to be expressions, e.g. COUNT(*) AS ...
#Column names containing spaces are not supported
if isinstance(s, basestring):
if s.count(' ') or s == '*':
return s;
return ''.join([self._key_delim,str(s),self._key_delim]);
elif isinstance(s, list):
return map(self.enclose_sys, s);
elif isinstance(s, tuple):
return tuple(map(self.enclose_sys, s));
else:
raise TypeError("Unknown argument type to enclose_sys");
#SELECT FROM table
def select(self, table, columns = None, where = None, op = "AND"):
if isinstance(columns, tuple):
columns = ",".join(map(lambda x: self.enclose_sys(x), columns));
elif isinstance(columns, basestring):
columns = self.enclose_sys(columns);
elif not columns:
columns = "*";
else:
raise TypeException("Invalid column definition");
(where_clause, where_params) = self.__expand_where_clause(where, op);
if not where_clause:
return self._query("SELECT %s FROM %s" % (columns, self.enclose_sys(table)));
else:
return self._query("SELECT %s FROM %s WHERE %s" % (columns, self.enclose_sys(table), where_clause), where_params);
#INSERT INTO table
def insert(self, table, values):
if isinstance(values, tuple):
values = [values];
if not isinstance(values, list):
raise TypeError("INSERT: Inappropriate argument type for parameter values");
cols = map(lambda x: self.enclose_sys(x[0]), values);
vals = tuple(map(lambda x: x[1], values));
sql = 'INSERT INTO %s(%s) VALUES (%s)' % (self.enclose_sys(table), ','.join(cols), ','.join( ['%s'] * len(vals) ));
return self._query(sql, vals);
#UPDATE table
def update(self, table, values, where = None, op = 'AND'):
if isinstance(values, tuple):
values = [values];
if not isinstance(values, list):
raise TypeError("UPDATE: Inappropriate argument type for parameter values");
cols = map(lambda x: self.enclose_sys(x[0])+'=%s', values);
vals = tuple(map(lambda x: x[1], values));
(where_clause, where_params) = self.__expand_where_clause(where, op);
if where_clause:
return self._query('UPDATE %s SET %s WHERE %s' % (self.enclose_sys(table), ','.join(cols), where_clause), list(vals) + list(where_params));
else:
return self._query('UPDATE %s SET %s' % (self.enclose_sys(table), ','.join(cols)), vals);
#DELETE FROM table
def delete(self, table, where = None, op = 'AND'):
(where_clause, where_params) = self.__expand_where_clause(where, op);
if where_clause:
return self._query("DELETE FROM %s WHERE %s" % (self.enclose_sys(table), where_clause), where_params);
else:
return self._query("DELETE FROM %s" % (self.enclose_sys(table)));
#upsert and merge perform the same task, having the same end result.
#The difference is that the former is optimised to work on data where usually little new rows are added
#while the latter is optimised in the case the majority of the data dealt with will be added, not already existing
def upsert(self, table, values, where):
self.update(table, values, where);
if not self.affected_rows():
self.insert(table, [values] + [where]);
def merge(self, table, values, where):
try:
self.insert(table, [values] + [where]);
except self._module.DatabaseError as e:
#TODO: Check error in case it's not due to a PK/Unique violation
self.update(table, values, where);
#Returns a row, instead of simply a list of 1. Inspired by Wordpress
def get_row(self, table, columns = None, where = None, op = "AND"):
r = self.select(table, columns, where, op);
return r[0] if r else None;
#Returns a variable. Useful for quick counts or returning of an id, for example. Inspired by Wordpress
def get_var(self, table, columns = None, where = None, op = "AND"):
r = self.select(table, columns, where, op);
return r[0].items()[0][1] if r else None;
#Count the rows of a table
def count(self, table, column, value = None):
where = (column, value) if value else None;
return self.get_var(table, 'COUNT(*) AS %s' % (self.enclose_sys('cunt')), where);
def drop(self):
self._query("DROP DATABASE " + self._dbname);
def create(self):
self._query("CREATE DATABASE " + self._dbname);
def purge(self):
#only works in MySQL, must find alternative for Postgres
self.drop();
self.create();
def truncate(self, table_name):
self._query("TRUNCATE TABLE " + self.enclose_sys(table_name));
#wrappers around transaction management functions
def commit(self):
self._con.commit();
def rollback(self):
self._con.rollback();
def autocommit(self, val):
self._autocommit(bool(val));
#getters...
def affected_rows(self):
return self._affected_rows;
def insert_id(self):
return self._insert_id;
def __is_escaped(self, s, pos):
for char in ["'", "\\"]:
j = pos - 1;
count = 0;
#count back the num. of appearances of certain char
while (j>=0 and s[j] == char):
j-=1;
count+=1;
#reduce the count in cases like \'' ,where the last ' to the left is escaped by 1 or more \
if (char == "'" and count and self.__isEscaped(s, pos-count)):
count-=1;
if (count):
break;
return True if (count % 2) else False;
#replaces MySQL style `backticks` with "double quotes", as per SQL standard.
#Required in order to support MySQL queries containing backticks
def __replace_backticks(self, str):
s = list(str);
delim = None;
inside = False;
for i in range(0, len(s)):
#only working on important characters
if (s[i] not in ['"',"'","`"]):
continue;
if inside:
if (s[i] == '`' or s[i] != delim): #if we encounter a wrong token, simply continue
continue;
if not self.__is_escaped(s, i):
inside = False;
delim = None;
else:
if s[i] == '`':
s[i] = '"';
continue;
if not self.__is_escaped(s, i):
inside = True;
delim = s[i];
return "".join(s);
#helper function, expands a tuple/list of tuples containing where parameters to string
def __expand_where_clause(self, where, op):
params = [];
clauses = [];
if where:
if isinstance(where, tuple):
where = [where];
if not isinstance(where, list):
raise TypeException("Unknown type for WHERE clause argument");
if where:
for clause in where:
clause_op = clause[2] if len(clause)==3 else '=';
clauses.append(self.enclose_sys(clause[0]) + (" %s " % clause_op) + '%s');
params.append(clause[1]);
where_clause = (' %s ' % op).join(clauses);
return (where_clause, tuple(params) if len(params) else None);
#returns an array containing the names of the columns of a table
def table_columns(self, table_name = None, cur = None):
if not cur:
try:
cur = self._con.cursor();
cur.execute("SELECT * FROM " + table_name + " LIMIT 1");
cur.close();
except self._module.DatabaseError as e:
raise Exception("Database Error: %s" % str(e));
cols = map(lambda x: x[0], cur.description);
return cols;
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T16:48:17.287",
"Id": "462076",
"Score": "0",
"body": "Glancing through, I don't quite see your rationale of using `**kwargs**` If `_username` and others are mandatory fields, why not just have the argument explicitly passed through the constructor?"
}
] |
[
{
"body": "<p>There's quite a lot of code so I'm going to comment only this small piece of code :</p>\n\n<pre><code>results = cur.fetchall();\nn = len(results);\ncols = self.table_columns(None, cur);\nretval = [];\nfor i in range(0,n):\n aux = results[i];\n row = {};\n for j in range(0,len(cols)):\n row[cols[j]] = aux[j];\n if len(row):\n retval.append(row);\nreturn retval\n</code></pre>\n\n<ol>\n<li>You don't need <code>;</code> at the end of the lines</li>\n<li>The best way to iterate on <code>something</code> in Python is via <code>for element in something</code> (or <code>for element,index in enumerate(something)</code> if you need the index).</li>\n<li>You can use the fact that the boolean evaluation of an empty container is false to write <code>if row</code> instead of <code>if len(row)</code>.</li>\n</ol>\n\n<p>Your code is now :</p>\n\n<pre><code>results = cur.fetchall();\ncols = self.table_columns(None, cur);\nretval = [];\nfor res in results:\n row = {};\n for col,j in enumerate(cols):\n row[col] = res[j];\n if row:\n retval.append(row);\nreturn retval\n</code></pre>\n\n<p>Now, you can create your <code>row</code> dictionnary direclty from <code>res</code> and <code>cols</code> (other solutions can be found <a href=\"https://stackoverflow.com/questions/209840/map-two-lists-into-a-dictionary-in-python\">on SO</a>):</p>\n\n<pre><code>results = cur.fetchall();\ncols = self.table_columns(None, cur);\nretval = [];\nfor res in results:\n row = dict(zip(cols,res))\n if row:\n retval.append(row);\nreturn retval\n</code></pre>\n\n<p>Now, there would be a way to make the whole thing a single expression using list comprehension but I am not quite sure this is a good idea.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T23:08:16.350",
"Id": "24879",
"ParentId": "24875",
"Score": "1"
}
},
{
"body": "<ol>\n<li><p>Comments like <code># Will be removed soon</code> make me think that this isn't really ready for review. It's best to fix all the problems you know about before submitting for review.</p></li>\n<li><p>There's no documentation. How is anyone supposed to use this? For example, what arguments should one pass to the constructor? What kind of object do I pass in if I want a <code>where</code> clause?</p></li>\n<li><p>Why inherit from <code>Singleton</code>? Does this mean I can't connect to more than one database? Isn't that a problem?</p></li>\n<li><p>There are <a href=\"http://en.wikipedia.org/wiki/SQL_injection\" rel=\"nofollow\">SQL injection vulnerabilities</a> everywhere, because <code>enclose_sys()</code> doesn't escape its argument if it contains a space. For example, if I run:</p>\n\n<pre><code> db = Database(username='foo', password='bar', database='mydb', driver='mysql')\n db.select('table', ('1; drop database; select *',))\n</code></pre>\n\n<p>then this issues the query</p>\n\n<pre><code> SELECT 1; drop database; select * FROM `table`\n</code></pre></li>\n<li><p>There's no separation of driver code into its own class. If I want to add a new backend (e.g. SQLite) how do I do it?</p></li>\n<li><p>Your <code>upsert()</code> method doesn't take advantage of the capability of some databases to do it in a single query, for example <a href=\"http://dev.mysql.com/doc/refman/5.1/en/insert-on-duplicate.html\" rel=\"nofollow\"><code>INSERT ... ON DUPLICATE KEY UPDATE</code></a> in MySQL.</p></li>\n<li><p>In <code>disconnect()</code> you don't clear <code>self._con</code>, so calling <code>disconnect()</code> twice will cause you to close the connection twice.</p></li>\n<li><p>It's better to write <code>values = list(values)</code> instead of testing <code>isinstance(values, list)</code> and then raising an exception if it's not. The former can accept iterators and generators.</p></li>\n<li><p>In <code>select()</code>, why does the <code>columns</code> argument have to be a tuple? Why not a list?</p></li>\n<li><p>Basically <code>if isinstance(arg, type1): ... elif isinstance(arg, type2): ...</code> is an anti-pattern in Python. It usually means that your interface is poorly thought out and you are trying to overload the meaning of your parameter. Better to choose a single type for each parameter.</p></li>\n<li><p>You <code>raise TypeException</code> in various places, but there is no such exception in Python. Presumably this is a typo for <code>TypeError</code>, but it suggests that you have never tested these error paths.</p></li>\n<li><p>Your <code>_query()</code> method always returns its results as a list of dictionaries, thus reading the entire result set into memory. This defeats the whole point of having database cursors, which is that the application can process records one at a time as they are returned from the database. This allows the application to proceed in parallel with the database, and avoids filling memory unnecessarily.</p></li>\n<li><p>It's not very portable to Python 3: <code>kwargs.has_key('host')</code>, <code>basestring</code>.</p></li>\n<li><p>You use Python's <a href=\"http://docs.python.org/2/tutorial/classes.html#private-variables-and-class-local-references\" rel=\"nofollow\">private variables</a> in a couple of places: <code>__is_escaped</code>, <code>__expand_where_clause</code>, <code>__replace_backticks</code>. This makes it impossible to test or experiment with these methods. You should use private variables only when you absolutely have to to avoid name clashes.</p></li>\n<li><p>There's a method <code>enclose_str</code> but it does not seem to be called.</p></li>\n<li><p>Many more problems which I have not the will to type up ... basically this is far from ready for anyone to use.</p></li>\n</ol>\n\n<p>Responding to your comments:</p>\n\n<ul>\n<li><p>To #3, you say, \"I needed a way to pass a 'main' database connection to other modules\". But this doesn't explain why <code>Database</code> inherits from <code>Singleton</code>. Why can't you just write:</p>\n\n<pre><code>main_db = Database(...)\n</code></pre>\n\n<p>and then pass <code>main_db</code> to the other modules? You should beware of letting a local concern (your program needs a main database connection) influence the design of a module that is supposed to be general.</p>\n\n<p>You go on to say, \"you can have how many you instances you like\". But in the <a href=\"http://en.wikipedia.org/wiki/Singleton_pattern\" rel=\"nofollow\">singleton pattern</a> there can be at most <em>one</em> instance of the class. Hence the name. So I don't understand this remark.</p></li>\n<li><p>To #4, you indicate that you don't think it's the responsibility of your class to avoid SQL injection attacks. That's fair enough, but one of the most important reasons to use an object-relational mapping system is that it takes care of this task, which is difficult and tedious to get right.</p></li>\n<li><p>To #10, you say, \"I'd rather have it take multiple types and return multiple types than write 3 separate functions.\" Yes, of course, as an implementor you want to make things easy for yourself. But I'm looking at your code from the perspective of a user or maintainer, and I would prefer interfaces to be simple and easy to understand.</p>\n\n<p>In any case, how hard is it to write:</p>\n\n<pre><code>def escape_list(self, seq):\n \"\"\"Escape all the elements in seq, and return them as a list.\"\"\"\n return map(self.escape, seq)\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-09T01:31:53.147",
"Id": "38449",
"Score": "0",
"body": "First, thanks for the answer. Since I'm a bit of a newbie, this helps a lot. All of your points are valid, though I'd like to discuss a few\n3.I needed a way to pass a \"main\" database connection to other modules. Appart from that, you can have how many you instances you like.\n4. enclose_sys doesn't escape **any** parameter. If one needs the marginal case of allowing users access to the structure of the table, he should do the escaping himself(should be written in the docs though).\n10.E.g.\"escape\", I'd rather have it take multiple types and return multiple types than write 3 separate functions."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-09T10:35:44.503",
"Id": "38474",
"Score": "0",
"body": "3.Singleton is an bad name choice, I do agree, but I couldn't find a better one. It's more of a \"main/default instance, but allow instantiation through the constructor as well if you need another\". The whole Singleton class itself is just a bunch of static methods anyway(get/set/clear).\n4.Yes it is, but I've yet to hear of escaping system identifiers(column names). Solved it by removing whitespace check & raising when I encounter a \" character.\n10.I'm not lazy, I just thought it was a more elegant solution. E.g. the list function, which does 2 things(unpacks if iterable, list of 1 if not)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T23:33:33.997",
"Id": "24880",
"ParentId": "24875",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "24880",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T22:34:04.393",
"Id": "24875",
"Score": "1",
"Tags": [
"python",
"database"
],
"Title": "Database abstraction class"
}
|
24875
|
<p>I recently built an improved version of a bank account program I made. It has no GUI or any interaction with users, but I simply built it to test it and play with it via <code>main()</code>. I'll post all my classes below and you can run the program yourself or just critique my code. I'll take any and all suggestions, so please leave corrections that you see (this code will most likely be rough, as I'm a beginner programmer altogether, but I'm still learning a lot).</p>
<p><code>Bank</code> Class:</p>
<pre><code>package improvedBank;
import java.util.*;
public class Bank {
public static ArrayList<Account> bankAccounts = new ArrayList<Account>();
static int time = 0;
int bankCash = 0;
public ArrayList<Account> addAcc(Account acc) {
bankAccounts.add(acc);
return bankAccounts;
}
public static void passTime(Account acc) {
time += 1;
acc.getInterest();
}
// testing code, not sure how to implement user control yet :/
public static void main(String[] args) {
Bank myBank = new Bank();
BusinessAccount billsAccount = new BusinessAccount("Bill's Donut Shop", "Bill", 372);
BusinessAccount joesAccount = new BusinessAccount("Joe's Italian Restaurant", "Joe", 568);
SavingsAccount dillonsAccount = new SavingsAccount("Dillon", 57);
SavingsAccount jessicasAccount = new SavingsAccount("Jessica", 72);
myBank.addAcc(billsAccount);
myBank.addAcc(joesAccount);
myBank.addAcc(dillonsAccount);
myBank.addAcc(jessicasAccount);
billsAccount.deposit(37);
System.out.println(bankAccounts);
dillonsAccount.withdraw(12);
jessicasAccount.deposit(12);
billsAccount.withdraw(4);
System.out.println(bankAccounts);
}
}
</code></pre>
<p><code>Account</code> class (abstract class):</p>
<pre><code>package improvedBank;
public abstract class Account {
public String accountType;
public String owner;
public int balance;
public int timeOpened;
public int getInterest() {
int newBal = (int) (balance * 0.15);
balance += newBal;
timeOpened += 1;
return balance & timeOpened;
}
public int deposit(int amount) {
Bank.passTime(this);
return balance += amount;
}
public int withdraw(int amount) {
Bank.passTime(this);
return balance -= amount;
}
public String toString() {
return "Account Type: " + this.accountType + " | Account owner: " + this.owner + " | Account balance: $" + this.balance + " | Account active for: " + timeOpened + " days";
}
}
</code></pre>
<p><code>SavingsAccount</code> class (extends <code>Account</code> class):</p>
<pre><code>package improvedBank;
public class SavingsAccount extends Account {
public SavingsAccount(String own, int cash) {
this.accountType = "Savings Account";
this.owner = own;
this.balance = cash;
System.out.println("Savings account created.");
Bank.passTime(this);
return;
}
}
</code></pre>
<p><code>BusinessAccount</code> class (also extends <code>Account</code> class):</p>
<pre><code>package improvedBank;
public class BusinessAccount extends Account {
String businessName;
public BusinessAccount(String bizName, String own, int cash) {
this.accountType = "Business Account";
this.businessName = bizName;
this.owner = own;
this.balance = cash;
System.out.println("Business account created");
Bank.passTime(this);
return;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Over-all, you say you are a beginner programmer, but you are off to a very nice start! All my suggestions focus around one concept: the Interface.\nYou are definitely ready to read <a href=\"http://www.informit.com/articles/article.aspx?p=1216151&seqNum=2\" rel=\"nofollow noreferrer\">Joshua Bloch's \"Effective Java 2nd Edition\"</a> which is all about creating great interfaces.</p>\n\n<p>+1 using generics with collections</p>\n\n<p>-1 import wildcard - Though it's a pain, you should really <a href=\"https://stackoverflow.com/questions/147454/why-is-using-a-wild-card-with-a-java-import-statement-bad\">specify each import</a>.</p>\n\n<h1>Prefer interfaces for return types:</h1>\n\n<p>OK:</p>\n\n<pre><code>public ArrayList<Account> addAcc(Account acc)...\n</code></pre>\n\n<p>Better:</p>\n\n<pre><code>public List<Account> addAcc(Account acc)...\n</code></pre>\n\n<p>Now you can use any kind of List without breaking client code. Heck if you can get away with it, it gives you even more freedom to use:</p>\n\n<pre><code>public List<Collection> addAcc(Account acc)...\n</code></pre>\n\n<h1>Careful with Static...</h1>\n\n<p>Static means this variable exists on the Bank class instead of having one for each object (instance). I think you want one list of accounts <em>for each</em> Bank which means you don't want Static.</p>\n\n<h1>Prefer Private to Public</h1>\n\n<p>Public means all clients can access it. </p>\n\n<p>Not so good:</p>\n\n<pre><code>public static ArrayList<Account> bankAccounts = new ArrayList<Account>();\n</code></pre>\n\n<p>Private means you have to provide get/set methods for users of your API to access this variable. Final means you can never create a new ArrayList for bankAccounts.</p>\n\n<pre><code>private final List<Account> bankAccounts = new ArrayList<Account>();\n</code></pre>\n\n<h1>Favor Interfaces over Inheritance</h1>\n\n<p>They are a little more work up front, but inheritance forces you to make variables and constructors protected instead of private. But if you want to use inheritance, then give Account a constructor to take on some of the work:</p>\n\n<pre><code>public abstract class Account {\n private String owner; // person or business\n private int balance;\n\n protected Account(String own, int cash) {\n owner = own; balance = cash;\n }\n\n public String getOwner() { return owner; }\n public void setOwner(String own) { owner = own; }\n\n public int getBalance() { return balance; }\n public void setBalance(int cash) { balance = cash; }\n\n public abstract String getAccountType();\n\n public String toString() {\n return new StringBuilder(\"Account Type: \")\n .append(this.getAccountType())\n .append(\" | Account owner: \").append(this.owner)\n .append(\" | Account balance: $\").append(this.balance)\n .append(\" | Account active for: \").append(timeOpened)\n .append(\" days\").toString();\n }\n ...\n</code></pre>\n\n<p>You notice I use a StringBuilder instead of string concatenation with plus. This can make a big speed and memory difference if the concatenation is ever done in a loop. In some situations what you did is OK, but I'm not sure about this one. Better safe than sorry.</p>\n\n<p>Then:</p>\n\n<pre><code>public class SavingsAccount extends Account {\n public final static String SAVINGS_ACCOUNT = \"Savings Account\";\n public SavingsAccount(String own, int cash) {\n // Call account constructor...\n super(own, cash);\n ...\n }\n public String getAccountType() { return SAVINGS_ACCOUNT; }\n}\n</code></pre>\n\n<p>This assumes you are going to add functionality to the individual Account sub-classes. If not, just make AccountType an enum inner class of Account:</p>\n\n<pre><code>public abstract class Account {\n public enum AccountType {\n PERSONAL(\"Savings Account\"), \n BUSINESS(\"Business Account\");\n private final String name;\n AccountType(String n) { name = n; }\n public String getName() { return name; }\n }\n private String owner;\n private int balance;\n private AccountType type;\n protected Account(String own, int cash, AccountType t) {\n owner = own; balance = cash; type = t;\n }\n ...\n}\n</code></pre>\n\n<h1>Interest Calculation</h1>\n\n<p>I think your interest calculation is done for fun, but having worked for a bank, it is a little disturbing. :-) For one thing, I can get very rich by just making repeated withdrawls and deposits to increment the time counter. For another, I can create a second bank Bank getRich = new Bank(); Every transaction I make there, affects all accounts at myBank because time is static, thus has a single copy on the Bank class, not on the individual Bank object instances.</p>\n\n<p>Worse yet, Bank.time is public, so without making a new bank, I can just call Bank.time = (Integer.MAX_VALUE - 1) - (myAccount.balance * 0.15); Then call myAccount.getInterest(); myAccount.withdraw(myAccount.balance);</p>\n\n<h1>Conclusion</h1>\n\n<p>Over-all, you are well on your way to becoming a great programmer. A code review necessarily focuses on the things you should change, but this is an excellent beginner effort. Actually, I think you are being humble calling yourself a beginner.</p>\n\n<p>To take it to the next level, I'd recommend you read Josh's book or find other sources for API design. The more you can make private, the less you can expose for clients of your API, the easier it is to make changes to your implementation down the road, and the fewer problems they'll have with it. Good luck!</p>\n\n<h1>P.S.</h1>\n\n<p>I'd recommend you spend some time with JavaDoc. Not only is it good to comment your code in general, but it makes you focus on the way someone else will view your classes - makes you view your work as an API. When I read my own generated JavaDocs, I always have, \"Oh, that's public? That's accessible?\" moments that end up making my code better.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-09T09:33:41.377",
"Id": "38472",
"Score": "0",
"body": "Wow, thanks for the great advice! You have no idea how much that means to me as a programmer. All the things you recommended are things that I'm learning about in the books I'm reading, so I'll make sure to bookmark this and take a look at your advice If I'm confused or need help. Thanks again, really. :D"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-09T10:18:36.630",
"Id": "38473",
"Score": "0",
"body": "Oh, and yes, I know how crappy the actual 'simulation of a bank' is implemented, but I know very little about finance, so I did five minutes of research on banks and used that. Thanks again."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T12:09:43.757",
"Id": "38557",
"Score": "0",
"body": "Glad I could help. Please notice I added a P.S. section in my answer suggesting that you spend some time playing with JavaDoc."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-09T03:35:34.273",
"Id": "24885",
"ParentId": "24877",
"Score": "14"
}
}
] |
{
"AcceptedAnswerId": "24885",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T23:04:12.337",
"Id": "24877",
"Score": "3",
"Tags": [
"java",
"beginner",
"finance"
],
"Title": "Virtual bank program"
}
|
24877
|
<p>I have started working with Cassandra database recently and I was trying to insert some data into one of my column family that I have created. Below is the code by which I am trying to insert into Cassandra database.</p>
<p>In my case I have around <code>20 columns</code> in my column family so that means I need to add below line</p>
<pre><code>mutator.newColumn("Column Name", "Column Value");
</code></pre>
<p><strong>Twenty times</strong> in my below code which looks ugly to me. Is there any way, I can simplify the below method either by using reflection or some other way so that If I have more than 20 columns, I should not keep on adding extra line in my below code.</p>
<pre><code>for (int userId = id; userId < id + noOfTasks; userId++) {
Mutator mutator = Pelops.createMutator(thrift_connection_pool);
mutator.writeColumns(column_family, String.valueOf(userId),
mutator.newColumnList(
mutator.newColumn("a_account", "{\"lv\":[{\"v\":{\"regSiteId\":null,\"userState\":null,\"userId\":" + userId + "},\"cn\":1}],\"lmd\":20130206211109}"),
mutator.newColumn("a_advertising", "{\"lv\":[{\"v\":{\"regSiteId\":null,\"userState\":null,\"userId\":" + userId + "},\"cn\":1}],\"lmd\":20130206211109}"),
mutator.newColumn("a_avg_selling_price_main_cats", "{\"lv\":[{\"v\":{\"regSiteId\":null,\"userState\":null,\"userId\":" + userId + "},\"cn\":1}],\"lmd\":20130206211109}"),
mutator.newColumn("a_cat_and_keyword_rules", "{\"lv\":[{\"v\":{\"regSiteId\":null,\"userState\":null,\"userId\":" + userId + "},\"cn\":1}],\"lmd\":20130206211109}"),
mutator.newColumn("a_csa_categories_purchased", "{\"lv\":[{\"v\":{\"regSiteId\":null,\"userState\":null,\"userId\":" + userId + "},\"cn\":1}],\"lmd\":20130206211109}"),
mutator.newColumn("a_customer_service", "{\"lv\":[{\"v\":{\"regSiteId\":null,\"userState\":null,\"userId\":" + userId + "},\"cn\":1}],\"lmd\":20130206211109}"),
mutator.newColumn("a_demographic", "{\"lv\":[{\"v\":{\"regSiteId\":null,\"userState\":null,\"userId\":" + userId + "},\"cn\":1}],\"lmd\":20130206211109}"),
mutator.newColumn("a_favorite_searches", "{\"lv\":[{\"v\":{\"regSiteId\":null,\"userState\":null,\"userId\":" + userId + "},\"cn\":1}],\"lmd\":20130206211109}"),
mutator.newColumn("a_favorite_sellers", "{\"lv\":[{\"v\":{\"regSiteId\":null,\"userState\":null,\"userId\":" + userId + "},\"cn\":1}],\"lmd\":20130206211109}"),
mutator.newColumn("a_financial", "{\"lv\":[{\"v\":{\"regSiteId\":null,\"userState\":null,\"userId\":" + userId + "},\"cn\":1}],\"lmd\":20130206211109}")
mutator.newColumn(some othe column, its value)
.....
.....
.....
));
mutator.execute(ConsistencyLevel.ONE);
}
</code></pre>
<p>Any help in simplifying the above method will be of great help to me. I was thinking of using a <code>Constant</code> class file like below which will have below methods for each column:</p>
<pre><code>public static void setAccount_epu(final Mutator mutator, final int userId) throws SQLException {
final String A_ACCOUNT = "{\"lv\":[{\"v\":{\"regSiteId\":null,\"userState\":null,\"userId\":" + userId + "},\"cn\":1}],\"lmd\":20130206211109}";
mutator.newColumn("a_account", A_ACCOUNT);
}
public static void setAdvertising_epu(final Mutator mutator, final int userId) throws SQLException {
final String A_ADVERTISING = "{\"lv\":[{\"v\":{\"thirdPartyAdsOnEbay\":null,\"ebayAdsOnThirdParty\":null,\"userId\":" + userId + "},\"cn\":2}],\"lmd\":20130206211109}";
mutator.newColumn("a_advertising", A_ADVERTISING);
}
public static void setClv_info_epu(final Mutator mutator, final int userId) throws SQLException {
final String A_CLV_INFO = "{\"lv\":[{\"v\":{\"tenureSiteReg\":null,\"bghtItms\":48,\"pnlValue\":105.478409,\"byrSgmnt\":2,\"cstmrId\":\"814296998\",\"slrRevRnk\":-99.0,\"soldItms\":0,\"slrSgmnt\":6,\"byrRevRnk\":0.013,\"mainAcct\":78,\"gmv\":0.0,\"cstmrRevRnk\":0.021,\"pnlRev\":313.438843,\"cstmrSgmnt\":51,\"gmb\":4674.76,\"totalVal\":142.536293,\"userId\":" + userId + "},\"cn\":42}],\"lmd\":20130206212543}";
mutator.newColumn("a_clv_info", A_CLV_INFO);
}
public static void setClv_behavior_epu(final Mutator mutator, final int userId) throws SQLException {
final String A_CLV_BEHAVIOR = "{\"lv\":[{\"v\":{\"behaviorInfo\":\"111:0.56,113:0.33,116:0.10,118:0.03,117:0.00,69:0.00,73:0.00,115:0.00,108:0.00\",\"usrId\":1001116884,\"userId\":" + userId + "},\"cn\":41}],\"lmd\":20130206212543}";
mutator.newColumn("a_clv_behavior", A_CLV_BEHAVIOR);
}
public static void setClv_churn_epu(final Mutator mutator, final int userId) throws SQLException {
final String A_CLV_CHURN = "{\"lv\":[{\"v\":{\"churnPrdctvDecileNum\":9,\"churnPrdctvScoreVal\":671.38116,\"userId\":" + userId + "},\"cn\":44}],\"lmd\":20130206212543}";
mutator.newColumn("a_clv_churn", A_CLV_CHURN);
}
</code></pre>
<p>Can I then use some reflection around that?</p>
|
[] |
[
{
"body": "<p>It looks like the pattern is alway the same, I am right? Then you could just do:</p>\n\n<pre><code>String commonColumnValue = \"{\\\"lv\\\":[{\\\"v\\\":{\\\"regSiteId\\\":null,\\\"userState\\\":null,\\\"userId\\\":\" + userId + \"},\\\"cn\\\":1}],\\\"lmd\\\":20130206211109}\"\nString[] columns = {\"a_account\", \"a_advertising\", ..., \"a_financial\"} //extend by your needs\n\nfor(String columnsItem : columns)\n mutator.newColumn(columnsItem, commonColumnValue);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-09T19:44:38.543",
"Id": "38500",
"Score": "0",
"body": "No that is for demonstration purpose. In general it will be different for all the columns."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T04:22:39.130",
"Id": "38510",
"Score": "3",
"body": "ok. How should we help, if we do not know the code? I do not understand the question then."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-09T18:15:00.643",
"Id": "24915",
"ParentId": "24878",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "24915",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-08T23:05:19.587",
"Id": "24878",
"Score": "2",
"Tags": [
"java",
"cassandra"
],
"Title": "Inserting data into column family"
}
|
24878
|
<p>I'm trying to create a wordpress plugin but checking for the existence of a value doesn't really feel right because there's a bunch of values that I have to check:</p>
<pre><code>$flickr_key = '';
if(!empty($ecom['ecom_options_flickr_api'])){
$flickr_key = $ecom['ecom_options_flickr_api'];
}
$flickr_secret = '';
if(!empty($ecom['ecom_options_flickr_secret'])){
$flickr_secret = $ecom['ecom_options_flickr_secret'];
}
$freebase_key = '';
if(!empty($ecom['ecom_options_freebase_api'])){
$freebase_key = $ecom['ecom_options_freebase_api'];
}
$ebay_key = '';
if(!empty($ecom['ecom_options_ebay_api'])){
$ebay_key = $ecom['ecom_options_ebay_api'];
}
</code></pre>
<p>Is there a more elegant alternative for this?</p>
|
[] |
[
{
"body": "<p><strong>Using ternary operators to removed un-necessary lines</strong></p>\n\n<p>Well you could use the <a href=\"http://www.php.net/manual/en/function.isset.php\" rel=\"nofollow noreferrer\">function isset</a> with the use of <a href=\"http://php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary\" rel=\"nofollow noreferrer\">ternary operators</a> in order to make the code more concise.</p>\n\n<p>I would do the following : </p>\n\n<pre><code>$flickr_key = isset($ecom['ecom_options_flickr_api']) ? $ecom['ecom_options_flickr_api'] : '' ;\n$flickr_secret = isset($ecom['ecom_options_flickr_secret']) ? $ecom['ecom_options_flickr_secret']; '';\n$freebase_key = isset($ecom['ecom_options_freebase_api']) ? $ecom['ecom_options_freebase_api'] : '';\n$ebay_key = isset($ecom['ecom_options_ebay_api']) ? $ecom['ecom_options_ebay_api'] : '';\n</code></pre>\n\n<hr>\n\n<p><strong>Reducing the code :</strong></p>\n\n<p>Well that is still ugly so you could make a function of it to reduce repetition of the array keys and to have something easier to read.</p>\n\n<pre><code>//You pass the reference of the supposed key\n//Since you passe the reference, there will be no notice.\nfunction assign(& $value $default = null){ \n return isset($value) ? $value : $default;\n}\n// then use like\n$flicker_key = assign($ecom['ecom_options_flickr_api'], '');\n</code></pre>\n\n<p>For more information see the <a href=\"https://stackoverflow.com/questions/5836515/what-is-the-php-shorthand-for-print-var-if-var-exist/5836648#5836648\">following Stack Overflow post</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-09T02:43:14.643",
"Id": "38454",
"Score": "0",
"body": "the second method is nice but I'm still getting notices that the index doesn't exists when I do it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-09T02:47:39.393",
"Id": "38455",
"Score": "0",
"body": "@leyasu What version of php are you using? And what do you mean by motices? I've been able to run it just fine on my localhost!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-09T03:27:06.420",
"Id": "38456",
"Score": "0",
"body": "I'm using PHP version 5.4.9. I'm getting this: `Notice: Undefined index: ecom_options_flickr_api`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-09T05:21:22.193",
"Id": "38457",
"Score": "0",
"body": "Using ternary operator with array will copy the full array before executing the statement so with a large array it will be slow. With simply ternary operator this code wil give you E_NOTICE if the index doesn't exists no matter what PHP version is it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-09T12:42:00.263",
"Id": "38480",
"Score": "0",
"body": "@PeterKiss Alright I've removed the second part, since it was throwing a notice, and that's not clean. Thank you for the feedback"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-09T02:13:27.233",
"Id": "24883",
"ParentId": "24882",
"Score": "1"
}
},
{
"body": "<p>As <a href=\"https://codereview.stackexchange.com/users/15555/hugo-dozois\">Hugo Dozois</a> suggested, using <code>isset</code> with the ternary operator is a good way to do this.</p>\n\n<p>If you can assume that the options have not been set to <code>NULL</code> or <code>false</code> and you can change the <code>$ecom</code> variable you can use <a href=\"http://php.net/manual/en/function.array-merge.php\" rel=\"nofollow noreferrer\"><code>array_merge</code></a> or the <a href=\"http://php.net/manual/en/language.operators.array.php\" rel=\"nofollow noreferrer\"><code>union</code></a> operator.</p>\n\n<pre><code>// Merge with your default values here.\n$ecom += array('ecom_options_flickr_api' => '',\n 'ecom_options_flickr_secret' => '',\n 'ecom_options_freebase_api' => '',\n 'ecom_options_ebay_api' => '');\n\n// Set the variables.\n$flickr_key = $ecom['ecom_options_flickr_api']; \n$flickr_secret = $ecom['ecom_options_flickr_secret'];\n$freebase_key = $ecom['ecom_options_freebase_api'];\n$ebay_key = $ecom['ecom_options_ebay_api'];\n</code></pre>\n\n<p>If they could be NULL or false you could set them using a short ternary as Hugo Dozois mentioned. The indexes will now be set thanks to the <code>union</code> so you won't get Notices for undefined indexes.</p>\n\n<h2>Other Suggestions</h2>\n\n<ul>\n<li><p>I think your structure would be better represented as a multidimensional array:</p>\n\n<p>$ecom['options'] = array('flickr_api' => '',\n 'flickr_secret' => 'etc.');</p></li>\n<li><p>Often intermediary variables such as <code>$flickr_secret</code> etc. are a bad idea IMO. I prefer to use <code>$ecom['options']['flickr_secret']</code> in my code. I find aliases normally just confuse the code.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-09T04:09:27.643",
"Id": "24886",
"ParentId": "24882",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-09T01:36:17.680",
"Id": "24882",
"Score": "1",
"Tags": [
"php"
],
"Title": "Alternative for checking the existence of a value in PHP"
}
|
24882
|
<p>There are not many available resources for refactoring go code. I'm a novice gopher who would appreciate any feedback on a small program which reads a .csv file, string converts and parses a few rows in order to perform a sub method. </p>
<pre><code>package main
import (
"encoding/csv"
"fmt"
"io"
"log"
"os"
"strconv"
)
const file = "csvdata/csvtest.csv"
// what should stay in main()? What should be refactored?
func main() {
f, err := os.Open(file)
if err != nil {
log.Fatalf("Error reading all lines: %v", err)
}
defer f.Close()
reader := csv.NewReader(f)
reader.Comma = ';'
for {
record, err := reader.Read()
if err == io.EOF {
break
} else if err != nil {
log.Print(err)
os.Exit(-1)
}
// need to refactor variables, could I use a type struct?
var num string = (record[2])
var name string = (record[3])
var eia string = (record[5])
var cia string = (record[6])
var inc_percent = (record[7])
var estIncTxn string = (record[8])
var inc_diff float64
// I would like to turn this chunk into it's own function
for i := 0; i < len(record[i]); i++ {
estInc, err := strconv.ParseFloat(eia, 64)
actInc, err := strconv.ParseFloat(cia, 64)
inc_diff = (actInc - estInc)
if err == nil {
//How could I turn the following into a template?
fmt.Println("============================================================\n")
fmt.Printf("Account: %+s - %+s exceeded the IncAmt by %+v same as $%+v\n", num, name, inc_percent, inc_diff)
fmt.Printf("over the monthly incoming amount of $%+v. Currently, the declared\n", actInc)
fmt.Printf("profile is established at $%+v with an expectancy of (%+v).\n", estInc, estIncTxn)
} else {
log.Fatalf("Error converting strings: +v", err)
}
}
fmt.Println()
}
}
</code></pre>
<p>Here is a single line of the csv file.</p>
<pre><code>30;4;102033657;COCACOLA;53764;15000.00;73010.58;387%;4;30;650%;15000.00;89558.96;497%;3;5;66%;DDA
</code></pre>
<p>Sample of the output:</p>
<blockquote>
<p>==============================================================================</p>
<p>Account: 102033657 - COCACOLA exceeded the IncAmt by 387% same as
$58010.58 over the monthly incoming amount of $73010.58. Currently,
the declared profile is established at $15000 with an expectancy of
(4).</p>
<p>==============================================================================</p>
</blockquote>
<p>Eventually I would be capturing the outgoing amount as well for each record (just to give everyone an idea of where I'm going with this). I'm assuming a template would be the best way to approach this situation? How could this be refactored?</p>
|
[] |
[
{
"body": "<pre><code> for i := 0; i < len(record[i]); i++ {\n</code></pre>\n\n<p>... I don't think that does what you intended. It seems like just luck from how the data is that it works, or did I miss something? :-) I think you can just take the for {} loop out altogether.</p>\n\n<p>I'd move the ParseFloat() calls up to where you assign the record[] values to named variables. Be sure to check the err return from both calls.</p>\n\n<p>Your idea of using a struct is also good.</p>\n\n<pre><code>type SomeRecord struct {\n Num int\n Name string\n Eia float\n // etc\n}\n</code></pre>\n\n<p>The for moving some of the code to a function: Have the function take a SomeRecord as a parameter and do the output.</p>\n\n<p>I don't know if using a template is necessary for such a short string, but if you want to then outside of the loop read the template file with text/template, specifically <a href=\"http://golang.org/pkg/text/template/#ParseFiles\" rel=\"nofollow\">template.ParseFiles</a> and then execute the template when appropriate with the record data or a new data structure if it needs data not in the record. If this is all the program does it might make most sense to have the <code>SomeRecord</code> struct have the data that the template needs (so include IncDiff).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-09T16:21:54.507",
"Id": "38493",
"Score": "0",
"body": "Thanks for your observations. Well in this case the for loop is superfluous because I only listed one record entry as a csv sample. However, my actual file contains over several thousand records."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-09T16:28:27.777",
"Id": "38494",
"Score": "0",
"body": "Actually, what I would like to do is create individual markdown files of the output for each record. I will be adding more implementation to the current template. What packages would you recommend I look at for this task?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-09T22:31:02.327",
"Id": "38507",
"Score": "0",
"body": "I meant the second loop (`for i := 0; i < len(record[i]); i++ {` ... that doesn't seem to do anything (useful/correctly). For Markdown have a look at blackfriday: http://github.com/russross/blackfriday"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-09T05:06:32.423",
"Id": "24887",
"ParentId": "24884",
"Score": "2"
}
},
{
"body": "<p>The first thing I would do is tidy up the code and fix obvious bugs. For example,</p>\n\n<pre><code>package main\n\nimport (\n \"encoding/csv\"\n \"fmt\"\n \"io\"\n \"log\"\n \"os\"\n \"strconv\"\n)\n\nconst file = \"csvdata/csvtest.csv\"\n\ntype Amounts struct {\n EstimatedAmt float64\n ActualAmt float64\n Percent string\n EstimatedTxn string\n}\n\ntype Account struct {\n Num string\n Name string\n In *Amounts\n Out *Amounts\n}\n\nconst reportSeparator = \"============================================================\\n\"\n\nfunc printAccountMonth(a *Account) error {\n fmt.Printf(\n reportSeparator,\n )\n fmt.Printf(\n \"Account: %+s - %+s exceeded the incoming amount by %+v, the same as $%+v\\n\",\n a.Num, a.Name, a.In.Percent, a.In.ActualAmt-a.In.EstimatedAmt,\n )\n fmt.Printf(\n \"over the monthly incoming amount of $%+v. Currently, the declared\\n\",\n a.In.ActualAmt,\n )\n fmt.Printf(\n \"profile is established at $%+v with an expectancy of (%+v).\\n\",\n a.In.EstimatedAmt, a.In.EstimatedTxn,\n )\n return nil\n}\n\nfunc readAmounts(r []string) (a *Amounts, err error) {\n a = new(Amounts)\n est := r[0]\n a.EstimatedAmt, err = strconv.ParseFloat(est, 64)\n if err != nil {\n return nil, fmt.Errorf(\"Error converting string: +v\", err)\n }\n act := r[1]\n a.ActualAmt, err = strconv.ParseFloat(act, 64)\n if err != nil {\n return nil, fmt.Errorf(\"Error converting string: +v\", err)\n }\n a.Percent = r[2]\n a.EstimatedTxn = r[3]\n return a, nil\n}\n\nfunc accountMonth(record []string) error {\n var err error\n var a Account\n a.Num = record[2]\n a.Name = record[3]\n a.In, err = readAmounts(record[5 : 5+6])\n if err != nil {\n return err\n }\n a.Out, err = readAmounts(record[11 : 11+6])\n if err != nil {\n return err\n }\n err = printAccountMonth(&a)\n return err\n}\n\nfunc main() {\n f, err := os.Open(file)\n if err != nil {\n log.Fatalf(\"Error opening file: %v\", err)\n }\n defer f.Close()\n\n rdr := csv.NewReader(f)\n rdr.Comma = ';'\n\n for {\n record, err := rdr.Read()\n if err != nil {\n if err == io.EOF {\n break\n }\n log.Fatal(err)\n }\n err = accountMonth(record)\n if err != nil {\n log.Fatal(err)\n }\n fmt.Printf(reportSeparator)\n }\n}\n</code></pre>\n\n<p>Input:</p>\n\n<pre><code>Record:\n[30 4 102033657 COCACOLA 53764 15000.00 73010.58 387% 4 30 650% 15000.00 89558.96 497% 3 5 66% DDA]\n0 30\n1 4\n2 102033657\n3 COCACOLA\n4 53764\n5 15000.00\n6 73010.58\n7 387%\n8 4\n9 30\n10 650%\n11 15000.00\n12 89558.96\n13 497%\n14 3\n15 5\n16 66%\n17 DDA\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>============================================================\nAccount: 102033657 - COCACOLA exceeded the incoming amount by 387%, the same as $58010.58\nover the monthly incoming amount of $73010.58. Currently, the declared\nprofile is established at $15000 with an expectancy of (4).\n============================================================\n</code></pre>\n\n<p>Obviously it needs a lot more work, but it's a start.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T07:29:43.400",
"Id": "38534",
"Score": "0",
"body": "this is definitely more idiomatic go code. I would upvote this answer right now but I have not been granted access."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-09T19:29:41.877",
"Id": "24919",
"ParentId": "24884",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "24919",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-09T02:50:52.063",
"Id": "24884",
"Score": "3",
"Tags": [
"beginner",
"parsing",
"csv",
"go"
],
"Title": "String converting and parsing a few rows of a .csv file"
}
|
24884
|
<p>I came across the following piece of code in a UI application I need to maintain. </p>
<pre><code>int tool_unhex( char c )
{
return( c >= '0' && c <= '9' ? c - '0'
: c >= 'A' && c <= 'F' ? c - 'A' + 10
: c - 'a' + 10 );
}
void unescape2QString(const char *sOrg, QString & str)
{
/*
* Remove URL hex escapes from s... done in place. The basic concept for
* this routine is borrowed from the WWW library HTUnEscape() routine.
*/
char* s = (char*)sOrg;
unsigned short w = 0;
str = "";
for ( ; *s != '\0'; ++s ) {
if ( *s == '%' ) {
if(*(s+1) == 'u')
{
s++;
if ( *++s != '\0' ) {
w = (wchar_t) (tool_unhex( *s ) << 12);
}
if ( *++s != '\0' ) {
w += (wchar_t) (tool_unhex( *s ) << 8);
}
if ( *++s != '\0' ) {
w += (wchar_t) (tool_unhex( *s ) << 4);
}
if ( *++s != '\0' ) {
w += (wchar_t) tool_unhex( *s );
}
str += QString::fromUtf16(&w, 1);
}
}
else
{
str += QString::fromAscii(s, 1);
}
}
}
</code></pre>
<ol>
<li>Isn't <code>QString</code> immutable? The comment says it's changing in place, but isn't each <code>str +=</code> creating a new <code>QString</code>?</li>
<li>Is this the most optimized way of doing this?</li>
</ol>
<p>It looks like the function is trying to implement <code>HTUnEscape()</code> from <a href="http://www.w3.org/Library/src/HTEscape.c" rel="nofollow">w3.org</a>, with UTF16 strings. </p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T02:30:05.537",
"Id": "38509",
"Score": "4",
"body": "Well, not really optimising, but for your four `if ( *++s != '\\0' )` conditions, if any but the last one fails, the loop will go off the end of the string and keep going - until it hits another \\0."
}
] |
[
{
"body": "<ul>\n<li><p>I can't quite tell what <code>tool_unhex()</code> is supposed to do. It looks like it converts a character (presumably a hex value) to a base-10 value (an <code>int</code> in this case). You may need to change the name to reflect on its primary purpose.</p>\n\n<p>The ternary is a little confusing. I almost mistook the last two statements as a redundancy since they only differ by one character. I'd recommend putting some comments stating what it's doing, or rewriting it to be a little clearer. Otherwise, there may be an STL functionality that serves the same purpose. In C++, it's best to utilize the library as much as possible.</p></li>\n<li><p>Overall, you use many magic numbers (and chars). In cases where ASCII values are used as offsets (such as in <code>tool_unhex()</code>), you may not need to define them. In <code>unescape2QString()</code>, however, you may need to at least add comments to state their significance. Otherwise, give any of them constants with relevant names.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-03T00:51:03.797",
"Id": "40705",
"ParentId": "24888",
"Score": "5"
}
},
{
"body": "<p>Firstly, to answer your first question, <code>QString</code> is definitely not immutable. Directly from the <a href=\"https://qt-project.org/doc/qt-5.0/qtcore/qstring.html#operator-2b-eq\">documentation</a>:</p>\n\n<blockquote>\n <p>This operation is typically very fast (constant time), because QString preallocates extra space at the end of the string data so it can grow without reallocating the entire string each time.</p>\n</blockquote>\n\n<p>I'm not a fan of the nested ternary statements in <code>tool_unhex</code>. Also, it does no error checking to make sure that whatever it is passed is actually a valid hex character. This is dangerous, as you use an <code>unsigned short</code> to store the shifted value of the character. If it's some character that's above <code>F</code> or <code>f</code>, then shifting and adding will potentially overflow and cause hard to track down bugs. For example, if there was a <code>g</code> that got in there somehow:</p>\n\n<pre><code>'g' - 'a' + 10; // Equals 16\nunsigned short w = (16 << 12) + (16 << 8) + (16 << 4) + 16; // Overflow\n</code></pre>\n\n<p>I'd suggest changing it to the following:</p>\n\n<pre><code>#include <cctype>\n\n// Converts the given (ASCII encoded) hex character to \n// an integer value 0 - 15.\n// throw std::out_of_range if the given character is not\n// a valid hex character.\nint tool_unhex(char c)\n{\n if(std::isdigit(c)) \n return c - '0';\n else if(c >= 'A' && c <= 'F')\n return c - 'A' + 10;\n else if(c >= 'a' && c <= 'f')\n return c - 'a' + 10;\n throw std::out_of_range(\"Not a hex character\");\n}\n</code></pre>\n\n<p>If you're sure that the character passed in will always be in range, this should be documented somewhere. Also, it should be documented that this will ONLY work for ASCII and ASCII-compatible encodings.</p>\n\n<p>Your <code>unescape</code> method has some confusing parts. The comments and the code don't match.</p>\n\n<pre><code>char* s = (char*)sOrg;\n</code></pre>\n\n<p>Why cast away the <code>const</code>ness of <code>sOrg</code>? You don't modify <code>s</code> anyway, so just work directly on the (<code>const</code>) <code>sOrg</code>. </p>\n\n<pre><code>str = \"\";\n</code></pre>\n\n<p>If you're just going to clear the <code>QString</code> passed in straight away, why not just create and return it instead of taking it as a reference?</p>\n\n<pre><code>if ( *s == '%' ) {\n if(*(s+1) == 'u')\n {\n s++;\n if ( *++s != '\\0' ) {\n w = (wchar_t) (tool_unhex( *s ) << 12);\n }\n if ( *++s != '\\0' ) {\n w += (wchar_t) (tool_unhex( *s ) << 8);\n }\n if ( *++s != '\\0' ) {\n w += (wchar_t) (tool_unhex( *s ) << 4);\n }\n if ( *++s != '\\0' ) {\n w += (wchar_t) tool_unhex( *s );\n }\n\n str += QString::fromUtf16(&w, 1);\n }\n}\n</code></pre>\n\n<p>This can certainly be simplified with a loop.</p>\n\n<p>In the end, I came up with something like this:</p>\n\n<pre><code>QString unescape2QString(const char *sOrg)\n{\n QString str;\n\n for ( ; *sOrg != '\\0'; ++sOrg ) {\n if (*sOrg == '%' && *(sOrg+1) == 'u') {\n {\n unsigned short w = 0;\n ++sOrg;\n // Left shift value\n int i = 12;\n while(*++sOrg != '\\0' && i >= 0) {\n w += (wchar_t) (tool_unhex(*sOrg) << i);\n i -= 4;\n }\n str += QString::fromUtf16(&w, 1);\n }\n else \n {\n str += QString::fromAscii(s, 1);\n }\n }\n return str;\n} \n</code></pre>\n\n<p>This definitely needs some documentation as to what exactly it's doing, as it is absolutely not clear currently.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-03T01:22:11.993",
"Id": "40708",
"ParentId": "24888",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "40708",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-09T07:22:12.900",
"Id": "24888",
"Score": "6",
"Tags": [
"c++",
"optimization",
"strings"
],
"Title": "Implementing HTUnEscape"
}
|
24888
|
<p>I have a few Python codes like this:</p>
<pre><code> workflow = []
conf = {}
result = []
prepare_A(workflow, conf)
prepare_B(workflow, conf)
prepare_C(workflow, conf)
result.append(prepare_D_result(workflow, conf))
prepare_E(workflow, conf)
#.... about 100 prepare functions has the same parameter list
</code></pre>
<p>I was wondering that whether I need to rewrite like this:</p>
<pre><code> workflow = []
conf = {}
result = []
def prepare_wrapper(prepare_function):
return prepare_function(workflow, conf)
prepare_wrapper(prepare_A)
prepare_wrapper(prepare_B)
prepare_wrapper(prepare_C)
result.append(prepare_wrapper(prepare_D_result))
prepare_wrapper(prepare_E)
#.... about 100 prepare functions has the same parameter list
</code></pre>
<p>Though it might reduce the burden of passing 2 parameters into the function each time, it might bring difficulties for those who read codes. Is there better ways to ameliorate the code quality in such situation?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-09T14:47:09.967",
"Id": "38489",
"Score": "0",
"body": "Your question isn't following the FAQ in that your don't appear to be presenting real code. It would be better if you could show us an actual example."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-09T14:58:30.003",
"Id": "38491",
"Score": "0",
"body": "Are you sure about this style of programming? all your \"functions\" work by performing side-effects, so your application will be a gigantic state container where any data structure can be modified anywhere else. Have you considered a more functional approach? (where functions that take values and return another values, no side-effects). It requires some more thought at first, but it pays off later."
}
] |
[
{
"body": "<p>Here's an idea, assuming your logic is really that straightforward:</p>\n\n<pre><code>workflow = [] \nconf = {}\nresult = []\n\nsteps = ((prepare_A, False),\n (prepare_B, False),\n (prepare_C, False),\n (prepare_D, True),\n (prepare_E, False))\n\nfor func, need_results in steps:\n res = func(workflow, conf)\n if need_results:\n result.append(res)\n</code></pre>\n\n<p>If you don't find that approach suitable, I'd suggest making your wrapper a class that encapsulates <code>workflow</code> and <code>conf</code>, and possibly <code>results</code> too.</p>\n\n<pre><code>class PrepareWrapper(object):\n def __init__(self):\n self.workflow = [] \n self.conf = {}\n\n def __call__(self, prepare_function):\n return prepare_function(self.workflow, self.conf) \n\nprepare_wrapper = PrepareWrapper() \nprepare_wrapper(prepare_A) \nprepare_wrapper(prepare_B) \n</code></pre>\n\n<p>Or, why not make all the prepare functions methods of this class? </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-09T07:39:25.857",
"Id": "24892",
"ParentId": "24889",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "24892",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-09T07:23:59.597",
"Id": "24889",
"Score": "0",
"Tags": [
"python"
],
"Title": "Is it worthy to create a wrapper function like this?"
}
|
24889
|
<p>I use this code to Load and Insert data to a table using a <code>DataGridView</code> in a C# windows application.</p>
<pre><code> SqlCommand sCommand;
SqlDataAdapter sAdapter;
SqlCommandBuilder sBuilder;
DataSet sDs;
DataTable sTable;
private void form1_Load(object sender, EventArgs e)
{
string connectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\Database1.mdf;Integrated Security=True;User Instance=True";
string sql = "SELECT * FROM mytable";
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
sCommand = new SqlCommand(sql, connection);
sAdapter = new SqlDataAdapter(sCommand);
sBuilder = new SqlCommandBuilder(sAdapter);
sDs = new DataSet();
sAdapter.Fill(sDs, "mytable");
sTable = sDs.Tables["mytable"];
connection.Close();
dataGridView1.DataSource = sDs.Tables["mytable"];
dataGridView1.ReadOnly = true;
save_btn.Enabled = false;
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
}
private void new_btn_Click(object sender, EventArgs e)
{
dataGridView1.ReadOnly = false;
save_btn.Enabled = true;
new_btn.Enabled = false;
delete_btn.Enabled = false;
}
private void delete_btn_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Are you sure?", "Delete", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
dataGridView1.Rows.RemoveAt(dataGridView1.SelectedRows[0].Index);
sAdapter.Update(sTable);
}
}
private void save_btn_Click(object sender, EventArgs e)
{
sAdapter.Update(sTable);
dataGridView1.ReadOnly = true;
save_btn.Enabled = false;
new_btn.Enabled = true;
delete_btn.Enabled = true;
}
}
</code></pre>
<p>It's ok and works, but when I try to work with a query that has a condition then no rows are added to the <code>DataGrid</code> and <code>MyTable</code> anymore</p>
<pre><code>sql = "SELECT * FROM mytable where col2 = 1";
</code></pre>
|
[] |
[
{
"body": "<p>It looks like your code should work and output rows if your database contains records corresponding to your condition.</p>\n\n<p>Since we are on a code review site I would like to highlight several code issues not related to your question:</p>\n\n<ul>\n<li>You should dispose all objects implementing <code>IDisposable</code> interface. In your code these objects are <code>SqlConnection</code>, <code>SqlCommand</code> and <code>SqlDataAdapter</code>. Easiest way to dispose objects properly is via <code>using</code> statement (note that you <a href=\"https://stackoverflow.com/questions/1195829/do-i-have-to-close-a-sqlconnection-before-it-gets-disposed\">don't need to close connection</a> if you dispose it).</li>\n<li>You don't need to use <code>DataSet</code> to populate a <code>DataTable</code>, you can populate <code>DataTable</code> directly from <code>DataAdapter</code>.</li>\n<li>Initialization of controls (<code>dataGridView1.ReadOnly</code>, <code>dataGridView1.SelectionMode</code> and <code>save_btn.Enabled</code> in <code>form1_Load</code>) can be done at design time, so that your code is not cluttered with it.</li>\n</ul>\n\n<p>As a result of described transformations your code may look like this:</p>\n\n<pre><code>private void form1_Load(object sender, EventArgs e)\n{\n string connectionString = \"Data Source=.\\\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\\\Database1.mdf;Integrated Security=True;User Instance=True\";\n string sql = \"SELECT * FROM mytable\";\n\n using (var connection = new SqlConnection(connectionString))\n using (var command = new SqlCommand(sql, connection))\n using (var adapter = new SqlDataAdapter(command))\n {\n connection.Open();\n var myTable = new DataTable();\n adapter.Fill(myTable);\n dataGridView1.DataSource = myTable;\n }\n}\n</code></pre>\n\n<p>This code is good enough for simple project, but it won't allow you to unit-test your project. If you start looking in this direction prepare to spend quite some time learning <a href=\"http://en.wikipedia.org/wiki/Object-relational_mapping\" rel=\"nofollow noreferrer\">ORM frameworks</a> and <a href=\"http://en.wikipedia.org/wiki/Inversion_of_control\" rel=\"nofollow noreferrer\">Inversion of Control</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-09T08:34:24.833",
"Id": "24894",
"ParentId": "24891",
"Score": "3"
}
},
{
"body": "<p>You have multiple problems in your code, to name a few:</p>\n\n<ul>\n<li>you don't close the connection nor dispose any of the <code>problematic</code> objects (SqlConnection, SqlCommand and SqlDataAdapter). Yes, I see you're using them later in the code, but trust me, it's a BAD idea</li>\n<li>as almaz already pointed out, you don't need <code>DataSet</code> in this situation at all</li>\n</ul>\n\n<p>What I'm troubled with the most is of a different matter:<br />\nYou don't separate layers at all! You mix and match UI logic, business logic and data access into one big ugly mess. This looks like a procedural code, completely ignoring every OOP rule. How did you come to the conclusion that your <code>Form</code> should be aware (and responsible!!!) for objects like <code>SqlConnection</code>? </p>\n\n<p>What you should do in the first place is to separate your logic into layers. For instance <a href=\"http://en.wikipedia.org/wiki/Multitier_architecture\" rel=\"nofollow\"><strong>this</strong></a> is a good place to start reading and learning the theory.</p>\n\n<p>If you fix this, I believe you won't have problems like this anymore, because you would be able to find the problem more easily without any external help. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-09T12:25:38.857",
"Id": "24900",
"ParentId": "24891",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-09T07:39:12.260",
"Id": "24891",
"Score": "-1",
"Tags": [
"c#",
".net",
"sql",
"winforms"
],
"Title": "Insert to datagridview when SELECT query has WHERE condition"
}
|
24891
|
<p>I've made an algorithm solving Hanoi Tower puzzles, for n disks and m pegs.</p>
<p>It uses lists as pegs, each list's element contains disks array - <code>{0, 0, 0}</code> means the peg is empty, <code>{1, 2, 0}</code> means the peg contains "1" and "2" disks, <code>{3, 0, 0}</code> means the peg contains the biggest disk only.</p>
<p>The algorithm is iterative (and has to be), to solve for 3 pegs it repeats the following steps:</p>
<ol>
<li>Move smallest disk to the right is number of disks is odd, move it to the left if even</li>
<li>Make only one possible move left, without toughing the smallest disk</li>
</ol>
<p>Very simple and cool algorithm. If pegs > 3, I repeat the above (pegs - 2) times - divide and conquer, until the last peg is filled.</p>
<hr>
<p><strong>My problem is that the algorithm is very ugly.</strong> As someone said: "If you need more than 3 levels of indentation, you're screwed anyway, and should fix your program.".</p>
<p>I've been thinking on how can I optimize my code for a couple of days, and I do not know what more I could possibly do.</p>
<p>This is the whole program (console output is not in English though, but variables are, so it should be clear enough): <a href="http://ideone.com/Jwt4nN" rel="nofollow">http://ideone.com/Jwt4nN</a></p>
<p>This is the working algorithm on ideone: <a href="http://ideone.com/woEg9o" rel="nofollow">http://ideone.com/woEg9o</a></p>
<p>And I'm pasting it here:</p>
<pre><code>void hanoi(rod **head, rod **tail)
{
time_start();
rod *temp, *temp2, *head_t = *head;
int flag = 0, div = 0;
for(int i = 0; i < rods - 2; i++)
{
while((*tail)->disks[n - 1] != n)
{
temp = *head, flag = 0;
if(div % 2 == 0) // move smallest disk to the right if odd, or left if even
{
while(temp != (*tail)->next)
{
if(flag == 1)
{
unshift(1, &temp->disks);
break;
}
if(temp->disks[0] == 1)
{
pop(&temp->disks);
flag = 1;
}
if(n % 2 == 0)
{
temp = (temp->next == (*tail)->next) ? *head : temp->next;
}
else
{
temp = (temp->prev == (*head)->prev) ? *tail : temp->prev;
}
}
}
else // make first possible move
{
while(temp != (*tail)->next && flag == 0)
{
temp2 = *head;
while(temp2 != (*tail)->next)
{
if((temp->disks[0] < temp2->disks[0] || temp2->disks[0] == 0) && temp->disks[0] != 1 && temp->disks[0] != 0 && temp->num != temp2->num)
{
int t = temp->disks[0];
pop(&temp->disks);
unshift(t, &temp2->disks);
flag = 1;
break;
}
temp2 = temp2->next;
}
temp = temp->next;
}
}
div++, moves++;
}
// divide and conquer
if(i < rods - 3)
{
if((*head)->num <= i + 1)
*head = (*head)->next;
if((*tail)->num <= i + 3)
*tail = (*tail)->next;
}
}
*head = head_t;
time_stop();
}
/**
* Input: {1, 2, 3, 4, 0}, el = 5
* Output: {5, 1, 2, 3, 4}
*
* Input array ALWAYS contains 0's at the end
*/
void unshift(int el, int **arr)
{
for(int i = (int)n - 1; i > 0; i--)
{
(*arr)[i] = (*arr)[i - 1];
}
(*arr)[0] = el;
}
/**
* Input: {1, 2, 3, 4}
* Output: {2, 3, 4, 0}
*/
void pop(int **arr)
{
for(int i = 0; i < (int)n - 1; i++)
{
(*arr)[i] = (*arr)[i + 1];
}
(*arr)[n - 1] = 0;
}
</code></pre>
<p>ROD is the name of the list structure. Head points to the first element, tail to the 3rd (at the beginning). If pegs > 3, head and tail move to the right repeatedly (pegs - 3) times.</p>
<p>If anything would be unclear, please write this in the comment, and I'll try to explain it best as I can.</p>
<p>Any suggestions would be welcomed.</p>
<p><strong>EDIT:</strong> You say it does not compile. I am using Visual Studio 2012, and it does compile for me - .cpp extension, C++ file, and I guess the compiler is also for C++.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-09T10:51:22.663",
"Id": "38477",
"Score": "0",
"body": "Your link to 'the working algorithm' leads to code that does not compile."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-09T11:42:07.947",
"Id": "38479",
"Score": "0",
"body": "As this code contains errors, it should be posted on Stack Overflow instead. Once it does work, you could always edit it into this post and someone could help with other concerns."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-09T14:44:48.097",
"Id": "38487",
"Score": "0",
"body": "It compiles in Visual Studio with .cpp extension. (C++ compiler)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-09T14:45:58.260",
"Id": "38488",
"Score": "0",
"body": "Pass input like 3, and 3 for both scanf's."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-09T14:48:54.633",
"Id": "38490",
"Score": "0",
"body": "The error in Ideone.com appears because no input (or wrong input) was passed. I use exit(EXIT_FAILURE) for this behavior."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T15:48:21.277",
"Id": "38570",
"Score": "0",
"body": "The easiest way to make this better looking would be to separate data structure management into its own class or set of functions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-29T07:20:14.133",
"Id": "455627",
"Score": "0",
"body": "This code doesn't compile since `rod` is not declared anywhere."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-29T09:27:07.953",
"Id": "455635",
"Score": "3",
"body": "@Roland, I'd say the correct close reason for that is Insufficient Context (we're just missing the declarations, just as we're missing the forward-declarations of `pop()` and `unshift()`). Broken/Unimplemented is should be used on questions where the code is unfinished, rather than having parts that clearly exist somewhere but omitted from the question."
}
] |
[
{
"body": "<p>The biggest problem is that there is very little abstraction going on here. There are plenty of places where a helper function would come in handy, but isn't used, and an object or abstract data type would be good for the individual rods or the set of rods as a whole. We can't get the big picture of what's going on if we're worried about what this boolean or that pointer are doing, instead of where this disk on that rod is going to go. </p>\n\n<p>I should be able to at least mostly read the hanoi() function with only an understanding of the towers of hanoi problem; I should not need any idea how you implemented the details of the rods or disks. When I tried to read it, I saw a for loop that contained a while loop that contained an if statement that contained a while loop that contained an if statement, and I had no idea what was going on. If it had been a for loop that contained a while loop that had instructions on which disks to put on which rods, it probably would have been easy to read. </p>\n\n<p>Names could also use some work. <code>temp</code> and <code>temp2</code> should probably be <code>source_rod</code> and <code>target_rod</code>, if I haven't misunderstood their purpose. <code>unshift</code> should probably be <code>push</code>. I don't know what <code>div</code> should be. It does get used with the mod operator, but that isn't what it is, just how it's used. <code>flag</code> is a flag, but I don't know what it means. It might mean that a move has been made. Name flags after what the flag would mean if it were true. If <code>flag == true</code> means the universe is going to blow up, don't name it <code>flag</code>, name it something like <code>universe_is_doomed</code>. </p>\n\n<p>If I've guessed correctly about what everything is doing, then this bit of code:</p>\n\n<pre><code> int t = temp->disks[0];\n pop(&temp->disks);\n unshift(t, &temp2->disks);\n flag = 1;\n</code></pre>\n\n<p>should be more like this:</p>\n\n<pre><code> int disk = pop(&source_rod);\n push(disk, &target_rod);\n moved = 1;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-19T04:58:51.297",
"Id": "35661",
"ParentId": "24897",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-09T09:52:52.510",
"Id": "24897",
"Score": "-1",
"Tags": [
"c++",
"algorithm",
"c",
"tower-of-hanoi"
],
"Title": "Hanoi Towers solver"
}
|
24897
|
<p>I need concurrent HashMap of List as value with following behavior:</p>
<ul>
<li>count of read/write ops approximately equals</li>
<li>support add/remove values in lists</li>
<li>thread safe iterations over lists</li>
</ul>
<p>After some research I implemented ConcurrentMapOfList, but I'm not sure in his correctness.</p>
<pre><code>public class ConcurrentMapOfList<Key, ListValue> {
private final ConcurrentMap<Key, ConcurrentList<ListValue>> values
= new ConcurrentHashMap<Key, ConcurrentList<ListValue>>();
public void add(Key key, Value value) {
List<Value> list = values.get(key);
if (list == null) {
final ConcurrentList<Value> newList = new ConcurrentList<Value>();
final ConcurrentList<Value> oldList = values.putIfAbsent(key, newList);
if (oldList == null) {
list = newList;
} else {
list = oldList;
}
}
list.add(value);
}
public List<ListValue> remove(Key key) {
return values.remove(key);
}
public boolean remove(Key key, ListValue value) {
final List<ListValue> list = values.get(key);
if (list == null) {
return false;
}
return list.remove(value);
}
public List<ListValue> obtainListCopy(Key key) {
final ConcurrentList<ListValue> list = values.get(key);
if (list == null) {
return Collections.emptyList();
}
return list.clone();
}
public void removeAll() {
values.clear();
}
private class ConcurrentList<V> extends ArrayList<V> {
final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
final Lock readLock = lock.readLock();
final Lock writeLock = lock.writeLock();
@Override
public boolean add(V v) {
writeLock.lock();
try {
return super.add(v);
}finally {
writeLock.unlock();
}
}
@Override
public V remove(int index) {
writeLock.lock();
try {
return super.remove(index);
}finally {
writeLock.unlock();
}
}
@Override
public ConcurrentList<V> clone() {
readLock.lock();
try {
return (ConcurrentList<V>)super.clone();
}finally {
readLock.unlock();
}
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-09T17:41:49.177",
"Id": "38496",
"Score": "0",
"body": "Is there a reason you do not use the wrapper interface `synchronizedMap` from `Collections`? It seems to me that this would be the easier and safer solution. From a quick look, your implementation will e.g. fail if you add element and copy it in parallel."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T06:21:49.113",
"Id": "38511",
"Score": "0",
"body": "ConcurrentMap better than syncronizedMap and I need additional synchronization on values of map(some Lists). Copy and changes list isn't be failed, because they synchronized with one [ReadWriteLock](http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/locks/ReadWriteLock.html)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T13:49:05.720",
"Id": "38565",
"Score": "0",
"body": "Map of List it is MultiMap, for example [in guava collections](http://guava-libraries.googlecode.com/svn/tags/release05/javadoc/com/google/common/collect/Multimaps.html#synchronizedMultimap(com.google.common.collect.Multimap))"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T17:37:13.907",
"Id": "38581",
"Score": "0",
"body": "For unknown reasons, I did not see this other part. Thanks for the hint. Then just one minor additional comment: I think you mixed up Value and ListValue at some places. At least, this will not compile in the current state (but is trivial to change)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-11T06:24:01.333",
"Id": "38643",
"Score": "0",
"body": "About Value and ListValue you are right. It happened at editing this question."
}
] |
[
{
"body": "<p>Ok, after the hint from the comment it makes more sense for me. I felt a bit bad because of the wrong comment, so I have investigated this deeper.</p>\n\n<p>As far as I see it, there is only one problem which I will explain in the next paragraph. But I have to admit, the implementation is rather complex because we have several layers of parallelization and locking with multiple data structures. It would need very carefully analysis to prove the correctness.</p>\n\n<p>The problem I found is the <code>remove</code> method. You have implemented <code>remove(int)</code>:</p>\n\n<pre><code>@Override\npublic V remove(int index) {\n writeLock.lock();\n try {\n return super.remove(index);\n }finally {\n writeLock.unlock();\n }\n}\n</code></pre>\n\n<p>But you are using <code>remove(Object)</code>:</p>\n\n<pre><code>public boolean remove(Key key, ListValue value) {\n final List<ListValue> list = values.get(key);\n\n if (list == null) {\n return false;\n }\n\n return list.remove(value);\n}\n</code></pre>\n\n<p>Test case to show it:</p>\n\n<pre><code> final int max = 500;\n final int maxThreads = 200;\n for (int i = 0; i < max; i++) {\n final int currentI = i;\n final List<Thread> threadList = new ArrayList<>();\n for (int j = 0; j < maxThreads; j++) {\n final int currentJ = j;\n threadList.add(new Thread(new Runnable() {\n @Override\n public void run() {\n map.add(currentI, currentJ);\n map.remove(currentI, currentJ);\n }\n }));\n }\n for (final Thread thread : threadList)\n thread.start();\n for (final Thread thread : threadList)\n thread.join();\n }\n\n if (map.getEntrySet().size() != max)\n System.err.println(\"entryset size should be: \" + maxThreads + \" is:\" + map.getEntrySet().size());\n\n for (final Entry<Integer, ConcurrentList<Integer>> entry : map.getEntrySet()) {\n final ConcurrentList<Integer> value = entry.getValue();\n if (value.size() != 0)\n System.err.println(\"value size should be: \" + 0 + \" is:\" + value.size() + \", value: \" + value);\n }\n</code></pre>\n\n<p>This can easily be solved, if you just implement the remove(Object) method:</p>\n\n<pre><code>@Override\npublic boolean remove(final Object o) {\n writeLock.lock();\n try {\n return super.remove(o);\n } finally {\n writeLock.unlock();\n }\n}\n</code></pre>\n\n<p>This errors could be avoided if you use one of the following patterns:</p>\n\n<ul>\n<li><p>Use a synchronized list here, <code>Vector</code> (not recommended), <code>CopyOnWriteArrayList</code> or <code>Collections.synchronizedList</code></p></li>\n<li><p>Use encapsulation, rather then extension. Do not extend <code>ArrayList</code>, use implements <code>List</code> and use a member field with the backed up data structure. This will be in the end, nearly the same as using <code>Collections.synchronizedList</code>, but you could avoid the mutex and use the ReantrantLocks if you really need it</p></li>\n</ul>\n\n<p>As already partly mentioned in my comment. To get the code running, I had to change the generic identifier <code>Value</code> to <code>ListValue</code> at some places, it looked like they were mixed up.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-11T06:51:58.737",
"Id": "38645",
"Score": "0",
"body": "My bad, I really wanted implement remove(Object). I found some info on [stackoverflow](http://stackoverflow.com/questions/3635292/high-performance-concurrent-multimap-java-scala)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-11T06:54:48.910",
"Id": "38646",
"Score": "0",
"body": "My [current implementation](https://github.com/komelgman/java-compote/blob/3a76ecd225bbcd6c05848977912037a6727d09cb/shared-classes/src/kom/util/collections/ConcurrentMultiMap.java) uses ConcurrentLinkedQueue"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T18:05:01.377",
"Id": "24972",
"ParentId": "24898",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "24972",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-09T10:17:59.760",
"Id": "24898",
"Score": "1",
"Tags": [
"java",
"multithreading",
"collections"
],
"Title": "Java concurrent Map of List"
}
|
24898
|
<p>I got this answer here: <a href="https://stackoverflow.com/questions/15902299/selecting-an-item-in-a-listbox-to-assign-it-as-a-temp-variable">https://stackoverflow.com/questions/15902299/selecting-an-item-in-a-listbox-to-assign-it-as-a-temp-variable</a></p>
<hr>
<p>Suppose you have loaded the <code>lisBox1</code> with objects of type <code>Genre</code>.</p>
<pre><code>lisBox1.Datasource = this.GetAllGenresFromTextFiles();
lisBox1.DisplayMember = "Genre";
</code></pre>
<p>Add an event to <code>SelectionChanged</code> of your <code>lstBox1</code> :</p>
<pre><code>lstBox1.SelectionChanged += lstBox1_SelectionChanged;
</code></pre>
<p>And then in this event, filter the data for listbox2 :</p>
<pre><code>void lstBox1_SelectionChanged(object sender, EventArgs e)
{
var movies = m_allMovies;
var genre = lstBox1.SelectedItem as Genre;
if(genre != null)
{
movies = movies.Where(m => m.Genre == genre.Genre).ToList();
}
lstbox2.Datasource = movies;
}
</code></pre>
<p><code>m_allMovies</code> is a list of all the movies you have loaded from your textfiles.<br>
You can also read your text file every time the user clicked a different genre, it will consume less memory but more CPU:</p>
<pre><code>void lstBox1_SelectionChanged(object sender, EventArgs e)
{
var movies = this.GetAllMoviesFromTextFiles();
var genre = lstBox1.SelectedItem as Genre;
if(genre != null)
{
movies = movies.Where(m => m.Genre == genre.Genre).ToList();
}
lstbox2.Datasource = movies;
}
</code></pre>
<p>The keypoint here is not to filter row from the <code>Listbox</code>. You must think of it as your <code>Listbox</code> contains a subset of all your movies.<br>
And each time you want to add or remove rows from a <code>Listbox</code>, in fact you are reloading it with appropriate datas.</p>
<hr>
<p><strong>and my problem is this:</strong></p>
<p>With the first 2 lines of code (At the top of the answer), where would i place this (I'm new to C# so <code>.Datasource</code> & <code>DisplayMember</code> are new things to me). Also where you have "this.GetAllGenresFromTextFiles" (and the same for <code>var movies = this.GetAllMoviesFromTextFiles)</code> --> would i place the location of my text file within the brackets?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-09T14:09:15.190",
"Id": "38484",
"Score": "0",
"body": "Winforms? Wpf? Webforms? Who gave you the code?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-09T14:15:10.317",
"Id": "38485",
"Score": "0",
"body": "It's C# (Visual Studio 2010) http://stackoverflow.com/questions/15902299/selecting-an-item-in-a-listbox-to-assign-it-as-a-temp-variable is the place i originally posted in"
}
] |
[
{
"body": "<p>Not sure if this question really fits here, but I'll try to help anyway.</p>\n\n<blockquote>\n <p>With the first 2 lines of code (At the top of the answer), where would\n i place this (I'm new to C# so .Datasource & DisplayMember are new\n things to me).</p>\n</blockquote>\n\n<p>DataSource is used when you're databinding a control to a collection. <br />\nDisplayMember is used to determine which member (property) of the databound type will be used. For instance you have a class <code>Person (id, firstname, lastname)</code> and you want to display lastnames in your listbox. So you set <code>listbox.DisplayMember = \"lastname\"</code> </p>\n\n<p>You can put these lines pretty much anywhere. When you fire up the method containing these commands, your listbox will get populated by the data specified in DataSource. You can use <code>Load</code> event for instance, however, I'd recommend to use an extra method called <code>PopulateListBox</code> and call that from Load event...</p>\n\n<blockquote>\n <p>would i place the location of my text file within the brackets?</p>\n</blockquote>\n\n<p>That depends on many things..For instance what exactly are you trying to achieve, how is the rest of your application structured, what are you programming habits etc...<br />\nIf you wanted to use the code from Scorpi0, the method <code>GetAllMoviesFromTextFiles</code> expects to have everything it needs without any input. It should contain a method body to get all movies. </p>\n\n<p>Furthermore, I'd suggest you one thing - if this is too advanced for you and you still don't understand, get some books and start with something simpler. You need to understand how to divide the application into logical layers, how to separate UI from data access etc. This is a topic for multiple books and a few years experience. You can't expect just to start typing some code and immediately get it all right. From a big part it's very opinionated as well, there are rarely \"the best practices\". You ask 10 different programmers and you get 10 different answers. You need to learn many things, so you will be able to decide for yourself what suits you the best in the current situation you're in.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-09T20:19:13.420",
"Id": "24922",
"ParentId": "24903",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-09T13:33:32.907",
"Id": "24903",
"Score": "1",
"Tags": [
"c#",
"winforms"
],
"Title": "selecting an item in a listbox to assign it as a temp variable - Review Code"
}
|
24903
|
<p>I'm no stranger to JS, but I think I still have a lot to learn. I originally wrote this code to manipulate a "help" bar, which would be positioned as a thin ribbon on the side of the browser window, which when hovering over or clicking would open up and display it's contents. Nothing major, but an okay example to use here.</p>
<pre><code>$(document).ready(function () {
var open = false;
var peek = false;
var helpBar = $(".help-bar");
var helpIcon = $(".help-icon");
var help = helpBar.add(helpIcon); // Put both together to do the same things
helpBar.click(function () {
toggleHelp();
});
helpBar.hover(function () {
togglePeek();
});
function toggleHelp() {
if (open) {
changeRightValue(help, "0", "slow");
toggleArrow("Open");
open = false;
}
else {
changeRightValue(help, "280", "fast");
toggleArrow("Close");
open = true;
}
}
function togglePeek() {
if (open == false) {
help.stop();
if (peek) {
changeRightValue(help, "0", "fast");
peek = false;
}
else {
changeRightValue(help, "5", "fast");
peek = true;
}
}
}
function changeRightValue(element, amount, speed) {
element.animate({ right: amount }, speed);
}
function toggleArrow(direction) {
helpIcon.css("background", "url('/images/buttons/zapp/arrow" + direction + ".png') no-repeat 0px 50%");
}
});
</code></pre>
<p>It works fine, but then I wondered whether grouping related items into objects might help a little:</p>
<pre><code> $(document).ready(function(){
var open = false;
var peek = false;
var helpBar = $(".help-bar");
var helpIcon = $(".help-icon");
var helpSection = helpBar.add(helpIcon); // Put both together to do the same things
var help = {};
var utils = {};
help.toggle = function(){
if (open) {
utils.changeRightValue(helpSection, "0", "slow");
utils.toggleArrow("Open");
open = false;
}
else {
utils.changeRightValue(helpSection, "280", "fast");
utils.toggleArrow("Close");
open = true;
}
};
help.peek = function(){
if (open == false) {
helpSection.stop();
if (peek) {
utils.changeRightValue(helpSection, "0", "fast");
peek = false;
}
else {
utils.changeRightValue(helpSection, "5", "fast");
peek = true;
}
}
};
utils.changeRightValue = function(element, amount, speed){
element.animate({right:amount}, speed);
};
utils.toggleArrow = function(direction){
helpIcon.css("background", "url('/images/buttons/zapp/arrow" + direction + ".png') no-repeat 0px 50%");
};
// jQuery DOM
helpBar.click(function () {
help.toggle();
};
helpBar.hover(function () {
help.peek();
};
});
</code></pre>
<p>Is this that much of an improvement over the first? Is there another way that I should be writing this kind of code? </p>
|
[] |
[
{
"body": "<p>A couple of pointers not in any particular order:</p>\n\n<p>If you use a single main object with methods it'll be easier to follow along later and add functionality etc. A pattern you can use is the observer pattern for setting up and triggering your events. Also if you use a single main object you can refer to the methods with <code>this.someMethod()</code> or to config options like <code>this.someOption</code>.</p>\n\n<p>Another thing is when you initialize your variables, you don't have to set them to false. If you do <code>var yolo;</code> it will be set to a falsy value so all you have to do later is set to <code>true</code>, or to test for if false use <code>!yolo</code>. On the other hand if you want to test for <code>true</code> just test for <code>(yolo)</code> like you have been doing. That way you can set any value to <code>yolo</code> and the test will be ok.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-09T15:02:14.137",
"Id": "24906",
"ParentId": "24904",
"Score": "0"
}
},
{
"body": "<p>As long as <code>help.toggle</code> and <code>help.peek</code> does not use <code>this</code>, you can simplify callback:</p>\n\n<pre><code>// jQuery DOM\nhelpBar.click( help.toggle );\n\nhelpBar.hover( help.peek );\n</code></pre>\n\n<p>And you can also chain it together</p>\n\n<pre><code>// jQuery DOM\nhelpBar.click( help.toggle ) \n .hover( help.peek );\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-09T19:25:19.947",
"Id": "24918",
"ParentId": "24904",
"Score": "0"
}
},
{
"body": "<p>If this is already your entire code, then you won't benefit much from namespacing your functions. Namespacing is basically assigning stuff to an object property. Accessing object properties is a minor overhead, but an overhead nevertheless. </p>\n\n<p>Also, it doesn't look like anything else is accessing the code made for click and hover, so I'd rather place them directly into the handler instead.</p>\n\n<p>You should be fine with simple functions in this case.</p>\n\n<p>I'd rather concentrate more on reducing redundant code. Here's what I have done:</p>\n\n<pre><code>//$(document).ready(fn) can be shortened to $(fn)\n$(function () {\n\n //declare variables in a function block up top\n //this is how the compiler sees them, so to avoid unexpected behavior\n //just follow suit\n var open = false\n , peek = false\n , helpBar = $(\".help-bar\")\n , helpIcon = $(\".help-icon\")\n , help = helpBar.add(helpIcon)\n ;\n\n //as explained, namespacing isn't an advantage at this level of code\n //and so, I have removed the functions and placed the code into the handlers\n\n //you can modify \"this\" in a function by using .call() or .apply()\n //in this case, element argument is removed and will be passed as \"this\"\n //this method will be explained later\n function changeRightValue(amount, speed) {\n this.animate({\n right: amount\n }, speed);\n }\n\n function toggleArrow(direction) {\n helpIcon.css(\"background\", \"url('/images/buttons/zapp/arrow\" + direction + \".png') no-repeat 0px 50%\");\n }\n\n //here we have our merged functions\n\n helpBar.on('click',function () {\n\n //if blocks that call the same functions but differ in parameters are messy\n //what I did here is made ternary ifs to pick arguments, not pick invocations\n //the calls will be made later\n var changeRightParams = open ? [0, 'slow'] : [280, 'fast']\n , direction = open ? 'Open' : 'Close'\n //this is a very short way to toggle booleans in the same variable\n , open = !open\n ;\n\n //here we call the functions with the \"picked\" arguments\n\n //here we use .apply to set the invoked function's this as help\n //and the arguments as the picked arguments\n //it's the same as calling \"help.changeRightValue(amount,speed)\n changeRightValue.apply(help, changeRightParams);\n toggleArrow(direction);\n\n }).on('hover',function () {\n\n //like above, declare variables up top to avoid unexpected behavior\n var changeRightParams;\n\n //here we use the \"early return\" pattern, to avoid nesting ifs\n //since nothing executes when open is true, we return early\n //we saved 1 indent level in the code\n if (open) return;\n\n //code after the early return assumes \"open\" is false\n //it would be similar to if(!open){/*stuff here*/}\n\n help.stop();\n\n //same as above, we pick arguments, toggle the boolean, call with the selected\n changeRightParams = peek ? [0, 'fast'] : [5, 'slow'];\n peek = !peek\n changeRightValue.apply(help, changeRightParams);\n\n });\n});\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T15:57:28.957",
"Id": "38571",
"Score": "0",
"body": "Thanks for the brilliant response. Nice to know that I'm heading along the right lines, but great to see where I can improve. Also wasn't aware of .apply(), so onwards and upwards!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-09T21:48:21.993",
"Id": "24923",
"ParentId": "24904",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "24923",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-09T14:38:05.857",
"Id": "24904",
"Score": "1",
"Tags": [
"javascript",
"jquery"
],
"Title": "Improving JavaScript - using objects vs. just functions"
}
|
24904
|
<p>I have the following dataset in numpy</p>
<pre><code>indices | real data (X) |targets (y)
| |
0 0 | 43.25 665.32 ... |2.4 } 1st block
0 0 | 11.234 |-4.5 }
0 1 ... ... } 2nd block
0 1 }
0 2 } 3rd block
0 2 }
1 0 } 4th block
1 0 }
1 0 }
1 1 ...
1 1
1 2
1 2
2 0
2 0
2 1
2 1
2 1
...
</code></pre>
<p>Theses are my variables</p>
<pre><code>idx1 = data[:,0]
idx2 = data[:,1]
X = data[:,2:-1]
y = data[:,-1]
</code></pre>
<p>I also have a variable <code>W</code> which is a 3D array.</p>
<p>What I need to do in the code is loop through all the blocks in the dataset and return a scalar number for each block after some computation, then sum up all the scalars, and store it in a variable called <code>cost</code>. Problem is that the looping implementation is very slow, so I'm trying to do it vectorized if possible. This is my current code. Is it possible to do this without for loops in numpy?</p>
<pre><code>IDX1 = 0
IDX2 = 1
# get unique indices
idx1s = np.arange(len(np.unique(data[:,IDX1])))
idx2s = np.arange(len(np.unique(data[:,IDX2])))
# initialize global sum variable to 0
cost = 0
for i1 in idx1s:
for i2 in idx2:
# for each block in the dataset
mask = np.nonzero((data[:,IDX1] == i1) & (data[:,IDX2] == i2))
# get variables for that block
curr_X = X[mask,:]
curr_y = y[mask]
curr_W = W[:,i2,i1]
# calculate a scalar
pred = np.dot(curr_X,curr_W)
sigm = 1.0 / (1.0 + np.exp(-pred))
loss = np.sum((sigm- (0.5)) * curr_y)
# add result to global cost
cost += loss
</code></pre>
<p>Here is some sample data</p>
<pre><code>data = np.array([[0,0,5,5,7],
[0,0,5,5,7],
[0,1,5,5,7],
[0,1,5,5,7],
[1,0,5,5,7],
[1,1,5,5,7]])
W = np.zeros((2,2,2))
idx1 = data[:,0]
idx2 = data[:,1]
X = data[:,2:-1]
y = data[:,-1]
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-01-23T00:48:33.853",
"Id": "354174",
"Score": "0",
"body": "Could you please edit the title of your question to be less generic?"
}
] |
[
{
"body": "<p>That <code>W</code> was tricky... Actually, your blocks are pretty irrelevant, apart from getting the right slice of <code>W</code> to do the <code>np.dot</code> with the corresponding <code>X</code>, so I went the easy route of creating an <code>aligned_W</code> array as follows:</p>\n\n<pre><code>aligned_W = W[:, idx2, idx1]\n</code></pre>\n\n<p>This is an array of shape <code>(2, rows)</code> where <code>rows</code> is the number of rows of your data set. You can now proceed to do your whole calculation without any for loops as:</p>\n\n<pre><code>from numpy.core.umath_tests import inner1d\npred = inner1d(X, aligned_W.T)\nsigm = 1.0 / (1.0 + np.exp(-pred))\nloss = (sigm - 0.5) * curr_y\ncost = np.sum(loss)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-09T15:55:12.177",
"Id": "24909",
"ParentId": "24905",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-09T15:00:43.700",
"Id": "24905",
"Score": "4",
"Tags": [
"python",
"optimization",
"numpy"
],
"Title": "Eliminate for loops in numpy implementation"
}
|
24905
|
<p>I was wondering if this is the correct implementation of a times task to destroy a thread after it overruns a predefined time period:</p>
<p>It works by creating a getting the thread from <code>runtime.getRuntime</code>, which it then uses to create a new process to run a command with the <code>exec()</code> method (creates a sub process). This is the process I want to terminate if it overruns. The code then handles the outputs streams from the process. before using <code>waitFor()</code> to let it finish running. However, in the circumstance it overruns, I have added a timer instance which I want it to use to terminate if the process overruns a defined time (retrieved using <code>getTimeout()</code>). However, I am worried the way I have done it will stop the original code from running.</p>
<p>Here is the timer code:</p>
<pre><code>timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run(){
processWasKilledByTimeout = true;
if(process != null){
process.destroy();
}
}
}, getTimeout();
</code></pre>
<p>I call this just after calling the exec method to create the subprocess.</p>
<p>Here is the full method:</p>
<pre><code>private Process process;
private boolean processWasKilledByTimeout = false;
public String executeCommand()throws Exception {
InputStreamReader inputStreamReader = null;
InputStreamReader inputErrorStreamReader = null;
BufferedReader bufferedReader = null;
BufferedReader bufferedErrorReader = null;
StringBuffer outputTrace = new StringBuffer();
StringBuffer errorTrace = new StringBuffer();
String templine = null;
Timer timer = null;
Runtime runtime = Runtime.getRuntime();
try {
// Running exec produces one of two streams- combine to produce common string.
process = runtime.exec(getCommand());
timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run(){
processWasKilledByTimeout = true;
if(process != null){
process.destroy();
}
}
}, getTimeout();
// The normal output stream
InputStream inputStream = process.getInputStream();
inputStreamReader = new InputStreamReader(inputStream);
bufferedReader = new BufferedReader(inputStreamReader);
while (((templine = bufferedReader.readLine()) != null) && (!processWasKilledByTimeout)) {
outputTrace.append(templine);
outputTrace.append("\n");
}
this.setStandardOut(outputTrace);
// The error output stream
InputStream inputErrorStream = process.getErrorStream();
inputErrorStreamReader = new InputStreamReader(inputErrorStream);
bufferedErrorReader = new BufferedReader(inputErrorStreamReader);
while (((templine = bufferedErrorReader.readLine()) != null) && (!processWasKilledByTimeout)) {
errorTrace.append(templine);
errorTrace.append("\n");
}
this.setErrorTrace(errorTrace);
//Wait for process to finish and return a code
int returnCode = process.waitFor();
//Set the return code
this.setReturnCode(returnCode);
if (processWasKilledByTimeout) {
//As process was killed by timeout just throw an InterruptedException
throw new InterruptedException("Process was killed before the waitfor was reached.");
}
} catch(IOException ioe) {
String error = "Error executing this command - "+getCommand() +". "+ioe.getMessage();
throw new CommandExecuterException(error);
}catch(IllegalArgumentException ile){
String error = "Illegal argument encountered while executing this command - "+getCommand() +". "+ile.getMessage();
throw new CommandExecuterException(error);
} catch(InterruptedException ie) {
error = "Process was killed after timeout by watchdog. "+ie.getMessage()+". ";
throw new CommandExecuterException(error);
} finally {
//cancel the timer not needed anymore
if(timer!= null){
timer.cancel();
}
try {
if(bufferedReader != null){
bufferedReader.close();
}
if(bufferedErrorReader != null){
bufferedErrorReader.close();
}
if(inputStreamReader != null){
inputStreamReader.close();
}
if(inputErrorStreamReader != null){
inputErrorStreamReader.close();
}
} catch(IOException ioe) {
String error = "Error closing stream - "+getCommand() +". "+ioe.getMessage();
throw new CommandExecuterException(error);
}
if(mProcess != null) {
mProcess.destroy();
}
}
//Assemble both the standardout and the errortrace
String tmpReturnString = getStandardOut().toString()+"\n"+getErrorTrace().toString();
return tmpReturnString;
}
</code></pre>
<p>Will this implementation override the threads run method?</p>
|
[] |
[
{
"body": "<p>The main idea looks ok for me. Use a timer with a given time to call the destroy.</p>\n\n<p>I would separate both concerns. One class is responsible for external program handling and it will provide a stop method. The stop method could be called from outside (e.g. the timer, but from manual interaction, too). The stop method will destroy the process and clean up.</p>\n\n<p>The exact implementation depends if you either want to call it asynchronous (call, let it run, do something else, get a callback) or synchronous (call, wait for finish, continue). But the main flow would be the same.</p>\n\n<p>I would not throw an exception (and even if, not with this hide and rethrow in other exception way). It is an expected behavior, not unexpected. So either call the corresponding callback function or provide a <code>hasFinished()</code> method or something like that and the caller could use it.</p>\n\n<p>I think your output-reading would not work in all cases. You have to take care about both channels, <code>stdout</code> and <code>stderr</code> together, not one after the other. You could do this in one loop if you want, but the better way is to read them with asynchronous running threads. <a href=\"http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html?page=4\" rel=\"nofollow\">This</a> shows the concept.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-09T18:08:51.740",
"Id": "24914",
"ParentId": "24907",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-09T15:33:46.063",
"Id": "24907",
"Score": "4",
"Tags": [
"java",
"strings",
"multithreading",
"timer",
"child-process"
],
"Title": "Timer/timertask to destroy a process that overruns a defined time limit"
}
|
24907
|
<p>I have a merge statement that takes around 10 minutes to process 5 million or more records.</p>
<p>The merge statement is part of a stored procedure that takes my newly bulk loaded staging table then runs data integrity checks, transforms the data into the proper format, and inserts that data where it should go.</p>
<p>Here are the tables:</p>
<pre><code>CREATE TABLE [dbo].[OrderFact]
(
Id BIGINT IDENTITY PRIMARY KEY
,CustomerId INT NOT NULL REFERENCES Customer (Id)
,BillingProcessorId INT NOT NULL REFERENCES BillingProcessor (Id)
,Quantity INT NOT NULL
,OrderStatus TINYINT NULL
,Cost MONEY NOT NULL
,AdjustedCost MONEY NOT NULL
,CreatedDate DATE NOT NULL DEFAULT GETUTCDATE()
,UpdatedDate DATE NOT NULL DEFAULT GETUTCDATE()
,IsDelete BIT NOT NULL DEFAULT (0)
);
GO
CREATE TABLE [Staging].[VendorAOrder]
(
OrderId INT
,Quantity INT NULL
,Cost MONEY NULL
,OrderStatus TINYINT NULL
,SellDate DATETIME2 NULL
,CustomerId NVARCHAR(20) NULL
,VendorPrefix NVARCHAR(20) NULL
,DataSetId INT NULL
)
GO
CREATE TABLE [Maps].[VendorAOrder]
(
Id BIGINT IDENTITY PRIAMRY KEY
,OrderFactId BIGINT NOT NULL REFERENCES OrderFact (Id)
,CreatedDate DATE NOT NULL DEFAULT GETUTCDATE()
,UpdatedDate DATE NOT NULL DEFAULT GETUTCDATE()
,IsDelete BIT NOT NULL DEFAULT (0)
);
GO
CREATE TABLE [Maps].[VendorARelatedOrder]
(
Id INT IDENTITY PRIMARY KEY
,VendorPrefix NVARCHAR(20) NOT NULL
,DataSetId INT NOT NULL REFERENCES DataSet (Id)
);
GO
CREATE TABLE [Maps].[VendorACustomer]
(
Id INT IDENTITY PRIMARY KEY
,CustomerId INT NOT NULL REFERENCES Customer (Id)
,OtherCustomerId NVARCHAR(20) NOT NULL
,CreatedDate DATE NOT NULL DEFAULT GETUTCDATE()
,UpdatedDate DATE NOT NULL DEFAULT GETUTCDATE()
,IsDelete BIT NOT NULL DEFAULT (0)
);
GO
</code></pre>
<p>Here is the merge statement:</p>
<pre><code>--In stored procedure
CREATE TABLE #OrderMaps
(
Id INT IDENTITY PRIMARY KEY
,OrderFactId BIGINT NOT NULL
,OrderId INT NOT NULL
,RelatedOrderId INT NOT NULL
)
-- Merge statement
-- Gets all non duplicate orders and inserts them into OrderFact
-- Outputs OrderId and new OrderFactId into temp table
-- Which is later inserted into [Maps].[VendorAOrder]
MERGE [OrderFact] AS [Target]
USING
(
SELECT
,mc.CustomerId
,b.Id AS BillingProcessorId
,o.OrderId
,ro.Id AS RelatedOrderId
,o.Quantity
,o.OrderStatus
,o.Cost
,AdjustedCost = CASE WHEN OrderStatus=1 THEN -Cost ELSE Cost END
,o.SellDate
FROM
(
SELECT *
FROM [Staging].[VendorAOrder] o
WHERE NOT EXISTS
(
SELECT 1
FROM [Maps].[VendorAOrder] orders
JOIN OrderFact of
ON order.OrderFactId = of.Id
AND orders.OrderId = o.OrderId
AND of.DataSetId = o.DataSetId
AND of.IsDelete = 0
)
) o
JOIN Maps.VendorARelatedOrder ro
ON or.VendorPrefix = o.VendorPrefix
AND or.DataSetId = o.DataSetId
JOIN BillingProcessor b
ON b.Id = o.BillingProcessorId
JOIN [Maps].VendorACustomer mc
ON mc.OtherCustomerId = o.CustomerId
AND mc.VendorId = o.VendorId
) AS [Source]
ON 1 = 0
WHEN NOT MATCHED BY TARGET THEN
INSERT
(
CustomerId
,BillingProcessorId
,Quantity
,OrderStatus
,Cost
,AdjustedCost
,SellDate
)
VALUES
(
[Source].CustomerId
,[Source].BillingProcessorId
,[Source].Quantity
,[Source].OrderStatus
,[Source].Cost
,[Source].AdjustedCost
,[Source].SellDate
)
OUTPUT (Inserted.Id, OrderId, RelatedOrderId)
INTO #OrderMaps(OrderFactId, OrderId, RelatedOrderId)
; -- End merge
</code></pre>
<p>Some things that I have tried that partially improved performance:</p>
<p>Create a temp table to pre filter orders</p>
<pre><code>CREATE TABLE #DistinctOrders
(
Id INT IDENTITY PRIMARY KEY
,OrderId NOT INT
,Quantity INT NOT NULL
,Cost MONEY NOT NULL
,OrderStatus TINYINT NOT NULL
,SellDate DATETIME2 NOT NULL
,CustomerId NVARCHAR(20) NOT NULL
,VendorPrefix NVARCHAR(20) NOT NULL
,DataSetId INT NOT NULL
,RelatedOrderId INT NOT NULL
);
GO
</code></pre>
<p>I could insert the orders into this table before I used the Merge Statement, but I am not sure of its performance increase.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-17T21:34:15.617",
"Id": "38995",
"Score": "1",
"body": "Why is your merge condition `ON 1 = 0`? It would help if you post index DDL as well as the execution plan for this query. And why do you say that you \"tried\" using a temp table but you're \"not sure of its performance increase\"? If you tried it, then presumably you know what the result was?"
}
] |
[
{
"body": "<p>Your <code>Staging</code> Table doesn't have a Primary Key in it, if it did that might speed things up a little bit, you gave your Temporary table a Primary key but not your Permanent <code>Staging</code> Table.</p>\n\n<hr>\n\n<p>Another thing that I noticed is that inside of your <code>Using</code> you use </p>\n\n<pre><code>SELECT *\n FROM [Staging].[VendorAOrder] o\n WHERE NOT EXISTS\n (\n SELECT 1\n FROM [Maps].[VendorAOrder] orders\n JOIN OrderFact of\n ON order.OrderFactId = of.Id\n AND orders.OrderId = o.OrderId\n AND of.DataSetId = o.DataSetId\n AND of.IsDelete = 0\n )\n</code></pre>\n\n<p>and then further down the line you use</p>\n\n<pre><code>ON 1 = 0\nWHEN NOT MATCHED BY TARGET THEN\n</code></pre>\n\n<p>could you make these both Agreeable? </p>\n\n<p>I am thinking that the <code>NOT MATCHED</code> and the <code>NOT EXIST</code> is causing some slowness in your Merge.</p>\n\n<p>I know that using <code><></code> or <code>NOT IN</code> can slow down a Query, could you possibly change these both to Positives instead of Negatives? </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-01T19:06:05.510",
"Id": "33665",
"ParentId": "24908",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-09T15:53:21.060",
"Id": "24908",
"Score": "1",
"Tags": [
"sql",
"sql-server"
],
"Title": "SQL Server merge statement"
}
|
24908
|
<p>This is my first attempt at using Python to send http requests. I want to keep a zone record on cPanel pointed at my home network's public IP. I'm just looking for some general feedback/suggestions. Is there an easier way to do this? Is there a more Pythonic way? My intent is to run this as a cronjob to stay ahead of my ISP's DHCP.</p>
<p>This file generates the http request containing the cPanel JSON API call.</p>
<pre><code>#!/usr/bin/python3
from http import client
from base64 import b64encode
from sys import argv
from netutils import PollIP
class ZoneUpdate:
def __init__ (self):
pass
def updateIP (self, passedIP):
newIP = passedIP
conn = client.HTTPSConnection('mydomain.com', 2083)
myAuth = b64encode(b'username:thepassword').decode('ascii')
authHeader = {'Authorization':'Basic ' + myAuth}
conn.request('GET', '/json-api/cpanel?cpanel_jsonapi_version=2&cpanel_jsonapi_module=ZoneEdit&cpanel_jsonapi_func=edit_zone_record&domain=mydomain.com&line=28&class=IN&type=A&name=homenet.mydomain.com.&ttl=3600&address=' + newIP, headers=authHeader)
myResponse = conn.getresponse()
print(myResponse.getcode())
data = myResponse.read()
if myResponse.getcode() != 200:
print('did not succeed')
print (data)
############################################
if __name__ == "__main__":
app = ZoneUpdate()
if len(argv) > 1:
newIP = argv[1]
print(argv[1])
else:
getIP = PollIP()
newIP = getIP.publicIP()
app.updateIP(newIP)
</code></pre>
<p>This module (imported by the preceding) will use the dyndns website to obtain my public IP address.</p>
<pre><code>#!/usr/bin/python3
from urllib import request
from re import compile
class PollIP:
def __init__(self):
pass
#Use the dyndns web-site to poll my public IP address
def publicIP(self):
myReq = request.urlopen('http://checkip.dyndns.com')
html = str(myReq.read())
myReg = compile('[\d.]+')
myMatch = myReg.search(html)
print(myMatch.group())
return myMatch.group()
</code></pre>
|
[] |
[
{
"body": "<p>Before anything else, I'd like to point out that there is probably an error with your indentation. I've fixed it in my code assuming that only one line was not indented properly..</p>\n\n<p><strong>Simple is better than complex.</strong></p>\n\n<ul>\n<li>You don't need the classes (you can also have a look at <a href=\"http://pyvideo.org/video/880/stop-writing-classes\" rel=\"nofollow\">this video</a>). After taking this simple comment into account, your code looks like this (I put everything in the same place for the sake of simplicity)</li>\n</ul>\n\n<pre>\n#!/usr/bin/python3\n\nfrom http import client\nfrom base64 import b64encode\nfrom sys import argv\nfrom netutils import PollIP\nfrom urllib import request\nfrom re import compile\n\n#Use the dyndns web-site to poll my public IP address \ndef publicIP():\n myReq = request.urlopen('http://checkip.dyndns.com')\n html = str(myReq.read())\n myReg = compile('[\\d.]+')\n myMatch = myReg.search(html)\n print(myMatch.group())\n return myMatch.group()\n\ndef updateIP (passedIP):\n newIP = passedIP \n conn = client.HTTPSConnection('mydomain.com', 2083)\n myAuth = b64encode(b'username:thepassword').decode('ascii')\n authHeader = {'Authorization':'Basic ' + myAuth}\n conn.request('GET', '/json-api/cpanel?cpanel_jsonapi_version=2&cpanel_jsonapi_module=ZoneEdit&cpanel_jsonapi_func=edit_zone_record&domain=mydomain.com&line=28&class=IN&type=A&name=homenet.mydomain.com.&ttl=3600&address=' + newIP, headers=authHeader)\n myResponse = conn.getresponse()\n print(myResponse.getcode())\n data = myResponse.read()\n if myResponse.getcode() != 200:\n print('did not succeed')\n print (data)\n\n############################################\n\nif __name__ == \"__main__\":\n if len(argv) > 1:\n newIP = argv[1]\n print(argv[1])\n else: \n newIP = publicIP()\n updateIP(newIP)\n</pre>\n\n<ul>\n<li><p>Your variables names are probably not that good. What do you mean by 'new' ? Also, many variables are not even required (I've been pretty far in the cleanup as it helped me to understand the code, you might want to keep some of the variables I've removed). Also, your function names are not really well chosen as it doesn't really describe what they do : <code>updateIP</code> does not seem to update the IP at all.</p></li>\n<li><p>Separate the concerns : do you want publicIP() to return a string or to print it ? It should probably just return it and then you print it from the main if you want. Please note that doing this introduces an interesting pattern : you print <code>newIP</code> from the 2 branches of your <code>if</code>. You can easily get rid of this duplicated code. In the same spirit, <code>updateIP(ip)</code> seems to be printing things and does not return anything. Let's name the function to make this easier to understand. Please note that : 1) you'd probably want this to return a string in a real life situation 2) you might want it to throw an exception if something fails 3) my functions names are terrible 4) there are naming convention for Python that you'll find in <a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">PEP 008</a> (it's worth a read).</p></li>\n<li><p>You can get rid of values (urls, ports, login, password, etc) in the middle of the code. This can be useful if you need to reuse them in different places. In any case, it's worth replacing <code>200</code> by <code>client.OK</code> which is much clearer.</p></li>\n</ul>\n\n<p>Once you've done so, here what you code is like :</p>\n\n<pre>\n#!/usr/bin/python3\n\nfrom http import client\nfrom base64 import b64encode\nfrom sys import argv\nfrom netutils import PollIP\nfrom urllib import request\nfrom re import compile\n\n#Use the dyndns web-site to poll my public IP address \ndef getPublicIP():\n html = str(request.urlopen('http://checkip.dyndns.com').read())\n reg = compile('[\\d.]+')\n match = reg.search(html)\n return match.group()\n\ndef printIPFromIP(ip):\n conn = client.HTTPSConnection('mydomain.com', 2083)\n conn.request('GET', '/json-api/cpanel?cpanel_jsonapi_version=2&cpanel_jsonapi_module=ZoneEdit&cpanel_jsonapi_func=edit_zone_record&domain=mydomain.com&line=28&class=IN&type=A&name=homenet.mydomain.com.&ttl=3600&address=' + ip, \n headers={'Authorization':'Basic ' + b64encode(b'username:thepassword').decode('ascii')})\n response = conn.getresponse()\n print(response.getcode())\n if response.getcode() != client.OK:\n print('did not succeed')\n print (response.read())\n\n############################################\n\nif __name__ == \"__main__\":\n ip = argv[1] if len(argv) > 1 else getPublicIP()\n print(ip)\n printIPFromIP(ip)\n</pre>\n\n<p>It's probably not perfect but I think I hilighted the main issues.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-09T18:14:06.463",
"Id": "38498",
"Score": "0",
"body": "Thank you for the thorough response and helpful resources!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-09T18:06:06.633",
"Id": "24913",
"ParentId": "24910",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "24913",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-09T16:17:12.057",
"Id": "24910",
"Score": "1",
"Tags": [
"python",
"https"
],
"Title": "Python script to update a cPanel zone record with my public IP"
}
|
24910
|
<p>This is my attempt at constructing a singly-linked-list with basic functions. I initially tried to build the whole list as a series of nodes, but ran into problems when trying to remove or pop index-0. This time I created a series of Node structs and a single List struct as their head. This allowed me to modify the list in place without risk of losing the first pointer.</p>
<p>Anyway, it's not for production. This was written on my own time. I have no interest in optimizing this code and am simply trying to understand c programming before I start my first computer science class this next year. If anything I'm doing seems like a bad approach, or worse, dangerous, let me know.</p>
<p><strong>linkedlist02.h:</strong></p>
<pre><code>#ifndef LINKED_LIST_02
#define LINKED_LIST_02
typedef struct NodeTag {
char *data;
struct NodeTag *next;
} Node;
Node *Node_create();
void Node_destroy(Node *node);
typedef struct ListTag {
struct NodeTag *first;
} List;
List *List_create();
void List_destroy(List *list);
void List_append(List *list, char *str);
void List_insert(List *list, int index, char *str);
char *List_get(List *list, int index);
int List_find(List *list, char *str);
void List_remove(List *list, int index);
char *List_pop(List *list, int index);
int List_length(List *list);
void List_print(List *list);
#endif
</code></pre>
<p><strong>linkedlist02.c:</strong></p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include "linkedlist02.h"
int main() {
List *l = List_create();
List_append(l, "jim");
List_append(l, "bob");
List_append(l, "joe");
List_append(l, "bean");
List_append(l, "junior");
List_insert(l, 3, "HAROLD");
List_insert(l, List_length(l), "CARL");
List_insert(l, 0, "MIKE");
List_remove(l, 2);
List_print(l);
printf("Length: %i\n", List_length(l));
printf("Pop 3: %s\n", List_pop(l, 3));
printf("Get 3: %s\n", List_get(l, 3));
printf("Find \"junior\": %i\n", List_find(l, "junior"));
List_destroy(l);
return 0;
}
Node *Node_create() {
Node *node = malloc(sizeof(Node));
assert(node != NULL);
node->data = "";
node->next = NULL;
return node;
}
void Node_destroy(Node *node) {
assert(node != NULL);
free(node);
}
List *List_create() {
List *list = malloc(sizeof(List));
assert(list != NULL);
Node *node = Node_create();
list->first = node;
return list;
}
void List_destroy(List *list) {
assert(list != NULL);
Node *node = list->first;
Node *next;
while (node != NULL) {
next = node->next;
free(node);
node = next;
}
free(list);
}
void List_append(List *list, char *str) {
assert(list != NULL);
assert(str != NULL);
Node *node = list->first;
while (node->next != NULL) {
node = node->next;
}
node->data = str;
node->next = Node_create();
}
void List_insert(List *list, int index, char *str) {
assert(list != NULL);
assert(str !=NULL);
assert(0 <= index);
assert(index <= List_length(list));
if (index == 0) {
Node *after = list->first;
list->first = Node_create();
list->first->data = str;
list->first->next = after;
} else if (index == List_length(list)) {
List_append(list, str);
} else {
Node *before = list->first;
Node *after = list->first->next;
while (index > 1) {
index--;
before = before->next;
after = after->next;
}
before->next = Node_create();
before->next->data = str;
before->next->next = after;
}
}
char *List_get(List *list, int index) {
assert(list != NULL);
assert(0 <= index);
assert(index < List_length(list));
Node *node = list->first;
while (index > 0) {
node = node->next;
index--;
}
return node->data;
}
int List_find(List *list, char *str) {
assert(list != NULL);
assert(str != NULL);
int index = 0;
Node *node = list->first;
while (node->next != NULL) {
if (strlen(str) == strlen(node->data)) {
int cmp = strcmp(str, node->data);
if (cmp == 0) {
return index;
}
}
node = node->next;
index++;
}
return -1;
}
void List_remove(List *list, int index) {
assert(list != NULL);
assert(0 <= index);
assert(index < List_length(list));
if (index == 0) {
Node *node = list->first;
list->first = list->first->next;
Node_destroy(node);
} else {
Node *before = list->first;
while (index > 1) {
before = before->next;
index--;
}
Node *node = before->next;
before->next = before->next->next;
Node_destroy(node);
}
}
char *List_pop(List *list, int index) {
assert(list != NULL);
assert(0 <= index);
assert(index < List_length(list));
if (index == 0) {
Node *node = list->first;
list->first = list->first->next;
char *data = node->data;
Node_destroy(node);
return data;
} else {
Node *before = list->first;
while (index > 1) {
before = before->next;
index--;
}
Node *node = before->next;
before->next = before->next->next;
char *data = node->data;
Node_destroy(node);
return data;
}
}
int List_length(List *list) {
assert(list != NULL);
Node *node = list->first;
int length = 0;
while (node->next != NULL) {
length++;
node = node->next;
}
return length;
}
void List_print(List *list) {
assert(list != NULL);
printf("[");
Node *node = list->first;
while (node->next != NULL) {
printf("%s", node->data);
node = node->next;
if (node->next != NULL) {
printf(", ");
}
}
printf("]\n");
}
</code></pre>
|
[] |
[
{
"body": "<p>Nice code, compiles almost cleanly. I'm impressed that this is your code <strong>before</strong> starting courses. I've met people with years of experience who couldn't write such good code. </p>\n\n<p>I have a few comments, starting with the concept. You have a list structure that you initialise to hold an empty node. I don't see what this gives you that a simple Node* pointer would not. The List structure might be of more use if you kept a pointer to the beginning and end of the list and maybe some metadata, like the length of the list. But really I think the List structure is redundant and complicates the functions and that the empty node is confusing.</p>\n\n<h2>General points</h2>\n\n<ul>\n<li>Add a <code>void</code> parameter list for functions with no parameters.</li>\n<li><p>Use <code>const</code> in parameter lists where the function does not change the parameter, eg.</p>\n\n<pre><code>int List_find(const List *list, const char *str);\n</code></pre></li>\n<li><p>handling of <code>malloc</code> failure with an <code>assert</code> is wrong. Adding an assert is much easier than handling the errors correctly, but asserts are for detecting logic failures, not runtime resource/data failures. For malloc failure you either print an error and exit (yes, that is what assert does, but asserts can be disabled with NDEBUG) or you return an error to the caller. Of course if you handled malloc failure by returning a NULL to the caller, you complicate your program throughout. That is why it is often ignored (though clearly it should not be).</p></li>\n<li><p>handling other conditions with assert is debatable. It is attractive because it is so easy, but it is lazy and is not universally applicable. For example, you can do it if you have a shell to return to - assert prints a message and exits; you see the message in the shell and maybe restart the process. But there are applications where there is no shell, for example embedded systems where it is not possible just to exit - you have to handle the error somehow. And then when you compile with NDEBUG, your error handling disappears completely. Best to use assert only for logic failures and handle data errors correctly with error returns.</p></li>\n<li><p>counting down in while- or for-loops is much less common than counting up. It can be done, but it saves nothing, is less intuitive and is more error-prone. Best to count up. Also for-loops are preferable when you have a loop variable like this:</p>\n\n<pre><code>while (index > 0) {\n ...\n index--;\n}\n</code></pre>\n\n<p>So I would prefer to see:</p>\n\n<pre><code>for (int i = 0; i < index; ++i) {\n ....\n}\n</code></pre></li>\n<li><p>a detailed point is that the strings you are adding to the list are almost certainly constant strings (eg in <code>List_append(l, \"jim\");</code>). So the functions returning strings from the list as <code>char *</code> are almost certainly wrong - they should be const. You can fix that by duplicating (ie. allocating) the strings when you create nodes - and freeing them later. This might be safer anyway, in case the caller passes your list function a string that is non-permanent (eg it is on the stack or temporarily allocated). So either make the return strings const or allocate a copy.</p></li>\n</ul>\n\n<h2>List_insert</h2>\n\n<p>This is rather complicated. Essentially what must be done is: create a node; hang it in the list. So creating and setting the data in the node is common and can be done first for all cases. Then you can insert it. Note that it is not clear why inserting beyond the end of the list must be considered an error - why not call it appending? Then <code>list_append()</code> can just call </p>\n\n<pre><code>list_insert(l, INT_MAX, str);\n</code></pre>\n\n<h2>List_find</h2>\n\n<p>Don't compare strings using first <code>strlen</code> and then <code>strcmp</code> - that is pointless. Just use <code>strcmp</code>. Also this:</p>\n\n<pre><code>int cmp = strcmp(str, node->data);\nif (cmp == 0) {\n return index;\n}\n</code></pre>\n\n<p>is more concisely written as</p>\n\n<pre><code>if (strcmp(...) == 0) { /* or even if (!strcmp(...)), though some don't like that */\n return index;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-09T20:00:27.420",
"Id": "38501",
"Score": "0",
"body": "Thank you! That is exactly the sort of input I was hoping for. I haven't been exposed to several of your points and will need to look into them (void parameter, const, etc.), while the errors I need to test for don't occur in Python, where I'm far more comfortable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-09T20:02:33.460",
"Id": "38502",
"Score": "0",
"body": "The choice to include a List struct was to solve the common problem of completing the task. I was wasting too much time trying to get nodes to cover my needs. Fortunately, I expect they'll come in handy when I make a doubly-linked-list."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-09T19:39:48.567",
"Id": "24921",
"ParentId": "24911",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "24921",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-09T17:16:28.170",
"Id": "24911",
"Score": "5",
"Tags": [
"c",
"linked-list"
],
"Title": "Singly Linked List (strings only)"
}
|
24911
|
<p>I have 3 fields:</p>
<ul>
<li>Net Price (ex. tax)</li>
<li>tax amount</li>
<li>Total price (price ex. vat + tax amount)</li>
</ul>
<p>The <code>NetPrice</code> and the <code>Total</code> are writable (i.e. you can change either of them and the other 2 values must be auto-calculated).</p>
<p>The way I've done it is using 3 observable and 2 computed knockout objects but I thought perhaps someone who knows Knockout a lot better could suggest a more efficient way to achieve this.</p>
<p><a href="http://jsfiddle.net/ruslans/vFK82/" rel="nofollow">Working jsFiddle</a></p>
<p>HTML:</p>
<pre><code>Net Price:
<input type="textbox" data-bind="value: NetPriceCalc" />
<br />Tax Amount:
<label data-bind="html: TaxAmt"></label>
<br />Total:
<input type="textbox" data-bind="value: TotalCalc" />
</code></pre>
<p>Script:</p>
<pre><code>var viewModel = {
NetPrice: ko.observable(100),
TaxAmt: ko.observable(20),
Total: ko.observable(120),
TaxRate: 0.2
};
viewModel.updateTaxAmt = function (useNetPrice) {
if (useNetPrice) {
return this.TaxAmt(this.NetPrice() * this.TaxRate);
} else {
var total = Number(this.Total());
var taxAmt = total - total / (1 + this.TaxRate);
return this.TaxAmt(taxAmt);
}
};
viewModel.updateNetPrice = function () {
this.NetPrice(Number(this.Total()) - Number(this.TaxAmt()));
};
viewModel.updateTotal = function () {
this.Total(Number(this.NetPrice()) + Number(this.TaxAmt()));
};
viewModel.NetPriceCalc = ko.computed({
read: function () {
console.log("NetPriceCalc read");
return viewModel.NetPrice();
},
write: function (value) {
console.log("NetPriceCalc write");
viewModel.NetPrice(value);
viewModel.updateTaxAmt(true);
return viewModel.updateTotal();
}
});
viewModel.TotalCalc = ko.computed({
read: function () {
console.log("TotalCalc read");
return viewModel.Total();
},
write: function (value) {
console.log("TotalCalc write");
viewModel.Total(value);
viewModel.updateTaxAmt(false);
return viewModel.updateNetPrice();
}
});
ko.applyBindings(viewModel);
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T09:32:50.767",
"Id": "38537",
"Score": "0",
"body": "Just in any case anybody also didn't knew knockout like me: http://knockoutjs.com/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-11T15:15:03.973",
"Id": "38673",
"Score": "1",
"body": "I answered your question on stackoverflow, check this http://stackoverflow.com/questions/15920306/circular-dependency-of-knockout-computed/15924786#15924786"
}
] |
[
{
"body": "<p>I will review and contrast the SO answer that I liked best: </p>\n\n<pre><code>function viewModel() {\n var self = this;\n\n self.NetPrice = ko.observable(100);\n\n self.TaxRate = 0.2;\n\n self.TaxAmt = ko.computed(function() {\n return parseFloat(self.NetPrice()) * self.TaxRate;\n });\n\n self.Total = ko.computed({\n read: function() { \n return parseFloat(self.NetPrice()) + self.TaxAmt();\n },\n write: function(val){\n var total = parseFloat(val);\n var taxAmt = total - total / (1 + self.TaxRate); \n self.NetPrice(total - taxAmt);\n }\n });\n}\n</code></pre>\n\n<ul>\n<li>It is more standard to create a constructor, then to create an object with object notation and then add functions.</li>\n<li>Not to big a fan of using <code>self</code> everywhere instead of <code>this</code> in the SO answer</li>\n<li>Do not use <code>console.log</code> in production code</li>\n<li>Do not use <code>calc</code> as part of the variable name</li>\n<li>Do not use a <code>useNetPrice</code> type of indicator, knockout can figure out the <code>computed</code> values on its own and knows when to recalculate what</li>\n<li><code>write</code> functions do not have to <code>return</code> anything</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T20:55:31.117",
"Id": "44797",
"ParentId": "24925",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "44797",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-09T22:15:26.260",
"Id": "24925",
"Score": "5",
"Tags": [
"javascript",
"knockout.js"
],
"Title": "Two Knockout computed dependent on each other"
}
|
24925
|
<p>I have constructed a simple implementation of a parallel loop:</p>
<pre><code>#include <algorithm>
#include <thread>
#include "stdqueue.h"
namespace Wide {
namespace Concurrency {
template<typename Iterator, typename Func> void ParallelForEach(Iterator begin, Iterator end, Func f) {
std::vector<Iterator> its;
while(begin != end)
its.push_back(begin++);
Queue<Iterator> its_queue(its.begin(), its.end());
auto threadnum = std::thread::hardware_concurrency() + 1;
std::atomic<bool> exception = false;
std::mutex exception_lock;
std::exception_ptr except;
std::vector<std::thread> threads;
for(int i = 0; i < threadnum; ++i) {
threads.push_back(std::thread([&] {
while(true) {
Iterator it;
if (!its_queue.try_pop(it))
break;
if (exception)
return;
try {
f(*it);
} catch(...) {
std::lock_guard lm(exception_lock);
except = std::current_exception();
exception = true;
return;
}
}
}));
}
for(auto&& thr : threads)
thr.join();
if (exception)
std::rethrow_exception(except);
}
}
}
</code></pre>
<p>The only non-standard class here is <code>Queue</code>, and it is simply a mutex over a <code>std::queue</code>, essentially (at least in this code path), although I have encapsulated the attempt to pop an object off into a single function <code>try_pop</code>, which you will recognize from PPL and TBB.</p>
<p>Also note that <code>f</code> will be hefty, not a light function at all. It is also likely that each invocation of <code>f</code> will run slightly different times depending on the contents of <code>*it</code>.</p>
<p>Kindly comment on the performance and safety of this function. I am obviously more concerned about safety than performance, so highly complex tricks to earn more performance are likely not viable for me.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T10:36:07.653",
"Id": "38540",
"Score": "0",
"body": "I can see a few errors that will stop this from even compiling. It should be `std::lock_guard<std::mutex>` for one. Depending on your compiler, it may barf at `std::vector<std::thread>` followed by `push_back(std::thread)`. You're likely better off doing `std::vector<std::thread> threads(threadnum)` followed by a `threads[i] = std::thread(...)`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T22:01:03.317",
"Id": "38628",
"Score": "0",
"body": "@Yuushi it should be `vector<unique_ptr<thread>>` then."
}
] |
[
{
"body": "<p>First, that <code>begin/end</code> range, <code>its</code> and <code>its_queue</code> are duplicates of each other.<br>\nIf we change <code>Iterator</code> to <code>RandomAccessIterator</code>, we can get rid of them:</p>\n\n<pre><code>template<typename RA_Iterator, typename Func> void ParallelForEach(RA_Iterator begin, RA_Iterator end, Func f) {\n const auto size = end - begin;\n std::atomic<std::size_t> pos = 0;\n\n ...\n std::thread([&] {\n while(true) {\n auto i = pos.fetch_add(1);\n if (i >= size)\n break;\n\n ...\n f(*(begin + i));\n</code></pre>\n\n<p>Second, creating threads for each <code>ForEach</code> costs a lot. Writing all that exception-transferring boilerplate doesn't look good either. That's why I'd use <code>std::async</code> which probably could reuse threads and also can deal with exceptions.</p>\n\n<pre><code> std::atomic<bool> exception = false;\n std::vector<std::future<void>> threads;\n for(int i = 0; i < threadnum; ++i) {\n threads.push_back(std::async([&] {\n MyScopeExit onExit([&]{ exception = true; });\n while(true) {\n ... \n if (exception)\n break;\n\n f(*it);\n }\n onExit.disarm();\n }));\n }\n for(auto&& thr : threads)\n thr.get();\n</code></pre>\n\n<p>And finally, the code could look like this:</p>\n\n<pre><code> const auto size = end - begin;\n std::atomic<std::size_t> pos = 0;\n ...\n std::vector<std::future<void>> threads;\n for(int i = 0; i < threadnum; ++i) {\n threads.push_back(std::async([&] {\n MyScopeExit onExit([&]{ pos = size; });\n while(true) {\n auto i = pos.fetch_add(1);\n if (i >= size)\n break;\n\n f(*(begin + i));\n }\n onExit.disarm();\n }));\n }\n for(auto&& thr : threads)\n thr.get();\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T22:03:40.890",
"Id": "24977",
"ParentId": "24927",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-09T23:19:58.713",
"Id": "24927",
"Score": "1",
"Tags": [
"c++",
"multithreading",
"c++11"
],
"Title": "parallel_for_each"
}
|
24927
|
<p>I have a functionality that imports data into a database, based on an Excel workbook and some meta data (both user-supplied). The functionality implements interface <code>IFunctionality</code> which essentially specifies an <code>AuthId</code> string property (used for fetching authorized AD groups for a functionality) as well as a <code>CanExecute</code> and <code>Execute</code> method.</p>
<p>The catch is that a <code>Functionality</code> must be COM-visible to be called via a legacy VB6 application and I want the COM interface as simple as it could be, and to me this means a <code>IFunctionality</code> implementation only has a parameterless constructor.</p>
<p>Below is the <em>almost</em> complete code (stripped a couple DAL calls and anonymized company-specifics) for one of those functionalities. I'm not going to supply DAL and Presentation layer code here, since my concerns are mainly around the Business Logic layer - but for the record I have DAL implemented with Linq to SQL and Presentation taken care of with WPF (which I just started learning).</p>
<pre><code>[ComVisible(true)]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(IFunctionality))]
public class ImportFunctionality : IFunctionality
{
private ImportWindow _window; // a WPF view
public ImportFunctionality()
{ }
public bool CanExecute()
{
return CurrentUser.IsAuthorized(AuthId);
}
public string AuthId
{
get { return GetType().ToString(); }
}
/// <summary>
/// Prompts for an Excel workbook filename and creates pricing tables from workbook data.
/// </summary>
public void Execute()
{
try
{
if (!CanExecute()) throw new NotAuthorizedException(resx.Functionality_Execute_NotAuthorised);
var xlData = GetExcelSourceData();
if (xlData == null) return;
var viewModel = GetImportSettings(xlData);
if (viewModel == null) return;
if (!GetUserConfirmation(viewModel)) return;
ImportGridContent(viewModel);
}
catch (NotAuthorizedException exception)
{
MsgBox.Failure(resx.NotAuthorized, exception.Message);
}
catch (Exception exception)
{
MsgBox.Error(exception);
}
}
private DataTable GetExcelSourceData()
{
var file = FileDialogHelper.GetOpenFileName(resx.FileDialogFilter_Excel97_2003);
if (file == string.Empty) return null;
return Excel8OleDbHelper.ImportExcelFile(file);
}
private ImportViewModel GetImportSettings(DataTable xlData)
{
var viewModel = new ImportViewModel(xlData);
// todo: add metadata to viewModel constructor...
using (var data = new ImportModel(Settings.Default.DefaultDb))
{
// Wrap Linq2SQL objects into UI-visible instances:
var meta = data.LoadImportMetadata()
.Select(e => new ImportMetaData
{
// named property setters
}).ToList();
// load metadata into ViewModel:
viewModel.SetMetadata(new ObservableCollection<ImportMetaData>(meta));
}
_window = new ImportWindow(viewModel);
viewModel.WindowClosing += viewModel_WindowClosing;
_window.ShowDialog();
var result = viewModel.DialogResult;
return (result == DialogResult.Ok)
? viewModel
: null;
}
private bool GetUserConfirmation(ImportViewModel viewModel)
{
var result = MsgBox.Prompt(resx.ConfirmationRequired, resx.ImportFunctionality_ConfirmProceed);
return (result == DialogResult.Yes);
}
void viewModel_WindowClosing(object sender, EventArgs e)
{
_window.Close();
}
/// <summary>
/// Returns a <see cref="IImportData"/> implementation that corresponds to database name specified by supplied <see cref="viewModel"/>.
/// </summary>
/// <param name="viewModel"></param>
/// <returns></returns>
public IImportData GetTargetConnection(ImportViewModel viewModel)
{
var connectionString = Settings.Default[viewModel.SelectedDatabase].ToString();
return viewModel.SelectedCompany == CompaniesEnum.Company1.ToString()
? new ImportDataCompany1(connectionString)
: viewModel.SelectedCompany == CompaniesEnum.Company2.ToString()
? new ImportDataCompany2(connectionString)
: new ImportData(connectionString)
// this is begging to be refactored
;
}
private void ImportGridContent(ImportViewModel viewModel)
{
using (var data = GetTargetConnection(viewModel))
{
var args = new AsyncImportEventArgs(viewModel, data);
var iterations = viewModel.GridSource.Rows.Count * viewModel.SelectedMetadata.Count();
data.BeginTransaction();
MsgBox.ProgressStatus<AsyncImportEventArgs>(resx.ImportFunctionality_Title, resx.ImportFunctionality_PleaseWait, DoAsyncImport, args, CancelAsyncImport, iterations);
if (args.Success)
data.CommitTransaction();
else
data.RollbackTransaction();
}
}
protected void DoAsyncImport(AsyncProgressArgs<AsyncImportEventArgs> e)
{
// Lengthy operation involving DAL calls and periodically updating the view
// ...
// Update the view:
e.UpdateProgress(resx.ProgressCompleted, maxProgressValue);
e.UpdateMessage(resx.ImportFunctionality_TitleCompleted);
}
private void CancelAsyncImport(AsyncImportEventArgs e)
{
e.Success = false;
e.Data.RollbackTransaction();
MsgBox.Info(resx.ImportFunctionality_Cancelled_Title, resx.ImportFunctionality_Cancelled_Msg);
}
#region nested types
/// <summary>
/// Encapsulates parameters passed to async method for importing pricing tables.
/// </summary>
public class AsyncImportEventArgs : EventArgs
{
public ImportViewModel ViewModel { get; private set; }
public IImportData Data { get; private set; }
public bool Success { get; set; }
public AsyncImportEventArgs(ImportViewModel dialog, IImportData data)
{
ViewModel = dialog;
Data = data;
}
}
#endregion
}
</code></pre>
<p>The questions I have are the following:</p>
<ol>
<li>If I wanted to write unit tests for this functionality, what would I need to do in order to make the code unit-testable? I have no issues making methods public, as they wouldn't be exposed to COM anyway (because only <code>IFunctionality</code> is accessible through COM). Or perhaps I should make them protected, and derive from this class so I could test it (the test wrapper class would expose public methods that call into the protected ones; tests would call those exposed public methods and it could even have dependencies injected into its constructor - am I thinking the right way about this?).</li>
<li>If I wanted to write unit tests for this functionality, I couldn't write a test for the <code>Execute</code> method, right? I'd have to test the more specialized code and figure out how to mock the DAL calls? And for <code>CanExecute</code>, I'd need a way to get rid of the <code>CurrentUser</code> dependency and inject some dummy provider that doesn't hit the database nor Active Directory, right?</li>
<li>Is this code "clean"? (easy to read, easy to understand, easy to maintain) I guess the sole fact that I'm asking this, answers for itself... How could it be made <em>cleaner</em> then?</li>
<li>Are static classes and methods hindering anything? (like <code>CurrentUser.IsAuthorized</code>, <code>FileDialogHelper.GetOpenFileName</code>, and <code>Excel8OleDbHelper.ImportExcelFile</code>) - <code>MsgBox</code> lives in the Presentation layer and it aims at replacing the ugly default message box, I think the static class is warranted in that particular case.</li>
<li>Sharp eyes will have noticed I initiate a db transaction, do some work while showing progress (the process can take anywhere between a minute and 2 hours, depending on inputs) and then committing or rolling back the transaction <em>only after the ProgressMsgBox has closed</em>. This leaves the affected tables unnecessarily locked, longer than they need to be. How can I work around this? (hmm now that I'm thinking about it, I could have the ViewModel raise an event when progress completes and handle it in this class to commit or rollback as needed... but I'd have to make <em>data</em> a property of the class... makes sense? Then I guess the functionality class would need to implement <code>IDisposable</code> and rely on the client code to properly dispose its resources, no?)</li>
</ol>
|
[] |
[
{
"body": "<p>The points you've specified in your question actually show that you (almost) see issues in your code yourselves, so thumbs up for that. I'll only expand on your points plus add a couple:</p>\n\n<ul>\n<li>your class is doing too much. You've noted that it has to be accessible from COM, but it doesn't mean that this exact class (business logic, BL) should be accessible from COM. What you should do is create a separate class/interface for accessing BL from COM (in terms of patterns it is called façade), and that class should wire up and issue calls to your BL, so that BL is not designed with restrictions/requirements imposed by COM;</li>\n<li>you should rewrite all your static classes/helpers like <code>CurrentUser</code>, <code>FileDialogHelper</code> and <code>Excel8OleDbHelper</code> to be instance classes implementing certain interfaces, and use them from main \"functionality\" class via interfaces only;</li>\n<li>do not use UI in business logic (<code>MsgBox.Failure</code>, <code>_window.ShowDialog</code>, <code>MsgBox.Prompt</code>, etc). The code that uses business logic should be responsible for providing data needed, and showing errors/messages to customer, and business logic should not reference any class from UI namespaces;</li>\n<li>you <strong>should not</strong> expose private methods as public/protected in order to unit-test them. Write as many unit tests (that use only public interface of your class) as you need to check all use cases of your class. Requirement \"all use cases\" ensures that they will verify all private methods as well;</li>\n<li>transactions should not depend on UI. If you need to expose progress of long-term operation - expose an event for that, but don't block on it. If you need a confirmation for final import - just expose another method that UI can call when user confirmed the import;</li>\n<li>extract DAL-related code into separate class with its own interface;</li>\n<li>wire up all the classes either manually in the COM-exposed class or using one of the IoC frameworks;</li>\n<li>test each class separately, mocking all external dependencies (that you should reference via interface) with one of the mocking frameworks (Moq, Rhino Mocks, etc)</li>\n<li>you haven't shown import code, but I would suggest looking into bulk upload methods, e.g. like suggested <a href=\"http://technico.qnownow.com/custom-data-reader-to-bulk-copy-data-from-object-collection-to-sql-server/\">here</a>.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T12:35:13.553",
"Id": "38559",
"Score": "0",
"body": "The actual import code was edited out, it involves such a specific algorithm that it belongs in its own class... and from your answer I get that most of the code also belongs in another class - thanks for an amazing answer, I'll look into this *façade* pattern! I've read on *Clean Code* and seen unit tests and DI and IoC in action, but never really implemented it myself, not for a real project that is - I *smell* the issues rather than *seeing* them :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T08:53:33.327",
"Id": "24946",
"ParentId": "24930",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "24946",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T01:30:40.743",
"Id": "24930",
"Score": "8",
"Tags": [
"c#",
"design-patterns",
"unit-testing"
],
"Title": "Unit-testing the importing of data into a database"
}
|
24930
|
<p>The problem I am facing is:
I need to interate through a bunch of lists, and there are separated conditions which needs to be satisfied by the list. conditons are not independent.</p>
<p>I care about the situation when all the conditions are matched. </p>
<p>The solutions I come up is nested interations mixed with conditions on each level, but it is rather ugly and not easy to maintain.</p>
<p>Is there a way for me to improve this code?</p>
<pre><code>[1, 2, 3].each do |n1|
if n1 == 1
[1, 2, 3].each do |n2|
if n2 == 2
[1, 2, 3].each do |n3|
if n3 == 3
[1, 2, 3].each do |n4|
if n4 == n3 # conditions are dependent
print n1, n2, n3, n4
end
end
end
end
end
end
end
end
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-11T14:58:29.423",
"Id": "38670",
"Score": "0",
"body": "The code you've provided appears to only print a single line, 1 2 3 3, in which case you should do away with the loops entirely. You should change your example code to give a more realistic insight into what you're trying to do."
}
] |
[
{
"body": "<p>In your example you iterate over the same collection. In that case I'd write:</p>\n\n<pre><code>[1, 2, 3].repeated_permutation(4).each do |n1, n2, n3, n4|\n if n1 == 1 && n2 == 2 && n3 == 3 && n3 == n4\n p [n1, n2, n3, n4]\n end\nend\n</code></pre>\n\n<p>If instead you need to iterate over different collections, check <code>Enumerable#product</code>. </p>\n\n<p>Of course, any of these alternatives will perform worse than your original code, since you drop whole groups of permutations when some condition is not satisfied. </p>\n\n<p>Note that you could create a compact abstraction as efficient as your original code (it would take collections to iterate and conditions -with procs?- over them), but this won't pay off if you are going to use it only once.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T07:09:11.770",
"Id": "24937",
"ParentId": "24932",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T02:19:17.793",
"Id": "24932",
"Score": "0",
"Tags": [
"ruby",
"iteration"
],
"Title": "How to flatten the nested for loops?"
}
|
24932
|
<p>I'm very new to coding and have been diving into the skill with Python as my first language. One of the first programs I wrote for a class was this Tic Tac Toe game. I re-wrote this game using classes and have just recently refactored it looking for different <em>smells</em>. The person who's been teaching the class suggested that I post it here for additional help optimizing it. Any help or suggestions for improvement is much appreciated! Is there anything that <em>smells</em> funky to you?</p>
<pre><code>#Written in Python 3.3.0, adapted for Python 2.7.3
#Tic Tac Toe Part 2
class Board(object):
"""Represents tic tac toe board"""
def __init__(self):
self.move_names = '012345678'
self.Free_move = ' '
self.Player_X = 'x'
self.Player_O = 'o'
self.moves = [self.Free_move]*9
def winner(self):
"""Wining combinations. Returns Player or None"""
winning_rows = [[0,1,2],[3,4,5],[6,7,8], # up and down
[0,3,6],[1,4,7],[2,5,8], # across
[0,4,8],[2,4,6]] # diagonal
for row in winning_rows:
if self.moves[row[0]] != self.Free_move and self.allEqual([self.moves[i] for i in row]):
return self.moves[row[0]]
def allEqual(self, list):
"""returns True if all the elements in a list are equal, or if the list is empty."""
return not list or list == [list[0]] * len(list)
def getValidMoves(self):
"""Returns list of valid moves"""
return [pos for pos in range(9) if self.moves[pos] == self.Free_move]
def gameOver(self):
return bool(self.winner()) or not self.getValidMoves()
def startover(self):
"""Clears board"""
self.moves = [self.Free_move]*9
class Player(object):
""" Represents player and his/her moves"""
def __init__(self, moves):
self.moves = moves
self.whoseturn = 1
def makeMove(self, move, player):
"""Plays a move. Note: this doesn't check if the move is legal!"""
self.moves[move] = player
class PlayerX(Player):
""" Player X's moves"""
def __init__(self, moves):
self.moves = moves
def xmove(self):
print("Move Player X")
move = int(input())
if -1 < move < 9:
for i in self.moves[move]:
if i == ' ':
super(PlayerX, self).makeMove(move, "X")
print(self.moves)
return 1
else:
print("That's not a valid move")
return 0
else:
print("That's not a valid move")
class PlayerO(Player):
""" Player O's Moves"""
def __init__(self, moves):
self.moves = moves
def ymove(self):
print("Move Player O")
move = int(input())
if -1 < move < 9:
for i in self.moves[move]:
if i == ' ':
super(PlayerO, self).makeMove(move, "O")
print(self.moves)
return 1
else:
print("That's not a valid move")
return 0
else:
print("That's not a valid move")
def tictac():
print(welcome_mes)
b = Board()
x = PlayerX(b.moves)
y = PlayerO(b.moves)
p = Player(b.moves)
while b.gameOver() == False:
if p.whoseturn % 2 == 0:
print("Turn #" + str(p.whoseturn))
if x.xmove() == 1:
p.whoseturn += 1
else:
print("Turn #" + str(p.whoseturn))
if y.ymove() == 1:
p.whoseturn += 1
print(b.winner() + " has won the game")
print("would you like to play again?")
Yes, yes, YES, yeah, Yeah = "yes","yes", "yes", "yes", "yes"
answer = input()
if str(answer) == "yes":
b.startover()
tictac()
else:
quit()
welcome_mes = """Welcome to Tic Tac Toe!
The Game board is as follows:
_0_|_1_|_2_
_3_|_4_|_5_
6 | 7 | 8 ""
</code></pre>
|
[] |
[
{
"body": "<p>For someone new to coding, there's a lot here that is good. Naming of classes, functions and variables are generally good. Comments follow convention, with simple, concise Docstrings for everything. Methods are generally simple and do only one thing, which is nice.</p>\n\n<hr>\n\n<p>Let's go through a few things that I think can be improved:</p>\n\n<p>In the <code>winner</code> function, every time this is called, <code>winning_rows</code> is recreated. However, this will be the same for any <code>Board</code>, and won't change. Hence, we can make this a <em>class attribute</em>:</p>\n\n<pre><code>class Board(object):\n\n winning_rows = [[0,1,2],[3,4,5],[6,7,8], # up and down\n [0,3,6],[1,4,7],[2,5,8], # across\n [0,4,8],[2,4,6]] # diagonal\n</code></pre>\n\n<p>In <code>winner</code>, we simply call it as follows:</p>\n\n<pre><code>def winner(self):\n \"\"\"Wining combinations. Returns Player or None\"\"\"\n for row in Board.winning_rows:\n #Code as before\n</code></pre>\n\n<p>In fact, the user of <code>Board</code> probably shouldn't change this. Other object-oriented language have the notion of <code>private</code> variables: variables that aren't visible and can't be accessed outside their own class. Python doesn't have this restriction, but it does have a convention that anything prefixed by an underscore should probably be treated as such, hence it should be <code>_winning_rows</code>.</p>\n\n<hr>\n\n<p>Naming is generally good, but just watch out for the few inconsistencies that are lurking around: <code>self.move_names</code> or <code>self.Free_move</code>? It's nice to keep things uniform, either start everything with lower case, or start everything with upper case. Starting everything with lowercase would be \"more pythonic\" in my eyes, but consistency is key. The same thing applies to method names, e.g. <code>gameOver</code> vs <code>startover</code>. </p>\n\n<hr>\n\n<p>Using <code>Player</code> as a base class and <code>PlayerX</code>, <code>PlayerY</code> as subclasses isn't really the way to go here. Note that <code>xmove</code> and <code>ymove</code> are almost exactly the same. This sort of code duplication is a definite sign that you should reconsider your design. Instead of subclassing for each type of <code>Player</code>, it would be far better to simply create difference <em>instances</em> of <code>Player</code>, each one with perhaps an attribute like <code>self.piece</code>. Hence, it would look something like:</p>\n\n<pre><code>class Player(object):\n\n \"\"\" Represents player and his/her moves\"\"\"\n def __init__(self, piece, moves):\n self.moves = moves\n self.piece = piece\n\n def getMove(self):\n print(\"Move Player %s\" % self.piece)\n #...\n\n def makeMove(self, move):\n #...\n\n def __str__(self):\n return \"Player \" + self.piece\n</code></pre>\n\n<p>I've modified the names and shuffled things around a bit here, but hopefully you can see what's going on. This cuts down on the repeated code. Note we've also directly created a <code>__str__</code> method that will be called whenever we call <code>str()</code> on a <code>Player</code>.</p>\n\n<hr>\n\n<p>There are a few bits of <em>leaky abstraction</em>. <code>self.whoseturn = 1</code> shouldn't live in <code>Player</code> - this doesn't really encapsulate anything about the player themselves, it's instead information about the state of the game - hence it's in the wrong spot. It likely shouldn't be a simple <code>int</code> either. In fact, I think the part of the code that needs the most work is the <code>tictac()</code> function. Instead of simply having a function, there should be another <code>class</code> that encapsulates the idea of a game. This will hold a <code>Board</code>, both the <code>Players</code>, and will co-ordinate whose turn it is, whether the game is finished, and perform cleanup and reset functions for a new game:</p>\n\n<pre><code>class Game(object):\n\n _welcome_mes = \"\"\"Welcome to Tic Tac Toe!\n\nThe Game board is as follows:\n\n _0_|_1_|_2_\n _3_|_4_|_5_\n 6 | 7 | 8 \"\"\"\n\n def __init__(self):\n self.board = Board()\n self.playerX = Player('x', self.board.moves)\n self.playerO = Player('o', self.board.moves)\n self._currentTurn = self.playerX\n\n def _swapCurrentTurn(self):\n if self._currentTurn == self.playerX:\n self._currentTurn = self.playerO\n else: self._currentTurn = self.playerX\n\n def start(self):\n print(Game._welcome_mes)\n while not self.isGameOver():\n print(\"Turn: \" + str(self._currentTurn))\n if self._currentTurn.move():\n self._swapCurrentTurn()\n self._atGameEnd()\n\n def _atGameEnd(self):\n print(self.board.winner() + \" has won the game\")\n print(\"Would you like to play again?\")\n answer = input()\n if str(answer).lower() in [\"yes\", \"y\", \"yeah\"]:\n self._restart()\n\n def _restart(self):\n self.board.clear()\n self.playerX = Player('x', self.board.moves)\n self.playerO = Player('o', self.board.moves)\n self._currentTurn = self.playerX \n\n def isGameOver(self):\n return self.board.gameOver()\n</code></pre>\n\n<p>To play the game, all you need to do is make a <code>Game</code> object and call <code>start()</code> on it. This cleans up the logic a bit (and was done a bit hastily, so can probably be further improved. However, it should give you a general idea at least). I've left out any docstrings, which you should add if you decide to go this route.</p>\n\n<p>I've also cleaned up the string checking to see if the user wants to play again: firstly, we convert it to lowercase, so we don't need to worry about dealing with the difference between \"yes\" and \"YES\", and then we simply check if it is in a few different options with <code>in</code>. </p>\n\n<hr>\n\n<p>There's another minor thing I would think about fixing/adding: having the board print out in rows of 3, instead of a single flat list. This should be fairly simple.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T07:11:10.300",
"Id": "24938",
"ParentId": "24934",
"Score": "7"
}
},
{
"body": "<p>In addition to what <a href=\"https://codereview.stackexchange.com/a/24938/10916\">Yuushi wrote</a>:</p>\n\n<ul>\n<li><p>It would be better to have <code>Board</code> validate the moves, instead of <code>Player</code>. That way the players would work even if you changed the size of the board. For an invalid move <code>Board</code> could raise an exception that you handle in the main game loop.</p></li>\n<li><p>If you moved the handling of user input to the <code>tictac</code> function, it would be easier to understand the whole user experience.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T07:21:25.807",
"Id": "24944",
"ParentId": "24934",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "24938",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T04:11:09.560",
"Id": "24934",
"Score": "5",
"Tags": [
"python",
"optimization",
"beginner",
"game"
],
"Title": "Help with refactoring my Tic Tac Toe game"
}
|
24934
|
<p>Here's a part of my controller and it's getting quite lengthy (the code works).</p>
<p>Would this code slow down the performance of my website? Can it be cleaned up and be written more efficiently? </p>
<pre><code>def create
@post = current_user.posts.build(params[:post])
if @post.save
if @post.verify
UserMailer.verify_email(@user).deliver
redirect_to root_path
else
flash[:success] = "Posted"
if @post.content.to_s.length > 140 and @post.image.present?
@twitter = Twitter::Client.new
@twitter.update(@post.content.truncate(120)+"... " +@post.image.path.to_s)
redirect_to root_path
elsif @post.content.to_s.length > 140
@twitter = Twitter::Client.new
@twitter.update(@post.content.truncate(140))
redirect_to root_path
elsif @post.content.to_s.length <= 140 and @post.image.present?
@twitter = Twitter::Client.new
@twitter.update(@post.content.truncate(120)+""+@post.image.path.to_s)
redirect_to root_path
else @post.content.to_s.length <= 140
@twitter = Twitter::Client.new
@twitter.update(@post.content)
redirect_to root_path
end
end
else
@feed_items = []
render 'static_pages/home'
end
end
</code></pre>
|
[] |
[
{
"body": "<p>You could create a method on your post model that converts a post to a tweet. If you do that you can clean up your controller a lot:</p>\n\n<p>Model:</p>\n\n<pre><code>class Post < ActiveRecord::Base\n def to_tweet\n if image.present?\n \"#{content.truncate(120)}... #{image.path.to_s}\"\n elsif content.length > 140\n \"#{content.truncate(120)}... more\"\n else\n content\n end\n end\nend\n</code></pre>\n\n<p>Controller:</p>\n\n<pre><code>def create\n @post = current_user.posts.build(params[:post])\n\n if @post.save\n if @post.verify\n UserMailer.verify_email(@user).deliver \n else\n flash[:success] = \"Posted\"\n Twitter::Client.new.update(@post.to_tweet)\n end\n\n redirect_to root_path\n else\n @feed_items = []\n render 'static_pages/home'\n end\nend\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T02:37:28.180",
"Id": "38515",
"Score": "1",
"body": "prepate > prepare. Otherwise this would definitely make the code a lot cleaner. It wouldn't necessarily make it any faster, though the OP probably needn't optimize prematurely."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T02:37:54.420",
"Id": "38516",
"Score": "0",
"body": "can you show me what the method in the post model would look like? that would help me out a lot"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T02:41:47.453",
"Id": "38518",
"Score": "0",
"body": "@user2159586, updated my answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-11T16:19:19.107",
"Id": "38676",
"Score": "0",
"body": "I'd argue that posts shouldn't know about Twitter."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T02:35:44.143",
"Id": "24940",
"ParentId": "24939",
"Score": "3"
}
},
{
"body": "<p>Roughly:</p>\n\n<pre><code>twitter = Twitter::Client.new\n\nimg, max = @post.image ? [@post.image.path.to_s, 120] : [\"\", 140]\ntwitter.update(\"#{@post.content.truncate(max)}#{img}\")\n\nredirect_to root_path\n</code></pre>\n\n<p>All the Twitter stuff shouldn't be in the controller, rather in a utility class. This makes testing easier, makes plugging in implementations easier, makes extension easier, and so on.</p>\n\n<p>Also, <code>truncate</code> should be already adding the <code>\"...\"</code> if truncation was necessary.</p>\n\n<p>Personally, I prefer Amit's answer. IMO it's easier to read and more obvious than mine.</p>\n\n<p>I would probably tighten it up a bit after an initial review to something like this:</p>\n\n<pre><code>s = @post.image ? \"#{@post.content.truncate(120)}... #{@post.image.path.to_s}\"\n : @post.content.truncate(140)\ntwitter.update(s)\n</code></pre>\n\n<p>It's formatted to highlight the similarities between the two, another option is to use string interpolation again, but it seems redundant in this particular case.</p>\n\n<p><em>(Obviously the string creation would go into a method in some sort of support decorator etc.)</em></p>\n\n<p><sup><em>All the above is untested, but probably close.</em></sup></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T09:40:42.680",
"Id": "38538",
"Score": "0",
"body": "nit-pick: `.present?` can be safely removed."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T02:38:57.913",
"Id": "24942",
"ParentId": "24939",
"Score": "6"
}
},
{
"body": "<p>Here's how you could simplify things, maintaining the existing logic. However, the <code>@twitter.update</code> logic which depends on the whether or not the <code>@post</code> has an image present should happen in a separate (non-ActiveRecord) model. I find it always helps to write your own wrapper class around whatever external API client you use. This has at least three benefits, (a) it allows you to expose precisely the interface you want to the rest of your application -- no more, no less; and (b) it allows you to unit test things a little more easily, and (c) most importantly, it minimizes the coupling between your code and this external library so if Twitter decides to totally change the client API you only have to make changes in one place.</p>\n\n<pre><code>def create\n @post = current_user.posts.build(params[:post])\n\n @feed_items = [] and render 'static_pages/home' and return unless @post.save\n\n if @post.verify\n UserMailer.verify_email(@user).deliver\n else\n flash[:success] = \"Posted\"\n\n @twitter = Twitter::Client.new\n\n if @post.image.present?\n @twitter.update(@post.content.truncate(120)+\"... \"+@post.image.path.to_s)\n else\n @twitter.update(@post.content.truncate(140))\n end\n end\n\n redirect_to root_path\nend\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T02:45:43.757",
"Id": "38529",
"Score": "0",
"body": "Personally, I think this is easier to read than mine. It's still in the wrong place, but that's a separate issue. Everything related to twitter should be completely removed from the code that creates the message, allowing for easier testing and alternative implementations."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T02:48:41.063",
"Id": "38530",
"Score": "0",
"body": "Yup, guess you commented before I edited."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T03:05:04.903",
"Id": "38531",
"Score": "0",
"body": "Yes, it's enough to just check `image.present?`. However, I don't think the one-liner with `@feed_items` will work. `render` won't stop the rest of the code being executed, resulting in a \"Render and/or redirect were called multiple times\" error."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T03:10:35.617",
"Id": "38532",
"Score": "0",
"body": "That's a good catch. I could stick on a `and return` before the `unless`, but it was already starting to feel a bit weird to me. I'll put it in for correctness, but the real right answer for the OP is to extract a bunch of the logic to other classes."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T02:39:07.800",
"Id": "24943",
"ParentId": "24939",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T02:27:51.947",
"Id": "24939",
"Score": "1",
"Tags": [
"ruby",
"ruby-on-rails",
"twitter"
],
"Title": "Saving posts, then tweeting them"
}
|
24939
|
<p>I have just started to try and learn 'OOP' but it appears I'm doing this wrong, according to the people on Stack Overflow. The code below is far from object-orientated, but I'm finding it hard as I'm self teaching my self and everyone does everything differently. </p>
<p>I'm building a shopping cart and I need to be able to have both the admin and user login, so obviously both user types can use the same login and logout functions. I'm guessing I could use inheritance there, but I just need some one to tell me what I have done wrong or if anything is done right to confirm this.</p>
<p>Below is my create user page and my database and user class:</p>
<pre><code>//Sanitize User Input
$username = $database->sanitize_admin_input($_POST['username']);
$password = $database->sanitize_admin_input($_POST['password']);
//Check if user already exists.
$exists = $database->check_user_exists($username);
//Creates a salt, then passes the salt in to create a secure password.
$salt = $database->createSalt();
//Create the password hash using the salt.
$password_hash = $database->make_password_hash($password,$salt);
//Add Admin user.
$admin->add_admin($username, $password_hash, $salt);
</code></pre>
<p><strong>Admin Class</strong></p>
<pre><code><?php
require_once('../includes/class.database.php');
class Admin
{
public $id;
public $username;
public $password;
public $first_name;
public $last_name;
public $number_of_users; //Holds the number of users in the DB.
function __construct()
{
$this->number_of_users = $this->number_of_users();
}
private function number_of_users()
{
global $database;
$results = $database->query("SELECT COUNT(*) FROM users");
$rows = mysqli_fetch_row($results);
$number = $rows[0];
return $number;
}
public function add_admin($username,$password_hash,$salt)
{
global $database;
$result = $database->query("INSERT INTO users (username, password, salt ) VALUES ('{$username}','{$password_hash}','{$salt}')");
return $result;
}
}//END OF CLASS
?>
</code></pre>
<p><strong>Database Class</strong></p>
<pre><code><?php
require_once('config.php');
class Database
{
private $connection;
public $last_query; //stores the lastquerys, measn we can call this from the DB.
function __construct()
{
$this->open_connection();
}
public function open_connection()
{
$this->connection = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
if(!$this->connection)
{
$output = "A connection to the database has failed, please check the config file.";
$output .= "<br />" . mysqli_connect_error();
die($output);
}
}
public function close_connection()
{
if(isset($this->connection))
{
mysqli_close($this->connection);
unset($this->connection);
}
}
public function query($sql) //Takes in a paramater (sql query)
{
$this->last_query = $sql;
$result = mysqli_query($this->connection,$sql);
$this->confirm_query($result);
return $result;
}
private function confirm_query($result)
{
if(!$result)
{
//IF the result failes, takes the connection error and displays that, on a new line it displays the last query used.
$output = "This query has failed" . mysqli_error($this->connection);
$output .= '<br />' . $this->last_query;
die($output); //Kills the script and outputs the error message
}
}
public function sanitize_admin_input($data)
{
$data = trim($data);
$data = filter_var($data, FILTER_SANITIZE_STRING);
$data = ereg_replace("[^A-Za-z0-9]", "", $data );
return $data;
}
public function check_user_exists($username)
{
global $database;
$results = $database->query("SELECT * FROM users WHERE 'username' ='{$username}'");
$row_cnt = $results->num_rows;
return $row_cnt;
}
public function make_password_hash($password,$salt)
{
$hash = hash('sha256', $password);
$password_hash = hash('sha256', $salt . $hash);
return $password_hash;
}
public function createSalt()
{
$string = md5(uniqid(rand(), true));
return substr($string, 0, 9);
}
}
$database = new Database();
?>
</code></pre>
<p><strong>Index.php</strong></p>
<pre><code> require_once('class.userAction.php');
require_once('class.database.php');
$database = new Database();
$userOne = new userActions($database, 'marinello12','2312');
$userOne->create();
</code></pre>
|
[] |
[
{
"body": "<p>First of all don't use global variables or constants. Use comments to explain your intention not your code. Put every class in a separate file.</p>\n\n<p>Afterwards you have to decide if you want to use your Admin/User as a representation of a concrete admin/user (keeping the data of one user) or as a kind of manager providing access to all users and just use simple arrays as your concrete user.</p>\n\n<p>Mixing the public properties with the (actually static) CRUD-method is a bad design and will lead to trouble.</p>\n\n<p>As soon as you have done your first step I would recommend to replace your database abstraction by PDO or any other major library and don't reinvent the wheel.</p>\n\n<hr>\n\n<p>Edit - Just a draft how I would structure your class if I wouldn't use PDO and create my own database abstraction:</p>\n\n<pre><code><?\nclass Database\n{\n private $conn;\n public function __construct( /*connection parameter*/)\n {\n $this->conn=...\n }\n\n public function query($sql)\n {\n $result=...\n if ( mysql_error()!='') throw SqlException(...);\n return $result;\n }\n\n public function fetch($result) {...} //fetch_object or fetch_array\n\n public function execute($query) \n {\n ...\n return mysql_affected_rows();\n }\n\n public function lastId() {...}\n}\n</code></pre>\n\n<p>Separate file:</p>\n\n<pre><code><?\npublic class UserManager //Or UserRepository\n{\n ...\n public function __construct($connection) {...}\n\n public function create ($username, $plainTextPassword, $isAdmin, ...)\n {\n $this->checkUniqueName($username);\n list($password,$salt)=$this->hash($plainTextPassword);\n $sql=\"INSERT ...\";\n $success=$this->conn->execute($sql);\n if ($success!=1) throw SomeException(...);\n //maybe return a User instance\n }\n\n private function checkUniqueName($username)\n {\n $query=\"SELECT COUNT(*) FROM ...\";\n ...\n }\n\n private function hash($password)\n {\n ...\n return array($password,salt);\n }\n\n public function delete(User $user) {...}\n public function update(User $user) {...}\n /*\n @return User\n */\n public function findByUsernameAndPassword($username,$password) {...} //e.g. used for checking the login.\n}\n</code></pre>\n\n<p>And maybe a class for the User instance:</p>\n\n<pre><code><?php\nclass User\n{\n private ...\n\n public __construct(array $row) //your database row\n {\n ...\n }\n //some getter/setter\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T11:22:14.443",
"Id": "38543",
"Score": "0",
"body": "What would you recommend I do instead of using globals? And should I create a class for 'User Actions'? e.g. Login, Logout functions and include that class in my admin and user class or should I use inheritance there?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T11:31:38.567",
"Id": "38550",
"Score": "0",
"body": "For easier testing I usual hand over the database connection as a parameter of the constructor. So I can easily mock this in the tests."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T11:33:06.583",
"Id": "38551",
"Score": "0",
"body": "Are you familar with the Model-View-Controller pattern? Put the database stuff in the model and the interaction between your objects in the controller."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T11:33:51.263",
"Id": "38552",
"Score": "0",
"body": "No sorry, never heard of that before."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T11:34:58.930",
"Id": "38553",
"Score": "0",
"body": "So google it ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T12:00:00.917",
"Id": "38556",
"Score": "0",
"body": "Just made things a lot more confusing."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T11:17:50.500",
"Id": "24950",
"ParentId": "24947",
"Score": "1"
}
},
{
"body": "<blockquote>\n <p>but it appears I'm doing this wrong</p>\n</blockquote>\n\n<p>I'm afraid you're right about this. OOP isn't only about a different way of writing things. It's about different thinking! In OOP every object is represented by a class. These objects have some properties (firstname, lastname...) and actions that are used for a mutual communication = methods.</p>\n\n<p>Some examples from your code:</p>\n\n<p>Method <code>number_of_users()</code> - how did you come to the conclusion it belongs to the class <code>Admin</code>? It doesn't make sense. You don't get number of users from the Admin, but rather from the database (so it should be a part of the user repository or something like that).</p>\n\n<p>Method <code>make_password_hash($password,$salt)</code> - again, why do you think the <code>Database</code> should be responsible for this? It should be a part of a class either containing multiple algorithms or class responsible for a custom way of hashing.</p>\n\n<p>Forget about the procedural php programming, try to think in a completely different way. Try to see the relations between objects, try to separate them. You need to learn how to separate different layers, how to decide <code>what</code> belongs to <code>which object</code> etc. Yes, it can be a little hard in the beginning, but it's definitely worth it. </p>\n\n<p>After few years of experience with OOP I can't really imagine how would I create an e-shop for instance without classes and object oriented way of thinking.... </p>\n\n<p>On the more positive note, you got something right - your methods are fairly short :) That's a good thing!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T12:48:59.773",
"Id": "38562",
"Score": "0",
"body": "I put the number_of_user() function in the admin class because it will only be used by that admin, its just to display a stat in the admin panel, that was my thinking around it, and If I'm right in thinking the make_password_hash() function should be in a class that both the admin and user can use so make a userFunctions class"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T12:53:23.590",
"Id": "38563",
"Score": "0",
"body": "If the `Admin` class was the only class that was accessing some data from the database, I believe you wouldn't merge those classes together (or at least I hope you wouldn't). Separation of concerns is a big thing when it comes to a clean code which you should strive for. And yes, some extra class for functions like this would be definitely a better idea than the `Database` class, at least for now."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T12:40:40.897",
"Id": "24959",
"ParentId": "24947",
"Score": "2"
}
},
{
"body": "<p>You asked about why not to use global variables.</p>\n\n<p>Procedural problem: Every piece of code was written for one purpose, and was tied to that project. Lifting this code for use elsewhere is time consuming.</p>\n\n<p>So we made objects. The purpose of objects is like best described as 'lego bricks'. A 'lego brick' has connectors but also properties that make it unique, also there can be many of these bricks. But the key property of a 'lego brick' is it acts dependently of all other bricks.</p>\n\n<p>So why not use 'global variables'? Objects should act like 'lego bricks' independent of each other. In order to access the properties of an object you should use 'private variables' that are accessed via functions of that object. Also commonly referred to as 'getters' and 'setters'.</p>\n\n<p>private variable;</p>\n\n<p>get_private_variable()\nset_private_variable()</p>\n\n<p>You can now have complete control of these variables in just one place. Any time they are set you can check they are set to what they should be expected to be set to. And when you get them you are not giving the person access to the variable to change itself but rather a copy of it forcing them to call the 'set' method if they want to change it.</p>\n\n<p>(*If you need to get and set without anything else having access in between then you implement this notion of 'locks'.</p>\n\n<p>private lock_variable;\nprivate variable;</p>\n\n<p>This is a huge topic as well that could not be fully covered here but the basic idea is in order to change something you need the key that only person can have at one time. </p>\n\n<h2>)</h2>\n\n<p>Model-View-Controller</p>\n\n<p>This is just a fancy way of saying: Look here, change there and remember what.</p>\n\n<p>Model; where all the data is stored and managed.</p>\n\n<p>View; what the user sees.</p>\n\n<p>Controller; where all operations should be.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-11T08:29:24.210",
"Id": "24983",
"ParentId": "24947",
"Score": "0"
}
},
{
"body": "<p>First of all you are using globals (<code>global $database;</code>) which is something you should pretty much always avoid. The purpose of OOP is exactly to protect data therefore having something global, especially a database connection, is not a really good idea. I suggest you to take a look at the <code>Dependency Injection</code> design pattern which will suggests you to pass the database connection class <code>Database</code> to the classes that uses them <code>Admin</code> via their constructor.</p>\n\n<p>Second, in the <code>Database</code> class you are mixing some application logic with the <code>sanitize_admin_input</code>, <code>check_user_exists</code>, <code>createSalt</code> and <code>make_password_hash</code> functions. You should stick to the <em>Single Responsibility</em> principle in this case: one class server one and only one purpose. You expect a database class to give an abstraction level over the database, therefore making queries and retrieving results easy for the user of that class. I would never expect a Database class to create a random salt, for example. Therefore I suggest you to move each of those functions to their proper classes. </p>\n\n<pre><code>sanitize_admin_input => Admin (static)\ncheck_user_exists => User (static)\ncreateSalt / make_password_hash => Hash or Auth\n</code></pre>\n\n<p>On a side note you should stick with any naming convention you decided in the first place and you really shouldn't mix camelCase methods with underscore_named methods in <code>check_user_exists</code> and <code>createSalt</code> for example. Either <code>checkUserExists</code> and <code>createSalt</code> or <code>check_user_exists</code> and <code>create_salt</code>.</p>\n\n<p>Finally I suggest you to remove the instantiation of the object <code>$database</code> in the Database class definition file. Instantiation and class definition should always be in two separated files.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-12T08:54:48.040",
"Id": "38708",
"Score": "0",
"body": "Thanks for the help :) I have edited my question with my reviewed class, think I got the just of this."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-11T13:56:12.157",
"Id": "24997",
"ParentId": "24947",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "24950",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T09:47:57.377",
"Id": "24947",
"Score": "2",
"Tags": [
"php",
"object-oriented",
"mysql",
"e-commerce"
],
"Title": "Object-oriented shopping cart"
}
|
24947
|
<p>I have recently created my first game in C++:</p>
<pre><code>#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
cout<<"\tWelcome to Guess my Number!\n";
const unsigned short kusiLower=1;
const unsigned short kusiHigher=100;
srand(time(0));
unsigned short usiComp=rand()%kusiHigher+kusiLower;
cout<<"Guess a number between 1 and 100: ";
unsigned short usiUser;
cin>>usiUser;
unsigned short usiGuesses=1;
while(usiUser!=usiComp)
{
cout<<((usiUser>usiComp)?"Your guess is too high.\n":"Your guess in too low\n");
cout<<"Guess a number between 1 and 100: ";
cin>>usiUser;
++usiGuesses;
}
cout<<"Congratulations! You guessed my number in "<<usiGuesses<<" guesses.";
}
</code></pre>
<p>And I came here to ask the standard question: can it be in any way optimized or improved? </p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T18:03:20.203",
"Id": "38583",
"Score": "0",
"body": "Is it...... 42?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-11T15:06:11.883",
"Id": "38672",
"Score": "0",
"body": "`using namespace std;` is still in your code. Read this page for more information about its alternatives: http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-a-bad-practice-in-c"
}
] |
[
{
"body": "<p>a few remarks:</p>\n\n<ul>\n<li>Use int instead of unsigned short</li>\n<li>Don't use Hungarian naming ('kusi/usi' prefix) - nobody uses that.</li>\n<li>Add argc/argv parameters to main</li>\n<li>Dont import everything from std with <code>using namespace std</code></li>\n<li>Add spaces around operators (=, != , ==, >>, << etc) and after 'while', 'if' etc.</li>\n<li>You have carefully used constants for the high/low boundaries, but your print statements don't use these constants (\"Guess a number between 1 and 100:\")</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-11T14:05:28.093",
"Id": "38665",
"Score": "1",
"body": "\"Use int instead of unsigned short\" logically speaking an unsigned short is right in this case. The fact that `int`s and `short`s are usually both implemented with 4 bytes is a whole another story. In any case, why would he use a signed integer while the numbers he is dealing with are in the range [1..100]?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-11T14:42:30.657",
"Id": "38669",
"Score": "2",
"body": "Why is short more logical - because its range is nearer to that of the 1..100 ? On that basis char would be the best fit. But using char could well be slower than int and I guess the same goes for short. On unsigned, see http://soundsoftware.ac.uk/c-pitfall-unsigned"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-16T19:19:53.370",
"Id": "102210",
"Score": "0",
"body": "A good reason to use `short` is if the extra two bytes storage for an `int` is really going to be a problem (for example, if you're going to store billions of these values in files). The fact that the expected range of data _happen_ to fit the smaller type is not really relevant in the absence of some other reason to _want_ to fit the values into a smaller type."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T14:18:13.537",
"Id": "24964",
"ParentId": "24948",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T09:50:05.153",
"Id": "24948",
"Score": "1",
"Tags": [
"c++",
"optimization",
"game"
],
"Title": "\"Guess my Number\" game in C++"
}
|
24948
|
<p>I have just started learning erlang...I am just practicing the recursion and all in erlang...I tried to write a few of the list processing functions on my own in erlang...Can someone review the code and give some advice on it...</p>
<pre><code>-module(listma).
-export([duplicates/1,reverse/1])
%% Remove the duplicates in a list
duplicates(List) ->
duplicates(List,[]).
duplicates([Head|Tail],Newlist) ->
Insert =
fun(H,N) ->
case [H] -- N of
[] -> N;
[H] -> [H|N]
end
end,
duplicates(Tail,Insert(Head,Newlist));
duplicates([],Outputlist) ->
reverse(Outputlist).
%% Reverse a list
reverse(List) ->
reverse(List,[]).
reverse([Head|Tail],Newlist) ->
reverse(Tail,[Head|Newlist]);
reverse([],Outputlist) ->
Outputlist.
</code></pre>
|
[] |
[
{
"body": "<p>Your <code>Insert</code> lambda doesn't use any context so you could rewrite it as a top-level function or move its body to the clause.\nAnd you could use <code>lists:member/2</code> instead of <code>--</code>.</p>\n\n<p>I'd write first clause like this:</p>\n\n<pre><code>duplicates([Head | Tail], Acc) ->\n NewAcc = case lists:member(Head, Acc) of\n true ->\n Acc;\n _ ->\n [Head | Acc]\n end,\n duplicates(Tail, NewAcc);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T12:30:59.847",
"Id": "38558",
"Score": "0",
"body": "Thanks for the feedback Dmitry...Thank you so much...The Insert Lambda is useless here as you said...I will remove it...I wanted to practice lists processing functions without the use of lists Built in functions like member,delete,append,etc..Thats why i ignored lists:member thing and used -- operator....Thanks again Dmitry...Thank you so much"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T12:37:35.160",
"Id": "38560",
"Score": "0",
"body": "Well, you can write your own `member` function too without use of `--` =)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T12:12:24.907",
"Id": "24957",
"ParentId": "24949",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T11:05:40.107",
"Id": "24949",
"Score": "1",
"Tags": [
"erlang"
],
"Title": "Feedback on Erlang Lists processing function"
}
|
24949
|
<p>I am using jQuery's collapsible lists grouped and named <code>#List01</code>, <code>#List02</code>, <code>#List03</code>, etc. My code captures clicks on list elements and remembers list items' ID for further processing. Each group has identically looking code so I was wondering how I could encapsulate it in one function.</p>
<pre><code>$(document).on('click', '#List01 li', function ()
{
var anchor = $(this).find('a');
sessionStorage.KenID = anchor.attr('id');
changePage();
});
$(document).on('click', '#List02 li', function ()
{
var anchor = $(this).find('a');
sessionStorage.KenID = anchor.attr('id');
changePage();
});
$(document).on('click', '#List03 li', function ()
{
var anchor = $(this).find('a');
sessionStorage.KenID = anchor.attr('id');
changePage();
});
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T05:21:35.633",
"Id": "38544",
"Score": "0",
"body": "why dont just use class as jquery selector since the function have no relation with it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T05:23:15.570",
"Id": "38546",
"Score": "0",
"body": "with jquery i don't thinks its anymore posible just find leaks in your code, optimize by hand and make it in one file and exucute part of code only on page, where it needs, for example many site have lots of jquery code running on every page, if page url is xyz then run this code only, and you should try clouse compiler to optimize it and use zepto instead of jquery (if you can afford),"
}
] |
[
{
"body": "<pre><code>$(document).on('click', '#List01 li, #List02 li, #List03 li', function () {\n var anchor = $(this).find('a');\n sessionStorage.KenID = anchor.attr('id');\n changePage();\n});\n</code></pre>\n\n<p>The <code>,</code> should do the trick.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T05:22:10.380",
"Id": "24952",
"ParentId": "24951",
"Score": "1"
}
},
{
"body": "<p>One handler will do all this:</p>\n\n<pre><code>$(document).on('click', '[id^=List] li', function ()\n {\n var anchor = $(this).find('a');\n sessionStorage.KenID = anchor.attr('id');\n changePage();\n });\n</code></pre>\n\n<p>see: <a href=\"http://www.w3.org/TR/css3-selectors/#attribute-substrings\" rel=\"nofollow\">http://www.w3.org/TR/css3-selectors/#attribute-substrings</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T05:23:36.510",
"Id": "24954",
"ParentId": "24951",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "24952",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T05:18:02.323",
"Id": "24951",
"Score": "2",
"Tags": [
"javascript",
"jquery"
],
"Title": "Capturing clicks on list items"
}
|
24951
|
<p>I'm trying to improve my OOP code and I think my User class is becoming way too fat.</p>
<p>In my program a user has rights over "lists". Read, Write, Update, Delete.
So I made a User class</p>
<pre><code>class User
{
protected $_id;
protected $_email;
protected $_username;
protected $_hashedPassword;
//...Various setters/getters
public function canRead(List $list){
//Database query verifies if user has READ rights
}
public function canUpdate(List $list){
//Database query verifies if user has UPDATE rights
}
//etc...
}
</code></pre>
<ul>
<li>Should canRead, canUpdate, canWrite, canDelete methods be moved to another class (UserAccessCheck or something...)?</li>
<li>If not, should the actual SQL be moved into the List object (listCanBeReadByUser()) ?</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-11T13:40:40.960",
"Id": "38664",
"Score": "0",
"body": "What exactly does `List` contains?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-11T14:41:19.770",
"Id": "38668",
"Score": "0",
"body": "To-do list, so there's some attributes (text, author...) and methods about them (createTodo, updateTodo...)"
}
] |
[
{
"body": "<p>If you have the feeling your classes are too big, you are usually right. Of course there are always different approaches how you could split classes and your idea seems to be reasonable.</p>\n\n<p>So you will have some plain Value Objects (the User), some UserRepository class for getting/updating the data in the database and some kind of UserAccessCheck/PermissionManager/... class for checking the actual user rights.</p>\n\n<p>In case you store your permission also in the database, you can of course extract a PermissionRepository to collect all the SQL statements in one location and don't mix your level of abstractions.</p>\n\n<p>To sum this up, <strong>the decision is up to you.</strong> A class with 4 properties, some Getters and 4 can...()-methods might be suitable in one scenario and splitting it up into 5 classes might be suitable in an other scenario. In general \"good\" (tm) developer tend to make there code more general/abstract than necessary and wasting there time or there clients money in premature optimization. \"Bad\" (tm) developer will never feel the need to split a class. Find the right way in between.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-11T10:00:43.997",
"Id": "24986",
"ParentId": "24956",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "24986",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T12:00:09.520",
"Id": "24956",
"Score": "1",
"Tags": [
"php",
"object-oriented",
"php5"
],
"Title": "Should a User class only contain attributes and no methods apart from getters/setters?"
}
|
24956
|
<p>Take the below code:</p>
<pre><code>public interface ISettingsManager
{
SettingData GetSettingByIdentifierOrCreateIfDoesNotExist(Enum identifier);
T GetSetting<T>(Enum identifier);
}
[IocComponent]
public class SettingsManager : ISettingsManager
{
private readonly ISettingGetItemByIdentifierService _settingGetItemByIdentifierService;
public SettingsManager(
ISettingGetItemByIdentifierService settingGetItemByIdentifierService)
{
_settingGetItemByIdentifierService = settingGetItemByIdentifierService;
}
public SettingData GetSettingByIdentifierOrCreateIfDoesNotExist(Enum identifier)
{
SettingData setting = //GetSetting from database;
return setting;
}
#region ISettingsManager Members
public T GetSetting<T>(Enum identifier)
{
var setting = GetSettingByIdentifierOrCreateIfDoesNotExist(identifier);
return (T)setting.Value;
}
#endregion
}
</code></pre>
<p>The <code>ISettingsManager</code> is created to retrieve settings for an application. The main logic is done in <code>GetSettingByIdentifierOrCreateIfDoesNotExist</code>. The logic is not shown in the example, but this should try to get the setting from the database.</p>
<p>The method <code>GetSetting</code> is a convenience method which basically retrieves the setting from the other method, and casts it to the required value as <code>setting.Value</code> is of type <code>object</code>.</p>
<p>I am trying to follow the Test-Driven-Development guidelines, and hence I assume a unit-test should be created for this method as well. As it is, one cannot just mock the <code>GetSettingByIdentifierOrCreateIfDoesNotExist</code>, as it is in the same class. </p>
<p>Does it make sense to split this out in another class, so one can mock it? Personally, I think that these two go together. Any ideas how one would approach this would be greatly appreciated :)</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T12:43:30.730",
"Id": "38561",
"Score": "2",
"body": "If you're following TDD, you should have written the tests `before` the actual code :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T17:10:17.900",
"Id": "38576",
"Score": "0",
"body": "I did create the tests, and they're not posted here :) I'm just thinking that it might be a bit of an over-kill, creating unit-tests for such simple methods, when it is just a 'convenience method'."
}
] |
[
{
"body": "<p>I'm not sure if you need <code>GetSettingByIdentifierOrCreateIfDoesNotExist</code> declaration in your interface... Do you have special use cases where <code>GetSetting<T></code> is not enough?</p>\n\n<p>If I'm right and all you need is just <code>GetSetting<T></code> method then you can go ahead and make <code>GetSettingByIdentifierOrCreateIfDoesNotExist</code> method private, thus you'll make it an implementation specific that doesn't need to be tested separately, you'll test it by testing <code>GetSetting<T></code>.</p>\n\n<p>If you do need <code>GetSettingByIdentifierOrCreateIfDoesNotExist</code> method, then I would go with a different approach: since <code>GetSetting<T></code> is just an additional feature on top of <code>GetSettingByIdentifierOrCreateIfDoesNotExist</code>, you can remove it from <code>ISettingsManager</code> interface and rewrite as an extension method like this:</p>\n\n<pre><code>public interface ISettingsManager\n{\n SettingData GetSettingByIdentifierOrCreateIfDoesNotExist(Enum identifier);\n}\n\npublic static class SettingsManagerExtensions\n{\n public static T GetSetting<T>(this ISettingsManager manager, Enum identifier)\n {\n var setting = manager.GetSettingByIdentifierOrCreateIfDoesNotExist(identifier);\n return (T)setting.Value;\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T12:56:35.693",
"Id": "24960",
"ParentId": "24958",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "24960",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T12:39:09.947",
"Id": "24958",
"Score": "1",
"Tags": [
"c#",
"unit-testing",
"tdd"
],
"Title": "unit-testing / mocking a class which contains functionality which depends on itself"
}
|
24958
|
<p>Without changing the semantics and performance, how can I make this where clause more readable?</p>
<pre><code>where
(@Category = 'all' or
(@Category = 'omitted' and Category is null) or
(@Category = Category and (
@SubCategory = 'all' or
(@SubCategory is null and SubCategory is null) or
(@SubCategory = SubCategory and (
@SubSubCategory = 'all' or
(@SubSubCategory is null and SubSubCategory is null) or
@SubSubCategory = SubSubCategory
))
))
)
</code></pre>
<p>At a high level, this clause represents a user query where the user has optionally specified a category, subcategory, and sub-subcategory on a table. For compatibility reasons, I cannot change any semantics (e.g., I cannot improve consistency by using <code>@Category is null</code> instead of <code>@Category = 'omitted'</code>)</p>
|
[] |
[
{
"body": "<p>This kind of condition may actually hurt performance quite a lot, because query optimizer most likely will be confused by complex filtering condition and would have to do a table scan rather than index seek (assuming that you have index over <code>Category</code> and <code>SubCategory</code>). In order to improve querying performance you should simplify <code>WHERE</code> clause.</p>\n\n<p>Best solution would be to utilize client-side ORM capabilities to generate dynamic filtering based on available data. If that isn't possible, then I would go with one of the following approaches (I would prefer Multiple queries approach in case when select statement is simple):</p>\n\n<ul>\n<li><p>Dynamic sql:</p>\n\n<pre><code>declare @sql nvarchar(max);\nset @sql = 'select [field_list] from table_name ' + case \n when @Category = 'all' then ''\n when @Category = 'omitted' then 'where Category is null'\n else 'where Category = @Category' + case\n when @SubCategory = 'all' then ''\n when @SubCategory is null then ' and SubCategory is null'\n else ' and SubCategory = @SubCategory' + case\n when @SubSubCategory = 'all' then ''\n when @SubSubCategory is null then ' and SubSubCategory is null'\n else ' and SubSubCategory = @SubSubCategory'\n end\n end\nend\n\nexec sp_executesql @stmt = @sql,\n @params = N'@Category varchar(100), @SubCategory varchar(100), @SubSubCategory varchar(100)',\n @Category = @Category,\n @SubCategory = @SubCategory,\n @SubSubCategory = @SubSubCategory;\n</code></pre></li>\n<li><p>Multiple queries approach:</p>\n\n<pre><code>if (@Category = 'all')\n select [field_list]\n from table_name\nelse if (@Category = 'omitted')\n select [field_list]\n from table_name\n where Category is null\nelse if (@SubCategory = 'all')\n select [field_list]\n from table_name\n where Category = @Category\nelse if (@SubCategory is null)\n select [field_list]\n from table_name\n where Category = @Category and SubCategory is null\nelse if (@SubSubCategory = 'all')\n select [field_list]\n from table_name\n where Category = @Category and SubCategory = @SubCategory\nelse if (@SubSubCategory is null)\n select [field_list]\n from table_name\n where Category = @Category and SubCategory = @SubCategory and SubSubCategory is null\nelse\n select [field_list]\n from table_name\n where Category = @Category and SubCategory = @SubCategory and SubSubCategory = @SubSubCategory\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T15:15:59.273",
"Id": "38566",
"Score": "0",
"body": "I refuse to replace working code with dynamic SQL. I would put up with your second solution, but considering the complexity of my select clause, I dislike this level of code repetition. The best of both worlds might be to make use of your second solution in a UDF, but not until MS fixes [Scalar UDF Performance](http://connect.microsoft.com/SQLServer/feedback/details/273443/the-scalar-expression-function-would-speed-performance-while-keeping-the-benefits-of-functions)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T15:24:29.167",
"Id": "38567",
"Score": "0",
"body": "Does your code run over indices with that kind of WHERE clause? I doubt it. So even if it does work on small amount of data, dynamic SQL will beat it on larger data (assuming that you have corresponding index). Of course it's still kind of hack, because this type of conditions should be evaluated on client side using ORMs"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T15:29:51.213",
"Id": "38568",
"Score": "0",
"body": "Actually, it does have an index on those columns. Regardless, this is moot; my team has a policy against using dynamic SQL unless absolutely necessary. Personally, I consider your dynamic SQL approach to be just as difficult to read."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T21:17:21.677",
"Id": "38624",
"Score": "0",
"body": "I asked about whether the query *runs over index* (does the index seek operation, not whether you *have index*. Both my options were attempts to improve performance rather than readability."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T23:23:23.507",
"Id": "38636",
"Score": "0",
"body": "OK, I'll be more explicit, it *does* run over the index. Anyhow, please note my original question, \"Without changing the semantics and performance, how can I make this where clause more readable?\" Performance is fine. Readability is my only concern."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T14:49:02.037",
"Id": "24966",
"ParentId": "24963",
"Score": "0"
}
},
{
"body": "<p>Add comments, they're the usual way of making complicated source code easier to understand.</p>\n\n<p>There's not a lot to add in your case because the meaning of the code is simple even if the implementation isn't easy to take in at a glance, but adding a few short comments may make it much more readable, especially for someone who's reading through the whole thing trying to understand the flow of logic. I would just do this:</p>\n\n<pre><code>where\n -- optional category\n (@Category = 'all' or\n (@Category = 'omitted' and Category is null) or\n (@Category = Category and (\n -- optional subcategory\n @SubCategory = 'all' or\n (@SubCategory is null and SubCategory is null) or\n (@SubCategory = SubCategory and (\n -- optional subsubcategory\n @SubSubCategory = 'all' or\n (@SubSubCategory is null and SubSubCategory is null) or\n @SubSubCategory = SubSubCategory\n ))\n ))\n)\n</code></pre>\n\n<p>Now I can quickly see the purpose of the code, and even if the detailed logic is awkward to follow it may not matter at all because I may not need to change it, just understand what it's doing. If I do need to modify it, I'll have no choice but to work through it in detail anyway, in which case the comments will help to point me in the right direction.</p>\n\n<p>You didn't mention if you're using SQL Server or Sybase, but if it's SQL Server and if you haven't read it already, <a href=\"http://www.sommarskog.se/dyn-search-2008.html\" rel=\"nofollow\">this article</a> is well worth reading. I wouldn't be too dogmatic about avoiding dynamic SQL, it certainly has its issues but it has its uses too.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-15T19:04:44.493",
"Id": "25112",
"ParentId": "24963",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "25112",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T14:14:53.300",
"Id": "24963",
"Score": "2",
"Tags": [
"sql",
"sql-server",
"t-sql"
],
"Title": "How can I make this WHERE clause more readable?"
}
|
24963
|
<p>I've combined some of my own functions with a function I found and I'm curious to know what others think of it. It will be used to upload and resize/crop images that are jpeg, jpg, png.</p>
<pre><code><?php
class ImageUploader {
var $multiple_file_upload = true;
var $max_size = 1024;
var $mime_types = array('bmp' => 'image/bmp', 'gif' => 'image/gif', 'jpeg' => 'image/jpeg', 'jpg' => 'image/jpeg', 'png' => 'image/png');
var $allowed_extensions;
function __construct() {
}
function get_image_information($file) {
return getimagesize($file);
}
function get_image_extension($file) {
return pathinfo($file, PATHINFO_EXTENSION);
}
function resize_image($source_image, $destination_filename, $width = 100, $height = 100, $quality = 70, $crop = false) {
$image_data = $this -> get_image_information($source_image);
switch( $image_data['mime'] ) {
case 'image/gif' :
$get_func = 'imagecreatefromgif';
$suffix = ".gif";
break;
case 'image/jpeg' :
$get_func = 'imagecreatefromjpeg';
$suffix = ".jpg";
break;
case 'image/png' :
$get_func = 'imagecreatefrompng';
$suffix = ".png";
break;
}
$img_original = call_user_func($get_func, $source_image);
$old_width = $image_data[0];
$old_height = $image_data[1];
$new_width = $width;
$new_height = $height;
$src_x = 0;
$src_y = 0;
$current_ratio = round($old_width / $old_height, 2);
$desired_ratio_after = round($width / $height, 2);
$desired_ratio_before = round($height / $width, 2);
if ($old_width < $width || $old_height < $height) {
/**
* The desired image size is bigger than the original image.
* Best not to do anything at all really.
*/
return false;
}
/**
* If the crop option is left on, it will take an image and best fit it
* so it will always come out the exact specified size.
*/
if ($crop) {
/**
* create empty image of the specified size
*/
$new_image = imagecreatetruecolor($width, $height);
/**
* Landscape Image
*/
if ($current_ratio > $desired_ratio_after) {
$new_width = $old_width * $height / $old_height;
}
/**
* Nearly square ratio image.
*/
if ($current_ratio > $desired_ratio_before && $current_ratio < $desired_ratio_after) {
if ($old_width > $old_height) {
$new_height = max($width, $height);
$new_width = $old_width * $new_height / $old_height;
} else {
$new_height = $old_height * $width / $old_width;
}
}
/**
* Portrait sized image
*/
if ($current_ratio < $desired_ratio_before) {
$new_height = $old_height * $width / $old_width;
}
/**
* Find out the ratio of the original photo to it's new, thumbnail-based size
* for both the width and the height. It's used to find out where to crop.
*/
$width_ratio = $old_width / $new_width;
$height_ratio = $old_height / $new_height;
/**
* Calculate where to crop based on the center of the image
*/
$src_x = floor((($new_width - $width) / 2) * $width_ratio);
$src_y = round((($new_height - $height) / 2) * $height_ratio);
}
/**
* Don't crop the image, just resize it proportionally
*/
else {
if ($old_width > $old_height) {
$ratio = max($old_width, $old_height) / max($width, $height);
} else {
$ratio = max($old_width, $old_height) / min($width, $height);
}
$new_width = $old_width / $ratio;
$new_height = $old_height / $ratio;
$new_image = imagecreatetruecolor($new_width, $new_height);
}
/**
* Where all the real magic happens
*/
imagecopyresampled($new_image, $img_original, 0, 0, $src_x, $src_y, $new_width, $new_height, $old_width, $old_height);
/**
* Save it as a JPG File with our $destination_filename param.
*/
imagejpeg($new_image, $destination_filename, $quality);
/**
* Destroy the evidence!
*/
imagedestroy($new_image);
imagedestroy($img_original);
/**
* Return true because it worked and we're happy. Let the dancing commence!
*/
return true;
}
}
?>
</code></pre>
<p>It works fine but any improvements or suggestions are welcome.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T17:32:42.743",
"Id": "38579",
"Score": "0",
"body": "var is depricated use protected,public or private."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T17:43:43.583",
"Id": "38582",
"Score": "0",
"body": "You shouldn't have member variables when you don't use them in functions. And your functions should also have protected,public or private."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-11T05:38:15.353",
"Id": "38642",
"Score": "0",
"body": "Skip all useless comments. Just comment the intention and not the code itself."
}
] |
[
{
"body": "<p>Some hints for (not) commenting your code.</p>\n\n<p>Change:</p>\n\n<pre><code>/**\n * Landscape Image\n */\nif ($current_ratio > $desired_ratio_after) {\n</code></pre>\n\n<p>To:</p>\n\n<pre><code>$isLandscape=$current_ratio > $desired_ratio_after;\nif ($isLandscape) {\n</code></pre>\n\n<p>Or:</p>\n\n<pre><code>if ($old_width < $width || $old_height < $height) {\n /**\n * The desired image size is bigger than the original image.\n * Best not to do anything at all really.\n */\n return false;\n}\n</code></pre>\n\n<p>To:</p>\n\n<pre><code>$toSmallToResize = $old_width < $width || $old_height < $height\nif ($toSmallToResize) return false;\n</code></pre>\n\n<p>(Maybe the <code>||</code> should be a <code>&&</code> ?)</p>\n\n<p>As I said in the comments, get rid of all comments without new informations for the reader.</p>\n\n<p>You could also move your switch into a separate method with a nice name to reduce the length of your main method. And the crop and resize_only part are also suitable for a private method. (This methods would also be very easily to test in PHPUnit; just a bunch of numbers and no real images required.)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-11T05:50:01.180",
"Id": "24978",
"ParentId": "24965",
"Score": "1"
}
},
{
"body": "<p>There are two ideas mixed together that complicate the code:</p>\n\n<ul>\n<li>Manipulating an image.</li>\n<li>Uploading an image.</li>\n</ul>\n\n<p>Separate the concerns into two different classes (e.g., <code>SimpleImage</code> and <code>SecureImageUpload</code>).</p>\n\n<p>See the <a href=\"http://www.white-hat-web-design.co.uk/articles/php-image-resizing.php\" rel=\"nofollow noreferrer\">SimpleImage class</a> for a reasonably designed class that handles image manipulation. It has methods to resize, scale, load, and save image files of <a href=\"http://www.phpclasses.org/browse/file/2743.html\" rel=\"nofollow noreferrer\">various formats</a>. I'd recommend that you extend the <code>SimpleImage</code> class to include methods that expose the extra functionality you desire.</p>\n\n<p>Encapsulation means that object data is manipulated by exposing methods to other objects. For example:</p>\n\n<pre><code>$image->load( \"filename.jpg\" );\n$image->scale( 100 );\n$image->save( \"thumbnails/filename.jpg\" );\n</code></pre>\n\n<p>Securely handling image file uploads in PHP is a daunting task to do correctly. See:</p>\n\n<ul>\n<li><a href=\"https://security.stackexchange.com/questions/32852/risks-of-a-php-image-upload-form\">https://security.stackexchange.com/questions/32852/risks-of-a-php-image-upload-form</a></li>\n<li><a href=\"https://stackoverflow.com/questions/4166762/php-image-upload-security-check-list\">https://stackoverflow.com/questions/4166762/php-image-upload-security-check-list</a></li>\n<li><a href=\"http://nullcandy.com/php-image-upload-security-how-not-to-do-it/\" rel=\"nofollow noreferrer\">http://nullcandy.com/php-image-upload-security-how-not-to-do-it/</a></li>\n<li><a href=\"http://www.net-security.org/dl/articles/php-file-upload.pdf\" rel=\"nofollow noreferrer\">http://www.net-security.org/dl/articles/php-file-upload.pdf</a></li>\n<li><a href=\"http://software-security.sans.org/blog/2009/12/28/8-basic-rules-to-implement-secure-file-uploads/\" rel=\"nofollow noreferrer\">http://software-security.sans.org/blog/2009/12/28/8-basic-rules-to-implement-secure-file-uploads/</a></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-30T22:37:02.767",
"Id": "26823",
"ParentId": "24965",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T14:45:01.583",
"Id": "24965",
"Score": "1",
"Tags": [
"php",
"optimization",
"object-oriented"
],
"Title": "Image Resize/Crop Class"
}
|
24965
|
<p>I've got a string that consists of an arbitrary combination of text and <code>{}</code> delimited python code, for instance, <code>A plus b is {a + b}</code>. However, braces are used for dictionary and set literals in python, so <code>You chose the {{1:"first", 2:"second"}[choice]} option</code> should also be interpretted correctly. It's also valid to have more than one python expression in the input, so <code>You picked {choice1} and {choice2}</code> is valid.</p>
<p>Here's my current code:</p>
<pre><code>protected String ParseStringForVariable([NotNull] String str)
{
PythonEngine.PythonEngine pythonEngine = GetCurrentCore().PythonEngine;
for (int i = 0; i < str.Length; i++)
{
if (str[i] != '{')
{
continue;
}
int opening = i;
foreach (var expression in from closing in str.IndexesWhere('}'.Equals)
where closing > opening
select new
{
Template = str.Substring(opening, closing - opening + 1),
Code = str.Substring(opening + 1, closing - opening - 1)
})
{
PythonByteCode compiled;
try
{
compiled = pythonEngine.Compile(expression.Code, PythonByteCode.SourceCodeType.Expression);
}
catch (PythonParseException)
{
// not valid python, try next expression
continue;
}
String result = pythonEngine.Evaluate(compiled).ToString();
str = str.Replace(expression.Template, result);
break;
}
}
return str;
}
</code></pre>
<p>It works by looking at progressively longer strings, attempting to parse them, and ignoring them if it's not valid python. This is done with the <code>PythonEngine</code> class, which is a wrapper around the IronPython interpretter, and has an extensive test suite, so can assumed to be correct.</p>
<ol>
<li><p>It appears to burp slightly if the value of the first of multiple python expression contains an opening brace: <code>{"{"} {"}"}</code>, what's the best way to prevent that?</p></li>
<li><p>Resharper is complaining about access to modified closures, can you provide a test case that exposes why that is an issue?</p></li>
<li><p>It works under all inputs I've tested it with, but what edge cases should be included in the test suite? (It's intended behaviour that invalid python code is left as-is). Current thoughts include:</p>
<ul>
<li>Empty string</li>
<li>without braces</li>
<li>empty braces</li>
<li>valid python in braces</li>
<li>invalid python</li>
<li>both valid and invalid</li>
<li>both valid and empty</li>
<li>both invalid and empty</li>
<li>valid, nested braces</li>
<li>invalid, nested braces</li>
<li>valid, evaluated to contain open brace</li>
<li>valid, evaluated to contain close brace - irrelevant, as parsing is LTR?</li>
<li>valid, evaluated to contain open brace followed by further invalid</li>
<li>valid, evaluated to contain open brace followed by further empty</li>
<li>unmatched open brace</li>
<li>unmatched close brace</li>
</ul></li>
<li><p>Are there any improvements that jump out? Clarity, performance, style?</p></li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T18:35:42.293",
"Id": "38593",
"Score": "0",
"body": "What are you using to execute the Python code? I can't seem to find types like `PythonByteCode` anywhere."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-11T08:04:39.003",
"Id": "38650",
"Score": "0",
"body": "@svick Post edited to clarify."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-11T09:31:50.490",
"Id": "38654",
"Score": "0",
"body": "reg 3.) Could you please add your test cases."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-11T10:27:20.170",
"Id": "38659",
"Score": "0",
"body": "@mnhg clarified slightly, but added."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-11T15:01:19.287",
"Id": "38671",
"Score": "0",
"body": "Regarding #2: http://stackoverflow.com/q/8898925/298754"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-11T15:25:23.430",
"Id": "38674",
"Score": "0",
"body": "@Bobson perhaps I'm just being dense, but I still don't get how that applies in this case. Hence asking for a test case: it works as expected in every situation I've tried. Or is it just Resharper being over-cautious?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-12T14:58:31.230",
"Id": "38723",
"Score": "0",
"body": "Where is it complaining?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-12T18:12:37.763",
"Id": "38738",
"Score": "0",
"body": "`str.Substring()` in the anonymous object constructor."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-17T06:09:16.830",
"Id": "38931",
"Score": "0",
"body": "This bit is troubling to me: `str = str.Replace(expression.Template, result);` You may want to push the result of the replacement on a stack instead of overwriting the `str`. What does the `i` mean in the outer loop after you replace an expression with its value, which usually is of a different length? I will have to come up with some test cases on weekend to definitely say that this is a bug, but I can at least say it is definitely confusing to read."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-17T13:36:56.370",
"Id": "38960",
"Score": "0",
"body": "@abuzittingillifirca That's the reason I'm using `i` rather than a foreach: After the replacement, `i` is the index of the first character of the result. I was tempted to add a line like `i += result.Length`... I can't remember the reasoning on why I didn't."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-17T13:39:29.300",
"Id": "38961",
"Score": "0",
"body": "Also, I'm replacing in place so that open braces in the code don't get parsed again: `this is a set: {{1,2}}` `{1,2}` is a valid set literal, `1,2` is a valid tuple literal."
}
] |
[
{
"body": "<p>I see an extra unnecessary variable that you can get rid of, or change another variable so that it makes more sense.</p>\n\n<pre><code>int opening = i;\n</code></pre>\n\n<p>you use this inside of a for loop. You can do 2 things with this.</p>\n\n<ol>\n<li>Just use the variable <code>i</code> where ever you had the variable <code>opening</code></li>\n<li><p>change the <code>i</code> variable to <code>opening</code> in the for loop like </p>\n\n<pre><code>for (int opening = 0; opening < str.Length; opening++)\n</code></pre></li>\n</ol>\n\n<p>hopefully this shows you how unnecessary that extra variable is, it isn't used anywhere else for anything other than the loops. </p>\n\n<hr>\n\n<p>Other than that I would need to play with it and spend some time with it to see if it plays well with others.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-09-04T18:44:39.230",
"Id": "61964",
"ParentId": "24969",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "11",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T16:29:01.217",
"Id": "24969",
"Score": "3",
"Tags": [
"c#",
"python",
"parsing"
],
"Title": "Interpolating code delimited with character that can appear in code"
}
|
24969
|
<p>Of all the macros that I put into heavy rotation these days, this one is running the slowest. ~4-5 seconds depending on the size of the files. It's not a lot but I'd like to know why code 16x as long is running much more instantly.</p>
<p>The code tries to merge documents (usually 2 excel docs out of at most 5) depending on their names and then rename those to exactly what I need. Then, another big issue, is using find/replace to fix a bunch of Unicode/character issues. I cant help but think that could be handled better. </p>
<p>I'd like to find out where the bottlenecks in this code are, how to handle these Unicode issues, perform the <code>Find/replace</code> better, and all in all how to execute better VBA practices.</p>
<pre><code>Option Explicit
Sub MergeBooks()
Dim wb As Workbook
Dim ws As Worksheet
On Error GoTo Handler:
Application.ScreenUpdating = False
For Each wb In Application.Workbooks
If wb.Name <> "CompanyBook.xlsm" Then
If FindString(wb.Name, "Report2") Then
wb.Worksheets.Move after:=Workbooks("CompanyBook.xlsm").Sheets("Aggregate")
ElseIf FindString(wb.Name, "Report1") Then
wb.Worksheets.Move after:=Workbooks("CompanyBook.xlsm").Sheets("Aggregate")
End If
End If
Next
For Each ws In Workbooks("CompanyBook.xlsm").Worksheets
If FindString(ws.Name, "Report2") Then
ws.Name = "Report2"
ElseIf FindString(ws.Name, "Report1") Then
ws.Name = "Report1"
End If
Next ws
'Char mishap replacements
With Workbooks("CompanyBook.xlsm")
.Worksheets("Report1").Cells.Replace What:="&amp;", Replacement:="&", LookAt:=xlPart, MatchCase:=False
.Worksheets("Report1").Cells.Replace What:="&quot;", Replacement:=Chr(34), LookAt:=xlPart, MatchCase:=False
.Worksheets("Report2").Cells.Replace What:="’", Replacement:="’", LookAt:=xlPart, MatchCase:=False
.Worksheets("Report2").Cells.Replace What:="…", Replacement:="…", LookAt:=xlPart, MatchCase:=False
.Worksheets("Report2").Cells.Replace What:="£", Replacement:="£", LookAt:=xlPart, MatchCase:=False
'.Worksheets("Report2").Cells.Replace What:="‘", Replacement:="‘L", LookAt:=xlPart, MatchCase:=False
.Worksheets("Company").Select
End With
Application.ScreenUpdating = True
Exit Sub
Handler:
Application.ScreenUpdating = True
MsgBox "Please make sure that one and only one type of each database file is open.", vbExclamation, "Merge Documents"
End Sub
Function FindString(strCheck As String, strFind As String) As Boolean
Dim intPos As Integer
intPos = InStr(strCheck, strFind)
FindString = intPos > 0
End Function
</code></pre>
|
[] |
[
{
"body": "<p>Not for efficiency, but you can start with this... Convert this block:</p>\n\n<pre><code>If FindString(wb.Name, \"Report2\") Then\n wb.Worksheets.Move after:=Workbooks(\"CompanyBook.xlsm\").Sheets(\"Aggregate\")\nElseIf FindString(wb.Name, \"Report1\") Then\n wb.Worksheets.Move after:=Workbooks(\"CompanyBook.xlsm\").Sheets(\"Aggregate\")\nEnd If\n</code></pre>\n\n<p>to the following:</p>\n\n<pre><code>If FindString(wb.Name, \"Report2\") or FindString(wb.Name, \"Report1\") Then\n wb.Worksheets.Move after:=Workbooks(\"CompanyBook.xlsm\").Sheets(\"Aggregate\")\nEnd If\n</code></pre>\n\n<p>Also, it looks like your <code>FindString</code> function is almost identical (just converting to <code>Boolean</code>) to the <code>InStr</code> you use within it, so why not just use <code>InStr</code>?</p>\n\n<p>i.e. </p>\n\n<pre><code>If FindString(ws.Name, \"Report2\") Then\n</code></pre>\n\n<p>change to</p>\n\n<pre><code>If InStr(ws.Name, \"Report2\") > 0 Then\n</code></pre>\n\n<p>For your specific question, you can do your replace on a string variable and write that value back to the cell, rather than search on the cell each time. Accessing the actual cell is very slow. Change this:</p>\n\n<pre><code>With Workbooks(\"CompanyBook.xlsm\")\n.Worksheets(\"Report1\").Cells.Replace What:=\"&amp;\", Replacement:=\"&\", LookAt:=xlPart, MatchCase:=False\n.Worksheets(\"Report1\").Cells.Replace What:=\"&quot;\", Replacement:=Chr(34), LookAt:=xlPart, MatchCase:=False\n.Worksheets(\"Report2\").Cells.Replace What:=\"’\", Replacement:=\"’\", LookAt:=xlPart, MatchCase:=False\n.Worksheets(\"Report2\").Cells.Replace What:=\"…\", Replacement:=\"…\", LookAt:=xlPart, MatchCase:=False\n.Worksheets(\"Report2\").Cells.Replace What:=\"£\", Replacement:=\"£\", LookAt:=xlPart, MatchCase:=False\n'.Worksheets(\"Report2\").Cells.Replace What:=\"‘\", Replacement:=\"‘L\", LookAt:=xlPart, MatchCase:=False\n.Worksheets(\"Company\").Select\nEnd With\n</code></pre>\n\n<p>To something like this:</p>\n\n<pre><code>With Workbooks(\"CompanyBook.xlsm\")\n For Each varCell In .Worksheets(\"Report1\").Cells ' THIS IS VERY BIG AND YOU SHOULD CONSIDER REFINING YOUR RANGE\n TempVal = varCell.Value2\n TempVal = Replace(TempVal, \"&amp;\", \"&\")\n 'and so on for all your replacements\n varCell.Value = TempVal\n Next varCell\nEnd With\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-12T02:22:11.020",
"Id": "38695",
"Score": "0",
"body": "thanks for the help. I think you've shed some light on how I can make this an overall better method."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-12T01:47:41.757",
"Id": "25015",
"ParentId": "24971",
"Score": "2"
}
},
{
"body": "<p>To supplement Gaffi's suggestions, I think you would benefit from changing this:</p>\n\n<pre><code>'Char mishap replacements\nWith Workbooks(\"CompanyBook.xlsm\")\n.Worksheets(\"Report1\").Cells.Replace What:=\"&quot;\", Replacement:=Chr(34), LookAt:=xlPart, MatchCase:=False\n.Worksheets(\"Report2\").Cells.Replace What:=\"’\", Replacement:=\"’\", LookAt:=xlPart, MatchCase:=False\n.Worksheets(\"Report2\").Cells.Replace What:=\"…\", Replacement:=\"…\", LookAt:=xlPart, MatchCase:=False\n.Worksheets(\"Report2\").Cells.Replace What:=\"£\", Replacement:=\"£\", LookAt:=xlPart, MatchCase:=False\n'.Worksheets(\"Report2\").Cells.Replace What:=\"‘\", Replacement:=\"‘L\", LookAt:=xlPart, MatchCase:=False\n.Worksheets(\"Company\").Select\nEnd With\n</code></pre>\n\n<p>To this:</p>\n\n<pre><code>Dim r1 As Excel.Range, r2 As Excel.Range\nSet r1 = Workbooks(\"CompanyBook.xlsm\").Worksheets(\"Report1\").Cells.SpecialCells(xlCellTypeConstants)\nSet r2 = Workbooks(\"CompanyBook.xlsm\").Worksheets(\"Report2\").Cells.SpecialCells(xlCellTypeConstants)\n\nWith r1\n .Replace What:=\"&amp;\", Replacement:=\"&\", LookAt:=xlPart, MatchCase:=False\n .Replace What:=\"&quot;\", Replacement:=Chr(34), LookAt:=xlPart, MatchCase:=False\nEnd With\n\nWith r2\n .Replace What:=\"…\", Replacement:=\"…\", LookAt:=xlPart, MatchCase:=False\n .Replace What:=\"£\", Replacement:=\"£\", LookAt:=xlPart, MatchCase:=False\nEnd With\n</code></pre>\n\n<p>This way, you narrow down the selection to only cells that have content for Excel to find/replace. Also, because you set the range to a variable once, Excel doesn't have to search through all cells multiple times like it is now.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-13T00:36:06.630",
"Id": "38747",
"Score": "0",
"body": "just a question. let's say that the those initial character errors weren't there. would i suffer a performance loss if i ran the replace commands anyway?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-13T05:20:06.523",
"Id": "38751",
"Score": "0",
"body": "@mango, yes, you would lose performance if those characters were not found. however, it would still run faster than if those characters were in there and the values were replaced after all. you can't really avoid it, to be honest. if you need to replace those characters than you need to check for them each time."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-12T03:11:24.430",
"Id": "25016",
"ParentId": "24971",
"Score": "4"
}
},
{
"body": "<p>What lowest performance is always having to refresh the display information. And if you have to switch between sheets, time delays are added focus allocation. </p>\n\n<pre><code>Application.ScreenUpdating = False\n</code></pre>\n\n<p>Besides optimizing You've already suggested, maybe you should think about the possibility of rewriting your own Replace function. I see you're using the same parameters in all calls. </p>\n\n<pre><code>LookAt: = xlPart, \nMatchCase: = False \n</code></pre>\n\n<p>The VB functions contain algorithms prepared for many different parameters. Are too complex for what you really need but it will always be less quick to use own functions and 100% designed for your target. </p>\n\n<p>If execution speed is your priority, you should reinvent the wheel but look worse encoded. </p>\n\n<p>Other general advice would directly access the value of the cells, without having to select them first.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-16T09:24:05.203",
"Id": "41787",
"ParentId": "24971",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "25016",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T17:58:51.613",
"Id": "24971",
"Score": "3",
"Tags": [
"performance",
"vba",
"excel"
],
"Title": "Merging worksheets and using find/replace"
}
|
24971
|
<p>I wish to create audit trails for specific tables and columns in my database, and document who made the change, when it was made, and what the change was.</p>
<p>To do so, I will create the following tables:</p>
<ol>
<li>Audits: Create a record whenever a change is made to any table, and stores the table, the date, the user who made the change, and the task (insert, update, remove).</li>
<li>Audits_1pk: 1-to-1 relationship to audits, and stores the primary key of any table which has a single primary key.</li>
<li>Audits_2pk: Same as audits_1pk except used for tables which have a compound primary key made up of (2) keys.</li>
<li>Audits_3pk: Same as audits_1pk except used for tables which have a compound primary key made up of (3) keys.</li>
<li>Audit_int: Stores the effected affected column name if is a int type, and has a 1-to-many relationship to audits.</li>
<li>Audit_text: Same as audit_int, but is for columns which are of text type.</li>
<li>Audit_var_45: Same as audit_int, but is for columns which are of varchar(45) type.</li>
</ol>
<p>I will then add triggers to the tables I wish to audit, and will write to the above tables.</p>
<p>Below is the fully working script. I include an example where the "students" table and the "courses_has_students" table is modified and audited.</p>
<p>Please comment on the appropriateness of my implementation, and whether you have any recommendations.</p>
<pre><code>SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES';
CREATE SCHEMA IF NOT EXISTS `auditTest` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci ;
USE `auditTest` ;
-- -----------------------------------------------------
-- Table `auditTest`.`users`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `auditTest`.`users` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT ,
`name` VARCHAR(45) NOT NULL ,
PRIMARY KEY (`id`) )
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `auditTest`.`auditTasks`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `auditTest`.`auditTasks` (
`task` CHAR(1) NOT NULL ,
`name` VARCHAR(45) NOT NULL ,
PRIMARY KEY (`task`) )
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `auditTest`.`audits`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `auditTest`.`audits` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT ,
`users_id` INT UNSIGNED NULL ,
`dateChanged` DATETIME NOT NULL ,
`dbUser` VARCHAR(45) NOT NULL ,
`requesting_ip` CHAR(15) NULL ,
`tableName` VARCHAR(45) NOT NULL ,
`task` CHAR(1) NOT NULL ,
PRIMARY KEY (`id`) ,
INDEX `fk_audits_users_idx` (`users_id` ASC) ,
INDEX `fk_audits_tasks1_idx` (`task` ASC) ,
CONSTRAINT `fk_audits_users`
FOREIGN KEY (`users_id` )
REFERENCES `auditTest`.`users` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_audits_tasks1`
FOREIGN KEY (`task` )
REFERENCES `auditTest`.`auditTasks` (`task` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `auditTest`.`audits_1pk`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `auditTest`.`audits_1pk` (
`audits_id` INT UNSIGNED NOT NULL ,
`pk1` VARCHAR(45) NOT NULL ,
PRIMARY KEY (`audits_id`) ,
CONSTRAINT `fk_audits_1pk_audits1`
FOREIGN KEY (`audits_id` )
REFERENCES `auditTest`.`audits` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `auditTest`.`audits_2pk`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `auditTest`.`audits_2pk` (
`audits_id` INT UNSIGNED NOT NULL ,
`pk1` VARCHAR(45) NOT NULL ,
`pk2` VARCHAR(45) NOT NULL ,
PRIMARY KEY (`audits_id`) ,
CONSTRAINT `fk_audits_2pk_audits1`
FOREIGN KEY (`audits_id` )
REFERENCES `auditTest`.`audits` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `auditTest`.`audits_3pk`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `auditTest`.`audits_3pk` (
`audits_id` INT UNSIGNED NOT NULL ,
`pk1` VARCHAR(45) NOT NULL ,
`pk2` VARCHAR(45) NOT NULL ,
`pk3` VARCHAR(45) NOT NULL ,
PRIMARY KEY (`audits_id`) ,
CONSTRAINT `fk_audits_3pk_audits1`
FOREIGN KEY (`audits_id` )
REFERENCES `auditTest`.`audits` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `auditTest`.`audit_int`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `auditTest`.`audit_int` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT ,
`audits_id` INT UNSIGNED NOT NULL ,
`columnName` VARCHAR(45) NOT NULL ,
`oldValue` INT NULL ,
`newValue` INT NULL ,
PRIMARY KEY (`id`) ,
INDEX `fk_audit_int_audits1_idx` (`audits_id` ASC) ,
CONSTRAINT `fk_audit_int_audits1`
FOREIGN KEY (`audits_id` )
REFERENCES `auditTest`.`audits` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `auditTest`.`audit_text`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `auditTest`.`audit_text` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT ,
`audits_id` INT UNSIGNED NOT NULL ,
`columnName` VARCHAR(45) NOT NULL ,
`oldValue` TEXT NULL ,
`newValue` TEXT NULL ,
PRIMARY KEY (`id`) ,
INDEX `fk_audit_int_audits1_idx` (`audits_id` ASC) ,
CONSTRAINT `fk_audit_int_audits10`
FOREIGN KEY (`audits_id` )
REFERENCES `auditTest`.`audits` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `auditTest`.`audit_var_45`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `auditTest`.`audit_var_45` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT ,
`audits_id` INT UNSIGNED NOT NULL ,
`columnName` VARCHAR(45) NOT NULL ,
`oldValue` VARCHAR(45) NULL ,
`newValue` VARCHAR(45) NULL ,
PRIMARY KEY (`id`) ,
INDEX `fk_audit_int_audits1_idx` (`audits_id` ASC) ,
CONSTRAINT `fk_audit_int_audits100`
FOREIGN KEY (`audits_id` )
REFERENCES `auditTest`.`audits` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `auditTest`.`students`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `auditTest`.`students` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT ,
`name` VARCHAR(45) NOT NULL ,
`ssn` CHAR(10) NOT NULL ,
`notes` TEXT NULL ,
`nickname` VARCHAR(45) NULL ,
PRIMARY KEY (`id`) )
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `auditTest`.`courses`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `auditTest`.`courses` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT ,
`name` VARCHAR(45) NOT NULL ,
`course_number` VARCHAR(45) NOT NULL ,
PRIMARY KEY (`id`) )
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `auditTest`.`courses_has_students`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `auditTest`.`courses_has_students` (
`courses_id` INT UNSIGNED NOT NULL ,
`students_id` INT UNSIGNED NOT NULL ,
`other_int` INT NULL ,
PRIMARY KEY (`courses_id`, `students_id`) ,
INDEX `fk_courses_has_students_students1_idx` (`students_id` ASC) ,
INDEX `fk_courses_has_students_courses1_idx` (`courses_id` ASC) ,
CONSTRAINT `fk_courses_has_students_courses1`
FOREIGN KEY (`courses_id` )
REFERENCES `auditTest`.`courses` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_courses_has_students_students1`
FOREIGN KEY (`students_id` )
REFERENCES `auditTest`.`students` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
USE `auditTest`;
DELIMITER $$
USE `auditTest`$$
CREATE TRIGGER tg_students_ins AFTER INSERT ON students
FOR EACH ROW
BEGIN
INSERT INTO audits(tableName,task,dateChanged,users_id,dbUser,requesting_ip) VALUES ('students', 'i', NOW(), @users_id, USER(), @requesting_ip );
SET @AID=LAST_INSERT_ID();
INSERT INTO audits_1pk(audits_id,pk1) VALUES (@AID,NEW.id );
IF NEW.name IS NOT NULL THEN
INSERT INTO audit_var_45(audits_id,columnName,oldValue,newValue) VALUES (@AID,'name',NULL,NEW.name);
END IF;
IF NEW.ssn IS NOT NULL THEN
INSERT INTO audit_var_45(audits_id,columnName,oldValue,newValue) VALUES (@AID,'ssn',NULL,NEW.ssn);
END IF;
IF NEW.notes IS NOT NULL THEN
INSERT INTO audit_text(audits_id,columnName,oldValue,newValue) VALUES (@AID,'notes',NULL,NEW.notes);
END IF;
END$$
USE `auditTest`$$
CREATE TRIGGER tg_students_upd AFTER UPDATE ON students
FOR EACH ROW
BEGIN
IF NOT NEW.name <=> OLD.name OR NOT NEW.ssn <=> OLD.ssn OR NOT NEW.notes <=> OLD.notes THEN
INSERT INTO audits(tableName,task,dateChanged,users_id,dbUser,requesting_ip) VALUES ('students', 'u', NOW(), @users_id, USER(), @requesting_ip );
SET @AID=LAST_INSERT_ID();
INSERT INTO audits_1pk(audits_id,pk1) VALUES (@AID,NEW.id );
IF NOT NEW.name <=> OLD.name THEN
INSERT INTO audit_var_45(audits_id,columnName,oldValue,newValue) VALUES (@AID,'name',OLD.name,NEW.name);
END IF;
IF NOT NEW.ssn <=> OLD.ssn THEN
INSERT INTO audit_var_45(audits_id,columnName,oldValue,newValue) VALUES (@AID,'ssn',OLD.ssn,NEW.ssn);
END IF;
IF NOT NEW.notes <=> OLD.notes THEN
INSERT INTO audit_text(audits_id,columnName,oldValue,newValue) VALUES (@AID,'notes',OLD.notes,NEW.notes);
END IF;
END IF;
END$$
USE `auditTest`$$
CREATE TRIGGER tg_students_del AFTER DELETE ON students
FOR EACH ROW
BEGIN
INSERT INTO audits(tableName,task,dateChanged,users_id,dbUser,requesting_ip) VALUES ('students', 'd', NOW(), @users_id, USER(), @requesting_ip );
SET @AID=LAST_INSERT_ID();
INSERT INTO audits_1pk(audits_id,pk1) VALUES (@AID,OLD.id );
END$$
DELIMITER ;
DELIMITER $$
USE `auditTest`$$
CREATE TRIGGER tg_courses_has_students_ins AFTER INSERT ON courses_has_students
FOR EACH ROW
BEGIN
INSERT INTO audits(tableName,task,dateChanged,users_id,dbUser,requesting_ip) VALUES ('courses_has_students', 'i', NOW(), @users_id, USER(), @requesting_ip );
SET @AID=LAST_INSERT_ID();
INSERT INTO audits_2pk(audits_id,pk1,pk2) VALUES (@AID,NEW.courses_id,NEW.students_id);
IF NEW.other_int IS NOT NULL THEN
INSERT INTO audit_int(audits_id,columnName,oldValue,newValue) VALUES (@AID,'other_int',NULL,NEW.other_int);
END IF;
END$$
USE `auditTest`$$
CREATE TRIGGER tg_courses_has_students_upt AFTER UPDATE ON courses_has_students
FOR EACH ROW
BEGIN
IF NOT NEW.other_int <=> OLD.other_int THEN
INSERT INTO audits(tableName,task,dateChanged,users_id,dbUser,requesting_ip) VALUES ('courses_has_students', 'u', NOW(), @users_id, USER(), @requesting_ip );
SET @AID=LAST_INSERT_ID();
INSERT INTO audits_2pk(audits_id,pk1,pk2) VALUES (@AID,NEW.courses_id,NEW.students_id);
IF NOT NEW.other_int <=> OLD.other_int THEN
INSERT INTO audit_int(audits_id,columnName,oldValue,newValue) VALUES (@AID,'other_int',OLD.other_int,NEW.other_int);
END IF;
END IF;
END$$
USE `auditTest`$$
CREATE TRIGGER tg_courses_has_students_del AFTER DELETE ON courses_has_students
FOR EACH ROW
BEGIN
INSERT INTO audits(tableName,task,dateChanged,users_id,dbUser,requesting_ip) VALUES ('courses_has_students', 'd', NOW(), @users_id, USER(), @requesting_ip );
SET @AID=LAST_INSERT_ID();
INSERT INTO audits_2pk(audits_id,pk1,pk2) VALUES (@AID,OLD.courses_id,OLD.students_id);
END$$
DELIMITER ;
SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
-- Required by audit tables
INSERT INTO auditTasks (task,name) VALUES ('i','insert');
INSERT INTO auditTasks (task,name) VALUES ('u','update');
INSERT INTO auditTasks (task,name) VALUES ('d','delete');
-- Get some business records
INSERT INTO users (id,name) VALUES (0,'John Doe');
INSERT INTO users (id,name) VALUES (0,'Jane Doe');
INSERT INTO courses (id,name,course_number) VALUES (0,'Math','123abc');
INSERT INTO courses (id,name,course_number) VALUES (0,'English','123abc');
-- Set by PHP application
SET @requesting_ip='555.555.555.555';
SET @users_id=1;
-- Start normal routines
INSERT INTO students (id,name,ssn,notes,nickname) VALUES (0,'Billy Bob','555-55-5555',NULL,'Bebop');
UPDATE students SET name='Bill Bob',notes='Some notes' WHERE id=1;
INSERT INTO courses_has_students (courses_id,students_id) VALUES (1,1);
INSERT INTO courses_has_students (courses_id,students_id) VALUES (2,1);
DELETE FROM courses_has_students WHERE courses_id=1 AND students_id=1;
DELETE FROM courses_has_students WHERE courses_id=2 AND students_id=1;
DELETE FROM students WHERE id=1;
-- Audit database
SELECT u.name AS user_name, at.name AS task, a.dateChanged, a.tableName, af.columnName, af.oldValue AS oldValue_text, af.newValue AS newValue_text, null AS oldValue_val_45, null AS newValue_val_45
FROM audits AS a
INNER JOIN users AS u ON u.id=a.users_id
INNER JOIN auditTasks AS at ON at.task=a.task
INNER JOIN audits_1pk AS apk ON apk.audits_id=a.id
LEFT OUTER JOIN audit_text AS af ON af.audits_id=a.id
WHERE a.tableName='students' AND apk.pk1=1
UNION
SELECT u.name AS user_name, at.name AS task, a.dateChanged, a.tableName, af.columnName, null AS oldValue_text, null AS newValue_text, af.oldValue AS oldValue_val_45, af.newValue AS newValue_val_45
FROM audits AS a
INNER JOIN users AS u ON u.id=a.users_id
INNER JOIN auditTasks AS at ON at.task=a.task
INNER JOIN audits_1pk AS apk ON apk.audits_id=a.id
LEFT OUTER JOIN audit_var_45 AS af ON af.audits_id=a.id
WHERE a.tableName='students' AND apk.pk1=1
ORDER BY dateChanged ASC;
SELECT u.name AS user_name, at.name AS task, a.dateChanged, a.tableName, af.columnName, af.oldValue, af.newValue
FROM audits AS a
INNER JOIN users AS u ON u.id=a.users_id
INNER JOIN auditTasks AS at ON at.task=a.task
INNER JOIN audits_2pk AS apk ON apk.audits_id=a.id
LEFT OUTER JOIN audit_int AS af ON af.audits_id=a.id
WHERE a.tableName='courses_has_students' AND apk.pk1=1 AND apk.pk2=1
ORDER BY dateChanged ASC;
</code></pre>
|
[] |
[
{
"body": "<p>An alternative way I have seen is to create separate audit tables for each table you want to audit and simply have a trigger that copies the entire row into the table plus the action (insert, update, delete), the user that made the change and timestamp of when it happened.</p>\n\n<p>It does involve more tables but it means you only add audit tables & triggers for the tables you actually want audited so is potentially a simplier solution since having several audit tables based on the keys and having to work out what goes where has more potential areas for bugs to creep in.</p>\n\n<p>One other advantage is that you can easily query the tables to see not only the type of change and affected fields but all fields allowing a snapshot of the data at time of change.</p>\n\n<p>Couple of disadvantages: you have to create audit tables and triggers for every table you want audited and if you need to create a timeline of changes across multiple tables then it takes a little more work but the userId and timestamp should help there.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-18T11:27:37.923",
"Id": "39031",
"Score": "0",
"body": "Thanks Nathan, Yes, I have seen the method you describe, and I understand your stated pros and cons to it. I have not, however, seen the method I am proposing, and that makes me think there must be something wrong with it. Have you ever seen it? Do you see any major drawbacks to it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-18T13:02:02.790",
"Id": "39039",
"Score": "0",
"body": "a few things spring to mind.\n1 - the intention seems to be to try and centralise the auditing but by having to have multiple tables you have a lot more moving parts so increase possibility that something could go wrong\n2 - if a user changes 10 fields on a record then you have to store 10 records in the audit table, so if you need to report on it it is harder to pull together a picture of the data & if you're having to report on it this is definately someting to take into account.\n3 - maintainability by other people, will they easily be able understand how it works to extend in the future"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-19T02:14:06.060",
"Id": "39089",
"Score": "0",
"body": "1 - The intention is to provide a framework where only given columns of given tables can be easily added to the \"audit list\". 2 - if a user changes 10 fields on a record then you have to store 10 records in the audit table, but only if you want to audit those 10 fields. 3 - maintainability by other people is not an immediate concern, but probably can be handled by a view. Not trying to necessarily defend my approach. Think the cons exceed the pros?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-19T08:36:38.683",
"Id": "39108",
"Score": "0",
"body": "I don't know your context but from an auditing point of view does it make sense to only audit certain fields? what value do you gain from only a few fields? I guess it will depend on how the audit information will be used, who is consuming it - a person or another system?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-20T10:37:57.580",
"Id": "39175",
"Score": "0",
"body": "Thanks Nathan, People will enter and use the data. Certain fields are more sensitive than others, and only the sensitive ones need be audited.d"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-21T18:31:59.990",
"Id": "39223",
"Score": "0",
"body": "Not sure if I am further along, but appreciate your help!"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-16T17:11:18.990",
"Id": "25144",
"ParentId": "24973",
"Score": "3"
}
},
{
"body": "<p>I agree with Nathan. The only change I would make is that I would add previous fields also, since you want to track the contents. So, to summarize, for each table there will be an audit table with twice as many columns as the original table (for before and after the change), plus an action, userid and timestamp. Once you have these info, you will be able to process it in application level to perform analytics.</p>\n\n<p>Your approach is logically alright, but I think it introduces unnecessary complexity for implemetation. The choice depends on your project. For example, if one of your table is a Session table that get updated for every user login (say every second) then duplicating it is probably not a good idea, your solution will be a better fit for that (you will save memory). But, if your tables are very important (like account information, or deals with money), then I think Nathan's solution is the way to go.</p>\n\n<p>Hope I can help :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-20T10:40:10.587",
"Id": "39176",
"Score": "0",
"body": "Thanks Faisal, I do have an oldValue to track all previous values. In one sense, I wonder if it is really even needed since oldValue is the same as the previous newValue, but it does I suppose make it more intuitive."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-21T06:05:45.197",
"Id": "39210",
"Score": "0",
"body": "Again, you are absolutely right. But, it does make one row depend on other row rather (which make the system more complex to handle). For me, I try to find a balance."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-22T09:55:22.937",
"Id": "39260",
"Score": "0",
"body": "@faisal if you snapshot the entire row on every change then you don't need to stored old value & new value, you can just look at the previous record and see what the value was. Admittedly can be more difficult working out what's changed unless you write a report to highlight the change made in each row which I'd think is what you actually want from an audit."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-20T06:35:51.903",
"Id": "25288",
"ParentId": "24973",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T18:06:19.567",
"Id": "24973",
"Score": "9",
"Tags": [
"mysql",
"sql"
],
"Title": "Strategy to create audit trails for a SQL database"
}
|
24973
|
<p>I'm learning Ember, and I've come across a situation where I haven't been able to find a pattern online.</p>
<p>My application's main route includes a list of "stories" (think scrum). However, this list also has a <code>StoryController</code> associated with it. I don't want to assign the stories in the <code>IndexRoute</code> file; it doesn't feel like it belongs there. I ended up adding a property to the <code>StoriesController</code> and calling the <code>App.Story.fetch()</code> method to the Controller's <code>init()</code> method. I can't help but feel there is a better, more "Ember" way to do this.</p>
<p><strong>App.IndexRoute</strong></p>
<pre><code>App.IndexRoute = Ember.Route.extend({
renderTemplate: function(){
this.render();
this.render('stories');
}
});
</code></pre>
<p><strong>App.StoriesController</strong></p>
<pre><code>App.StoriesController = Ember.ArrayController.extend({
init : function(){
this.stories = App.Story.find();
}
});
</code></pre>
|
[] |
[
{
"body": "<p>I think you can pass in the controller to the \"stories\" render function and use the model hook :</p>\n\n<p><strong>App.IndexRoute</strong></p>\n\n<pre><code>App.IndexRoute = Ember.Route.extend({\n renderTemplate: function(){\n this.render();\n this.render('stories', {controller: App.StoriesController}); \n }\n});\n</code></pre>\n\n<p><strong>App.StoriesController</strong></p>\n\n<pre><code>App.StoriesController = Ember.ArrayController.extend({\n model : function() {\n return App.Story.find();\n }\n});\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-05T16:00:32.620",
"Id": "29400",
"ParentId": "24975",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T19:22:20.313",
"Id": "24975",
"Score": "1",
"Tags": [
"javascript",
"design-patterns",
"ember.js"
],
"Title": "Ember App - Initial State"
}
|
24975
|
<p>I want to do some object-oriented programming in Lua, and I decided on something like this:</p>
<pre class="lang-lua prettyprint-override"><code>local B = {} -- in real life there is other stuff in B
B.Object = {
constructor = function() end,
extend = function(this, that, meta)
if not that then that = {} end
if not meta then meta = {} end
meta.__index = this
setmetatable(that, meta)
return that
end,
isa = function(this, that)
for meta in function() return getmetatable(this) end do
if this == that then return true end
this = meta.__index
end
return this == that
end,
new = function(this, ...)
local that = this:extend()
that:constructor(...)
return that
end,
}
</code></pre>
<p>All objects (including "class-like objects") extend <code>B.Object</code>, directly or indirectly. For example:</p>
<pre class="lang-lua prettyprint-override"><code>-- Request handler base
B.RequestHandler = B.Object:extend()
-- override these
function B.RequestHandler:accept() error "not implemented" end
function B.RequestHandler:process() error "not implemented" end
-- URL-encoded POST handler
B.PostHandler_URLEncoded = B.RequestHandler:extend()
function B.PostHandler_URLEncoded:accept()
return self.method == "POST" and
self.content_type == "application/x-www-form-urlencoded"
end
function B.PostHandler_URLEncoded:process()
-- some code
end
-- Multipart POST handler
B.PostHandler_Multipart = B.RequestHandler:extend()
-- etc.
</code></pre>
<p>It might be used something like this:</p>
<pre class="lang-lua prettyprint-override"><code>B.request_handlers = {
GetHandler:new(),
URLEncodedPostHandler:new(),
MultipartPostHandler:new(),
}
B.handle_request = function()
for k, v in ipairs(B.request_handlers) do
if v:accept() then
return v:process()
end
end
error "request not handled"
end
</code></pre>
<p>As far as I know, this is pretty much the normal way to handle inheritance in Lua. Did I miss anything? Is there anything that needs improvement?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-05-06T13:51:16.770",
"Id": "163137",
"Score": "2",
"body": "I would suggest adding some comments to describe the intent of your code. The biggest issue is probably private properties. I tried some ideas some time ago, but every option is either horribly incomplete (and as such would require loads of boilerplate code) or will introduce at least two more levels to the call stack. So my suggestion is: Try it without inheritance. Most issues of code replication can be resolved without inheritance."
}
] |
[
{
"body": "<p><strong>Example Usage</strong></p>\n\n<p>The example that you provide does not really help to explain how the code should work. I trust that it does work, but the variables don't exactly match up.</p>\n\n<p>For example, this code here:</p>\n\n<pre><code>B.request_handlers = {\n GetHandler:new(),\n URLEncodedPostHandler:new(), \n MultipartPostHandler:new(), \n}\n</code></pre>\n\n<p>What is <code>B.request_handlers</code> before this? You define the \"class\" like so in the former code block: <code>B.RequestHandler = B.Object:extend()</code> but now it is lower case and has an underscore. The same for the three calls inside those brackets. What does <code>GetHandler</code> call? I don't see a matching method anywhere. It's all just a little confusing.</p>\n\n<p><strong>Lack of Comments</strong></p>\n\n<p>The first code block is the most important one, because that is where you are establishing the actual Lua inheritance. The problem with the code it that it is very dense, and there is no explanation whatsoever about how it is expected to be used.</p>\n\n<p>For example, you define the extend method like this:</p>\n\n<pre><code>extend = function(this, that, meta)\n if not that then that = {} end\n if not meta then meta = {} end\n meta.__index = this\n setmetatable(that, meta)\n return that\nend,\n</code></pre>\n\n<p>But then in your example you call it like this:</p>\n\n<pre><code>B.RequestHandler = B.Object:extend()\n</code></pre>\n\n<p>After reading through the method, I can understand that if <code>extend()</code> is called without any arguments, the arguments will be filled in inside the method. I think that it would be very helpful to have a comment explaining the valid ways of calling the <code>extend</code> method. In most languages, when a method has arguments they must be supplied or the compiler will complain. Since Lua is a dynamic language, you won't get this checking, and so I believe the comments explaining how to use your OOP implementation become even more important. </p>\n\n<p><strong>This, That, and the other</strong></p>\n\n<p>This code is very hard to understand:</p>\n\n<pre><code>isa = function(this, that)\n for meta in function() return getmetatable(this) end do\n if this == that then return true end\n this = meta.__index\n end\n return this == that\nend,\n\nnew = function(this, ...)\n local that = this:extend()\n that:constructor(...)\n return that\nend,\n</code></pre>\n\n<p>All of the this, that, then, this == that, return that, etc etc just twists my brain up into a knot. If I read the code very carefully line by line, I can eventually puzzle out what it does, but I think that this is a failure of the code.</p>\n\n<p>It's true, you probably do not intend anyone to read your inheritance code. Rather, once you have set it up, it will just work and allow someone using the code to extend objects in a classical OOP way. However, I still think that by using better variable names, some comments, and a few more lines of code, it could be written in such a way that it could be understood immediately when reading it.</p>\n\n<p>Also consider that someone who is not a native English speaker may struggle with the difference between this and that, and the then keyword does not help the situation.</p>\n\n<p><strong>Something Good</strong></p>\n\n<p>I like this code here:</p>\n\n<pre><code>-- override these\nfunction B.RequestHandler:accept() error \"not implemented\" end\nfunction B.RequestHandler:process() error \"not implemented\" end\n</code></pre>\n\n<p>The comment makes it very clear that these are the methods that should be overridden, and the string that will be returned if they are not will make it very clear what has gone wrong. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-07-05T15:31:47.077",
"Id": "95878",
"ParentId": "24979",
"Score": "13"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-11T06:52:41.173",
"Id": "24979",
"Score": "29",
"Tags": [
"object-oriented",
"lua",
"prototypal-class-design"
],
"Title": "Lua OOP and classically-styled prototypal inheritance"
}
|
24979
|
<p>I have this piece of Java (Android) code that adds a list of brokers to a local SQLite database as one single SQL instruction.</p>
<pre><code>public void Add(List<Broker> brokers)
{
if(brokers == null || brokers.size() == 0)
return;
String sql = "INSERT INTO " + TABLE_NAME + " SELECT " + brokers.get(0).getId() + " AS '" + COLUMN_BROKERID + "', "+ brokers.get(0).getOfficeId() + " AS '" + COLUMN_OFFICEID + "', '"+ brokers.get(0).getName() + "' AS '" + COLUMN_NAME + "', "+ brokers.get(0).getSuccessRate() + " AS '" + COLUMN_SUCCESSRATE + "'";
for(int i=1; i<brokers.size(); i++)
{
sql = sql + " UNION SELECT " + brokers.get(i).getId() + ", " + brokers.get(i).getOfficeId() + ", '" + brokers.get(i).getName() + "', " + brokers.get(i).getSuccessRate();
}
databaseManager.ExecuteNonQuery(sql);
}
</code></pre>
<p>But what slows this down a lot is the change in the string 'sql'. The last line, which is a call to <code>ExecuteNonQuery()</code>, takes a millisecond, but the above takes a lot. How can I speed this up?</p>
<p><code>databaseManager</code> is an interface that is implemented by a class of <code>SQLiteOpenHelper</code> and simply executes an SQL statement (but don't take this into account; it doesn't take any time as much as the rest of the code).</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-11T08:04:43.947",
"Id": "38651",
"Score": "0",
"body": "Add some line breaks ;)"
}
] |
[
{
"body": "<p>A classicel one. String concatenation with the <code>+</code> operator is very inefficient, because it creates a new copy of the string every time.<br>\nSee for example item 51 in Effective Java from Joshua Bloch or here: <a href=\"http://www.javapractices.com/topic/TopicAction.do?Id=4\" rel=\"nofollow\">http://www.javapractices.com/topic/TopicAction.do?Id=4</a></p>\n\n<p>Try to change it to <code>StringBuilder</code>:</p>\n\n<pre><code>public void Add(List<Broker> brokers)\n{\n if(brokers == null || brokers.size() == 0)\n return;\n\n StringBuilder query = new StringBuilder(brokers.size() * 50); // size is a guess, could be furhter investigated\n query.append(\"INSERT INTO \").append(TABLE_NAME).append(\" SELECT \").append(brokers.get(0).getId()).append(\" AS '\").append(COLUMN_BROKERID).append(\"', \").append(brokers.get(0).getOfficeId()).append(\" AS '\").append(COLUMN_OFFICEID).append(\"', '\").append(brokers.get(0).getName()).append(\"' AS '\").append(COLUMN_NAME).append(\"', \").append(brokers.get(0).getSuccessRate()).append(\" AS '\").append(COLUMN_SUCCESSRATE).append(\"'\"); // it is not that important to change this line. this will probably be done by the java compiler anyway\n\n for(int i=1; i<brokers.size(); i++)\n query.append(\" UNION SELECT \").append(brokers.get(i).getId()).append(\", \").append(brokers.get(i).getOfficeId()).append(\", '\").append(brokers.get(i).getName()).append(\"', \").append(brokers.get(i).getSuccessRate());\n\n databaseManager.ExecuteNonQuery(query.toString(););\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-11T08:02:41.783",
"Id": "38648",
"Score": "1",
"body": "Actually the compiler is [optimizing](http://stackoverflow.com/questions/1296571/what-happens-when-java-compiler-sees-many-string-concatenations-in-one-line) the + to StringBuilder in some cases. So I prefer the + outside of the loop or local in the loop for readability and only use the append between the loop iteration. In most common cases readability is more worth than some mircoseconds, especially as the SQL/Netweork is the slowest part here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-11T08:04:18.010",
"Id": "38649",
"Score": "0",
"body": "Just scrolled to the very right and found your comment stating the same ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-11T09:03:26.017",
"Id": "38652",
"Score": "0",
"body": "Yes, I agree, readability should always be the first main goal. I do not have a clear opinion what is the best way for mixing string with variables. We have +, append, String.format, one line, multiple lines, and so on. For readability, I like the possibility from php to just use a variable inside the string."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-11T07:43:25.457",
"Id": "24981",
"ParentId": "24980",
"Score": "4"
}
},
{
"body": "<p>This is my take. Longer but separates each concern, making updating/investigating the SQL statement itself easier.</p>\n\n<pre><code>private final static String SQL_TEMPLATE = \"INSERT INTO {0} SELECT {1} AS '{2}',\" +\n \" {3} AS '{4}', '{5}' AS '{6}', {7} AS '{8}'\";\nprivate final static String UNION_TEMPLATE = \" UNION SELECT {0}, {1}, '{2}', {3}\";\n\npublic void add(List<Broker> brokers) {\n // consider using Apache Commons StringUtils.isBlank(str):\n // catches empty and null Strings\n if (brokers == null || brokers.isEmpty()) {\n return;\n }\n\n Broker firstBroker = broker.get(0);\n String sql = java.text.MessageFormat.format(\n SQL_TEMPLATE,\n TABLE_NAME,\n firstBroker.getId(),\n COLUMN_BROKERID,\n firstBroker.getOfficeId(),\n COLUMN_OFFICEID,\n firstBroker.getName(),\n COLUMN_NAME,\n firstBroker.getSuccessRate(),\n COLUMN_SUCCESSRATE);\n\n for (int i = 1; i < brokers.size(); i++) {\n Broker nextBroker = brokers.get(i);\n\n String unionClause = java.text.MessageFormat.format(UNION_TEMPLATE,\n nextBroker.getId(),\n nextBroker.getOfficeId(),\n nextBroker.getName(),\n nextBroker.getSuccessRate());\n sql.concat(unionClause);\n }\n\n databaseManager.executeNonQuery(sql);\n}\n</code></pre>\n\n<ol>\n<li>Java Naming conventions: method names should start with a lowercase letter (\"Add\" -> \"add\", \"Execute\" -> \"execute\"</li>\n<li>Use all methods API gives you, for example <code>List.isEmpty()</code> instead of <code>List.size() == 0</code> to improve readability / expressiveness.</li>\n<li>Since TABLE_NAME, COLUMN_BROKERID, etc. appear to be constants I'd include them in the SQL template to decrease number of required replaces and improve readability.</li>\n<li>Since there are so many parameters in each SQL you could consider using a different mechanism that supports named parameters (for example <code>:id</code>, <code>:broker</code> rather than ordered like <code>{0}</code>, <code>{1}</code> etc.)</li>\n<li>I wouldn't worry about String concatenation performance as it's not likely to be the bottleneck; calling the DB will be orders of magnitue more time-consuming,</li>\n<li>Doesn't SQLite support PreparedStatements? Is SQL injection a viable threat in your application?</li>\n</ol>\n\n<hr>\n\n<p>Update: sorry, I didn't notice your \"takes a millisecond\" remark; to be honest I find it hard to believe that String concatenation (even for multiple loop iterations) could take significantly more time that a DB update; is your profiling methodology 100% reliable?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-11T11:31:26.827",
"Id": "24989",
"ParentId": "24980",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "24981",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-11T07:18:33.597",
"Id": "24980",
"Score": "3",
"Tags": [
"java",
"optimization",
"sql",
"android"
],
"Title": "Adding a list of brokers to a local SQLite database"
}
|
24980
|
<p>I have a abstract class which is extended by many many other classes:</p>
<p><strong>What I have done:</strong></p>
<pre><code>public abstract class AbstractActionHandler {
protected WorkItem currentWI;
protected String status;
protected String field;
protected void init(WorkItem currentWI, String status, String field) throws IllegalArgumentException, SecurityException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {
this.currentWI = currentWI;
this.status = status;
this.field = field;
if(couldBeExecuted()) {
this.executeAction();
}
}
protected boolean couldBeExecuted() throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, SecurityException, NoSuchMethodException {
long start = System.currentTimeMillis();
DataObjectFactory fact = DataObjectFactory.getFactory(currentWI);
DataWorkItem currentWI = fact.getDataWorkItem("current");
long end = System.currentTimeMillis();
System.out.println("+++++ " + " Workitem Factory takes " + (end-start) + "ms " + "+++++");
// Other logic which returns false or true
// [...]
}
// Implementation of business logic
protected abstract void executeAction();
// Should call init function
public void execute(WorkItem currentWI, String status, String field) throws IllegalArgumentException {
this.init(currentWI, status, field);
}
}
</code></pre>
<p>Now I figured out that the creation of <code>DataWorkItem</code> object takes a lot of time. Because I am using an abstract factory I can simply change the line </p>
<p><code>DataObjectFactory fact = DataObjectFactory.getFactory(currentWI);</code> </p>
<p>to</p>
<p><code>DataObjectFactory fact = DataObjectFactory.getBoostFactory(currentWI);</code></p>
<p>and provide another implementation of <code>DataWorkItem</code> object.</p>
<p>Old implementation which calls an external API function which needs a lot of time and which is basically only necessary to call once:</p>
<pre><code>public DataWorkItem(IWorkItem wi, String revision) {
OtherExternService externService = (OtherExternService) PlatformContext
.getPlatform().lookupService(OtherExternService.class);
IPObjectList listOfRevs = externService.getDataService().getObjectHistory(wi);
}
</code></pre>
<p>New implementation which calls API function only one time because of singleton implementation:</p>
<pre><code>public DataWorkItem(WorkItem wi, String revision, boolean global) {
// +++
// We use a global object here which holds the history of current work item.
// We only need to read this history once so we create a singleton here.
// The performance is hardly improved by this pattern.
// We use this constructor in DataBoostObjectFactory.
// +++
IPObjectList listOfRevs = WorkItemGlobal.getInstance(wi).getObjectList();
}
</code></pre>
<p><strong>Singleton class:</strong></p>
<pre><code>public class WorkItemGlobal {
public static WorkItemGlobal instance = null;
private IPObjectList listOfRevs;
private WorkItemGlobal(WorkItem wi) {
OtherExternService externService = (OtherExternService) PlatformContext
.getPlatform().lookupService(OtherExternService.class);
listOfRevs = externService.getDataService().getObjectHistory(wi);
}
public static WorkItemGlobal getInstance(WorkItem wi) {
if(instance == null) {
instance = new WorkItemGlobal(wi);
}
return instance;
}
public static void deleteInstance() {
instance = null;
}
public IPObjectList getObjectList() {
return listOfRevs;
}
}
</code></pre>
<p><strong>Question:</strong></p>
<p>Is it good to use a Singleton here? </p>
<p>Of course I can avoid using a singleton if I create the <code>DataWorkItem</code> object outside of the classes which extends <code>AbstractActionHandler</code> and pass the object to the constructor (for example).</p>
<p>But with this approach I have to adjust ALL classes which extends <code>AbstractActionHandler</code> because I have to call a function (or change constructor) which passes the <code>DataWorkItem</code> object to the abstract class.</p>
<p>At all it works good (for now). I can see a hardly improved performance because the call to the external API function is only done once.</p>
<p>Other suggestions or ideas?</p>
|
[] |
[
{
"body": "<p>Your question is: <strong>Is it good to use a Singleton here?</strong></p>\n\n<p>My answer is: <strong>If you can avoid</strong> using a singleton, do it! And you answer this yourself: \"Of course I can avoid using a singleton if (...)\".</p>\n\n<p>Passing a <code>DataWorkItem</code> object to the constructor or some other method is more preferable than using a singleton-pattern. This is part of the principle <a href=\"http://pragprog.com/articles/tell-dont-ask\" rel=\"nofollow\">Tell, don't ask</a>.</p>\n\n<p>The <code>deleteInstance</code> method in your \"singleton\" defies the <a href=\"http://en.wikipedia.org/wiki/Singleton_pattern\" rel=\"nofollow\">Singleton pattern</a>, which states that it </p>\n\n<blockquote>\n <p>restricts the Instantiation of a class to one object.</p>\n</blockquote>\n\n<p>By using a <code>deleteInstance</code> method, you allow multiple objects. (Not at the same time, but still multiple objects).</p>\n\n<p><strong>Other comments</strong></p>\n\n<p>You have one field <code>protected WorkItem currentWI;</code> and one local variable in your <code>couldBeExecuted</code> method: <code>DataWorkItem currentWI = fact.get..</code>. They share the same variable name. This leads to confusion for me. I don't see much of your field. (Of course, I don't see your subclasses to this method). You might want to pass the object on to the methods instead of storing it as a field (again with the principle **Tell, don't ask). Will that object ever be used again after <code>init</code> has been called? If not, remove it.</p>\n\n<p>In your <code>DataWorkItem</code>, you declare a new local variable <strong>on the last line of the constructor</strong></p>\n\n<pre><code>IPObjectList listOfRevs = externService.getDataService().getObjectHistory(wi);\n</code></pre>\n\n<p>This should give you a \"unused variable\" warning from the compiler. What happens to this variable once the method is finished? Nothing!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-21T14:45:54.760",
"Id": "58338",
"Score": "0",
"body": "Thank you for your comments! You are right. One of the \"currentWI\" variable should be renamed -> done. The protected currentWI field is used by sub classes. After the last line \"IPObjectList listOfRevs = externService.getDataService().getObjectHistory(wi);\" in my question there is also other relevant code which uses \"listOfRevs\". I forgot to comment that other code follows. However, you answer my question to avoid the Singleton (because it is just possible...independing of the effort)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-19T21:08:37.110",
"Id": "35722",
"ParentId": "24982",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "35722",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-11T07:55:05.077",
"Id": "24982",
"Score": "2",
"Tags": [
"java",
"singleton"
],
"Title": "Abstract class which uses a abstract factory -> New implementation with Singleton"
}
|
24982
|
<p>Here's a fiddle: <a href="http://jsfiddle.net/YF8cg/" rel="nofollow">http://jsfiddle.net/YF8cg/</a></p>
<p>Focussing entirely on the javascript and on the structure of the HTML (<code>.qapair .question and .answer</code>), how could I improve this system?</p>
<p>JS:</p>
<pre><code>$(document).ready(function() {
$('.question').click(function() {
$(this).siblings('.answer').slideToggle(400); // Display the clicked answer
$(this).parents('.QApair').siblings('.QApair').children('.answer').each( // Hide all the others
function() {
if($(this).is(':visible')) { // Detects if it's visible
$(this).slideToggle(400); // If true then toggles it
}
});
});
});
</code></pre>
<p>HTML: </p>
<pre><code><div class="qapair">
<h4 class="question">First Question</h4>
<div class="answer">Here would be lods of boring text, or some images, or some tables, or some fish, or some lets-pick-another-random-nouns, you get the picture. I just needed to fill space.
</div>
</div>
<div class="qapair">
<h4 class="question">Second Question</h4>
<div class="answer">I've run out of anything to write. So keyboard spas in 5... 4... 3... 2... 1... agdkfdakgjajgjregafgi iej fujagijrfgj rhgjahngufg ughuafng uuagj u unhu up u dnfajng hfgnajgnurngr gugnjfngja uugf n ndnfaung urgjangjnfg. That was interesting....
</div>
</div>
</code></pre>
<p>I'm fairly new to jQuery, so any help would be appreciated.</p>
<p>Thanks in advance.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-11T09:50:54.093",
"Id": "38655",
"Score": "1",
"body": "Cache your selectors for starters"
}
] |
[
{
"body": "<p>HTML: The only change is that they are wrapped in a div id'ed <code>container</code> which will be used in event handling, explained below.</p>\n\n<pre><code><div id=\"container\">\n <div class=\"qapair\">\n <h4 class=\"question\">First Question</h4>\n <div class=\"answer\"></div>\n </div>\n <div class=\"qapair\">\n <h4 class=\"question\">Second Question</h4>\n <div class=\"answer\"></div>\n </div>\n <div class=\"qapair\">\n <h4 class=\"question\">Third Question</h4>\n <div class=\"answer\"></div>\n </div>\n</div>\n</code></pre>\n\n<p>JS: Explained in the comments</p>\n\n<pre><code>//shorthand for $(document).ready(fn) is $(fn)\n$(function () {\n\n //container will be used for delegated event handling\n var container = $('#container'),\n //since questions remain static, it's best we reference ahead of time\n questions = $('.question',container);\n\n //take advantage of delegation which assigns one handler to the parent\n //for all events in it's descendant. Here, we place a handler on container\n //for all question instead of putting a handler per question\n container.on('click', '.question', function (event) {\n var question = $(this);\n\n //we use 'next' which directly gets the next sibling instead of siblings(selector). \n //though internal implementations might be the same, but at least we avoid\n //writing that many selectors in our implementation\n question\n .next()\n .slideToggle(400);\n\n //using the referenced questions, we remove the currently clicked, pick\n //their answers that are currently visible and slide them up\n questions\n .not(question)\n .next(':visible')\n .slideUp(400);\n });\n});\n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/YF8cg/2/\" rel=\"nofollow\">Here's running code</a>. It's more of a readability and maintainability optimization rather than performance.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-11T10:25:16.350",
"Id": "38658",
"Score": "0",
"body": "Thanks. I learnt some intersting things from that, notable the delegation part. I'd upvote if I had enough rep, but for the time being I've just selected as answer."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-11T10:01:19.753",
"Id": "24987",
"ParentId": "24985",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "24987",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-11T09:30:51.663",
"Id": "24985",
"Score": "4",
"Tags": [
"javascript",
"jquery",
"html"
],
"Title": "jQuery - Drop Down QA"
}
|
24985
|
<p>I'm new to Rhino mock and I would like to know if the test I did is not fake testing, as I've read a lot about it. Are there any improvements that need to be done?</p>
<pre><code>[Test]
public void GenerateDateTable_Returns_DataTableOfGroup()
{
//Arrange
var groupStub = MockRepository.GenerateStub<Group>();
var groupEnumerable = new[] { groupStub };
var mockgroup = MockRepository.GenerateMock<FillTableRow<Group>>();
mockgroup.Replay();
//Act
mockgroup.GenerateDateTable(groupEnumerable);
//Assert
Assert.IsTrue(mockgroup.DataTableBatch.Columns.Count == 3);
}
public class FillTableRow<T>
{
public DataTable DataTableBatch { get; set; }
public DataTable GenerateDateTable(IEnumerable<T> enumerable)
{
IDbObjectFactory<T> tableFactory = new TableFactory<T>();
DataTableBatch = (DataTable)tableFactory.GetDbObject();
foreach (var row in enumerable)
{
AddRow(row);
}
return DataTableBatch;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>As far as I can understand (I use Moq as an isolation framework and not rhino mocks) in your test you are testing not an implementation of your class FillTableRow, but a mock, generated by isolation framework. You should always use your real class as systam under test (obviously). You use stubs to provide context in which your system under tests works, just to emulate the system's environment. And you use mocks if the state of your system under test is not changing during your test and you need to be sure that correct methods of external classes has been called.\nI recomend you to read \"<a href=\"http://www.manning.com/osherove/\" rel=\"nofollow\">The Art of Unit Testing</a>\" book by Roy Osherove. It gives very good explanation of how and when you should use mocks and stubs.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-11T12:07:31.890",
"Id": "24991",
"ParentId": "24990",
"Score": "6"
}
},
{
"body": "<p>You should introduce Dependency Injection so that <code>FillTableRow<T></code> receives the object of type <code>IDbObjectFactory<T></code> rather than instantiates it itself. Once you've done that you can write tests by injecting stub of <code>IDbObjectFactory<T></code> into <code>FillTableRow<T></code>.</p>\n\n<p>In your current code there is no need in creating mock for <code>FillTableRow<T></code> since it's the object under test, and you can instantiate it directly (you can use mock for object under test e.g. if you're testing abstract class). Also you may not need stub for <code>Group</code> object (it looks like a data object) if you can instantiate it with required configuration yourselves.</p>\n\n<p>Fixed code for your current implementation:</p>\n\n<pre><code>[Test]\npublic void GenerateDateTable_Returns_DataTableOfGroup()\n{\n //Arrange\n var groupEnumerable = new[] { new Group() };\n var sut = new FillTableRow<Group>();\n\n //Act\n var result = sut.GenerateDateTable(groupEnumerable);\n\n //Assert\n Assert.IsTrue(result.Columns.Count == 3); //I would also verify all 3 columns\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-12T07:51:23.273",
"Id": "38706",
"Score": "2",
"body": "@Maro - you would also benefit from doing this assert `Assert.AreEqual(3, result.Columns.Count);` instead. That way, if the count is something other than 3, the test failure would be `expected 3, got 4` rather than `expected true, got false` which gives less context to the actual failure."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-11T12:40:06.107",
"Id": "24994",
"ParentId": "24990",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "24991",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-11T11:55:26.593",
"Id": "24990",
"Score": "1",
"Tags": [
"c#",
"unit-testing",
"mocks"
],
"Title": "Possible fake testing with Rhino mock"
}
|
24990
|
<p>You can find a <a href="http://jsfiddle.net/mAuJr/" rel="nofollow">JSFiddle demo of my tabs</a>.</p>
<p>The jQuery tabs work well as intended. However I was asked to include arrows alongside the tabs so readers could navigate through tabs using them instead of the tab titles alone.</p>
<p>So I used:</p>
<pre><code>$("li.tab").click( function() {
$('#div1').removeClass( 'hide' );
$('#div2').removeClass( 'hide' );
$('#div3').removeClass( 'hide' );
$('#div1').removeClass( 'show' );
$('#div2').removeClass( 'show' );
$('#div3').removeClass( 'show' );
} );
$("a.rightarrow1").click( function() {
$('#div1').addClass( 'hide' );
$('#div2').addClass( 'show' );
$('#div2').removeClass( 'hide' );
$('#div3').addClass( 'hide' );
$('li.tab2').addClass( 'current' );
$('li.tab1').removeClass( 'current' );
$('li.tab3').removeClass( 'current' );
} );
$("a.leftarrow1").click( function() {
$('#div1').addClass( 'hide' );
$('#div2').addClass( 'hide' );
$('#div3').addClass( 'show' );
$('#div3').removeClass( 'hide' );
$('li.tab3').addClass( 'current' );
$('li.tab2').removeClass( 'current' );
$('li.tab1').removeClass( 'current' );
} );
$("a.rightarrow2").click( function() {
$('#div1').addClass( 'hide' );
$('#div2').addClass( 'hide' );
$('#div3').addClass( 'show' );
$('#div3').removeClass( 'hide' );
$('li.tab3').addClass( 'current' );
$('li.tab2').removeClass( 'current' );
$('li.tab1').removeClass( 'current' );
} );
$("a.leftarrow2").click( function() {
$('#div1').addClass( 'show' );
$('#div1').removeClass( 'hide' );
$('#div2').addClass( 'hide' );
$('#div3').addClass( 'hide' );
$('li.tab1').addClass( 'current' );
$('li.tab2').removeClass( 'current' );
$('li.tab3').removeClass( 'current' );
} );
$("a.rightarrow3").click( function() {
$('#div1').addClass( 'show' );
$('#div1').removeClass( 'hide' );
$('#div2').addClass( 'hide' );
$('#div3').addClass( 'hide' );
$('li.tab1').addClass( 'current' );
$('li.tab2').removeClass( 'current' );
$('li.tab3').removeClass( 'current' );
} );
$("a.leftarrow3").click( function() {
$('#div1').addClass( 'hide' );
$('#div2').addClass( 'show' );
$('#div2').removeClass( 'hide' );
$('#div3').addClass( 'hide' );
$('li.tab2').addClass( 'current' );
$('li.tab3').removeClass( 'current' );
$('li.tab1').removeClass( 'current' );
} );
</code></pre>
<p>It's long, but it works. But can it be made more elegant?</p>
|
[] |
[
{
"body": "<p>Firstly, the obvious:</p>\n\n<p>Both <code>.addClass</code> and <code>.removeClass</code> can deal with multiple classes at once, so wherever you have something like</p>\n\n<pre><code> $('#div1').removeClass( 'hide' );\n ...\n $('#div1').removeClass( 'show' );\n ...\n</code></pre>\n\n<p>you can instead write</p>\n\n<pre><code> $('#div1').removeClass(['hide', 'show']);\n</code></pre>\n\n<hr>\n\n<p>You have a few places where you're just removing the same set of classes from a series of elements. You might consider crafting your selector differently to select them all at once, or at the very least define an intermediate function so that you can write something like</p>\n\n<pre><code>stripClasses([\"#div1\", \"#div2\", ...], ['hide', 'show']);\n</code></pre>\n\n<hr>\n\n<p>All of this actually seems to be pointless, because if the idea is just to navigate through tabs with arrow buttons, you can use the <a href=\"https://stackoverflow.com/a/1335299\">built-in <code>selected</code> option</a>, both to find out which is currently active and to change it.</p>\n\n<p>The fundamental reason you've got so much complexity in that code block is that you seem to have decided to manually manage all the class changes that go along with moving from one tab to another. You don't actually need to do that.</p>\n\n<p>Something like</p>\n\n<pre><code>$(\"#tabs\").tabs();\n\n$(\".left-arrow\").click(function () { changeTab(\"#tabs\", -1)});\n$(\".right-arrow\").click(function () { changeTab(\"#tabs\", +1)});\n\nfunction changeTab(elem, by) {\n var sel = $(elem).tabs(\"option\", \"selected\");\n var newTab = bounded(0, sel+by, 3);\n $(elem).tabs(\"option\", \"selected\", newTab);\n}\n\nfunction bounded(lower, num, upper) {\n return Math.min(upper, Math.max(lower, num));\n}\n</code></pre>\n\n<p>should work fine (change the <code>newTab</code> expression to get different behavior, like wrapping, out of it). Just be mindful of your local namespaces and styles.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-11T15:27:30.490",
"Id": "24999",
"ParentId": "24992",
"Score": "4"
}
},
{
"body": "<p>I see you are using the <a href=\"http://jquerytools.org/\" rel=\"nofollow\">jquery tools plugin</a>. You can achieve the functionality you are looking for without having to write any extra javascript by naming the tabs: </p>\n\n<pre><code><!-- wrap each tab with an <a> and name the tab in the href attribute -->\n<ul class=\"large-tabs\">\n <li><h2><a href=\"#tab1\">Tab 1</a></h2></li>\n <li><h2><a href=\"#tab2\">Tab 2</a></h2></li>\n <li><h2><a href=\"#tab3\">Tab 3</a></h2></li>\n</ul>\n</code></pre>\n\n<p>and then simply link your prev/next anchors to the tab href:</p>\n\n<pre><code><!-- tab 1 -->\n<div>\n <p>Tab 1 Text</p>\n <a href=\"#tab3\" class=\"leftarrow1\">&laquo; Prev</a>\n <a href=\"#tab2\" class=\"rightarrow1\">Next &raquo;</a>\n</div>\n\n<!-- tab 2 -->\n<div>\n <p>Tab 2 Text</p>\n <a href=\"#tab1\" class=\"leftarrow1\">&laquo; Prev</a>\n <a href=\"#tab3\" class=\"rightarrow1\">Next &raquo;</a>\n</div>\n\n<!-- tab 3 -->\n<div>\n <p>Tab 3 Text</p>\n <a href=\"#tab2\" class=\"leftarrow1\">&laquo; Prev</a>\n <a href=\"#tab1\" class=\"rightarrow1\">Next &raquo;</a>\n</div> \n</code></pre>\n\n<p>Alternatively, you could use the slideshow plugin with tabs and create one prev and one next button to control all slides.</p>\n\n<pre><code>$(\"ul.large-tabs\")\n .tabs(\"div.large-panes > div.large-pane\")\n .slideshow({\n next: '.next', // element class to use for next\n prev: '.prev' // element class to use for prev\n });\n</code></pre>\n\n<p>The HTML like so:</p>\n\n<pre><code><!-- tab \"panes\" -->\n<div class=\"large-panes\"> \n\n <!-- previous link with class '.prev' --> \n <a class=\"prev arrow leftarrow1\">&laquo; Prev</a>\n\n <!-- the div panes -->\n <div class=\"large-pane\"> ... </div>\n <div class=\"large-pane\"> ... </div>\n\n <!-- next link with class '.next' -->\n <a class=\"next arrow rightarrow1\">Next &raquo;</a>\n\n</div>\n</code></pre>\n\n<p>Unless the tabs are a fixed height you might not want to use the slideshow plugin.</p>\n\n<p>See the <a href=\"http://jsfiddle.net/836tw/1/\" rel=\"nofollow\">Fiddle</a></p>\n\n<p>The jquerytools documentation is good with lots of examples. It'd be worth checking out. :) Hope that helps!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-13T08:26:09.687",
"Id": "25053",
"ParentId": "24992",
"Score": "3"
}
},
{
"body": "<p>First make some adjustments to the HTML :</p>\n\n<ul>\n<li>Give all the arrows <code>class=\"arrow\"</code></li>\n<li>Give all the arrows a <code>rel=\"n\"</code> attribute, where n = 1, 2 or 3</li>\n<li>Give all the li tabs \"class=tab\"</li>\n</ul>\n\n<p>With these adjustments in place, the jQuery will boil down to a couple of lines : </p>\n\n<pre><code>$(\"a.arrow\").click(function(evt) {\n $('#div' + this.rel).removeClass('hide').addClass('show').siblings(\"div\").addClass('hide');\n $(this).closest(\"li.tab\").addClass('current').siblings(\".tab\").removeClass('current');\n});\n</code></pre>\n\n<p><em>untested</em></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-16T04:22:48.013",
"Id": "25119",
"ParentId": "24992",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-11T12:30:16.657",
"Id": "24992",
"Score": "0",
"Tags": [
"javascript",
"jquery"
],
"Title": "Switching tabs, with previous/next arrows, using jQuery"
}
|
24992
|
<p>I'm trying to convert TimeSpan object to text that can be read like a sentence.
e.g. </p>
<pre><code>TimeSpan(2, 1, 0, 0) --> "2 days and an hour"
TimeSpan(1, 2, 1, 0) --> "A day, 2 hours and a minute"
</code></pre>
<p>Some more samples for conversion are in the 'TestCases' object under 'TimeSpanPrettyFormatterTests' class.</p>
<p>Is there any better way to do it than the one i suggested here?</p>
<p>Thanks</p>
<pre><code>using System;
using JetBrains.Annotations;
using NUnit.Framework;
namespace Client.Tests
{
[TestFixture]
public class TimeSpanPrettyFormatterTests
{
[UsedImplicitly]
static object[] TestCases =
{
new object[] { new TimeSpan(0, 0, 0, 0), string.Empty },
new object[] { new TimeSpan(1, 0, 0, 0), "A day" },
new object[] { new TimeSpan(2, 0, 0, 0), "2 days" },
new object[] { new TimeSpan(0, 1, 0, 0), "An hour" },
new object[] { new TimeSpan(1, 1, 0, 0), "A day and an hour" },
new object[] { new TimeSpan(2, 1, 0, 0), "2 days and an hour" },
new object[] { new TimeSpan(0, 2, 0, 0), "2 hours" },
new object[] { new TimeSpan(1, 2, 0, 0), "A day and 2 hours" },
new object[] { new TimeSpan(2, 2, 0, 0), "2 days and 2 hours" },
new object[] { new TimeSpan(0, 0, 1, 0), "A minute" },
new object[] { new TimeSpan(1, 0, 1, 0), "A day and a minute" },
new object[] { new TimeSpan(2, 0, 1, 0), "2 days and a minute" },
new object[] { new TimeSpan(0, 1, 1, 0), "An hour and a minute" },
new object[] { new TimeSpan(1, 1, 1, 0), "A day, an hour and a minute" },
new object[] { new TimeSpan(2, 1, 1, 0), "2 days, an hour and a minute" },
new object[] { new TimeSpan(0, 2, 1, 0), "2 hours and a minute" },
new object[] { new TimeSpan(1, 2, 1, 0), "A day, 2 hours and a minute" },
new object[] { new TimeSpan(2, 2, 1, 0), "2 days, 2 hours and a minute" },
new object[] { new TimeSpan(0, 0, 2, 0), "2 minutes" },
new object[] { new TimeSpan(1, 0, 2, 0), "A day and 2 minutes" },
new object[] { new TimeSpan(2, 0, 2, 0), "2 days and 2 minutes" },
new object[] { new TimeSpan(0, 1, 2, 0), "An hour and 2 minutes" },
new object[] { new TimeSpan(1, 1, 2, 0), "A day, an hour and 2 minutes" },
new object[] { new TimeSpan(2, 1, 2, 0), "2 days, an hour and 2 minutes" },
new object[] { new TimeSpan(0, 2, 2, 0), "2 hours and 2 minutes" },
new object[] { new TimeSpan(1, 2, 2, 0), "A day, 2 hours and 2 minutes" },
new object[] { new TimeSpan(2, 2, 2, 0), "2 days, 2 hours and 2 minutes" }
};
[Test, TestCaseSource("TestCases")]
public void ParseTimespan_ShouldReturn(TimeSpan timeSpan, string expectedResult)
{
string formatedText = timeSpan.ToPrettyFormat();
Assert.AreEqual(expectedResult, formatedText);
}
}
public static class StringExtensions
{
public static string UppercaseFirst(this string s)
{
if (string.IsNullOrEmpty(s))
{
return string.Empty;
}
return char.ToUpper(s[0]) + s.Substring(1);
}
}
public static class TimeSpanExtensions
{
public static bool HasDays(this TimeSpan timeSpan)
{
return timeSpan.Days != 0;
}
public static bool HasMinutes(this TimeSpan timeSpan)
{
return timeSpan.Minutes != 0;
}
public static bool HasHours(this TimeSpan timeSpan)
{
return timeSpan.Hours != 0;
}
public static string ToPrettyFormat(this TimeSpan timeSpan)
{
string result;
if (timeSpan.HasDays())
{
if (timeSpan.HasHours())
{
if (timeSpan.HasMinutes())
{
result = GetDays(timeSpan) + ", " + GetHours(timeSpan) + " and " + GetMinutes(timeSpan);
}
else
{
result = GetDays(timeSpan) + " and " + GetHours(timeSpan);
}
}
else
{
result = GetDays(timeSpan) + (timeSpan.HasMinutes() ? " and " + GetMinutes(timeSpan) : string.Empty);
}
}
else
{
if (timeSpan.HasHours())
{
result = GetHours(timeSpan) + (timeSpan.HasMinutes() ? " and " + GetMinutes(timeSpan) : string.Empty);
}
else
{
result = GetMinutes(timeSpan);
}
}
return result.UppercaseFirst();
}
private static string GetMinutes(TimeSpan timeSpan)
{
if (timeSpan.Minutes == 0) return string.Empty;
if (timeSpan.Minutes == 1) return "a minute";
return timeSpan.Minutes + " minutes";
}
private static string GetHours(TimeSpan timeSpan)
{
if (timeSpan.Hours == 0) return string.Empty;
if (timeSpan.Hours == 1) return "an hour";
return timeSpan.Hours + " hours";
}
private static string GetDays(TimeSpan timeSpan)
{
if (timeSpan.Days == 0) return string.Empty;
if (timeSpan.Days == 1) return "a day";
return timeSpan.Days + " days";
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-12T09:28:36.550",
"Id": "38710",
"Score": "0",
"body": "duplicate with http://codereview.stackexchange.com/questions/25009/format-a-timespan-with-years"
}
] |
[
{
"body": "<p><code>ToPrettyFormat</code> method can definitely be improved. Instead writing the conditional statement for all possible permutations of <code>HasDays</code>, <code>HasHours</code> and <code>HasMinutes</code> it's better to step back and define rules for resulting string:</p>\n\n<ul>\n<li>string may consist of 3 parts (days, hours and minutes)</li>\n<li>if there is 0 or one non-empty part - it is a final result</li>\n<li>if there are 2 non-empty parts - there should be \"and\" between them</li>\n<li>if there are 3 non-empty parts - first 2 should be separated by comma + \"and\" before last part. Note that we can actually generalize last two rules for N parts (months, weeks, etc) - instead of \"3\" we can say <em>combine first N-1 parts with comma and add last one with \"and\"</em></li>\n</ul>\n\n<p>As a result you can get a bit simplified code:</p>\n\n<pre><code>public static string ToPrettyFormat(this TimeSpan timeSpan)\n{\n var dayParts = new[] { GetDays(timeSpan), GetHours(timeSpan), GetMinutes(timeSpan) }\n .Where(s => !string.IsNullOrEmpty(s))\n .ToArray();\n\n var numberOfParts = dayParts.Length;\n\n string result;\n if (numberOfParts < 2)\n result = dayParts.FirstOrDefault() ?? string.Empty;\n else\n result = string.Join(\", \", dayParts, 0, numberOfParts - 1) + \" and \" + dayParts[numberOfParts - 1];\n\n return result.UppercaseFirst();\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-11T13:54:00.603",
"Id": "24996",
"ParentId": "24995",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "24996",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-11T13:15:00.320",
"Id": "24995",
"Score": "5",
"Tags": [
"c#"
],
"Title": "convert timespan to readable text"
}
|
24995
|
<p>numerator: Value being divided.</p>
<p>denominator: Divisor value.</p>
<p>method so far:</p>
<pre><code>def calc_percentage(numerator, denominator)
((numerator/ (denominator.to_f.nonzero? || 1 )) * 100)
end
</code></pre>
<p>What are the bad practices you see in the code above? How can I improve it or write it in a better way ? </p>
|
[] |
[
{
"body": "<p>Well to me the bad thing is that the function produces an <em>unexpected behavior</em>.</p>\n\n<p>You try to divide by <code>0</code>, it divides by <code>1</code>. Huh?</p>\n\n<p>What I would do is throw an Argument Error Exception (or what ever other exception that you think is appropriate).</p>\n\n<pre><code>def calc_percentage(numerator, denominator)\n if denominator.to_f.nonzero\n then (numerator/ denominator.to_f) * 100\n else raise ArgumentError, \"Denominator can not be 0.\", caller\n end \nend \n</code></pre>\n\n<p>This way it produces something that is logic and consistent.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-11T19:12:36.380",
"Id": "38678",
"Score": "1",
"body": "Notes: 1) This `nonzero` is a remnant of the original question? 2) is it using caller as third argument to `raise` idiomatic? 3) I don't like inline conditionals, but they fit nicely here :-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-11T19:19:58.440",
"Id": "38679",
"Score": "0",
"body": "@tokland about 1), Wel; since we don't have much context I went with what I thought was the expected behavior of a function with a denominator! 2) It might be idiomatic and could prolly be removed I'm not a ruby guy, but still answered the question to the best of my ruby knowledge with how would I have done the same in any other language!. 3) I'll add it. Thank you for the feedback"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-11T19:40:32.077",
"Id": "38681",
"Score": "0",
"body": "about (2) I asked because I hadn't seen never before, not that I thought it was wrong :-) Seeing your edit, I'd definitely write it differently: using a `if` with `else`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-11T19:45:49.570",
"Id": "38682",
"Score": "1",
"body": "@tokland I took it from this interesting article http://phrogz.net/ProgrammingRuby/tut_exceptions.html and thought it was nice to have the trace, and wasn't sure about default behavior in Ruby!"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-11T18:41:15.043",
"Id": "25002",
"ParentId": "25001",
"Score": "3"
}
},
{
"body": "<p>Notes:</p>\n\n<ul>\n<li><code>def calc_percentage</code>. Where do you have this method? or is it a \"free function\"? usually you'd put it as a method in your own module (i.e. <code>module MyMath</code>), or extend the existing module <code>Math</code> or even, for very general abstractions, add it to the class as a method (<code>Numeric#percentage</code>). Adding methods to existing module/classes (monkeypatching) is common in Ruby, but potentially dangerous.</li>\n<li><code>def calc_percentage</code>: Drop this <code>calc</code>, it's redundant.</li>\n<li>Ruby follows <a href=\"http://en.wikipedia.org/wiki/IEEE_754\" rel=\"nofollow\">IEEE_754</a>, infinites are supported by default. Of course your requirements come first, but it's usually a good idea to go along with the philosophy of the language (in this case, allow infinity as a percentage value).</li>\n</ul>\n\n<p>So I'd write:</p>\n\n<pre><code>module MyMath\n def self.percentage(numerator, denominator)\n (numerator / denominator.to_f) * 100.0\n end\nend\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-11T19:37:48.487",
"Id": "38680",
"Score": "0",
"body": "Thanks, intresting info about IEEE_754, didn't know... I have this method in a helper module defined. In the app->helpers folder."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-11T19:50:38.057",
"Id": "38683",
"Score": "1",
"body": "@user1899082: a Rails helper? Then I don't think it's the best place to put it, this method has nothing to do with views (if it returned a string with '%' it'd be different)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-11T19:08:34.893",
"Id": "25005",
"ParentId": "25001",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "25002",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-11T18:30:29.363",
"Id": "25001",
"Score": "3",
"Tags": [
"ruby"
],
"Title": "Preventing Division by Zero"
}
|
25001
|
<p>I have this ugly age printing method. Can you do better?</p>
<pre><code>def age(birth_date)
today = Date.today
years = today.year - birth_date.year
months = today.month - birth_date.month
(months -1) if today.day < birth_date.day
if years == 0 && months == 1
age = "#{months} month"
elsif years == 0 && months > 1
age = "#{months} months"
elsif years > 0 && months > 0
age = years == 1 ? "1 year, #{months} months" : "#{years} years, #{months} months"
elsif years > 0 && months < 0
months = months + 12
years = years - 1
age = "#{months} months" if years == 0
age = "1 year, #{months} months" if years == 1
age = "#{years} years, #{months} months" if years == 1
end
age
end
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-11T21:33:23.280",
"Id": "38692",
"Score": "0",
"body": "You could consider using `Time.zone.today` or `Date.current` instead of `Date.today` as those methods are time-zone safe"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-13T15:16:06.740",
"Id": "38760",
"Score": "0",
"body": "http://en.wikipedia.org/wiki/Ruby_(programming_language)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-13T16:21:43.837",
"Id": "38761",
"Score": "0",
"body": "http://en.wikipedia.org/wiki/Ruby_on_Rails"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-13T20:04:34.297",
"Id": "38765",
"Score": "0",
"body": "@Nakilon: Did you remove the `ruby-on-rails` tag? if that code is what it seems (a helper in a Rails project) it's relevant information, as we can freely use `active_support` (as I do below with `String#pluralize`)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-13T21:19:55.830",
"Id": "38770",
"Score": "0",
"body": "Ok, you can return it."
}
] |
[
{
"body": "<p>Some notes:</p>\n\n<ul>\n<li><code>(months -1) if today.day < birth_date.day</code>. Note that this is doing nothing, <code>months - 1</code> is evaluated and dropped.</li>\n<li>There is a <code>age =</code> in every branch of the conditional, and finally <code>age</code> is returned. That's unnecessary and not idiomatic, in Ruby conditionals are expressions, so we don't need to create a variable. </li>\n<li><p>About this:</p>\n\n<pre><code>age = \"#{months} months\" if years == 0\nage = \"1 year, #{months} months\" if years == 1\n</code></pre>\n\n<p>It's preferable not to use in-line conditionals when you are dealing with assignments or expressions (it's ok if you are performing side-effects, i.e. <code>fail(\"error\") if x < 0</code>). In general follow <a href=\"https://code.google.com/p/tokland/wiki/RubyFunctionalProgramming\" rel=\"nofollow\">functional programming</a> guidelines, specially when dealing with logic (if you do some programming that does not deal with logic, please let me know ;-)). It should look (you could also use a <code>case</code>) something like this:</p>\n\n<pre><code>age = if years == 0\n \"#{months} months\"\nelsif years == 1\n #{months} months\" if years == 1\n...\nend\n</code></pre></li>\n</ul>\n\n<p>I'd write:</p>\n\n<pre><code>def age(birth_date)\n today = Time.zone.today\n total_months = (today.year*12 + today.month) - (birth_date.year*12 + birth_date.month)\n years, months = total_months.divmod(12)\n strings = [[years, \"year\"], [months, \"month\"]].map do |value, unit|\n value > 0 ? [value, unit.pluralize(value)].join(\" \") : nil\n end\n strings.compact.join(\", \")\nend\n</code></pre>\n\n<p>Note that, to keep it simple, this code (as yours) ignores the day of the month, which gives a slightly wrong answer.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-11T21:30:28.500",
"Id": "38691",
"Score": "1",
"body": "Since the question's tagged with Rails, one could just use [`pluralize`](http://api.rubyonrails.org/classes/String.html#method-i-pluralize) instead of the `map` and `case` construct. It'd also make it localizable if that's a concern"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-11T22:16:49.570",
"Id": "38693",
"Score": "0",
"body": "@Flambino: I hadn't seen the Rails tags. But I don't understand what you mean, I can use `pluralize` for the `#{unit}s` part, indeed, but how can it replace the whole map/case block? can you paste the code?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-11T22:53:12.173",
"Id": "38694",
"Score": "0",
"body": "Actually, I was thinking of just returning an interpolated string, but I'd overlooked the part about about leaving zero values out. So you'll still need an array to `map` and `join`, but I think it can be shortened to `... .map { |value, unit| \"#{value} #{unit.pluralize(value)}\" unless value.zero? }` which can be then be compacted and joined"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-12T07:14:11.903",
"Id": "38702",
"Score": "0",
"body": "I see. I've edited the code with your suggestion in mind."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-11T19:29:02.150",
"Id": "25006",
"ParentId": "25003",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "25006",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-11T18:44:50.433",
"Id": "25003",
"Score": "3",
"Tags": [
"ruby",
"ruby-on-rails"
],
"Title": "Nasty Age Printing Method"
}
|
25003
|
<p>Before I try to make this work, I wondered if anyone had tried this, whether it was a good idea or not, etc.</p>
<p>I find myself doing this a lot:</p>
<pre><code>if some_result is None:
try:
raise ResultException
except ResultException:
logger.exception(error_msg)
raise ResultException(error_msg)
</code></pre>
<p>I would rather try this:</p>
<pre><code>if some_result is None:
with ResultException:
logger.exception(error_msg)
</code></pre>
<p>Where the <code>__exit__()</code> statement would always raise the exception in the context.</p>
<p>Would this be clearer? Is this possible?</p>
<p>I only ask because I imagine someone else has tried this, or at least attempted it. But I don't seem to find any common patterns for accomplishing this after doing a couple of Google searches.</p>
<h2>UPDATE</h2>
<p>Here's some more information on this particular issue.</p>
<p>I have a method that goes to a database and determines what the user's id is via their email. The problem is that if the user isn't found, it'll return <code>None</code>. This is okay for most calls, but when it's incorporated in higher-level methods, this can happen:</p>
<pre><code>def change_some_setting(setting, email):
user_id = user_id_by_email(email) # None
_change_some_setting(setting, id)
</code></pre>
<p>Now when <code>_change_some_setting</code> attempts to change the setting for a user who's id is <code>None</code>, we get a very vague <code>ProgrammingException</code> from the database library.</p>
<p>This helps prevent that. Is there a better way?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-11T19:56:36.767",
"Id": "38685",
"Score": "0",
"body": "Why not log the exception when you actually handle it? The traceback will show where it's from."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-11T20:09:35.363",
"Id": "38686",
"Score": "0",
"body": "As far as this example is concerned, this is handling it. It catches result sets that are empty, logs the complaint, and then bails out of execution."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-11T20:56:17.967",
"Id": "38689",
"Score": "0",
"body": "Can you show the code that catches the exception?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-02T07:13:58.283",
"Id": "39854",
"Score": "0",
"body": "The fix is that `user_id_by_email` should raise an exception, as @JanneKarila said in his answer (however creating a wrapper is only acceptable if you really can't change `user_id_by_email`)."
}
] |
[
{
"body": "<p>This:</p>\n\n<pre><code>if some_result is None:\n with ResultException:\n logger.exception(error_msg)\n</code></pre>\n\n<p>would seem to be equivalent (for most cases) to:</p>\n\n<pre><code>if some_result is None:\n logger.exception(error_msg)\n raise ResultException\n</code></pre>\n\n<p>And so using a context manager as you describe it would not seem to be helpful. That's probably why you can't find any instances of it. But this would not actually work because when you call <code>logger.exception</code>, you need to be in an exception handler. </p>\n\n<p>You could do:</p>\n\n<pre><code>def raise_logged(exception):\n try:\n raise exception\n except: \n logging.exception(str(exception))\n raise exception\n</code></pre>\n\n<p>Then use it like</p>\n\n<pre><code> if some_result is None:\n raise_logged( ResultException(\"not so good\") )\n</code></pre>\n\n<p>However, throwing the exception just to catch it and log it is a bit yucky. Do you really need to log the exception as this point? Usually, we log exceptions when they are caught. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-11T20:52:02.153",
"Id": "38688",
"Score": "0",
"body": "I updated my question with more specific information about my problem."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-11T20:14:58.360",
"Id": "25008",
"ParentId": "25004",
"Score": "2"
}
},
{
"body": "<p>Your issue is that a function returns <code>None</code> when raising an exception would be more useful to you. I would create a wrapper for the function for the sole purpose of raising the exception. Then catch the exception normally where it makes sense to you, and log it from there.</p>\n\n<pre><code>def checked_user_id_by_email(email):\n result = user_id_by_email(email) \n if result is None:\n raise LookupError(\"User not found by email '%s'\" % email)\n return result\n</code></pre>\n\n<p>You might use a decorator to wrap your functions like this.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-12T05:49:42.460",
"Id": "25018",
"ParentId": "25004",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "25008",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-11T18:48:47.783",
"Id": "25004",
"Score": "2",
"Tags": [
"python",
"exception-handling",
"logging"
],
"Title": "Wrapping an Exception with context-management, using the with statement"
}
|
25004
|
<p>I have a class with 2 date properties: <code>FirstDay</code> and <code>LastDay</code>. <code>LastDay</code> is nullable. I would like to generate a string in the format of <code>"x year(s) y day(s)"</code>. If the total years are less than 1, I would like to omit the year section. If the total days are less than 1, I would like to omit the day section. If either years or days are 0, they should say "day/year", rather than "days/years" respectively.</p>
<p><strong>Examples:</strong><br/>
2.2 years: "2 years 73 days"<br/>
1.002738 years: "1 year 1 day"<br/>
0.2 years: "73 days"<br/>
2 years: "2 years"<br/></p>
<p>What I have works, but it is long:</p>
<pre><code>private const decimal DaysInAYear = 365.242M;
public string LengthInYearsAndDays
{
get
{
var lastDay = this.LastDay ?? DateTime.Today;
var lengthValue = lastDay - this.FirstDay;
var builder = new StringBuilder();
var totalDays = (decimal)lengthValue.TotalDays;
var totalYears = totalDays / DaysInAYear;
var years = (int)Math.Floor(totalYears);
totalDays -= (years * DaysInAYear);
var days = (int)Math.Floor(totalDays);
Func<int, string> sIfPlural = value =>
value > 1 ? "s" : string.Empty;
if (years > 0)
{
builder.AppendFormat(
CultureInfo.InvariantCulture,
"{0} year{1}",
years,
sIfPlural(years));
if (days > 0)
{
builder.Append(" ");
}
}
if (days > 0)
{
builder.AppendFormat(
CultureInfo.InvariantCulture,
"{0} day{1}",
days,
sIfPlural(days));
}
var length = builder.ToString();
return length;
}
}
</code></pre>
<p>Is there a more concise way of doing this (but still readable)?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-11T20:51:17.813",
"Id": "38687",
"Score": "1",
"body": "Is there a reason why you are using a solar year (365.242 days) vs a calendar year (365 or 366 days) - not going to make a huge difference, but just looks odd since you are talking about days and calendar years but using a solar year as the denominator in the equation?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-11T20:58:40.283",
"Id": "38690",
"Score": "1",
"body": "You might want to check out [this answer](http://codereview.stackexchange.com/questions/24995/convert-timespan-to-readable-text)."
}
] |
[
{
"body": "<p>Overall, your code doesn't look bad. You have good use of white space and indentation. I found your variable names to be a little confusing (what's the difference between totalDays and days? Without actually digging into the code, it's not obvious).</p>\n\n<p>I like that you are using StringBuilder for concatenating strings, that is a good habit to get into.</p>\n\n<p>I think you are doing too much manipulation on the years and days. I was able to take your 5 lines of code to calculate the years and days, and make it 3</p>\n\n<pre><code>var totalDays = Math.Floor(lengthValue.TotalDays);\nvar years = totalDays / DaysInAYear; \nvar days = totalDays % DaysInAYear;\n</code></pre>\n\n<p>Years will be totalDays divided by the number of days in a year. Days will be the remainder of the same division.</p>\n\n<p>I would move the pluralize out into its own method. There is no need to use an anonymous method in this instance.</p>\n\n<p>You are repeating yourself when you are creating the string. If you look closely, the code is almost identical. The differences are easily passed in as variables. The way I corrected this is to create a method called CreateWords. This method returns the formatted string from variables passed in:</p>\n\n<pre><code>private string CreateWords(int value, string measure)\n{\n if (value == 0) return string.Empty;\n\n return string.Format(\"{0} {1}{2}\",\n value,\n measure,\n PluralSuffix(value));\n}\n\nprivate string PluralSuffix(int value)\n{\n return value > 1 ? \"s\" : string.Empty\n}\n</code></pre>\n\n<p>Your main method would then call:</p>\n\n<pre><code>builder.Append(CreateWords(years, \"year\"));\nbuilder.Append(CalculateSpaceCharacter(days));\nbuilder.Append(CreateWords(days, \"day\"));\n</code></pre>\n\n<p>where <code>CalculateSpaceCharacter</code> would look like:</p>\n\n<pre><code>private static string CalculateSpaceCharacter(int value)\n{\n return value > 0 ? \" \" : string.Empty;\n}\n</code></pre>\n\n<p>And finally, there is no need to assign the <code>length</code> variable at the end. Just return <code>builder.ToString()</code></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-11T21:38:42.830",
"Id": "25012",
"ParentId": "25009",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "25012",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-11T20:23:26.477",
"Id": "25009",
"Score": "1",
"Tags": [
"c#",
".net",
"formatting"
],
"Title": "Format A TimeSpan With Years"
}
|
25009
|
<p>I want to know if using <code>volatile</code> in this scenario will give better performance than using <code>synchronized</code>, specifically for the paused and running instance variable in the <code>SimulationManager</code> class.</p>
<pre><code>public class SimulationManager {
private List<SimulationPanel> simulations;
private boolean paused = false;
private boolean running = false;
private volatile PausableStopabbleThread observer;
public SimulationManager() {
simulations = new ArrayList<>();
}
public SimulationManager(List<SimulationPanel> simulations) {
this.simulations = Collections.unmodifiableList(simulations);
}
public void start() {
if (isRunning()) {
return;
}
for (SimulationPanel sim : simulations) {
sim.tableInsertion.start();
}
setRunning(true);
observer = new SimulationsObserver();
observer.start();
}
public void play() {
if (!isRunning() && !isPaused()) {
return;
}
setPaused(false);
for (SimulationPanel sim : simulations) {
sim.tableInsertion.play();
}
observer.play();
}
public void reset() {
if (!isRunning()) {
return;
}
setRunning(false);
setPaused(false);
observer.stopWork();
observer = null;
for (SimulationPanel sim : simulations) {
sim.tableInsertion.stopWork();
}
}
public void pause() {
if (!isRunning() && isPaused()) {
return;
}
setPaused(true);
observer.pause();
for (SimulationPanel sim : simulations) {
sim.tableInsertion.pause();
}
}
private synchronized void setPaused(boolean b) {
this.paused = b;
}
private synchronized boolean isPaused() {
return paused;
}
public synchronized boolean isRunning() {
return running;
}
private synchronized void setRunning(boolean running) {
this.running = running;
}
/**
* Specifies when the simulations has finished
*
* @author Victor J.
*
*/
class SimulationsObserver extends PausableStopabbleThread {
private final int nSimulations = simulations.size();
@Override
public void run() {
int finished = 0;
while (!stopRequested()) {
for (SimulationPanel sim : simulations) {
if (!sim.tableInsertion.isAlive()) {
finished++;
}
}
if (finished == nSimulations) {
setRunning(false);
return;
} else {
finished = 0;
}
pausePoint();
}
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p><code>volatile</code> should perform better and is appropriate in this situation. A volatile read/write is almost as fast as a non volatile read/write on modern architectures. On the other hand, locking with <code>synchronized</code> will have an overhead, especially in a highly contented scenario (many threads fighting for the lock).</p>\n\n<p>Note however that unless you call the pause/run methods thousands or millions of times per second, you will probably not notice the difference.</p>\n\n<p><strong>Additional comments</strong></p>\n\n<p>This line:</p>\n\n<pre><code>this.simulations = Collections.unmodifiableList(simulations);\n</code></pre>\n\n<p>probably does not do what you think it does: <code>this.simulations</code> is unmodifiable, but the calling code can still modify the original collection, and the changes will be reflected to your local version (or they won't depending on memory consistency). It would probably be better to do a defensive copy:</p>\n\n<pre><code>this.simulations = new ArrayList<> (simulations);\n</code></pre>\n\n<p>Another note: because your <code>simulations</code> is effectively immutable,</p>\n\n<pre><code>this.simulations = new ArrayList<> ();\n</code></pre>\n\n<p>could be replaced by:</p>\n\n<pre><code>this.simulations = Collections.emptyList();\n</code></pre>\n\n<p>And by the way, you could make <code>simulations</code> final.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-12T16:47:23.053",
"Id": "38732",
"Score": "0",
"body": "`A volatile read/write is almost as fast as a non volatile read/write on modern architectures` I would not agree with this. Even on modern architectures, memory access is a lot slower than level1 or level2 cache access, could be a factor of 50 to 1000. Nevertheless, it does not influence most of the situations, it happens very rarely that this is the limiting factor."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-12T18:01:32.143",
"Id": "38736",
"Score": "0",
"body": "Thank you for your additional comments. Making a defensive copy will certainly behave as I want it. \nAdditionally I could:\n`this.simulations = Collections.unmodifiableList(new ArrayList<>(simulations);`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-13T07:42:48.697",
"Id": "38753",
"Score": "0",
"body": "@tb- On modern architectures, the CPU is generally smart enough to determine when the volatile can be read from L1 only - if the volatile needs to come from the main memory, then yes, you get a performance hit. See for example: http://stackoverflow.com/questions/4633866/is-volatile-expensive"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-13T07:49:16.690",
"Id": "38754",
"Score": "0",
"body": "In other words I should have said: *uncontended* volatile read/write operations are almost as fast as..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-14T13:50:48.637",
"Id": "38801",
"Score": "0",
"body": "I did not further investigate it at asm level, but a small test confirmed my numbers. Just tried to read a static int with and without volatile in 1 or multiple threads inside a loop. In all cases significant slower. Did you try it, too?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-15T16:17:03.710",
"Id": "38850",
"Score": "0",
"body": "@tb- I just ran a few micro benchmarks: normal reads and volatile reads take about the same time (including with many threads), whereas volatile writes are around 10-20x (depending on the level of contention) slower than normal writes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-15T22:46:59.400",
"Id": "38866",
"Score": "0",
"body": "Could you provide the sample code? I would be interested. My example can be seen here: http://ideone.com/O4kN8s If there is really a (unknown) difference, I would investigate this further."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-15T22:54:46.380",
"Id": "38867",
"Score": "0",
"body": "@tb- on my mobile right now - I used the openjdk jmh performance testing library. Your test only runs interpreted code (method called less than 10,000 times), after that threshold the method is compiled to assembly. It could be the reason. Will check later."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-16T06:25:42.043",
"Id": "38877",
"Score": "0",
"body": "@tb- After allowing for JVM warmup etc., I still get similar results as yours. Checking the assembly, what happens is that volatile prevents the loop from being optimised hence the performance hit (which is due to less optimisations rather than synchronization penalty). My original claim is based on [this post](http://cs.oswego.edu/pipermail/concurrency-interest/2005-October/002024.html) written by Doug Lea - I tend to believe whatever he says, because he has been testing that kind of things for years."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-11T23:59:15.140",
"Id": "25014",
"ParentId": "25011",
"Score": "2"
}
},
{
"body": "<p>I do not think, that this will work as you want. In general, I would avoid the use of volatile. Only use it if you really have to, because of some requierements. Otherwise, use the java.util.concurrent.atomic package (they may use volatile, but you do not have to care about the implementation details), use synchronized or other concepts from here: <a href=\"http://docs.oracle.com/javase/tutorial/essential/concurrency/index.html\" rel=\"nofollow\">http://docs.oracle.com/javase/tutorial/essential/concurrency/index.html</a></p>\n\n<p>In your code, this is one of the examples, which could fail:</p>\n\n<pre><code>public void reset() {\n if (!isRunning()) {\n return;\n }\n setRunning(false);\n setPaused(false);\n observer.stopWork();\n observer = null;\n for (SimulationPanel sim : simulations) {\n sim.tableInsertion.stopWork();\n }\n\n}\n</code></pre>\n\n<p>You can enter the reset method with 2 threads, both are behind the if check. First thread sets observer to null, second throws a NullPointerException. Same happens for other methods.</p>\n\n<p>The easiest way to fix this is to use a mutex-object for nearly all methods. Better solutions depend on further analysis.</p>\n\n<hr>\n\n<pre><code>private synchronized void setPaused(boolean b) { ... }\nprivate synchronized boolean isPaused() { ... }\npublic synchronized boolean isRunning() { ... }\nprivate synchronized void setRunning(boolean running) { ... }\n</code></pre>\n\n<p>I would rather use an AtomicBoolean instead of synchronized methods to set a boolean. I would avoid boolean parameters. Use method names like enableRunning(), disableRunning() or something similar. Or setRunning(), unsetRunning(). Or runningEnable(), runningDisable().</p>\n\n<hr>\n\n<p>Some words about volatile. There are (at least?) two signs that volatile is not enough: If a write depends on the current value (Such as var = var + x). Or if the volatile variable depends on some other variable(s) (Such as if(volatileVariable && otherVariable), which is similar to your code). The first can be solved with atomic manipulate functions for primitives, the second needs most probably some sort of mutex or semaphore.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-12T17:55:14.423",
"Id": "38735",
"Score": "0",
"body": "Thank you it definitely makes sense to use a mutex object for the unsynchronized methods. Even though in the project scope there is only one thread using the **SimulationManager** class. But with your answer it made me realized that its better to a have a thread-safe class."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-12T16:28:17.513",
"Id": "25041",
"ParentId": "25011",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "25014",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-11T21:27:05.190",
"Id": "25011",
"Score": "3",
"Tags": [
"java",
"multithreading",
"thread-safety",
"synchronization"
],
"Title": "Using volatile instead of synchronized for a simulation"
}
|
25011
|
<p>Tonight I decided to revamp some code I wrote a few months ago. One part of that was to do with showing (and hiding) tooltips. The functions are called with:</p>
<pre><code>jQuery(element).showTooltip('HTML');
jQuery(element).hideTooltip();
</code></pre>
<p><strong>The old code</strong></p>
<pre><code>$.fn.showTooltip = function(text)
{
/* Remove any existing tooltip. */
$(this).removeTooltip();
/* Generate a unique reference for the tooltip. */
var ref = $(this).attr('name');
/* Create the tooltip and add it after the element. */
$tooltip = $('<span class="tooltip" data-ref="' + ref + '"></span>')
.html(text)
.css('display','none')
.insertAfter($(this))
.fadeIn(animationSpeed);
}
$.fn.removeTooltip = function()
{
var ref = $(this).attr('name');
/* Remove the tooltip. */
$('span[data-ref="' + ref + '"]')
.stop()
.fadeOut(animationSpeed, function() {
$(this).remove();
});
}
</code></pre>
<p>This code did the trick, but the were a few occasions where a tooltip either wouldn't appear or disappear when required. Equally the animations were a bit off.</p>
<p><strong>The new <em>revamped</em> code</strong></p>
<pre><code>$.fn.showTooltip = function(html) {
var
/* Create a unique reference to the element to be used in the
* tooltip. */
tooltipRef = $(this).attr('name'),
/* Create a reference to any current tooltip for the element. */
existingTooltip = $('[data-ref="' + tooltipRef + '"]'),
/* Create a variable to be used to hold the new tooltip. */
$tooltip
;
/* If existingTooltip doesn't match an existing object then create
* the new tooltip object, asigning its HTML and hiding it before
* inserting it after the element. */
if(typeof existingTooltip != 'object'
|| typeof existingTooltip.length != 'number'
|| existingTooltip.length === 0)
$tooltip = $('<span class="tooltip"></span>')
.attr('data-ref', tooltipRef)
.html(html)
.hide()
.insertAfter($(this));
/* If existingTooltip is visible and that contains the same html
* which is being passed in then there is no need to recreate. */
else if(existingTooltip.is(':visible')
&& existingTooltip.html() === html)
return;
/* If existingTooltip is visible but does not contain the same html
* then hide existingTooltip then set its HTML and set $tooltip as
* existingTooltip. */
else if(existingTooltip.is(':visible'))
{
$(this).hideTooltip();
$tooltip = existingTooltip;
$tooltip.queue(function() {
$tooltip.html(html);
$(this).dequeue();
});
}
/* If existingTooltip isn't visible but contains the same HTML, set
* $tooltip as existingTooltip. */
else if(existingTooltip.html() === html)
$tooltip = existingTooltip;
/* If existingTooltip isn't visible and doesn't contain the same
* HTML, set its HTML and set $tooltip as existingTooltip. */
else if(existingTooltip.html() !== html)
{
existingTooltip.html(html);
$tooltip = existingTooltip;
}
/* If none of the above applies then something has gone wrong. */
else
return;
/* Ensure any current animation isn't occuring before displaying
* the new (or modified) tooltip. */
$tooltip.queue(function() {
$(this)
.stop()
.fadeIn(global.animationSpeed);
$(this).dequeue();
});
};
$.fn.hideTooltip = function() {
var
/* Get the unique reference from the element to be used to
* get the tooltip object. */
tooltipRef = $(this).attr('name'),
/* Use the above reference to get the tooltip object. */
$tooltip = $('span[data-ref="' + tooltipRef + '"]')
;
/* If there is no tooltip then there is no need to proceed. */
if(typeof $tooltip != 'object'
|| typeof $tooltip.length != 'number'
|| $tooltip.length === 0
|| !$tooltip.is(':visible'))
return;
/* Hide the tooltip. */
$tooltip
.stop()
.fadeOut(global.animationSpeed);
}
</code></pre>
<p>The main flaw that I'm currently aware of with this (which I'll sort out tomorrow) is that the element currently requires a <code>name</code> in order for the tooltip to work.</p>
<p>I think I've covered all bases with the large <code>if</code> statement within the <code>showTooltip</code> function, but I'm not sure if maybe I've gone too overboard with it. Is there any way I could condense the code?</p>
<p>I'm certainly no JavaScript expert, so any criticism would be very welcome!</p>
<p>Here's a JSFiddle example: <a href="http://jsfiddle.net/UPAXV/" rel="nofollow">http://jsfiddle.net/UPAXV/</a></p>
<p>Many thanks.</p>
|
[] |
[
{
"body": "<p>You can check out the <a href=\"http://jsfiddle.net/UPAXV/9/\" rel=\"nofollow\">optimized code at work here</a></p>\n\n<p>CSS: removed positioning and moved it to JS to make it dynamic</p>\n\n<pre><code>.tooltip {\n background:#000;\n color:#fff;\n padding:2px 5px;\n line-height:20px;\n}\n</code></pre>\n\n<p>JS: in the comments</p>\n\n<pre><code>//protect your code inside an immediate function\n//that way, you can get away with all the crazy stuff you do\n//while protecting yourself from all the crazy stuff other codes do\n;(function (window, document, $, undefined) {\n\n //for constants, I'd declare then up top so they are easily configurable\n var animationSpeed = 250 //this one's for animation speed\n , fn = {} //this is for our methods, explained later\n , offset = 12 //the offset caused by the triangle\n , dataName = 'tooltip' //our data name\n ;\n\n //our tooltip methods\n\n fn.show = function (html) {\n\n //cache frequently used values to avoid refetching\n var element = $(this)\n , tooltip\n , offset\n , visible\n , same\n ;\n\n //this condition will return true if there was no data found\n //thus no tooltip was created beforehand\n if (!(tooltip = element.data(dataName))) {\n\n //so we create one and reference it to tooltip variable\n //we won't rely on CSS for style and dynamically calculate\n //the tooltip's position upon attachment\n tooltip = $('<span class=\"tooltip\" />')\n .hide()\n .insertAfter(element)\n .css({\n position: 'absolute',\n left: offset.left + element.outerWidth(true) + 12,\n top: offset.top\n });\n\n //we use jQuery's data() to avoid circular references\n //http://stackoverflow.com/q/10004593/575527\n element.data(dataName, tooltip);\n }\n\n\n visible = tooltip.is(':visible');\n same = tooltip.text() === html;\n\n //beware of single-line if statements. althout it looks cleaner\n //but never forget the semicolon or you'll run into problems\n\n //visible same - do nothing\n //visible not same - fade out, change, fade in\n //not visible not same - change, fade in\n //not visible same - fade in\n\n if (visible && same) return;\n if (visible) tooltip.fadeOut(animationSpeed);\n if (!same) {\n tooltip.queue(function () {\n $(this).text(html).dequeue();\n });\n }\n\n tooltip.queue(function () {\n $(this).stop().fadeIn(animationSpeed).dequeue();\n });\n\n }\n\n fn.hide = function () {\n var tooltip;\n //so we check if there is an existing tooltip \n //and if that existing tooltip is visible\n if ((tooltip = $(this).data(dataName)) && tooltip.is(':visible')) tooltip.fadeOut(animationSpeed);\n }\n\n //now I have reformatted the tooltip to only use one name to avoid\n //possible collisions with other plugins from other developers\n //so calling targets.tooltip('show',arg1,arg2,...,argN) is the same as\n //target.show(arg1,arg2,...,argN) for each element in the set\n $.fn.tooltip = function (event) {\n\n //get the selected method to run\n var toExecute = fn[event],\n //remove the first argument since it only determines the method to use\n args = Array.prototype.slice.call(arguments, 1);\n\n //check if the method exists, return if non-existent\n if (typeof toExecute !== 'function') return;\n\n //run the method for each of the elements in the set\n $(this).each(function () {\n toExecute.apply(this, args);\n });\n }\n\n}(this, document, jQuery));\n\n//usage\n$(function () {\n $('button#btShow').on('click', function () {\n $('input').tooltip('show', Math.random());\n });\n $('button#btHide').on('click', function () {\n $('input').tooltip('hide');\n })\n});\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-12T07:45:06.673",
"Id": "38704",
"Score": "0",
"body": "I had hard-coded the CSS for flexibility (not necessarily forcing the tooltip to display in a certain way). I'll take the `.data()` suggestion on board, I wasn't aware of any circular reference problem. Could you explain what the the top bit is doing (`;(function (window, document, $, undefined)`)? The only issue with this is that the tooltip doesn't redisplay itself when you click Show more than once - I probably should have made that a bit clearer before though! Thanks!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-12T07:49:28.683",
"Id": "38705",
"Score": "1",
"body": "That bit is part of the [IIFE (Immediately Invoked Function Expression)](http://benalman.com/news/2010/11/immediately-invoked-function-expression/), used to create an enclosed scope for your script. Call it your \"private scope\". Basically it's function expression that's immediately called, invoked at the bottom with `(this, document, jQuery)` as `window`, `document` and `jQuery` respectively."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-12T15:24:44.680",
"Id": "38726",
"Score": "1",
"body": "@JamesDonnelly Updated the script. Now it redisplays the tooltip when show is triggered more than once."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-12T16:04:59.143",
"Id": "38728",
"Score": "0",
"body": "Ah awesome! Is there a reason for the \"undefined\" in `;(function (window, document, $, undefined) { ...`? Also, would I add more functions to this particular wrapper or would I have separate `(function (...` wrappers for each? Also, is there supposed to be a `;` at the start?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-12T20:58:18.593",
"Id": "38742",
"Score": "1",
"body": "@JamesDonnelly because `undefined` is like a variable in JS, and not a constant. It's value can be changed. Thus, we create a true `undefined` in our scope by passing nothing as the 4th argument, making it truly undefined. The `;` at the beginning is to guard the our scope, especially when a function comes before it which makes JS think the starting `(` invokes it. To add functionality, just add to the `fn` collection."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-12T21:12:24.403",
"Id": "38744",
"Score": "0",
"body": "Ah I see, thanks a lot for the words of wisdom!"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-12T06:02:11.890",
"Id": "25019",
"ParentId": "25013",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "25019",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-11T22:37:22.180",
"Id": "25013",
"Score": "1",
"Tags": [
"javascript",
"jquery"
],
"Title": "Have I put too much into my tooltip showing and hiding functions?"
}
|
25013
|
<p>Generally speaking, I try and write my classes so they are highly cohesive.</p>
<p>Sometimes I have accessors (this problem isn't limited to accessors) which derive their value from non-public data only, which lowers cohesion. (<a href="http://www.ndepend.com/metrics.aspx#LCOM">http://www.ndepend.com/metrics.aspx#LCOM</a>)</p>
<p>Take the following class example:</p>
<pre><code>public class Person
{
public DateTime Birth { get; set; }
public DateTime? Death { get; set; }
public double Age
{
get
{
return (Death ?? DateTime.Now - Birth).TotalDays / 365;
}
}
}
</code></pre>
<p>Ignoring the probable compile errors and lack of error checking, <code>Age</code> could easily be an extension method <code>GetAge</code> as it doesn't rely on non-public data.</p>
<p>The code would look as follows:</p>
<pre><code>public class Person
{
public DateTime Birth { get; set; }
public DateTime? Death { get; set; }
}
public static class PersonExtensions
{
public static double GetAge(this Person person)
{
return (person.Death ?? DateTime.Now - person.Birth).TotalDays / 365;
}
}
</code></pre>
<p>What is a good approach to determine whether something should be an extension method or implemented in the class itself?</p>
<p>Some arguments against doing this that I find extension methods have lower visibility, you have to know the extension exists, while if it was a class property its existence would be obvious.</p>
<p>For languages that don't use extension methods (C++, php, etc.) the extension method could be written as a static method which accepts a <code>Person</code> as it's parameter.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-12T10:17:22.903",
"Id": "38712",
"Score": "2",
"body": "I'm not a fan of that property/method since it calls `DateTime.Now`. I'd rather pass in a `DateTime`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-21T09:53:17.153",
"Id": "110025",
"Score": "0",
"body": "Also, if the class is generated by some tool, it would be convenient to use extension methods."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-21T12:59:19.283",
"Id": "110074",
"Score": "0",
"body": "A year has 365 days and a quarter I think. I'm not sure this can cause a problem in your code though.."
}
] |
[
{
"body": "<p>My personal view is create an extension method if:</p>\n\n<ul>\n<li>The class/interface you wish to extend <em>is not</em> created by you.</li>\n<li>The class/interface <em>is</em> created by you but the behavior of the extension method is only required in an assembly that doesn't contain the class (e.g. <code>class Person</code> is defined in MyApp.dll, but <code>GetAge()</code> is only required in MyApp.UI.exe).</li>\n<li>The behavior can be defined against a more generic abstraction than the class itself where the implementation is the same but the classes don't share a common base. e.g. create an <code>ILifeSpan</code> interface with <code>DateTime DateOfBirth</code> and <code>DateTime DateOfDeath</code> properties and create the extension method <code>public static double GetAge(this ILifeSpan lifeSpan)</code></li>\n</ul>\n\n<p>FYI extension methods are just a compiler trick, the generated IL just calls the static method, the <code>this</code> keyword just allows you to write less code in visual studio.</p>\n\n<p>when you call <code>person.GetAge();</code>, it is compiled to <code>PersonExtensions.GetAge(person);</code></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-12T08:04:19.667",
"Id": "25023",
"ParentId": "25017",
"Score": "11"
}
},
{
"body": "<p>Maybe a god approach would be to use extension method when you would duplicate data if you would put another property or method into your class.</p>\n\n<p>In your example you would do that: storing (i know you don't store both of them) the date of birth and the age is redundant.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-12T12:22:29.657",
"Id": "25031",
"ParentId": "25017",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "25023",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-12T03:44:48.197",
"Id": "25017",
"Score": "5",
"Tags": [
"c#",
".net",
"extension-methods"
],
"Title": "Extension methods for methods and properties that don't use non-public data"
}
|
25017
|
<p>A friend of mine asked me a question recently. He was needed to subscribe to an event of some object (window button click) and unsubscribe from it on a first call of a handler. Also he noticed that object is dynamically created and his handler is a delegate.</p>
<p>After some thinking I came up with a solution using closures of an object and a delegate itself:</p>
<pre><code>class Program
{
class A
{
public event EventHandler OnRaise;
public void RaiseEvent(string text)
{
Console.WriteLine("a said: " + text);
if (OnRaise != null)
OnRaise(this, null);
}
}
static void Main(string[] args)
{
var a = new A();
EventHandler handler = null;
handler = (x, y) =>
{
Console.WriteLine("handler's working");
a.OnRaise -= handler;
};
a.OnRaise += handler;
a.RaiseEvent("blah blah ");
a.RaiseEvent("beep beep ");
handler = null;
a = null;
GC.Collect();
Console.ReadKey();
}
}
</code></pre>
<p>It does all requested behavior but I'm not sure if it's good and safe from memory-leaks. It would be great if anyone can review the code and help with advice or offer a better way to solve the problem.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T20:37:16.470",
"Id": "38697",
"Score": "0",
"body": "@Jesse The question is really very concrete, \"does this code leak X\" is not subjective; it either does or it doesn't, making it appropriate on SO. Were it just, \"make this better\" (even if \"better were properly defined) then it would be a codereview kind of question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T21:39:42.890",
"Id": "38698",
"Score": "0",
"body": "@Servy You might be right; it was just a first impression because of word use, I guess. Though, I think I am personally getting hung up on *the question isn't about a **specific** problem*."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T21:55:27.067",
"Id": "38699",
"Score": "0",
"body": "@Jesse Sorry for misleading. My bad. It was more about the memory-leak. I just meant if someone would like to say \"Oh, God! What a crappy code. Even a babysitter can do it better. Check this out: ...\" he is free to post here. Thanks for the advice."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T22:24:45.877",
"Id": "38700",
"Score": "0",
"body": "@michaels No need to apologize, we were all new somewhere once - it happens. I was just trying to provide some insight into why it *might not* be appropriate here - it was by no means any type of scolding. =)"
}
] |
[
{
"body": "<p>The code that you have will not result in holding onto a reference to any variables that the anonymous handler closes over once that handler is fired and the <code>handler</code> variable leaves scope or is set to something else (i.e. <code>null</code>), even if the <code>A</code> instance is kept alive.</p>\n\n<p>So in short, it's fine.</p>\n\n<p>Note that this is only ever a problem in the first place if the anonymous even handler closes over a variable that is a) expensive to keep alive, i.e. a very large collection of data and b) has a much shorter lifetime than the object that has the event being subscribed to. If the object holding the event goes out of scope before, or very soon after, whatever is being closed over, then the object is not held in memory any longer than if the event handler is unsubscribed. That specific case isn't actually all that common.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T22:24:38.657",
"Id": "38701",
"Score": "0",
"body": "Thanks for the response. Regarding the b) - I was not told any details of a task. Just \"anonymous method event handler of some dynamically created window\". So for now it's not possible to say if it cause any lifetime related issues in this case."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T20:14:21.997",
"Id": "25021",
"ParentId": "25020",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "25021",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-10T20:09:04.103",
"Id": "25020",
"Score": "1",
"Tags": [
"c#",
"delegates"
],
"Title": "Possible memory-leak on a self-removable event handler"
}
|
25020
|
<pre><code>public function getStuff($brand)
{
$web=FALSE;
if($this->getWebcorners()):
foreach ($this->getWebcorners() as $webcorner):
if(strtolower($webcorner->getBrand()->getName())== $brand):
return $webcorner;
endif;
if($webcorner->getBrandId()==NULL):
$web=$webcorner;
endif;
endforeach;
endif;
return $web;
}
</code></pre>
<p>the function is suppose to list a collection of webcorners and return the first that matches a brand, then the one that is null (in this order). There's a possibility to have many other webcorners according to the brand (but no matching the one that is passed by parameter to the function).</p>
|
[] |
[
{
"body": "<p>Just cleaned up your method a little: (Guard condition, better variable name, less nesting)</p>\n\n<pre><code>public function getStuff($brand)\n{\n if(!$this->getWebcorners()) return false;\n $fallback=false;\n foreach ($this->getWebcorners() as $webcorner) {\n if(strtolower($webcorner->getBrand()->getName())== $brand) return $webcorner;\n if($webcorner->getBrandId()==NULL) $fallback=$webcorner;\n }\n return $fallback;\n}\n</code></pre>\n\n<p>If you want to return the first item without a brand you have to add the <code>$fallback==false</code> condition to your second if. Otherwise you use the last suitable item.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-12T10:56:20.957",
"Id": "38713",
"Score": "0",
"body": "I'm not too convinced by the `if(!$this->getWebcorners()) return false;` as it adds duplicated code without improving anything as far as I can tell."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-12T11:07:41.233",
"Id": "38714",
"Score": "1",
"body": "@Josay Not everybody likes this guard conditions, it's a matter of taste. The big advantage is that you get rid of all the additional nesting levels which leads to better readability, in my opinion. It's not that much in this example but in the case you can extract 3-4 guards you will see the benefit. In addition to that you can easily identify the special cases of a methods and don't have to thing about the else-branches."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-12T13:08:24.143",
"Id": "38717",
"Score": "0",
"body": "Thx both I kinda like the version of mnhg, for the readability, but I'don't like so much all of these returns perhaps offering too much leak, or unpredictable side effects...I spend quite a lot of time figure out alternativ solution but nothing came..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-14T06:57:49.430",
"Id": "38792",
"Score": "0",
"body": "If you rely on the metric to write short methods, with a limited amount of work done, it's pretty easy to address this issue and you can easily put your method under test. If you run some code coverage tool along with your test you will see the next benefit of clear and simple guard conditions, as you can test this branches first and don't have to bother in your \"real\" tests."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-14T08:11:26.923",
"Id": "38793",
"Score": "1",
"body": "@mnhg Rule of thumb in PHP (and many other languages): Return early, keep your code on the left side. But I would set the `return` statements on a separate line, so they are easier to see."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-12T10:03:59.660",
"Id": "25026",
"ParentId": "25024",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "25026",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-12T08:37:10.473",
"Id": "25024",
"Score": "1",
"Tags": [
"php"
],
"Title": "List a collection of webcorners"
}
|
25024
|
<p>I'm fairly new to JavaScript and jQuery and this is my first attempt at creating a plugin. The code below I've written to parse a JSONP feed from a search engine API (funnelback) using ajax() calls. The returned object is used to create a set of results, some pagination links, a facetted navigation etc, everything you'd expect from a basic search results UI. </p>
<p>I suspect there is a fair amount of redundant code, code that could be merged or performance hits written in so I'd appreciate your expert opinion as to what I could modify to improve these aspects.</p>
<p>I'd also appreciate any best practice advice I could incorporate to further develop my own skills and knowledge.</p>
<p>You'll notice there's a reference to the jQuery version used, this is because this plugin can be used with a range of CMS templates that have anything from jQuery 1.3.2 to 1.7 and beyond, so I need to cover the bases. (in reference to the on(), delegate() and live() methods) </p>
<pre><code>(function($) {
$.fn.uclfunnelback = function(options) {
// define the default values of parameters
// these can be overwritten from the plugin call
var defaults = {
collection: 'enterprise-case-studies-demo',
query: '!showmeall',
categories: [{"facet_group_id": "discipline", "facet_group_title": "Discipline", "facet_items": {"mathematical-physical-sciences": "Mathematical & Physical Sciences", "arts-humanities": "Arts & Humanities", "engineering": "Engineering", "built-environment": "Built Environment", "social-historical-science": "Social & Historical Science", "life-medical-sciences": "Life & Medical Sciences", "laws": "Laws"}}, {"facet_group_id": "mechanisms", "facet_group_title": "Mechanisms", "facet_items": {"research-collaborations-studentships": "Research Collaborations Studentships", "student-engagement": "Student Engagement", "placements": "Placements", "business-support": "Business Support", "consultancy": "Consultancy", "partnerships": "Partnerships", "licenses": "Licenses", "spin-out": "Spin Out", "subsidiary": "Subsidiary"}}, {"facet_group_id": "grand_challenges", "facet_group_title": "Grand Challenges", "facet_items": {"sustainable-cities": "Sustainable Cities", "intercultural-interaction": "Intercultural Interaction", "global-health": "Global Health", "human-wellbeing": "Human Wellbeing"}}]
};
options = $.extend(defaults, options);
// Define the global vars
var jq_version = $().jquery,
facetsSelected = {},
qs,
facetqs,
objid,
categories = {},
facetgroups,
facetTotals = {},
catArray = options.categories,
catLen = catArray.length;
// jq_version - The jquery version being used.
// facetsSelected - The facets that are selected by the facetted navigation, used to generate the facetLabels
// qs - The main query string passed to ajaxCall()
// facetqs - The query string that is generated by the facetted navigation, used to perform the ajax call
// objid - The main id of the container div into which everything is output
// categories - The empty JavaScript object for all of the facet categories, used by facetLabels and checkBoxTotals
// facetgroups - The collections of facets from each facet group
// facetTotals - The JavaScript object for all the total articles matching each category, used by facettedNav and checkBoxTotals
// catArray - Assign the user supplied list of categories to an Array, used by facettedNav & below
// catLen - Predetermine the array length to speed up the for loop, used by facettedNav & below
// Merge each of the category facets together into the JavaScript object 'categories'
for (var i=0; i < catLen; i++) {
facetgroups = catArray[i].facet_items;
$.extend(categories, facetgroups);
}
Object.size = function(obj) {
var size = 0, key;
for (key in obj) {
if (obj.hasOwnProperty(key)) {
size++;
}
}
return size;
};
function AjaxTimer(status) {
// A timer to record the funnelback json response time
var aCounter = 0;
var airSeconds = $('#air_seconds');
var anInterval;
if (status === "start") {
anInterval = setInterval(function () {
aCounter += 1;
airSeconds.text(aCounter);
}, 1000);
} else {
clearInterval(anInterval);
anInterval = null;
}
}
function showLoading() {
// Display the AJAX loading icon & the timer if slow to load
$('#awaiting_response').show();
$('#fb-data').hide();
$("#error").hide();
AjaxTimer("start");
}
function ajaxError(request, type, errorThrown) {
// Handle the AJAX load errors
AjaxTimer("stop");
$("#awaiting_response").hide();
$('#fb-data').hide();
$("#error").show();
var message = "There was an error requesting the data.";
switch (type) {
case 'timeout':
message += "The data took too long to retrieve.";
break;
case 'notmodified':
message += "The request was not modified but was retrieved from the cache.";
break;
case 'parsererror':
message += "The data was badly formatted.";
break;
default:
message += "HTTP Error: (" + request.status + " " + request.statusText + ").";
}
message += "<br />";
$("#error").append(message);
}
function paginationClicky(pageNo) {
// Click function for the pagination buttons
if ( facetqs ) {
ajaxCall(pageNo, facetqs);
} else {
ajaxCall(pageNo, null);
}
}
function bindPaginationEvent(pagclass, pageNo) {
// Bind the pagination events, with modifications for older versions of jQuery
if (jq_version >= '1.7') {
// As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers.
$(objid).off('click', pagclass);
$(objid).on('click', pagclass, function(e) {
paginationClicky(pageNo);
e.preventDefault();
});
} else if ( jq_version >= '1.4.3' && jq_version < '1.7') {
// Users of jQuery versions 1.4.3 to 1.7 should use .delegate() in preference to .live().
$(objid).undelegate(pagclass, 'click');
$(objid).delegate(pagclass, 'click', function(e){
paginationClicky(pageNo);
e.preventDefault();
});
} else {
// Users of jquery 1.3.2 have no choice but to use live()
$(pagclass).die('click');
$(pagclass).live('click', function(e){
paginationClicky(pageNo);
e.preventDefault();
});
}
}
function checkboxToggle(checkbox) {
// Toggle function for the checkboxes
if (checkbox.attr("checked")) {
facetsSelected[checkbox.attr('value')] = checkbox.val();
} else {
delete facetsSelected[checkbox.attr('value')];
}
facetFormSubmit();
}
function bindCheckboxToggle(selectorStr) {
// Bind the checkbox toggle events, with modifications for older versions of jQuery
var checkboxSelector = 'input:checkbox.' + selectorStr;
if (jq_version >= '1.7') {
// As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers.
$(objid).off('change', checkboxSelector);
$(objid).on('change', checkboxSelector, function() {
var $this = $(this);
checkboxToggle($this);
});
} else if ( jq_version >= '1.4.3' && jq_version < '1.7') {
// Users of jQuery versions 1.4.3 to 1.7 should use .delegate() in preference to .live().
$(objid).undelegate(checkboxSelector, 'change');
$(objid).delegate(checkboxSelector, 'change', function(){
var $this = $(this);
checkboxToggle($this);
});
} else {
// Users of jquery 1.3.2 have no choice but to use live()
$(checkboxSelector).die('change');
$(checkboxSelector).live('change', function(){
var $this = $(this);
checkboxToggle($this);
});
}
}
function bindFacetLabel(facetid) {
// Bind the facetLables click events, with modifications for older versions of jQuery
var facetselector = 'a.' + facetid;
var checkboxSelector = 'input:checkbox.' + facetid;
if (jq_version >= '1.7') {
// As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers.
$(objid).off('click', facetselector);
$(objid).on('click', facetselector, function(e) {
delete facetsSelected[facetid];
$(checkboxSelector).removeAttr('checked');
e.preventDefault();
facetFormSubmit();
});
} else if ( jq_version >= '1.4.3' && jq_version < '1.7') {
// Users of jQuery versions 1.4.3 to 1.7 should use .delegate() in preference to .live().
$(objid).undelegate(facetselector, 'click');
$(objid).delegate(facetselector, 'click', function(e){
delete facetsSelected[facetid];
$(checkboxSelector).removeAttr('checked');
e.preventDefault();
facetFormSubmit();
});
} else {
// Users of jquery 1.3.2 have no choice but to use live()
$(facetselector).die('click');
$(facetselector).live('click', function(e){
delete facetsSelected[facetid];
$(checkboxSelector).removeAttr('checked');
e.preventDefault();
facetFormSubmit();
});
}
}
function facetLabels(totalMatching) {
// Generate the facet labels
var freeText = $("#fbquery").val();
var res, csText;
var facetLen = Object.size(facetsSelected);
var facetoutput = "";
if (totalMatching === 1) {
res = " result";
csText = " Item";
} else {
res = " results";
csText = " Items";
}
if (facetLen > 0) {
facetoutput += "<div id='pillboxes'><h3>Active Filters</h3><ul>";
for (var prop in facetsSelected) {
if (facetsSelected.hasOwnProperty(prop)) {
facetoutput += "<li><a class='"+ prop +"' href='#'>" + categories[prop] + "</a></li>";
bindFacetLabel(prop);
}
}
facetoutput += "</ul><div style='clear:both;'></div></div>";
}
facetoutput += "<h3><span class='resultCount'>" + totalMatching + "</span> ";
if (facetLen === 0 && !freeText) {
facetoutput += csText + " found";
} else if (facetLen === 0 && freeText) {
facetoutput += res + " matched your search for <span class='searchTerm'>'" + freeText + "'</span>";
} else {
var facetCounter = 0;
for (var facet in facetsSelected) {
if (facetsSelected.hasOwnProperty(facet)) {
facetCounter++;
var facetTitle = categories[facetsSelected[facet]];
if (facetCounter === 1) {
facetoutput += res + " matched your search for <span class='searchTerm'>" + facetTitle + "</span>";
} else if (facetCounter === facetLen - 1) {
facetoutput += ", <span class='searchTerm'>" + facetTitle + "</span>";
} else {
if (!freeText) {
facetoutput += " and <span class='searchTerm'>" + facetTitle + "</span>";
} else {
facetoutput += ", <span class='searchTerm'>" + facetTitle + "</span>";
}
}
}
}
if (freeText) {
facetoutput += " and <span class='searchTerm'>'" + freeText + "'</span>";
}
}
facetoutput += "</h3>";
$('.resultcount').html(facetoutput);
}
function searchResults(currStart, data) {
// Generate the basic search results
// the results are derived from the json feed (data).
var i,
res_output = "",
searchItems = data.response.resultPacket.results;
res_output += "<ol start='" + currStart + "'><br />";
for (i in searchItems) {
if (searchItems.hasOwnProperty(i)) {
res_output += "<li><h4><a href='" + searchItems[i].liveUrl + "'>" + searchItems[i].title + "</a></h4><p>" + searchItems[i].summary+"</p></li>";
}
}
res_output += '</ol>';
$(objid).html(res_output);
}
function pagination (currStart, numPages, currPage, numRanks, nextStart, prevStart) {
// Generate the pagination links
var linksString = "<p class='fb-page-nav'>";
var page_class;
if (currStart > 1) {
// previous links
linksString += "<a class='fb-previous-result-page' href='#'>Prev 10</a> ";
bindPaginationEvent('.fb-previous-result-page',prevStart);
}
var startRank = 1;
if (numPages > 1) {
for (i=0; i<numPages; i++){
if (i !== currPage) {
// if the page is not the current page
page_class = "fb-result-page"+ (1+i);
linksString += "&nbsp;<a class='" + page_class + "' href='#'>" + (1+i) +"</a> ";
bindPaginationEvent('a.' + page_class,startRank);
} else {
// if the page is the current page
linksString += "&nbsp;<a class='fb-current-result-page' href='#'>" + (1+i) + "</a>";
bindPaginationEvent('.fb-current-result-page',startRank);
}
startRank += numRanks;
}
}
if (nextStart) {
// next links
linksString += "&nbsp; <a class='fb-next-result-page fb-page-nav' href='#'>Next 10</a>";
bindPaginationEvent('.fb-next-result-page',nextStart);
}
linksString += "</p>";
$('.pagination').html(linksString);
}
function contains(array, value) {
// function to determine if a value is contained within an array
// Faster than inArray() and indexOf() and..
// supported by *all* browsers unlike indexOf()
var index = -1,
length = array.length;
while (++index < length) {
if (array[index] === value) {
return true;
}
}
return false;
}
function checkboxTotals(facetData) {
// Calculate the facet checkbox totals
var temp, tally, isMultiFacetted;
// iterate the 'categories' json array
for (var facet in categories) {
if (categories.hasOwnProperty(facet)) {
facetTotals[facet] = 0;
}
}
// iterate the rmcs json object {}
for (var i in facetData) {
if (facetData.hasOwnProperty(i)) {
temp = i.slice(2,i.length);
tally = facetData[i];
isMultiFacetted = contains(temp, ',');
if (isMultiFacetted) {
// if temp is more than one item
// split it and make an array
var token = temp.split(",");
var tokenlen = token.length;
// iterate the array
// and compare the item (j) found with each item in categories object
// if j and c same then increment facetTotals for the appropriate facet
for (var j=0; j<tokenlen; j++) {
for (var c in categories) {
if (categories.hasOwnProperty(c)) {
if (token[j] === c) {
facetTotals[c] += tally;
break;
}
}
}
}
} else {
facetTotals[temp] += tally;
}
}
}
}
function resetForm() {
// Event handler to reset the form back to the defaults
$('.reset-button').die('click');
$('.reset-button').live('click', function(){
facetsSelected = {};
ajaxCall(null, null);
});
}
function facettedNav() {
// Generate the facetted Navigation
var facetoutput = '';
// catArray & catLen are global vars.
for (var i = 0; i < catLen; i++) {
// Generate the facet titles from the json objects in catArray
facetoutput += '<h3>' + catArray[i].facet_group_title + '</h3>\n<ul>';
// iterate the json array of the facet iems to generate the checkboxes
var itemsObj = catArray[i].facet_items;
var groupID = catArray[i].facet_group_id;
var metadataClass = 'meta_' + groupID.charAt(0).toUpperCase() + '_sand';
for (var key in itemsObj) {
if (itemsObj.hasOwnProperty(key)) {
// if there total no of results for any given facet is greater than 0, display the facet checkbox
if (facetTotals[key] > 0) {
if (facetsSelected.hasOwnProperty(key)) {
facetoutput += '<li id="' + key + '" style="opacity: 1;"><label><input type="checkbox" class="' + key + '" name="' + metadataClass + '" value="' + key + '" checked>' + itemsObj[key] + ' <span class="count">(' + facetTotals[key] + ')</span> </label></li>';
} else {
facetoutput += '<li id="' + key + '" style="opacity: 1;"><label><input type="checkbox" class="' + key + '" name="' + metadataClass + '" value="' + key + '">' + itemsObj[key] + ' <span class="count">(' + facetTotals[key] + ')</span> </label></li>';
}
bindCheckboxToggle(key);
} else {
// else show the facet checkbox but disable it and lowever the labels opacity
facetoutput += '<li id="' + key + '" style="opacity: 0.5;"><label><input type="checkbox" class="' + key + '" disabled="disabled" name="' + metadataClass + '" value="' + key + '">' + itemsObj[key] + ' <span class="count">(' + facetTotals[key] + ')</span> </label></li>';
}
}
}
facetoutput += '</ul>';
}
// Add the reset button
facetoutput += '<input class="reset-button" type="reset" name="reset" value="Reset">';
resetForm();
// Insert the generated output to the appropriate div
$('.facetted-nav').html(facetoutput);
}
function facetFormSubmit() {
// Generte the new query string everytime the form is submit
facetqs = $('#facetsearch').serialize();
ajaxCall(null, facetqs);
}
function parseResults(data){
// Parse the json feed and render the results
// 1st stop the timer
AjaxTimer("stop");
// & show or hide the appropriate divs
$('#awaiting_response').hide();
$('#fb-data').show();
$("#error").hide();
// collate the data from the json feed
var totalMatching = data.response.resultPacket.resultsSummary.totalMatching;
var numRanks = data.response.resultPacket.resultsSummary.numRanks;
var currStart = data.response.resultPacket.resultsSummary.currStart;
var prevStart = data.response.resultPacket.resultsSummary.prevStart;
var nextStart = data.response.resultPacket.resultsSummary.nextStart;
var numPages = Math.ceil(totalMatching/numRanks);
var currPage = Math.floor(currStart/numRanks);
var facetData = data.response.resultPacket.rmcs;
// Calculate the checkbox totals
checkboxTotals(facetData);
// Display the facetted navigation beneath the search
facettedNav();
// Display the heading and the filtering info
facetLabels(totalMatching);
// Display the search results in the appropriate div
searchResults(currStart, data);
// Display the pagination
pagination(currStart, numPages, currPage, numRanks, nextStart, prevStart);
// Bind an event handler to the form "submit" JavaScript event
$('#facetsearch').submit(function(e) {
facetFormSubmit();
e.preventDefault();
});
}
function ajaxCall(startRank, facetqs) {
// This is the universal ajax call method
// Reset the query string to '' first
qs = '';
// Build the query string for the ajax() call
// Generate the 'query' element so that if facets are checked they concatenate
if (facetqs && facetqs !== 'query=') {
// Trim 'query=' off the beginning of facetqs
var trimmedFacetqs = facetqs.substring(6);
qs += '&query=' + trimmedFacetqs;
} else {
// If no facets checked, set the default 'query' element to options.query
qs += '&query=' + options.query;
}
// Append the collection
qs += '&collection=' + options.collection;
// And append the startRank, if there is one
if (startRank) {
qs += '&start_rank=' + startRank;
}
// set the base funnelback url
var baseurl = 'http://funnelback-uat.ucl.ac.uk/s/search.json?callback=?';
// var testingurl = 'http://localhost:8217/silva/default-funnelback-search/search.json';
$.ajax({
type:'GET',
data: qs,
url: baseurl,
dataType: "jsonp",
// url: testingurl,
// dataType: "json", // Test dataType
beforeSend: showLoading,
timeout: 5000,
error: ajaxError,
scriptCharset: "utf-8",
success: function (json) {
parseResults(json);
}
});
}
// Initiate the plugin
return this.each(function() {
// set some variables
var obj = $(this);
objid = "#" + obj.attr('id');
// perform the inital ajaxCall
ajaxCall(null, null);
});
};
})(jQuery);
</code></pre>
<p>I appreciate any help!!</p>
|
[] |
[
{
"body": "<p>Johntyb, the main problem you will have is with all those vars defined in the <code>$.fn.uclfunnelback</code> namespace; <code>options</code>, <code>defaults</code>, <code>facetsSelected</code>, etc. </p>\n\n<p>Any vars defined there belong to the plugin itself, not to each instance of the plugin, therefore different instances of the plugin will crosstalk. </p>\n\n<p>The plugin pattern explained/advocated <a href=\"http://docs.jquery.com/Plugins/Authoring\" rel=\"nofollow\">here</a> shows how this can be overcome. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-17T11:09:14.580",
"Id": "38942",
"Score": "1",
"body": "Ahh, thanks. I'll have a read of that page. Much appreciated."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-16T03:15:18.193",
"Id": "25117",
"ParentId": "25029",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-12T11:34:57.633",
"Id": "25029",
"Score": "1",
"Tags": [
"javascript",
"jquery",
"performance"
],
"Title": "jQuery plugin: Parsing a JSONP feed using ajax()"
}
|
25029
|
<p>I submitted a previous version of this program but I've completely rewritten it in an Object Oriented style. This is only my second attempt at OO programming so I'm interested in hearing how I can improve things.</p>
<p>Here's the main program:</p>
<pre><code>import tweepy
import sqlite3
import json
import re
import time
import datetime
import math
import jinja2
import PyRSS2Gen
class Tweets (object):
def __init__(self, account_data, params):
auth = tweepy.auth.OAuthHandler(account_data['consumer_key'],
account_data['consumer_secret'])
auth.set_access_token(account_data['access_token_key'],
account_data['access_token_secret'])
api = tweepy.API(auth)
self.db = params['db']
self.tweets = []
for tweet in api.home_timeline(count=100, include_rts=0):
try:
url = tweet.entities['urls'][0]['expanded_url']
except IndexError:
url = False
if (url is not False):
self.tweets.append((
tweet.id_str,
self.extract_urls(tweet.text),
url,
str(tweet.created_at).replace(' ', 'T'),
tweet.retweet_count,
tweet.user.screen_name,
tweet.user.followers_count
))
def save(self):
tdb = TweetDatabase(self.db)
tdb.save(self.tweets)
tdb.purge()
def extract_urls(self, text):
text = re.sub('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|'
'[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', '',
text).strip()
text = re.sub('\:$', '', text)
return text
class TweetDatabase (object):
def __init__(self, db):
self.conn = sqlite3.connect(db)
self.c = self.conn.cursor()
def create(self):
try:
self.c.execute('''CREATE TABLE tweets
( id int not null unique,
text text,
url text,
created_at text,
retweet_count int,
screen_name text,
followers_count int);''')
self.conn.commit()
return True
except sqlite3.OperationalError:
return False
def load(self):
return self.c.execute('''select * from tweets;''')
def save(self, data):
self.create()
self.c.executemany('''INSERT OR REPLACE INTO tweets
VALUES (?,?,?,?,?,?,?)''', data)
self.conn.commit()
return True
def purge(self):
self.c.execute('''
delete from tweets
where datetime(created_at) < date('now','-8 day');
''')
self.c.execute('vacuum;')
self.conn.commit()
return True
class FilteredTweets (object):
def __init__(self, params):
self.filtered_tweets = []
self.blacklist = params['blacklist']
self.whitelist = params['whitelist']
self.db = TweetDatabase(params['db'])
self.tweets = self.db.load()
for tweet in self.tweets:
id, text, url, created_at, retweet_count, screen_name, \
followers_count = tweet
score = self.build_score(retweet_count, followers_count)
if (self.check_blacklist(text) and (
score > params['threshold'] or
self.check_whitelist(screen_name))):
self.filtered_tweets.append(
{
'id': id,
'text': text,
'url': url,
'created_at': created_at,
'retweet_count': retweet_count,
'screen_name': screen_name,
'followers_count': followers_count,
'score': score
})
self.filtered_tweets = sorted(self.filtered_tweets, key=lambda
tup: tup['score'], reverse=True)
def check_blacklist(self, text):
for phrase in self.blacklist:
if phrase.strip() in text:
return False
return True
def check_whitelist(self, screen_name):
for whitelist_name in self.whitelist:
if screen_name == whitelist_name:
return True
return False
def build_score(self, retweet_count, followers_count):
retweet_count -= 1
if retweet_count > 2:
retweet_score = pow(retweet_count, 1.5)
raw_score = (retweet_score / followers_count)*100000
score = round(math.log(raw_score, 1.09))
else:
score = 0
return int(score)
def load_by_date(self, close, far):
self.date_filtered_tweets=[]
counter = 0
for tweet in self.filtered_tweets:
self.created_at_object = datetime.datetime.strptime(
tweet['created_at'], '%Y-%m-%dT%H:%M:%S')
if (self.created_at_object > self.build_date(far)
and self.created_at_object < self.build_date(close)
and counter < 40):
self.date_filtered_tweets.append(tweet)
counter += 1
return self.date_filtered_tweets
def build_date(self, day_delta):
filter_date = (
datetime.datetime.today() -
datetime.timedelta(days=day_delta)).replace(
hour=0, minute=0, second=0, microsecond=0)
return filter_date
class Output (object):
def build_webpage(self, yesterdays_items, last_weeks_items, params):
with open(params['html_template']) as f:
template = jinja2.Template(f.read())
self.html_output = template.render(yesterdays_items = yesterdays_items,
last_weeks_items = last_weeks_items)
with open(params['html_output'], 'w') as f:
f.write(self.html_output.encode('utf-8'))
return True
def build_rss(self, items, output_file):
rss_items = []
sorted_items = sorted(items, key=lambda
tup: tup['created_at'],
reverse=True)
for item in sorted_items:
rss_items.append(PyRSS2Gen.RSSItem(
title = '%s: %s - Score: %s' % (
item['screen_name'],
item['text'],
item['score']),
link = item['url'],
pubDate = datetime.datetime.strptime(
item['created_at'], '%Y-%m-%dT%H:%M:%S')))
rss = PyRSS2Gen.RSS2(
title = 'Mike\'s News',
link = 'http://mikeshea.net/news/',
description = 'Mike\'s personal news filtered by Tweet Threshold.',
lastBuildDate = datetime.datetime.now(),
items = rss_items
)
with open(output_file, 'w') as f:
rss.write_xml(f)
return True
def build_json(self, items, output_file):
with open(output_file, 'w') as f:
f.write(json.dumps(items))
return True
def main(accounts, params):
for account in accounts:
remote_tweets = Tweets(account, params)
remote_tweets.save()
tweets = FilteredTweets(params)
wp = Output()
wp.build_webpage(tweets.load_by_date(0,1), tweets.load_by_date(1,6), params)
wp.build_rss(tweets.load_by_date(0,1), params['rss_output_file'])
wp.build_json(tweets.load_by_date(0,7), params['json_output_file'])
</code></pre>
<p>Here's the script that executes it.</p>
<pre><code>import tweet_threshold
TWITTER_ACCOUNT_DATA = [
{'consumer_key': 'accountkey',
'consumer_secret': 'accountkey',
'access_token_key': 'accountkey',
'access_token_secret': 'accountkey'},
{'consumer_key': 'accountkey',
'consumer_secret': 'accountkey',
'access_token_key': 'accountkey',
'access_token_secret': 'accountkey'}]
PARAMS = {
'db': '/path/to/your/dir/tweet_threshold.sqlite',
'html_output': '/path/to/your/dir/index.html',
'html_template': '/path/to/your/dir/html_template.txt',
'rss_output_file': '/path/to/your/dir/yesterday.xml',
'json_output_file': '/path/to/your/dir/items.json',
'threshold': 50,
'blacklist': (
'Congress',
'Representative',
'DHS',
'Fox',
'CISPA',
'Republicans',
'[Sponsor]'),
'whitelist': (
'mshea',
'slyflourish',
'yourwife',
'yourbestfriend')}
tweet_threshold.main(TWITTER_ACCOUNT_DATA, PARAMS)
</code></pre>
|
[] |
[
{
"body": "<p>using <code>'''...'''</code> creates <code>'/n'</code> at the end of your lines, which you may find unexpected and is not explict.</p>\n\n<p>A pythonic alternative is to use:</p>\n\n<pre><code>'CREATE TABLE tweets ('\n'id int not null unique'\n'text text,'\n'url text,'\n</code></pre>\n\n<p>and so on. Python will join all there to one line, without errant new lines.</p>\n\n<p>replace <code>if (url is not False):</code> with <code>if url</code>:</p>\n\n<p><code>'''select * from tweets;'''</code> is only on one line so use <code>'select * from tweets;'</code></p>\n\n<p>beware of extracting from list like so:</p>\n\n<pre><code>id, text, url, created_at, retweet_count, screen_name, followers_count = tweet\n</code></pre>\n\n<p>because index is important here. If you change something elsewhere in the code is is easy to loose track. I suggest using inserting a dict instead and accessing <code>id</code>, <code>text</code>, and <code>url</code> by pulling out the dict, and doing <code>tweet['id']</code>, <code>tweet['text']</code>, and <code>tweet['url']</code>. If you cant store a dict instead store the dict as JSON. Makes this much more maintainable. You are doing this anyway in <code>self.filtered_tweets.append({...})</code></p>\n\n<p>replace <code>datetime.datetime.strptime( tweet['created_at'], '%Y-%m-%dT%H:%M:%S')</code> with <code>self.created_at_object = tweet['created_at'].isoformat()</code></p>\n\n<p>replace </p>\n\n<pre><code>if (self.created_at_object > self.build_date(far) \n and self.created_at_object < self.build_date(close)\n and counter < 40):\n</code></pre>\n\n<p>with</p>\n\n<pre><code>if counter < 40 and self.build_date(close) > self.created_at_object > self.build_date(far):\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-12T16:27:22.827",
"Id": "38730",
"Score": "0",
"body": "Why avoid newlines in SQL?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-12T18:09:28.220",
"Id": "38737",
"Score": "0",
"body": "I said \"which you may find unexpected and is not explicit.\" - remember explicit is better than implicit, - and making a habit of using '''...''' sparingly will prevent unexpected newlines in future."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-12T20:03:58.717",
"Id": "38741",
"Score": "0",
"body": "For me, the inconvenient thing about multiline string literals is the indentation that gets included. I don't see anything unexpected in line breaks between lines."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-12T21:10:08.753",
"Id": "38743",
"Score": "0",
"body": "convoluted example\n\nIn : `print ''.join('''multi\nline''')`\nout: `multi\\nline`\n\n...just sayin'"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-13T08:50:16.583",
"Id": "38756",
"Score": "0",
"body": "Another issue is that mistakes like this are easy to make and hard to spot: `\"select c\" \"from t\"` (forgot whitespace between `c` and `from`)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-13T09:37:59.870",
"Id": "38758",
"Score": "0",
"body": "Im not an SQL person, but I suspect `'''select c_\nfrom t'''` would have the same problem? *note '_' = carriage return."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-13T10:18:14.730",
"Id": "38759",
"Score": "0",
"body": "No, `\"select c\\nfrom t\"` would be fine, `\\n` is whitespace."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-12T14:17:05.980",
"Id": "25037",
"ParentId": "25034",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-12T13:12:56.063",
"Id": "25034",
"Score": "1",
"Tags": [
"python",
"object-oriented",
"twitter"
],
"Title": "Object-oriented Twitter filter"
}
|
25034
|
<p>I would like feedback on how to optimize this jQuery plugin used for triggering change event on any DOM element.
This plugin doesn't use a timer to check for DOM changes but instead extends some jQuery native functions.
I'm mostly concerned by the <code>.on()</code> method extension because I'm sure there is better way of doing this.</p>
<p><a href="http://jsfiddle.net/UZcJu/" rel="nofollow">jsFiddle to test</a></p>
<pre><code>;(function ($) {
var fctsToObserve = {
append: [$.fn.append, 'self'],
prepend: [$.fn.prepend, 'self'],
remove: [$.fn.remove, 'parent'],
before: [$.fn.before, 'parent'],
after: [$.fn.after, 'parent']
}, fctsObserveKeys = '';
$.each(fctsToObserve, function (key, element) {
fctsObserveKeys += "hasChanged." + key + " ";
});
var oOn = $.fn.on;
$.fn.on = function () {
if (arguments[0].indexOf('hasChanged') != -1) arguments[0] += " " + fctsObserveKeys;
return oOn.apply(this, arguments);
};
$.fn.hasChanged = function (types, data, fn) {
return this.on(fctsObserveKeys, types, null, data, fn);
};
$.extend($, {
observeMethods: function (namespace) {
var namespace = namespace ? "." + namespace : "";
var _len = $.fn.length;
delete $.fn.length;
$.each(fctsToObserve, function (key) {
var _pre = this;
$.fn[key] = function () {
var target = _pre[1] === 'self' ? this : this.parent(),
ret = _pre[0].apply(this, arguments);
target.trigger("hasChanged." + key + namespace, arguments);
return ret;
};
});
$.fn.length = _len;
}
});
$.observeMethods()
})(jQuery);
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-16T14:14:40.047",
"Id": "38894",
"Score": "0",
"body": "Something you should check out: **Pub/Sub**. An awesome way of setting up, turning off, and triggering events. Links:\nhttp://msdn.microsoft.com/en-us/magazine/hh201955.aspx\nhttps://gist.github.com/addyosmani/1321768"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-19T14:25:08.380",
"Id": "39121",
"Score": "0",
"body": "Oh yeah also you might want to check for elements that already have this functionality \"built in\" so you're not repeating or overriding those presets. Elements like `select`, etc."
}
] |
[
{
"body": "<p>I dont know if there is a better way to do it, but it seems quite smart and minimally intrusive.</p>\n\n<p>From a once over style perspective:</p>\n\n<ul>\n<li><code>function (key, element)</code> <- since you dont use element, you can remove it from the signature</li>\n<li><p>This</p>\n\n<pre><code>$.each(fctsToObserve, function (key, element) {\n fctsObserveKeys += \"hasChanged.\" + key + \" \";\n});\n</code></pre>\n\n<p>would have been better served with <code>Array.reduce</code>, not sure if you want to support <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce#Browser_compatibility\" rel=\"nofollow\">browsers that don't have <code>Array.reduce</code></a></p></li>\n<li>Naming.. Any code reviewer would be remiss if they did not point that you abbreviate your variables too much which makes the code needlessly harder to understand</li>\n<li>In the <code>if</code> in <code>$.fn.on = function () {</code> you should use curly braces or a least a newline.</li>\n<li><p>There is no point in declaring <code>var namespace</code> here:</p>\n\n<pre><code>observeMethods: function (namespace) {\n var namespace = namespace ? \".\" + namespace : \"\";\n</code></pre>\n\n<p>just go for</p>\n\n<pre><code>observeMethods: function (namespace) {\n namespace = namespace ? \".\" + namespace : \"\";\n</code></pre></li>\n<li>Comments, some of the more trickier concepts could have used a line of comment</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-03T17:04:59.213",
"Id": "64664",
"ParentId": "25035",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-12T13:53:22.340",
"Id": "25035",
"Score": "4",
"Tags": [
"javascript",
"jquery"
],
"Title": "Optimize jquery plugin \"on\" method extension"
}
|
25035
|
<p>I'm understanding the question, but I want to know whether or not my implementation is correct.</p>
<p>The question is:</p>
<blockquote>
<p>Write a method that accepts as its argument a BinaryTree object and
returns true if the argument tree is a binary search tree. Examine
each node in the given tree only once.</p>
</blockquote>
<p>This is my implementation:</p>
<pre><code>public boolean isBST (BinaryTree<String> tree)
{
BinaryNode Node = new BinaryNode (tree.getRootData);
if(tree == null || Node.isLeaf() )
return true;
if(Node.getData > Node.getLeftChild && Node.getData < Node.getRightChild)
{
boolean leftTree = isBST(new BinaryTree(Node.getLeftChild));
boolean rightTree = isBST(new BinaryTree(Node.getRightChild));
return leftTree && rightTree ;
}
else return false ;
}
</code></pre>
|
[] |
[
{
"body": "<p>Your implementation looks good but I can spot a some flaws in it.</p>\n\n<p>To begin, you check that <code>tree == null</code> after having already dereferenced it at <code>BinaryNode Node = new BinaryNode (tree.getRootData);</code>.</p>\n\n<p>Moreover I'd like more to see an <code>IllegalArgumentException</code> in the case of a <code>null</code> tree rather than getting the <code>true</code> answer.</p>\n\n<p>I don't even get why you create a new <code>BinaryNode</code>. Why can't you use the nodes you already have in the original tree? In your implementation you try to access the left and right children but you never set them before in <code>Node</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-12T18:28:24.893",
"Id": "38739",
"Score": "1",
"body": "Thank You so much @mariosangiorgio for your helpful comments :) , and about the last point it's cuz i'm doing the code for a specific ADT classes i got where i cannot access the Node of the Tree unless by calling a getter method which is in BinaryNode class , and for that i need to create an object of BinaryNode class so i can call the getter method and start work on it .. Hope i could explain clear and well !~"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-12T15:31:56.663",
"Id": "25039",
"ParentId": "25036",
"Score": "1"
}
},
{
"body": "<p>As mariosangiorgio already said, the concept looks good, with some small improvements possible. </p>\n\n<p>You should write some tests to test it. You would easily find out the mentioned problems with some good tests.</p>\n\n<p>To get you an idea of a fixed version, a typical implementation could look like:</p>\n\n<pre><code>public boolean isBinarySearchTree(BinaryTree tree)\n{\n if (tree == null)\n throw new IllegalArgumentException(\"Tree is null\");\n return isBinarySearchTree(tree.getRootNode());\n}\n\nprivate boolean isBinarySearchTree(Node node) // note: the name is not completely correct, because we investigate a node now. But for private and together with the other method, it would be fine\n{\n if(node == null || node.isLeaf() ) //hint: node == null can only happen in one case, we could remove it here, if we change the other method\n return true;\n\n if (!(node.getLeftChild().getData().compareTo(node.getData()) <= 0 && \n node.getData().compareTo(node.getRightChild().getData()) <= 0))\n return false; // not sorted\n\n return isBinarySearchTree(node.getLeftChild()) && isBinarySearchTree(node.getRightChild()); \n} \n</code></pre>\n\n<hr>\n\n<p>A final suggestion: Avoid abbreviations.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-12T17:24:59.880",
"Id": "25042",
"ParentId": "25036",
"Score": "-2"
}
},
{
"body": "<p>The answers above are very wrong as it is NOT enough to just compare the node data with its left children and right children. It should compare the node data with the MAX of the left subtree and compare with the MIN of the right subtree.</p>\n\n<p>The so-called improved one is still very wrong. It should have some way to record the max and min. Check the correct answer from leetcode.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-12T20:47:45.767",
"Id": "57071",
"Score": "2",
"body": "Could you provide a link to that correct answer?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-12T20:21:45.893",
"Id": "35249",
"ParentId": "25036",
"Score": "3"
}
},
{
"body": "<p>There are some serious problems with this function.</p>\n\n<h3>Issues of correctness</h3>\n\n<ul>\n<li><strong>Code won't compile:</strong> If <code>BinaryNode</code> indeed has fields named <code>getData</code>, <code>getLeftChild</code>, and <code>getRightChild</code> that are of type <code>String</code>, then you can't use operators <code><</code> and <code>></code> on them. For strings, as with any object, you have to use <code>a.compareTo(b)</code>.</li>\n<li><strong>No consideration for unbalanced or incomplete trees:</strong> If a node has only one child, what happens?</li>\n<li><strong>Check for <code>tree == null</code> after <code>tree.getRootData</code>:</strong> There's no point in checking for <code>tree == null</code>, since it would have crashed on <code>tree.getRootData</code> with a <code>NullPointerException</code> already if that were the case.</li>\n<li><strong>Recursive check is insufficient:</strong> As @user2668926 points out, you have to verify that all nodes within a subtree fall within a range of values.</li>\n</ul>\n\n<h3>Serious violations of style conventions</h3>\n\n<ul>\n<li><strong>Using an uppercase variable name:</strong> In Java, variable names should be <code>lowerCase</code>, except constants, which should be <code>ALL_CAPS</code>. By naming a variable <code>Node</code>, you hurt readability tremendously by making it look like the name of a class.</li>\n<li><strong>Using <code>getSomething</code> as field names:</strong> The convention is that <code>getSomething()</code> is the name of a getter <em>method</em> (i.e., a member <em>function</em>), usually corresponding to an instance variable named <code>something</code>. Instead, you seem to have instance <em>variables</em> named <code>getRootData</code>, <code>getData</code>, <code>getLeftChild</code>, and <code>getRightChild</code> in your <code>BinaryTree</code> and <code>BinaryNode</code> classes, which is exceedingly weird.</li>\n</ul>\n\n<p>I consider these two issues to be extremely serious, even if the compiler accepts the code and the algorithm runs. These are not \"merely\" conventions — they are major traps for anyone else who works with your code, enough for every programmer to go facepalm.</p>\n\n<h3>Less serious issues of style</h3>\n\n<ul>\n<li><strong>Distinction between <code>BinaryTree</code> and <code>BinaryNode</code>:</strong> Wrapping nodes as trees and unwrapping the tree's root node is cumbersome. Do you really have to make a distinction between trees and nodes? Could you not just treat any node as a tree rooted there?</li>\n<li><p><strong>Use of generics:</strong> The <code>BinaryTree</code> class is genericized, so your code should also aim to be generic. The method signature should look something like</p>\n\n<pre><code>public class BSTVerifier {\n public static <T extends Comparable> boolean isBST(BinaryTree<T> tree) {\n ...\n }\n}\n</code></pre>\n\n<p>Alternatively,</p>\n\n<pre><code>public class BSTVerifier<T extends Comparable> {\n public boolean isBST(BinaryTree<T> tree) {\n ...\n }\n}\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T00:43:10.057",
"Id": "57091",
"Score": "0",
"body": "I think that having separate `BinaryTree` can make sense. You can for example keep `Count` there and it also means empty collection can work nicely."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T00:53:07.757",
"Id": "57092",
"Score": "0",
"body": "If there are to be `BinaryTree` and `BinaryNode` classes, then I would suggest that the function be made private, and accept a `BinaryNode` argument. The public function, accepting a `BinaryTree`, can unwrap the tree's root just once and call the private version."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-12T22:52:42.633",
"Id": "35261",
"ParentId": "25036",
"Score": "4"
}
},
{
"body": "<p>The below code checks if both the left and right subtrees are binary search trees, if they are then compares the nodes data with the maximum element in the nodes left subtree and minimum element in the nodes right sub tree.</p>\n\n<pre><code>class Node{\n int data;\n Node left;\n Node right;\n Node(int x){\n data = x;\n }\n}\npublic class isBST {\n\n public static Node getMin(Node root)\n {\n while(root.left != null)\n {\n root = root.left;\n }\n\n return root;\n }\n public static Node getMax(Node root)\n {\n while(root.right != null)\n {\n root = root.right;\n }\n\n return root;\n }\n public static boolean isBST(Node root)\n {\n // for null node\n if(root == null )\n {\n return true;\n }\n // for single node\n if(root.left == null && root.right == null)\n {\n return true;\n }\n // for a non null node\n if(isBST(root.left ) && isBST(root.right) )\n {\n if(root.left != null && root.right != null)\n {\n return root.data < getMin(root.right).data && root.data > getMax(root.left).data;\n }\n else \n {\n if(root.left != null)\n {\n return root.data > getMax(root.left).data;\n }\n else\n {\n return root.data < getMin(root.right).data;\n }\n }\n }\n else\n {\n return false;\n } \n }\n\n public static void main(String[] args) {\n // TODO Auto-generated method stub\n Node root = new Node(5);\n root.left = new Node(3);\n root.right = new Node(7);\n root.left.left = new Node(2);\n root.left.right = new Node(4);\n root.right.left = new Node(6);\n root.right.right = new Node(9);\n System.out.println(isBST(root));\n }\n\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-04-07T16:21:15.090",
"Id": "233281",
"Score": "0",
"body": "Hi. Welcome to Code Review! Usually we prefer to mix in some review with our code suggestions in answers. As is, this is much more like a question than an answer. If you do post this as a question, I think you could get some good reviews. All you need is a title and problem statement."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-04-07T16:43:49.000",
"Id": "233294",
"Score": "0",
"body": "hi i gave this an answer rather than question. Can u suggest any changes for this anwer?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-04-07T16:56:38.250",
"Id": "233306",
"Score": "0",
"body": "As an answer, you should explain why you made changes from the original code."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-04-07T15:54:30.017",
"Id": "125081",
"ParentId": "25036",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "25042",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-12T14:11:46.460",
"Id": "25036",
"Score": "5",
"Tags": [
"java",
"algorithm",
"binary-search",
"tree"
],
"Title": "Check if a Binary Tree <String> is aBinary Search Tree"
}
|
25036
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.