body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>I have overrode Rails' <code>ActionDispatch::Routing::RouteSet::Dispatcher.controller_reference</code> method to check if a controller exists by checking for the required constants and then creating them based upon a controller with the same name in the <code>Generic</code> namespace. </p>
<p>The problem w/ my code is that it is using <code>begin/rescue</code>, it won't work w/ deeply namespaced controllers, and it's rather verbose. </p>
<p>Can anyone provide some improvements to this code?</p>
<pre><code>class ActionDispatch::Routing::RouteSet::Dispatcher
private
def controller_reference(controller_param)
const_name = @controller_class_names[controller_param] ||= "#{controller_param.camelize}Controller"
obj = Object
const_name.split('::').each do |cn|
begin
obj = obj.const_get(cn)
rescue
if obj == Object
obj = obj.const_set(cn, Class.new(ApplicationController))
else
puts "Creating #{obj}::#{cn} based on Generic::#{cn}"
obj = obj.const_set(cn, Class.new("Generic::#{cn}".constantize))
end
end
end
ActiveSupport::Dependencies.constantize(const_name)
end
end
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-26T15:05:12.613",
"Id": "84652",
"Score": "0",
"body": "you can use `const_defined?` instead of the begin/rescue, the rest looks just fine... :-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-02-09T14:07:17.403",
"Id": "357144",
"Score": "0",
"body": "I think this code is good, but it's better to catch only `NameError` to avoid suppressing errors not related to this patch."
}
] |
[
{
"body": "<p>Disclaimer: this should be a comment, my reputation at the moment does not allow me to comment your question</p>\n\n<p>What about exploiting <code>const_missing</code>? \n<a href=\"https://apidock.com/ruby/Module/const_missing\" rel=\"nofollow noreferrer\">https://apidock.com/ruby/Module/const_missing</a></p>\n\n<p>I used it in an app to declare <code>ActiveRecord</code> models at runtime. If you are interested in this approach I suggest you to namespace all Dynamic controllers i.e.</p>\n\n<pre><code>module Dyn\n def self.const_missing(sym)\n # Declare class Dyn::MyDynamicController\n # without overriding or patching Rails classes\n end\nend\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-09-07T07:55:36.247",
"Id": "175020",
"ParentId": "26294",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-17T13:15:31.320",
"Id": "26294",
"Score": "8",
"Tags": [
"ruby",
"ruby-on-rails"
],
"Title": "Dynamic Controller Creation in Rails"
}
|
26294
|
<p>2 months ago, I wrote a chrome extension called <a href="https://chrome.google.com/webstore/detail/hotfix/bfmckmhcljhakgkngnfjhmmffaabdafi?hl=en" rel="nofollow">hotfix</a>. I recently went back to look over the code and it made me cringe a bit. I refactored it a little, but before I get knee deep in it, I would like to ask for suggestions on the best way to proceed. I'm not expecting anyone to completely rewrite it, just to give me some suggestions on how to make it more efficient. However, if you like the project and want to submit a pull request to help, you can find it <a href="https://github.com/FajitaNachos/hotfix" rel="nofollow">here</a> on GitHub. </p>
<pre><code>(function(){
// If there is no hotfix data in local storage then the user is not authenicated
// so we should show the authorization page, otherwise the user is authenticated
// and we can proceed.
if(!localStorage.getItem('hotfix')){
document.getElementById('unauthorized').style.display = 'block';
}
else{
document.getElementById('authorized').style.display = 'block';
var localData = JSON.parse(localStorage['hotfix']),
repoList = document.getElementById('repo-list'),
selectUser = document.getElementById('select-user'),
repoDiv = document.getElementById('repos'),
branchDiv = document.getElementById('branches'),
branchList = document.getElementById('branch-list'),
currentUser = localData.username,
resources;
// Get the access token that we will use to authenticate with github.
// Initiate github.js instance.
// This is included from another file.
var github = new Github({
token: localData.accessToken,
auth: "oauth"
});
// Initiate a user in github.js.
var user = github.getUser();
//Populate the user select list with the user and their organizations
showUser(user);
//show the users repositories on initial page load
showRepos(currentUser);
// Generate a list of resources that has been edited.
chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
if (request.greeting == "show resources") {
document.getElementById('edited-resources').innerHTML = '';
// Populate the resources array
resources = request.showResource;
// Create a container div for holding the resource
showResources();
// Add an event listener for each remove resource span
removeResource();
// Add an event listener for each edit resource span
editPaths();
// Add an event listener to each commit button.
commit();
// Send a response to devtools.js via eventPage.js to make sure devResources
// and resources are in sync (ids, paths, etc...)
sendResponse({updatedArray : resources });
}
});
selectUser.addEventListener('change',function(){
currentUser = selectUser.options[selectUser.selectedIndex].text;
repoList.options.length = 1;
branchDiv.style.visibility = 'hidden';
showRepos(currentUser);
});
// Add listener for a change on the repo-list select element.
repoList.addEventListener('change',function(){
var repoName = repoList.options[repoList.selectedIndex].text;
branchList.options.length = 0;
if(repoName && repoName !== 'No repositories found'){
// Get the selected repository details.
showBranches(repoName);
}
else{
//Hide the branches if user unselects the repository.
branchDiv.style.visibility = 'hidden';
}
});
}
//Listen for a message from eventPage.js to reload the panel after successful authentication.
chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
if (request.greeting == "reload_panel"){
localStorage['hotfix'] = JSON.stringify(request.data);
document.location.reload();
}
});
//Listen for a message from eventPage.js to reload the panel after successful authentication.
chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
if (request.greeting == "unload_panel"){
localStorage.removeItem('hotfix');
localStorage.removeItem('hotfix-welcome');
document.location.reload();
}
});
// Send a message to eventPage.js to open a new window with the github authorization url.
document.getElementById("authorize-button").addEventListener("click", function() {
chrome.extension.sendMessage({greeting: "authorize_me"}, function(response) {});
});
//Send a message to eventPage.js to log out current user out of GitHub
document.getElementById("logout").addEventListener("click", function() {
chrome.extension.sendMessage({greeting: "logout"}, function(response) { });
});
function loadSpinner(location){
return new Spinner({
color: '#aaa',
lines:11,
length: 0,
width: 3,
radius: 5,
trail: 46,
top: '26px',
speed: 1.5
}).spin(location);
};
// List user/organization repositories.
function showRepos(currentUser, cb){
var repoDiv = document.getElementById('repos');
//Load spinner in the repository div while we wait
var spinner = loadSpinner(repoDiv);
var getRepos = user.userRepos(currentUser,function(err, repos){
var select = document.getElementById('repo-list');
// Populate the select list with the users' repos.
if(repos.length<1){
select.options.add(new Option('No repositories found'))
}
else{
for(var i=0; i < repos.length; i++){
var repo = repos[i].name;
select.options.add(new Option(repo))
}
}
spinner.stop();
});
}
function showBranches(repoName){
var repo = github.getRepo(currentUser, repoName);
// Show a spinner while the branches load.
var spinner = loadSpinner(branchDiv)
// Show the branch select box
branchDiv.style.visibility = 'visible';
// List all branches of the selected repository.
repo.listBranches(function(err, branches){
for(var i=0; i < branches.length; i++){
var branch = branches[i];
branchList.options.add(new Option(branch))
}
//Stop the spinner.
spinner.stop();
});
}
function showUser(user){
var userOption = document.createElement('option');
userOption.text = currentUser;
selectUser.options.add(userOption);
var userOrgs = user.orgs(function(err, orgs) {
for(var i=0; i < orgs.length; i++){
var org = orgs[i].login;
selectUser.options.add(new Option(org))
}
});
}
function removeResource(){
// Get all of the remove resource spans
var resources = document.getElementsByClassName('remove-resource');
for (var i = 0; i < resources.length; i++) {
resources[i].addEventListener('click', function() {
// Get the numeric id of the resource div which will correspond
// to the resources id in the resources.
var parentId = this.parentNode.parentNode.id;
var id = parentId.replace('resource-','');
for (var key in resources) {
if (resources[key].hasOwnProperty('id') && resources[key].id == id) {
// Remove the div on the screen and send a message to
// devtools.js via eventPage.js to remove it from the
// DevArray
this.parentNode.parentNode.remove();
chrome.extension.sendMessage({greeting: "remove resource", data: id}, function(response) {});
}
}
});
}
}
function editPaths(){
// Get all of the edit resource span
var paths = document.getElementsByClassName('edit-path');
for (var i = 0; i < paths.length; i++) {
paths[i].addEventListener('click', function() {
// Get the numeric id of the resource div which will correspond
// to the resources id in the resources.
var parentId = this.parentNode.parentNode.id;
var id = parentId.replace('resource-','');
for (var key in resources) {
if (resources[key].hasOwnProperty('id') && resources[key].id == id) {
// Get the text of the current path link.
var editButton = this;
var path = this.previousSibling;
// Create a new contentEditable span with that text
path.contentEditable = true;
// Create save button.
var savePath = document.createElement('span');
var savePathText = document.createTextNode('Save');
savePath.appendChild(savePathText);
savePath.className = "save-path";
// Add event listener for new save button.
savePath.addEventListener('click', function() {
path.contentEditable = false;
resources[id].path = path.innerText;
this.style.display = 'none';
editButton.style.display = "inline-block";
// Send a message to Dev Tools.js via eventPage.js to make sure the arrays stay in sync.
chrome.extension.sendMessage({greeting: "update devResource", data: resources}, function(response) {});
});
this.parentNode.insertBefore(savePath);
// Remove old path link and edit button.
this.style.display = 'none';
}
}
});
}
}
function commit() {
var commitButtons = document.getElementsByClassName('commit-button');
console.log(commitButtons.length);
for (var i = 0; i < commitButtons.length; i++) {
commitButtons[i].addEventListener('click', function() {
var repoName = repoList.options[repoList.selectedIndex].text;
// Check that a valid repository was selected.
if(!repoName){
alert('Please select a respository on the left');
return;
}
else if(repoName == "No repositories found"){
alert("It appears you haven't created any GitHub repositories. You should create one on GitHub, then log out of hotfix and log back in.");
return;
}
else{
// Get the id from the parent div that corresponds to the
// resources id property in our resources array.
var parentId = this.parentNode.parentNode.id;
var parentNode = this.parentNode.parentNode;
var id = parentId.replace('resource-','');
// Check that the user has saved the full commit path.
var checkPath = parentNode.getElementsByClassName('resource-path')[0];
if (checkPath.contentEditable == "true"){
alert('The full commit path needs to be saved.');
return;
}
// Get commit message from the textarea.
var commitMessageTextArea = 'commit-message-'+id;
commitMessage = document.getElementById(commitMessageTextArea).value;
// Check that the user has in fact entered a commit message.
if(!commitMessage){
alert('Please enter a commit message.');
return;
}
// And that it's not just a bunch of spaces.
var allSpaces = commitMessage.trim();
if(allSpaces.length == 0){
alert('Please enter a valid commit message.');
return;
}
// Create an overlay div and a loading spinner while we send the
// commit to GitHub.
var overlayDiv = document.createElement('div');
overlayDiv.className='overlay';
parentNode.appendChild(overlayDiv);
var spinner = new Spinner({
color:'#aaa',
lines: 14,
length: 18,
width: 3,
radius: 18,
corners: .8,
rotate: 56,
trail: 65,
speed: .9
}).spin(parentNode);
// Get the variables we need to send with our request to GitHub.
var branch = branchList.options[branchList.selectedIndex].text;
var repo = github.getRepo(currentUser,repoName);
repo.write(branch,resources[id].path, resources[id].content,commitMessage,function(err){
if(err){
alert('Sorry. There was a problem pushing your commit to GitHub. Please try again.');
spinner.stop();
parentNode.remove();
}
else{
// Create a div to show the success image.
var successImage = document.createElement('div');
successImage.id = 'success-image';
parentNode.appendChild(successImage);
var checkImg = document.getElementById('success-image');
setTimeout(function () {
checkImg.style.opacity = 1;
spinner.stop();
}, 5);
// Send a message to devtools.js via eventPage.js to remove
// the resource we just committed from the devResources array.
chrome.extension.sendMessage({greeting: "remove resource", data: id}, function(response) {});
// And remove it from view.
setTimeout(function(){
parentNode.remove();
},1000);
}
});
}
});
}
}
function showResources(){
var editedResources = document.getElementById('edited-resources');
// This part gets a little messy. We have to dynamically create numerous
// divs and spans for every resource that was edited.
// ToDo: Refactor this.
for (i=0; i<resources.length;i++){
// Add an id to all of the objects in rour esourceArray.
resources[i].id = i;
// Create an achor element and set the href and target.
var a = document.createElement('a');
a.href = resources[i].url;
a.target = '_blank';
// Extract the path and hostname from the anchor element.
var resourcePath = a.pathname;
var hostName = a.hostname;
var host = hostName.replace(/^www\./,'');
// Remove the leading / and add it to the resources.
if (resourcePath.charAt(0) == "/") {
resourcePath = resourcePath.substr(1);
}
// If resources.path is already set then
// use it instead of generating a new path.
// This lets us persist the commit path when it has been edited by a user.
if(!resources[i].path){
resources[i].path = resourcePath;
}
// Create a div to hold the resource and give it an id.
var resourceDiv = document.createElement('div');
resourceDiv.id = 'resource-' + i;
resourceDiv.className = "resource";
// Create a div for the domain that this resource came from.
var source = document.createElement('div');
source.className = 'source';
var domainText = document.createTextNode(host);
source.appendChild(domainText);
// Create a list element to hold the resource and path.
var file = document.createElement('li');
var fileText = document.createTextNode('Resource: ');
var fileName = resourcePath.substring(resourcePath.lastIndexOf('/')+1);
var fileNameText = document.createTextNode(fileName);
var fileSpan = document.createElement('span');
fileSpan.appendChild(fileNameText);
fileSpan.className = ('file-name')
file.appendChild(fileText);
file.appendChild(fileSpan);
file.className = 'file';
// Create an li element and add the full path to it.
var li = document.createElement('li');
var resourceText = document.createTextNode(resources[i].path);
var resourceLabel = document.createTextNode('Full commit path: ');
resourceLabel.className = 'resource-label';
var resourceSpan = document.createElement('span');
resourceSpan.className = 'resource-path';
resourceSpan.appendChild(resourceText);
var editPath = document.createElement('span');
editPath.className = ('edit-path');
editPathText = document.createTextNode('Edit');
editPath.appendChild(editPathText);
// Append the anchor element to the li element we just created.
li.appendChild(resourceLabel);
li.appendChild(resourceSpan);
li.appendChild(editPath);
// Create a span to hold the remove icon and give it a class.
var removeSpan = document.createElement('span');
removeSpan.className = 'remove-resource';
// Append the span to the li element.
source.appendChild(removeSpan);
// Create a div to hold the commit label, textarea(commit message),
// and commit button.
var commitWrapper = document.createElement('div');
commitWrapper.className = 'commit-wrapper';
// Create a label for the commit message and append it to the wrapper.
var commitInputLabel = document.createElement('label');
var inputLabelText = document.createTextNode('Commit message: ');
commitInputLabel.appendChild(inputLabelText);
commitWrapper.appendChild(commitInputLabel);
// Create the textarea and give it an id so we can access it later.
var commitInput = document.createElement('textarea');
commitInput.id = 'commit-message-' + i;
commitInput.className = 'commit-textarea';
// Create the commit button, give it some text, and add a class.
var commitButton = document.createElement('button');
var buttonText = document.createTextNode('Commit');
commitButton.className = 'commit-button';
commitButton.appendChild(buttonText);
// Append the textarea and button to the commit wrapper div
commitWrapper.appendChild(commitInput);
commitWrapper.appendChild(commitButton);
// Append the source, resource, path, and commit info to the
// container div.
resourceDiv.appendChild(source);
resourceDiv.appendChild(file);
resourceDiv.appendChild(li);
resourceDiv.appendChild(commitWrapper);
// Finally append the resource container to the main div.
editedResources.appendChild(resourceDiv);
}
}
})();
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-17T14:34:00.060",
"Id": "40720",
"Score": "0",
"body": "The first thing I usually recommend is having separate files... If you don't want to leak globals and stuff, you can use tools like browserify. I've already [made an extension](https://github.com/Ralt/remoteprez/tree/master/extension) with it, and it works great."
}
] |
[
{
"body": "<p>A few things in no particular order:</p>\n\n<ul>\n<li>You should re-organize your code. Pick a design pattern and stick to it. If you can't find one that you like, you could probably make a hybrid one. I would say the <a href=\"http://www.yuiblog.com/blog/2007/06/12/module-pattern/\" rel=\"nofollow\">Module pattern</a> would be a good one. You might also benefit from the <a href=\"http://msdn.microsoft.com/en-us/magazine/hh201955.aspx\" rel=\"nofollow\">Observer pattern aka Pub/Sub</a>. I think especially the Pub/Sub because you can use it to \"publish\" when a resource gets edited and then minimize the tests and DOM manipulations. That brings me to point #2:</li>\n<li>DOM manipulations are the most expensive thing like ever. Ha well maybe not, but the point still gets across. I saw your \"ToDo\" comment in <code>showResouces()</code> function and strongly suggest you spend the majority of your time there - even though that may sound like a broken record. All those manipulations would probably be the most significant and apparant improvement performance wise. Not only that but by forcing yourself to refactor that function, you'll probably end up refactoring the other ones as well to fit the changes made. Which is a win win I would say.</li>\n<li>On a personal note: don't use alerts. They annoy the heck out of people, my self in particular. Most modern browsers allow you to block messages like that or even do it automatically, causing your messages to go caput. But that could also be just me that has a grudge for them and it's up to you whether to swap them out or not.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-17T14:55:06.633",
"Id": "40723",
"Score": "0",
"body": "Thanks for the comments. I was reading up on the Module pattern earlier today and found it pretty interesting. I'll look into it more. Regarding the DOM manipulations, I have to create all the elements dynamically because I won't every know how many elements I am creating, or their details until the page is shown. I'm all ears on a better way to do it. I agree about the alerts. I need to get them out of there. It was a quick fix, that I never went back and implemented properly."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-17T15:00:20.267",
"Id": "40725",
"Score": "0",
"body": "Take some time to read up on Pub/Sub. I really think that's right up your alley. Applied to your case, it works something like this: \"Oh hey, I'm done editing these resources you can do your stuff now. And btw here's all the info you'll ever need.\" And then you can have another piece of code \"subscribed\" to that and go form there."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-17T14:51:33.207",
"Id": "26300",
"ParentId": "26296",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-17T14:06:55.797",
"Id": "26296",
"Score": "2",
"Tags": [
"javascript",
"git",
"google-chrome"
],
"Title": "Chrome extension that lets you push changes from Chrome Developer Tools directly to GitHub"
}
|
26296
|
<p>I understand .NET very well until Principles of OOP come into view, so I guess we can say very little. So to work on this, I am making a console app that will catalog my digital media to a MySQL database. I've been working on this for a few days. It's not done but I also don't want to get to far ahead and find out that this is a tragic design mess.</p>
<ol>
<li><p>I'm employing a <code>using</code> alias directive, which is the only way that I found that will work but I don't like how I have named it and it seems very patchy. Any ideas or insight on its use and naming structure?</p></li>
<li><p>Please ignore the use of hard coding MySQL properties. I will be adding them to a config file later on.</p></li>
<li><p>I was debating on using MSSQL Server or MySQL, so I was aiming to decouple my Data Access Layer as best that I can. I don't like how I have to hard code the column names and types. Is there any better way?</p></li>
</ol>
<pre class="lang-none prettyprint-override"><code> * Program.cs
* [Business]
* BusinessController.cs
* AlbumArtist.cs
* MusicFile.cs
* [Data]
* DataAccessController.cs
* [MySQL]
* MySQL.cs
* [Select]
* AlbumArtist.cs
* [Update]
* AlbumArtist.cs
* [Delete]
* AlbumArtist.cs
* [Insert]
* AlbumArtist.cs
</code></pre>
<h1>Program.cs</h1>
<pre class="lang-cs prettyprint-override"><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using TagLib;
using MediaExporter.Business;
using MySql.Data.MySqlClient;
namespace MediaExporter
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("## Media Exporter ##");
Console.WriteLine("## Version 0.1 / 05.09.13 ##");
Console.WriteLine("## Jon Holderman ##");
Console.WriteLine();
Console.Write("Enter Media Directory: ");
string mediaDirectory = Console.ReadLine();
Console.WriteLine();
List<MusicFile> musicFiles = new List<MusicFile>();
string[] files = Directory.GetFiles(mediaDirectory, "*.mp3", SearchOption.AllDirectories);
for (int i = 0; i <= 100; i++)
{
TagLib.File f = TagLib.File.Create(files[i]);
MusicFile mf = new MusicFile();
mf.AlbumArtist = f.Tag.AlbumArtists.First(s => !string.IsNullOrEmpty(s));
mf.Genre = f.Tag.Genres.First(s => !string.IsNullOrEmpty(s));
mf.AlbumTitle = f.Tag.Album;
mf.Year = Convert.ToInt32(f.Tag.Year);
mf.Type = f.MimeType;
mf.TrackNumber = Convert.ToInt32(f.Tag.Track);
mf.TrackTitle = f.Tag.Title;
mf.Duration = f.Properties.Duration;
mf.Bitrate = f.Properties.AudioBitrate;
mf.FileSize = GetFileSizeInMB(files[i]);
mf.FilePath = files[i].ToString().Remove(0, 8);
musicFiles.Add(mf);
BusinessController BC = new BusinessController();
BC.AddMusicFileToDB(mf);
}
Console.ReadLine();
}
public static decimal GetFileSizeInMB(string filePath)
{
FileInfo fi = new FileInfo(filePath);
return (fi.Length / 1024) / 1024;
}
}
}
</code></pre>
<h3>Business/BusinessController.cs</h3>
<pre class="lang-cs prettyprint-override"><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MediaExporter.Data;
namespace MediaExporter.Business
{
public class BusinessController
{
public DataAccessController DAC = new DataAccessController();
public void AddMusicFileToDB(MusicFile musicFile)
{
if(isAlbumArtist(musicFile.AlbumArtist))
{
Console.WriteLine("Album Artist is in DB...");
}
else
{
Console.WriteLine("Album Artist is not in DB...");
}
}
private bool isAlbumArtist(string albumArtistName)
{
return DAC.isAlbumArtist(albumArtistName);
}
}
}
</code></pre>
<h3>Business/MusicFile.cs</h3>
<pre class="lang-cs prettyprint-override"><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MediaExporter.Business
{
public class MusicFile
{
public string AlbumArtist { get; set; }
public string Genre { get; set; }
public string AlbumTitle { get; set; }
public int Year { get; set; }
public string Type { get; set; }
public int TrackNumber { get; set; }
public string TrackTitle { get; set; }
public TimeSpan Duration { get; set; }
public decimal FileSize { get; set; }
public int Bitrate { get; set; }
public string FilePath { get; set; }
public MusicFile(string albumArtist, string genre, string albumTitle, int year, string type, int trackNumber, string trackTitle, TimeSpan duration, decimal fileSize, int bitrate, string filePath)
{
AlbumArtist = albumArtist;
Genre = genre;
AlbumTitle = albumTitle;
Year = year;
Type = type;
TrackNumber = trackNumber;
TrackTitle = trackTitle;
Duration = duration;
FileSize = fileSize;
Bitrate = bitrate;
FilePath = filePath;
}
public MusicFile()
{
}
}
}
</code></pre>
<h3>Business/AlbumArtist.cs</h3>
<pre class="lang-cs prettyprint-override"><code>using System;
using MediaExporter.Data;
namespace MediaExporter.Business
{
class AlbumArtist
{
public DataAccessController DAC = new DataAccessController();
public int AlbumArtistID { get; set; }
public string Name { get; set; }
public int Rating { get; set; }
public AlbumArtist(int albumArtistID, string name, int rating)
{
AlbumArtistID = albumArtistID;
Name = name;
Rating = rating;
}
public AlbumArtist()
{
}
public bool isAlbumArtist(string albumArtistName)
{
if (DAC.isAlbumArtist(albumArtistName))
{
return true;
}
return false;
}
}
}
</code></pre>
<h3>Data/DataAccessController.cs</h3>
<pre class="lang-cs prettyprint-override"><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MediaExporter.Data
{
public class DataAccessController
{
public Data.MySQL.Select.AlbumArtist albumArtist = new MySQL.Select.AlbumArtist();
public bool isAlbumArtist(string albumArtistName)
{
return albumArtist.isAlbumArtist(albumArtistName);
}
}
}
</code></pre>
<h3>Data/MySQL/MySQL.cs</h3>
<pre class="lang-cs prettyprint-override"><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
namespace MediaExporter.Data.MySQL
{
public class MySQL
{
public string ServerAddress = "xxx";
public string UserName = "xxx";
public string Password = "xxx";
public string DataBase = "xxx";
public MySqlConnection MySqlConnection;
public MySQL()
{
Initialize();
}
private void Initialize()
{
MySqlConnection = new MySqlConnection(GetConnectionString());
}
public void OpenConnection()
{
try
{
MySqlConnection.Open();
}
catch (MySqlException exception)
{
Console.WriteLine("Error: " + exception.Message);
}
}
public void CloseConnection()
{
try
{
MySqlConnection.Close();
}
catch (MySqlException exception)
{
Console.WriteLine("Error: " + exception.Message);
}
}
private string GetConnectionString()
{
return String.Format("SERVER={0};DATABASE={1};UID={2};PASSWORD={3};", ServerAddress, DataBase, UserName, Password);
}
}
}
</code></pre>
<p>This is where the <code>using</code> alias directive is located:</p>
<h3>Data/MySQL/Select/AlbumArtist.cs</h3>
<pre class="lang-cs prettyprint-override"><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
using MediaExporter.Business;
namespace MediaExporter.Data.MySQL.Select
{
using B_AlbumArtist = MediaExporter.Business.AlbumArtist;
public class AlbumArtist : MediaExporter.Business.AlbumArtist
{
MySQL MySQLData = new MySQL();
public bool isAlbumArtist(string albumArtistName)
{
int count = 0;
try
{
MySqlConnection mySQLCnn = MySQLData.MySqlConnection;
string query = "SELECT Count(AlbumArtistID) FROM AlbumArtist WHERE AlbumArtist.Name = @AlbumArtistName;";
MySQLData.OpenConnection();
using (MySqlCommand mySQLCmd = new MySqlCommand(query, mySQLCnn))
{
mySQLCmd.Parameters.AddWithValue("@AlbumArtistName", albumArtistName);
count = int.Parse(mySQLCmd.ExecuteScalar().ToString());
}
}
catch (Exception e)
{
Console.WriteLine("{0} Exception caught.", e);
}
if (count >= 1)
{
return true;
}
MySQLData.CloseConnection();
return false;
}
public int GetAlbumArtistID(string albumArtistName)
{
int albumArtistID = -1;
try
{
MySqlConnection mySQLCnn = MySQLData.MySqlConnection;
string query = "SELECT ALbumArtistID FROM AlbumArtist WHERE AlbumArtist.Name = @AlbumArtistName;";
MySQLData.OpenConnection();
using (MySqlCommand mySQLCmd = new MySqlCommand(query, mySQLCnn))
{
mySQLCmd.Parameters.AddWithValue("@AlbumArtistName", albumArtistName);
albumArtistID = (int)mySQLCmd.ExecuteScalar();
}
}
catch (Exception e)
{
Console.WriteLine("{0} Exception caught.", e);
}
MySQLData.CloseConnection();
return albumArtistID;
}
public string GetAlbumArtistName(int albumArtistID)
{
string albumArtistName = String.Empty;
try
{
MySqlConnection mySQLCnn = MySQLData.MySqlConnection;
string query = "SELECT Name FROM AlbumArtist WHERE AlbumArtist.AlbumArtistID = @AlbumArtistID;";
MySQLData.OpenConnection();
using (MySqlCommand mySQLCmd = new MySqlCommand(query, mySQLCnn))
{
mySQLCmd.Parameters.AddWithValue("@AlbumArtistID", albumArtistID);
albumArtistName = mySQLCmd.ExecuteScalar().ToString();
}
}
catch (Exception e)
{
Console.WriteLine("{0} Exception caught.", e);
}
MySQLData.CloseConnection();
return albumArtistName;
}
public List<B_AlbumArtist> GetAllAlbumArtists()
{
List<B_AlbumArtist> albumArtistList = new List<B_AlbumArtist>();
try
{
MySqlConnection mySQLCnn = MySQLData.MySqlConnection;
string query = "SELECT * FROM AlbumArtist;";
MySQLData.OpenConnection();
using (MySqlCommand mySQLCmd = new MySqlCommand(query, mySQLCnn))
{
MySqlDataReader mySQLReader = mySQLCmd.ExecuteReader();
B_AlbumArtist tempAlbumArtist = new B_AlbumArtist();
while (mySQLReader.Read())
{
for (int i = 0; i < mySQLReader.FieldCount; i++)
{
tempAlbumArtist.AlbumArtistID = mySQLReader.GetInt32("AlbumArtistID");
tempAlbumArtist.Name = mySQLReader.GetString("Name");
tempAlbumArtist.Rating = mySQLReader.GetInt32("Rating");
albumArtistList.Add(tempAlbumArtist);
}
}
}
}
catch (Exception e)
{
Console.WriteLine("{0} Exception caught.", e);
}
MySQLData.CloseConnection();
return albumArtistList;
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-17T16:22:09.500",
"Id": "40734",
"Score": "0",
"body": "Have you considered using an ORM, like Entity Framework? Also, you didn't have to include all that code if you want feedback about the `using`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-17T16:30:02.783",
"Id": "40735",
"Score": "0",
"body": "@svick - I have, but I dont want to get to far ahead while I am still not understanding OOP concepts. Would you reccomend that if I was still learning OOP design? Part (3) of my question was related to folder structure and namespace structure of the program and I was hoping to get an assessment of the OOP design that I have so far. I hope that is not a far reach with this question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-17T18:15:48.630",
"Id": "40740",
"Score": "0",
"body": "@JonH - ORMs make OOP easier. You can actually deal with objects and storing them in the database, without worrying about *how* they connect. That being said, this design is poor even for a non-ORM design. Consider what is involved in adding an `AlbumArtwork` class, or just an `Artist` class that groups `AlbumArtist`s together? You'd have to duplicate four files for each new class... Look into \"Code-first Entity Framework\""
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-18T03:17:03.340",
"Id": "40759",
"Score": "0",
"body": "@Bobson - Thanks for the input I will be looking into \"Code First Entity Framework\""
}
] |
[
{
"body": "<p>Initial formatting suggestions:</p>\n\n<ol>\n<li>Class members should be <code>camelCase</code>, or _camelCase with an _ in front of them.</li>\n<li>No need to keep empty constructors around your code. They are put in by default by the compiler.</li>\n<li>For non-static classes, initialize class members in the constructor, that's what they are there for.</li>\n<li>Methods in C# should be <code>PascalCase</code></li>\n<li>I would read up on the <code>var</code> keyword for declaring local variables.</li>\n<li>Catch specific exceptions in your try/catch blocks. This will allow specific targeting of exceptions, and make debugging / reporting much easier.</li>\n</ol>\n\n<p>Overall, you seems to have a good basic understanding of OOP, and your code is well formatted with mostly well named variables, making it really easy to scan and get an understanding of what you are doing.</p>\n\n<p>You should look into dependency injection(DI) as a next step. Doing DI brings out much of the power of OOP.</p>\n\n<p>Good luck.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-18T03:19:20.253",
"Id": "40760",
"Score": "0",
"body": "Thanks! Since I am new here, how bad is it for me to repost a similar questions perhaps a month or two from now with a refresh of what I changed?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-20T17:32:24.180",
"Id": "40848",
"Score": "0",
"body": "@JonH - Nope, not at all. You can link back to this question, but as long as you frame it as a new one (i.e. \"This is what I have, how is it?\", rather than \"this is what's new, were the changes good?\"), it's perfectly fine to ask again."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-17T18:21:30.137",
"Id": "26307",
"ParentId": "26303",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "26307",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-17T15:45:25.143",
"Id": "26303",
"Score": "2",
"Tags": [
"c#",
".net",
"mysql"
],
"Title": "Cataloging digital media to a MySQL database"
}
|
26303
|
<p>I am creating an "explosion" of circle sprites from the character with this code, and I was wondering if there is a more effective way to do such things, because this just seems too stupid.
(This is cocos2d)</p>
<pre><code>int tileSize = 29;
explosionLenght += 1;
if (explosionLenght >= 7)
{
explosionLenght = 1;
}
CCSprite *circle0 = [[CCSprite alloc]initWithFile:@"Circle.png"];
CCSprite *circle1 = [[CCSprite alloc]initWithFile:@"Circle.png"];
CCSprite *circle2 = [[CCSprite alloc]initWithFile:@"Circle.png"];
CCSprite *circle3 = [[CCSprite alloc]initWithFile:@"Circle.png"];
CCSprite *circle4 = [[CCSprite alloc]initWithFile:@"Circle.png"];
CGPoint circle0position = ccp(_cat.position.x , _cat.position.y);
CGPoint circle1position = ccp(_cat.position.x - tileSize , _cat.position.y);
CGPoint circle2position = ccp(_cat.position.x + tileSize , _cat.position.y);
CGPoint circle3position = ccp(_cat.position.x , _cat.position.y -tileSize);
CGPoint circle4position = ccp(_cat.position.x , _cat.position.y + tileSize);
CGPoint c0TileCoordt = [self tileCoordForPosition:circle0position];
CGPoint c1TileCoordt = [self tileCoordForPosition:circle1position];
CGPoint c2TileCoordt = [self tileCoordForPosition:circle2position];
CGPoint c3TileCoordt = [self tileCoordForPosition:circle3position];
CGPoint c4TileCoordt = [self tileCoordForPosition:circle4position];
CGPoint c0TileCoord = [self positionForTileCoord:c0TileCoordt];
CGPoint c1TileCoord = [self positionForTileCoord:c1TileCoordt];
CGPoint c2TileCoord = [self positionForTileCoord:c2TileCoordt];
CGPoint c3TileCoord = [self positionForTileCoord:c3TileCoordt];
CGPoint c4TileCoord = [self positionForTileCoord:c4TileCoordt];
circle0.position = c0TileCoord;
circle1.position = c1TileCoord;
circle2.position = c2TileCoord;
circle3.position = c3TileCoord;
circle4.position = c4TileCoord;
CGPoint centreTileCoord = ccp(circle0.position.x, circle0.position.y);
CGPoint leftTileCoord = ccp(circle1.position.x, circle1.position.y);
CGPoint bottomTileCoord = ccp(circle3.position.x, circle3.position.y);
CGPoint rightTileCoord = ccp(circle2.position.x, circle2.position.y);
CGPoint topTileCoord = ccp(circle4.position.x, circle4.position.y);
CGPoint cTileCoord = [self tileCoordForPosition:centreTileCoord];
CGPoint lTileCoord = [self tileCoordForPosition:leftTileCoord];
CGPoint bTileCoord = [self tileCoordForPosition:bottomTileCoord];
CGPoint rTileCoord = [self tileCoordForPosition:rightTileCoord];
CGPoint tTileCoord = [self tileCoordForPosition:topTileCoord];
if ([self isValidTileCoord:cTileCoord] && ![self isWallAtTileCoord:cTileCoord])
{
[self addChild:circle0];
}
if ([self isValidTileCoord:lTileCoord] && ![self isWallAtTileCoord:lTileCoord])
{
[self addChild:circle1];
if (explosionLenght >= 2)
{
CCSprite *circle = [[CCSprite alloc]initWithFile:@"Circle.png"];
circle.position = ccp(circle1.position.x - tileSize * 1, circle1.position.y);
[self addChild:circle];
id fade = [CCSequence actionOne:[CCMoveTo actionWithDuration:1 position:circle.position] two:[CCScaleTo actionWithDuration:1 scale:0]];
[circle runAction:fade];
if (explosionLenght >= 3)
{
CCSprite *circle = [[CCSprite alloc]initWithFile:@"Circle.png"];
circle.position = ccp(circle1.position.x - tileSize * 2, circle1.position.y);
[self addChild:circle];
id fade = [CCSequence actionOne:[CCMoveTo actionWithDuration:1 position:circle.position] two:[CCScaleTo actionWithDuration:1 scale:0]];
[circle runAction:fade];
if (explosionLenght >= 4)
{
CCSprite *circle = [[CCSprite alloc]initWithFile:@"Circle.png"];
circle.position = ccp(circle1.position.x - tileSize * 3, circle1.position.y);
[self addChild:circle];
id fade = [CCSequence actionOne:[CCMoveTo actionWithDuration:1 position:circle.position] two:[CCScaleTo actionWithDuration:1 scale:0]];
[circle runAction:fade];
if (explosionLenght >= 5)
{
CCSprite *circle = [[CCSprite alloc]initWithFile:@"Circle.png"];
circle.position = ccp(circle1.position.x - tileSize * 4, circle1.position.y);
[self addChild:circle];
id fade = [CCSequence actionOne:[CCMoveTo actionWithDuration:1 position:circle.position] two:[CCScaleTo actionWithDuration:1 scale:0]];
[circle runAction:fade];
if (explosionLenght >= 6)
{
CCSprite *circle = [[CCSprite alloc]initWithFile:@"Circle.png"];
circle.position = ccp(circle1.position.x - tileSize * 5, circle1.position.y);
[self addChild:circle];
id fade = [CCSequence actionOne:[CCMoveTo actionWithDuration:1 position:circle.position] two:[CCScaleTo actionWithDuration:1 scale:0]];
[circle runAction:fade];
if (explosionLenght >= 7)
{
CCSprite *circle = [[CCSprite alloc]initWithFile:@"Circle.png"];
circle.position = ccp(circle1.position.x - tileSize * 6, circle1.position.y);
[self addChild:circle];
id fade = [CCSequence actionOne:[CCMoveTo actionWithDuration:1 position:circle.position] two:[CCScaleTo actionWithDuration:1 scale:0]];
[circle runAction:fade];
if (explosionLenght >= 8)
{
explosionLenght = 1;
}
}
}
}
}
}
}
}
if ([self isValidTileCoord:bTileCoord] && ![self isWallAtTileCoord:bTileCoord])
{
[self addChild:circle3];
if (explosionLenght >= 2)
{
CCSprite *circle = [[CCSprite alloc]initWithFile:@"Circle.png"];
circle.position = ccp(circle3.position.x , circle3.position.y- tileSize * 1);
[self addChild:circle];
id fade = [CCSequence actionOne:[CCMoveTo actionWithDuration:1 position:circle.position] two:[CCScaleTo actionWithDuration:1 scale:0]];
[circle runAction:fade];
if (explosionLenght >= 3)
{
CCSprite *circle = [[CCSprite alloc]initWithFile:@"Circle.png"];
circle.position = ccp(circle3.position.x, circle3.position.y - tileSize * 2);
[self addChild:circle];
id fade = [CCSequence actionOne:[CCMoveTo actionWithDuration:1 position:circle.position] two:[CCScaleTo actionWithDuration:1 scale:0]];
[circle runAction:fade];
if (explosionLenght >= 4)
{
CCSprite *circle = [[CCSprite alloc]initWithFile:@"Circle.png"];
circle.position = ccp(circle3.position.x, circle3.position.y - tileSize * 3);
[self addChild:circle];
id fade = [CCSequence actionOne:[CCMoveTo actionWithDuration:1 position:circle.position] two:[CCScaleTo actionWithDuration:1 scale:0]];
[circle runAction:fade];
if (explosionLenght >= 5)
{
CCSprite *circle = [[CCSprite alloc]initWithFile:@"Circle.png"];
circle.position = ccp(circle3.position.x, circle3.position.y - tileSize * 4);
[self addChild:circle];
id fade = [CCSequence actionOne:[CCMoveTo actionWithDuration:1 position:circle.position] two:[CCScaleTo actionWithDuration:1 scale:0]];
[circle runAction:fade];
if (explosionLenght >= 6)
{
CCSprite *circle = [[CCSprite alloc]initWithFile:@"Circle.png"];
circle.position = ccp(circle3.position.x, circle3.position.y - tileSize * 5);
[self addChild:circle];
id fade = [CCSequence actionOne:[CCMoveTo actionWithDuration:1 position:circle.position] two:[CCScaleTo actionWithDuration:1 scale:0]];
[circle runAction:fade];
if (explosionLenght >= 7)
{
CCSprite *circle = [[CCSprite alloc]initWithFile:@"Circle.png"];
circle.position = ccp(circle3.position.x , circle3.position.y- tileSize * 6);
[self addChild:circle];
id fade = [CCSequence actionOne:[CCMoveTo actionWithDuration:1 position:circle.position] two:[CCScaleTo actionWithDuration:1 scale:0]];
[circle runAction:fade];
if (explosionLenght >= 8)
{
explosionLenght = 1;
}
}
}
}
}
}
}
}
if ([self isValidTileCoord:rTileCoord] && ![self isWallAtTileCoord:rTileCoord])
{
[self addChild:circle2];
if (explosionLenght >= 2)
{
CCSprite *circle = [[CCSprite alloc]initWithFile:@"Circle.png"];
circle.position = ccp(circle2.position.x + tileSize * 1, circle2.position.y);
[self addChild:circle];
id fade = [CCSequence actionOne:[CCMoveTo actionWithDuration:1 position:circle.position] two:[CCScaleTo actionWithDuration:1 scale:0]];
[circle runAction:fade];
if (explosionLenght >= 3)
{
CCSprite *circle = [[CCSprite alloc]initWithFile:@"Circle.png"];
circle.position = ccp(circle2.position.x + tileSize * 2, circle2.position.y);
[self addChild:circle];
id fade = [CCSequence actionOne:[CCMoveTo actionWithDuration:1 position:circle.position] two:[CCScaleTo actionWithDuration:1 scale:0]];
[circle runAction:fade];
if (explosionLenght >= 4)
{
CCSprite *circle = [[CCSprite alloc]initWithFile:@"Circle.png"];
circle.position = ccp(circle2.position.x + tileSize * 3, circle2.position.y);
[self addChild:circle];
id fade = [CCSequence actionOne:[CCMoveTo actionWithDuration:1 position:circle.position] two:[CCScaleTo actionWithDuration:1 scale:0]];
[circle runAction:fade];
if (explosionLenght >= 5)
{
CCSprite *circle = [[CCSprite alloc]initWithFile:@"Circle.png"];
circle.position = ccp(circle2.position.x + tileSize * 4, circle2.position.y);
[self addChild:circle];
id fade = [CCSequence actionOne:[CCMoveTo actionWithDuration:1 position:circle.position] two:[CCScaleTo actionWithDuration:1 scale:0]];
[circle runAction:fade];
if (explosionLenght >= 6)
{
CCSprite *circle = [[CCSprite alloc]initWithFile:@"Circle.png"];
circle.position = ccp(circle2.position.x + tileSize * 5, circle2.position.y);
[self addChild:circle];
id fade = [CCSequence actionOne:[CCMoveTo actionWithDuration:1 position:circle.position] two:[CCScaleTo actionWithDuration:1 scale:0]];
[circle runAction:fade];
if (explosionLenght >= 7)
{
CCSprite *circle = [[CCSprite alloc]initWithFile:@"Circle.png"];
circle.position = ccp(circle2.position.x + tileSize * 6, circle2.position.y);
[self addChild:circle];
id fade = [CCSequence actionOne:[CCMoveTo actionWithDuration:1 position:circle.position] two:[CCScaleTo actionWithDuration:1 scale:0]];
[circle runAction:fade];
if (explosionLenght >= 8)
{
explosionLenght = 1;
}
}
}
}
}
}
}
}
if ([self isValidTileCoord:tTileCoord] && ![self isWallAtTileCoord:tTileCoord])
{
[self addChild:circle4];
if (explosionLenght >= 2)
{
CCSprite *circle = [[CCSprite alloc]initWithFile:@"Circle.png"];
circle.position = ccp(circle4.position.x , circle4.position.y+ tileSize * 1);
[self addChild:circle];
id fade = [CCSequence actionOne:[CCMoveTo actionWithDuration:1 position:circle.position] two:[CCScaleTo actionWithDuration:1 scale:0]];
[circle runAction:fade];
if (explosionLenght >= 3)
{
CCSprite *circle = [[CCSprite alloc]initWithFile:@"Circle.png"];
circle.position = ccp(circle4.position.x, circle4.position.y + tileSize * 2);
[self addChild:circle];
id fade = [CCSequence actionOne:[CCMoveTo actionWithDuration:1 position:circle.position] two:[CCScaleTo actionWithDuration:1 scale:0]];
[circle runAction:fade];
if (explosionLenght >= 4)
{
CCSprite *circle = [[CCSprite alloc]initWithFile:@"Circle.png"];
circle.position = ccp(circle4.position.x, circle4.position.y + tileSize * 3);
[self addChild:circle];
id fade = [CCSequence actionOne:[CCMoveTo actionWithDuration:1 position:circle.position] two:[CCScaleTo actionWithDuration:1 scale:0]];
[circle runAction:fade];
if (explosionLenght >= 5)
{
CCSprite *circle = [[CCSprite alloc]initWithFile:@"Circle.png"];
circle.position = ccp(circle4.position.x, circle4.position.y + tileSize * 4);
[self addChild:circle];
id fade = [CCSequence actionOne:[CCMoveTo actionWithDuration:1 position:circle.position] two:[CCScaleTo actionWithDuration:1 scale:0]];
[circle runAction:fade];
if (explosionLenght >= 6)
{
CCSprite *circle = [[CCSprite alloc]initWithFile:@"Circle.png"];
circle.position = ccp(circle4.position.x, circle4.position.y + tileSize * 5);
[self addChild:circle];
id fade = [CCSequence actionOne:[CCMoveTo actionWithDuration:1 position:circle.position] two:[CCScaleTo actionWithDuration:1 scale:0]];
[circle runAction:fade];
if (explosionLenght >= 7)
{
CCSprite *circle = [[CCSprite alloc]initWithFile:@"Circle.png"];
circle.position = ccp(circle4.position.x , circle4.position.y- tileSize * 6);
[self addChild:circle];
id fade = [CCSequence actionOne:[CCMoveTo actionWithDuration:1 position:circle.position] two:[CCScaleTo actionWithDuration:1 scale:0]];
[circle runAction:fade];
if (explosionLenght >= 8)
{
explosionLenght = 1;
}
}
}
}
}
}
}
}
int waitTime = 1;
int shrinkTime = 1;
id circle0done = [CCSequence actionOne:[CCMoveTo actionWithDuration:waitTime position:c0TileCoord] two:[CCScaleTo actionWithDuration:shrinkTime scale:0]];
id circle1done = [CCSequence actionOne:[CCMoveTo actionWithDuration:waitTime position:c1TileCoord] two:[CCScaleTo actionWithDuration:shrinkTime scale:0]];
id circle2done = [CCSequence actionOne:[CCMoveTo actionWithDuration:waitTime position:c2TileCoord] two:[CCScaleTo actionWithDuration:shrinkTime scale:0]];
id circle3done = [CCSequence actionOne:[CCMoveTo actionWithDuration:waitTime position:c3TileCoord] two:[CCScaleTo actionWithDuration:shrinkTime scale:0]];
id circle4done = [CCSequence actionOne:[CCMoveTo actionWithDuration:waitTime position:c4TileCoord] two:[CCScaleTo actionWithDuration:shrinkTime scale:0]];
[circle0 runAction:circle0done];
[circle1 runAction:circle1done];
[circle2 runAction:circle2done];
[circle3 runAction:circle3done];
[circle4 runAction:circle4done];
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-17T21:32:30.013",
"Id": "40747",
"Score": "0",
"body": "You could replace the enumerated variables by an array, e.g. `CCSprint **circles`. The giant `if`-cascades can be replaced by a loop from `2` to `explosionLength`; bound checking happens in the first few lines, so don't repeat it with the `>= 7` and `>= 8` tests which cannot return true (?). Once you have rewritten the code to use loops, further simplifications will present themselves."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-17T21:41:26.440",
"Id": "40748",
"Score": "0",
"body": "`for`loops! So simple! Why didn't I think of that. Will implement, thanks. @amon"
}
] |
[
{
"body": "<p>For someone who of some weird reason needs to do the same thing, here's the code I ended up using. </p>\n\n<pre><code> -(void)explosionFromPoint:(CGPoint)explosionPoint withSprite:(CCSprite*)sprite;\n{\n //int \n explosionLenght += 1;\n if (explosionLenght >= 7) //Just for testing purposes, don't have a way to increase it naturally. \n {\n explosionLenght = 1;\n }\n\n BOOL topB = YES;\n BOOL leftB = YES;\n BOOL bottomB = YES;\n BOOL rightB = YES;\n\n int bombX = (explosionPoint.x + 1);\n int bombY = (explosionPoint.y + 1);\n int bombNegX = (explosionPoint.x - 1);\n int bombNegY = (explosionPoint.y - 1);\n\n CGPoint top = ccp(explosionPoint.x, bombY);\n CGPoint left = ccp(bombNegX, explosionPoint.y);\n CGPoint bottom = ccp(explosionPoint.x, bombNegY);\n CGPoint right = ccp(bombX, explosionPoint.y);\n\n if (![self isLocationBombable:top])\n {topB = NO;}\n if (![self isLocationBombable:left])\n {leftB = NO;}\n if (![self isLocationBombable:bottom])\n {bottomB = NO;}\n if (![self isLocationBombable:right])\n {rightB = NO;}\n\n for (int i = 0; i <= explosionLenght; i++) {\n\n int bombX = (explosionPoint.x + i);\n int bombY = (explosionPoint.y + i);\n int bombNegX = (explosionPoint.x - i);\n int bombNegY = (explosionPoint.y - i);\n\n CGPoint top = ccp(explosionPoint.x, bombY);\n CGPoint left = ccp(bombNegX, explosionPoint.y);\n CGPoint bottom = ccp(explosionPoint.x, bombNegY);\n CGPoint right = ccp(bombX, explosionPoint.y);\n\n CCSprite *circleTop = [[CCSprite alloc]initWithFile:@\"Circle.png\"];\n CCSprite *circleLeft = [[CCSprite alloc]initWithFile:@\"Circle.png\"];\n CCSprite *circleBottom = [[CCSprite alloc]initWithFile:@\"Circle.png\"];\n CCSprite *circleRight = [[CCSprite alloc]initWithFile:@\"Circle.png\"];\n\n if ([self isLocationBombable:top] && topB == YES)\n {\n circleTop.position = [self positionForTileCoord:top];\n [self addChild:circleTop];\n id fadeTop = [CCSequence actionOne:[CCMoveTo actionWithDuration:1 position:circleTop.position] two:[CCScaleTo actionWithDuration:1 scale:0]];\n [circleTop runAction:fadeTop];\n }\n if ([self isLocationBombable:left] && leftB == YES)\n {\n circleLeft.position = [self positionForTileCoord:left];\n [self addChild:circleLeft];\n id fadeLeft = [CCSequence actionOne:[CCMoveTo actionWithDuration:1 position:circleLeft.position] two:[CCScaleTo actionWithDuration:1 scale:0]];\n [circleLeft runAction:fadeLeft];\n }\n if ([self isLocationBombable:bottom] && bottomB == YES)\n {\n circleBottom.position = [self positionForTileCoord:bottom];\n [self addChild:circleBottom];\n id fadeBottom = [CCSequence actionOne:[CCMoveTo actionWithDuration:1 position:circleBottom.position] two:[CCScaleTo actionWithDuration:1 scale:0]];\n [circleBottom runAction:fadeBottom];\n }\n if ([self isLocationBombable:right] && rightB == YES)\n {\n circleRight.position = [self positionForTileCoord:right];\n [self addChild:circleRight];\n id fadeRight = [CCSequence actionOne:[CCMoveTo actionWithDuration:1 position:circleRight.position] two:[CCScaleTo actionWithDuration:1 scale:0]];\n [circleRight runAction:fadeRight];\n }\n }\n\n [currentBombs addObject:sprite];\n\n NSLog(@\"Explosion done, call checkdamage\");\n\n [self schedule:@selector(checkDamageForBomb)];\n [self performSelector:@selector(removeSprite:) withObject:sprite afterDelay:3];\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-27T11:54:05.120",
"Id": "41329",
"Score": "0",
"body": "Feel free to comment about further improvements to this code."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-27T11:53:28.697",
"Id": "26666",
"ParentId": "26311",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "26666",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-17T20:07:25.437",
"Id": "26311",
"Score": "2",
"Tags": [
"optimization",
"c",
"objective-c",
"ios"
],
"Title": "Creating an expanding CCSprite cluster"
}
|
26311
|
<p>I have been trying to figure out a way to optimize the solving of ODEs in Python but haven't been able to achieve this goal. I tried getting help via a bounty on SO using Cython but nothing came of that. </p>
<p>The code below isn't too slow but it is an example of code I tend to run a lot. Some of the code I use can take forever since I am simulating space flight trajectories. If I can get some help with this code, I can work on the rest myself with ideas and knowledge I gain.</p>
<p>The code isn't short but not too long. The crux of the matter is the performance of the ODE solving. The rest is solving constants that go into the ODE or IC.</p>
<pre><code>import numpy as np
from scipy.integrate import ode
import pylab
from mpl_toolkits.mplot3d import Axes3D
from scipy.optimize import brentq
from scipy.optimize import fsolve
me = 5.974 * 10 ** 24 # mass of the earth
mm = 7.348 * 10 ** 22 # mass of the moon
G = 6.67259 * 10 ** -20 # gravitational parameter
re = 6378.0 # radius of the earth in km
rm = 1737.0 # radius of the moon in km
r12 = 384400.0 # distance between the CoM of the earth and moon
rs = 66100.0 # distance to the moon SOI
Lambda = np.pi / 6 # angle at arrival to SOI
M = me + mm
d = 300 # distance the spacecraft is above the Earth
pi1 = me / M
pi2 = mm / M
mue = 398600.0 # gravitational parameter of earth km^3/sec^2
mum = G * mm # grav param of the moon
mu = mue + mum
omega = np.sqrt(mu / r12 ** 3)
# distance from the earth to Lambda on the SOI
r1 = np.sqrt(r12 ** 2 + rs ** 2 - 2 * r12 * rs * np.cos(Lambda))
vbo = 10.85 # velocity at burnout
h = (re + d) * vbo # angular momentum
energy = vbo ** 2 / 2 - mue / (re + d) # energy
v1 = np.sqrt(2.0 * (energy + mue / r1)) # refer to the close up of moon diagram
# refer to diagram for angles
theta1 = np.arccos(h / (r1 * v1))
phi1 = np.arcsin(rs * np.sin(Lambda) / r1)
#
p = h ** 2 / mue # semi-latus rectum
a = -mue / (2 * energy) # semi-major axis
eccen = np.sqrt(1 - p / a) # eccentricity
nu0 = 0
nu1 = np.arccos((p - r1) / (eccen * r1))
# Solving for the eccentric anomaly
def f(E0):
return np.tan(E0 / 2) - np.sqrt((1 - eccen) / (1 + eccen)) * np.tan(0)
E0 = brentq(f, 0, 5)
def g(E1):
return np.tan(E1 / 2) - np.sqrt((1 - eccen) / (1 + eccen)) * np.tan(nu1 / 2)
E1 = fsolve(g, 0)
# Time of flight from r0 to SOI
deltat = (np.sqrt(a ** 3 / mue) * (E1 - eccen * np.sin(E1)
- (E0 - eccen * np.sin(E0))))
# Solve for the initial phase angle
def s(phi0):
return phi0 + deltat * 2 * np.pi / (27.32 * 86400) + phi1 - nu1
phi0 = fsolve(s, 0)
nu = -phi0
gamma = 0 * np.pi / 180 # angle in radians of the flight path
vx = vbo * (np.sin(gamma) * np.cos(nu) - np.cos(gamma) * np.sin(nu))
# velocity of the bo in the x direction
vy = vbo * (np.sin(gamma) * np.sin(nu) + np.cos(gamma) * np.cos(nu))
# velocity of the bo in the y direction
xrel = (re + 300.0) * np.cos(nu) - pi2 * r12
yrel = (re + 300.0) * np.sin(nu)
u0 = [xrel, yrel, 0, vx, vy, 0]
def deriv(u, dt):
return [u[3], # dotu[0] = u[3]
u[4], # dotu[1] = u[4]
u[5], # dotu[2] = u[5]
(2 * omega * u[4] + omega ** 2 * u[0] - mue * (u[0] + pi2 * r12) /
np.sqrt(((u[0] + pi2 * r12) ** 2 + u[1] ** 2) ** 3) - mum *
(u[0] - pi1 * r12) /
np.sqrt(((u[0] - pi1 * r12) ** 2 + u[1] ** 2) ** 3)),
# dotu[3] = that
(-2 * omega * u[3] + omega ** 2 * u[1] - mue * u[1] /
np.sqrt(((u[0] + pi2 * r12) ** 2 + u[1] ** 2) ** 3) - mum * u[1] /
np.sqrt(((u[0] - pi1 * r12) ** 2 + u[1] ** 2) ** 3)),
# dotu[4] = that
0] # dotu[5] = 0
dt = np.linspace(0.0, 259200.0, 259200.0) # secs to run the simulation
u = odeint(deriv, u0, dt)
x, y, z, x2, y2, z2 = u.T
fig = pylab.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot(x, y, z, color = 'r')
# adding the moon
phi = np.linspace(0, 2 * np.pi, 100)
theta = np.linspace(0, np.pi, 100)
xm = rm * np.outer(np.cos(phi), np.sin(theta)) + r12 - pi2 * r12
ym = rm * np.outer(np.sin(phi), np.sin(theta))
zm = rm * np.outer(np.ones(np.size(phi)), np.cos(theta))
ax.plot_surface(xm, ym, zm, color = '#696969', linewidth = 0)
ax.auto_scale_xyz([-8000, 385000], [-8000, 385000], [-8000, 385000])
# adding the earth
xe = re * np.outer(np.cos(phi), np.sin(theta)) - pi2 * r12
ye = re * np.outer(np.sin(phi), np.sin(theta))
ze = re * np.outer(np.ones(np.size(phi)), np.cos(theta))
ax.plot_surface(xe, ye, ze, color = '#4169E1', linewidth = 0)
ax.auto_scale_xyz([-8000, 385000], [-8000, 385000], [-8000, 385000])
pylab.savefig("test.eps", format = "eps", dpi = 1000)
pylab.show()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-20T19:24:08.477",
"Id": "40859",
"Score": "0",
"body": "Check out PyDSTool written by my good friend Rob Clewley. His code is better optimized than the MATLAB and vetted for almost 4-5 years now. It has been started while he was postdoc at Cornell. [1]http://www.ni.gsu.edu/~rclewley/PyDSTool/FrontPage.html"
}
] |
[
{
"body": "<p>I would manually \"eliminate common sub-expressions\" in the <code>deriv</code>:</p>\n\n<pre><code>def deriv(u, dt):\n norm1 = np.sqrt(((u[0] + pi2 * r12) ** 2 + u[1] ** 2) ** 3)\n norm2 = np.sqrt(((u[0] - pi1 * r12) ** 2 + u[1] ** 2) ** 3)\n return [u[3], # dotu[0] = u[3] \n u[4], # dotu[1] = u[4] \n u[5], # dotu[2] = u[5] \n (2 * omega * u[4] + omega ** 2 * u[0] - mue * (u[0] + pi2 * r12) /\n norm1 - mum *\n (u[0] - pi1 * r12) /\n norm2),\n # dotu[3] = that \n (-2 * omega * u[3] + omega ** 2 * u[1] - mue * u[1] /\n norm1 - mum * u[1] /\n norm2),\n # dotu[4] = that \n 0] # dotu[5] = 0 \n</code></pre>\n\n<p>And BTW is the <code>tan(0)</code> in <code>f(E0)</code> actually <code>tan(nu0 / 2)</code>?</p>\n\n<p><sub>I am not a Python programmer.</sub></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-17T14:59:45.577",
"Id": "29891",
"ParentId": "26314",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-18T00:30:48.493",
"Id": "26314",
"Score": "6",
"Tags": [
"python",
"optimization",
"performance"
],
"Title": "How do I optimize the solving of ODEs?"
}
|
26314
|
<p>I recently came across a lecture on DFA. I tried to use it to determine whether a given 'search string' is found in the 'input string'. Please tell me if there is a better way.</p>
<pre><code>(display "Enter input string")
(define input-str (read-line (current-input-port)))
(display "Enter Search String")
(define search-str (read-line (current-input-port)))
(define (search-match in-str sr-str)
(let* ((in-str-len (string-length in-str))
(start-state 0)
(end-state (string-length sr-str)))
(letrec ((iter (lambda (i curr-state)
(cond ((= curr-state end-state) #t)
((= i in-str-len) #f)
((equal? (string-ref in-str i)
(string-ref sr-str curr-state))
(iter (+ i 1) (+ curr-state 1)))
(else
(iter (+ i 1) start-state))))))
(iter 0 0))))
(search-match input-str search-str)
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2013-05-18T05:35:30.567",
"Id": "26316",
"Score": "2",
"Tags": [
"strings",
"search",
"scheme",
"state-machine"
],
"Title": "String matching"
}
|
26316
|
<p>I am new to PHP and put this contact page together using the w3Schools.com example as a guide along with a couple other sources. As far as I can tell, it works fine, but before I put it up on my page I would like to know if there is any potential for abuse. Any feedback is appreciated.</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<?php include 'header.php'; ?>
</head>
<body>
<?php
require_once "Mail.php";
function spamCheck($field) {
$field = filter_var($field, FILTER_SANITIZE_EMAIL);
if (filter_var($field, FILTER_VALIDATE_EMAIL)) {
return true;
} else {
return false;
}
}
if (isset($_REQUEST['email'])) {
$mailcheck = spamCheck($_REQUEST['email']);
if ($mailcheck == false) {
echo "Invalid Input";
} else {
$from = $_REQUEST['email'];
$body = "From\n" . $from . "\n\n" . $_REQUEST['message'];
$to = "<REMOVED>";
$subject = "$_REQUEST['subject'];
$host = "<REMOVED>";
$port = "<REMOVED>";
$username = "<REMOVED>";
$password = "<REMOVED>";
$headers = array('From' => $from, 'To' => $to, 'Subject' => $subject);
$smtp = Mail::factory('smtp',array ('host' => $host,
'port' => $port,
'auth' => true,
'username' => $username,
'password' => $password));
$mail = $smtp->send($to, $headers, $body);
if (PEAR::isError($mail)) {
echo("<p>" . $mail->getMessage() . "</p>");
} else {
echo("<p>Message successfully sent!</p>");
}
}
} else {
echo "<h1>Send me an email if you like.</h1>
<br><form method='post' action='contact.php'><br>
<p>Your Email: <input name='email' type='text'>
Subject: <input name='subject' type='text'></p>
<p>Message:<br>
<textarea name='message' rows='15' cols='40'>
</textarea><br>
<input type='submit'></p>
</form>";
}
?>
</body>
<?php include "footer.php"?>
</html>
</code></pre>
|
[] |
[
{
"body": "<p>In case anyone else is interested I was able to increase the security somewhat. After some research, I think that I have made it more secure, from spammers, at least. I implemented a <a href=\"http://www.phpcaptcha.org\" rel=\"nofollow\">captcha by Securimage</a>. It was pretty simple to use and I tested it out and think it does a fine job. They have good documentation and a simple quickstart guide right <a href=\"http://www.phpcaptcha.org/documentation/quickstart-guide/\" rel=\"nofollow\">here</a>. I am going to spend some more time learning about it, but it was quick and easy to get up and running. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T05:09:06.523",
"Id": "26402",
"ParentId": "26317",
"Score": "0"
}
},
{
"body": "<p>You're <code>spamCheck</code> function isn't really doing a proper check. It's removing all the invalid characters from the e-mail address and then checking if it's valid, so even if the e-mail had invalid characters it would still passes.</p>\n\n<p>For example:</p>\n\n<pre><code>$dangerousEmail = \"localhost\\nCc:recipient@beingspammed.com\";\n\n// This will output \"Email is valid!\" even though it isn't\nif(spamCheck($dangerousEmail))\n echo \"Email is valid!\";\n</code></pre>\n\n<p>A better check would be just to use <code>filter_var</code> with <code>FILTER_VALIDATE_EMAIL</code> directly:</p>\n\n<pre><code>if (filter_var($email, FILTER_VALIDATE_EMAIL))\n{\n // Sanitize the e-mail to be extra safe.\n // I think Pear Mail will automatically do this for you\n $email = filter_var($field, FILTER_SANITIZE_EMAIL);\n\n echo \"Email is valid!\";\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T04:05:30.493",
"Id": "40976",
"Score": "0",
"body": "This is exactly the find of feedback I was hoping for. Thank you very much. I see the error in my logic."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T04:16:24.577",
"Id": "40977",
"Score": "0",
"body": "Is it safe to assume that I should validate THEN sanitize in all cases?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T11:51:26.440",
"Id": "26419",
"ParentId": "26317",
"Score": "4"
}
},
{
"body": "<p>I use a blank input field in the form and hide it with css. If the field exists upon form submit, I know it's spam and just ignore it.</p>\n\n<pre><code><form method=\"post\">\n<input type=\"text\" name=\"email\" />\n<input type=\"text\" name=\"email2\" style=\"display:none;\" />\n<input type=\"submit\" />\n</form>\n\n<?php if (!$_POST['email2']) { // not spam } ?>\n</code></pre>\n\n<p>Of course this only works with bots and spammers who scrape sites to get all the input fields, but since I've implemented it, it's worked great.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T18:48:03.720",
"Id": "26487",
"ParentId": "26317",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "26419",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-18T05:44:39.863",
"Id": "26317",
"Score": "2",
"Tags": [
"php",
"security"
],
"Title": "Is this PHP Email Form Secure from injections or other abuses?"
}
|
26317
|
<p>My site consists of a lot of asynchronous calls, and because of this a lot of content is dynamically added to the page. For this section of code I've dynamically added tabs to a page and need to create the selected tab section. This function is fired when a tab is clicked (note that <code>$devices_page</code> is a pre-existing divider):</p>
<pre><code>function populateDevicesPage(deviceArray) {
// Hide the current page
$devices_page.stop().slideUp(animationSpeed, function() {
// Check if the $devices_page has any current children
if($devices_page.children().length > 0)
{ /* Ignore this part, it's the below else that matters */ }
// If not, create page elements
else
{
// Create the main devices page elements
var
$device_name = $('<h1/>').appendTo($devices_page),
$device_inner_page = $('<div id="devices-page-inner"/>').appendTo($devices_page),
$commands_table = $('<table/>').appendTo($device_inner_page),
$commands_thead = $('<thead/>').appendTo($commands_table),
$commands_tbody = $('<tbody/>').appendTo($commands_table),
$commands_thead_row = $('<tr/>').appendTo($commands_thead)
;
// Create the table headings
$('<th/>').text('Name').appendTo($commands_thead_row);
$('<th/>').text('Command').appendTo($commands_thead_row);
// Loop through each of the commands to populate the table
for(var i=0;i<deviceArray.commands.length;i++)
{
var $command_tbody_row = $('<tr/>').appendTo($commands_tbody);
$('<td/>').text(deviceArray.commands[i].name).appendTo($command_tbody_row);
$('<td/>').text(deviceArray.commands[i].com).appendTo($command_tbody_row);
}
$device_name.text(deviceArray.deviceName);
}
// Show the newly populated page
$devices_page.stop().slideDown(animationSpeed);
});
}
</code></pre>
<p>As you can see there are a lot of elements being created and added to the pre-existing <code>$devices_page</code> divider. This does only happen once (when a tab is selected for the first time), but I was wondering if there's a much better approach I could adopt instead.</p>
<p>The full code can be seen here if anyone wants a further poke around: <a href="https://github.com/JamesDonnelly/WebRemoteNotifier/blob/master/js/generic.js" rel="nofollow">https://github.com/JamesDonnelly/WebRemoteNotifier/blob/master/js/generic.js</a>. Do note that this is a very rough draft of a project I've only spent about 3-4 hours working on, so I imagine there are a lot of imperfections; for now I'm only really concerned about the above function.</p>
<p>Thanks a lot!</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-19T14:12:52.933",
"Id": "40799",
"Score": "0",
"body": "Check out knockout.js. It provides data (JSON) binding to an existing markup template (HTML). This will remove your need to manually generate as much markup."
}
] |
[
{
"body": "<p>If you don't need the data as JSON, you could just have the server send you the table markup. Then just inject it straight into the page using <a href=\"http://api.jquery.com/load/\" rel=\"nofollow\"><code>.load()</code></a></p>\n\n<p>Alternatively, if you want JSON data, or can't/won't mess with the server side, you might consider having a hidden, empty table in the markup to begin with, so you don't need to create the entire thing from scratch. Then you can just populate the header cells with the relevant text, and only worry about adding the rows to <code>tbody</code>.</p>\n\n<p>Of course, it'll introduce tighter coupling between the markup and the JS, which you might want to avoid. Since this is a new project that's probably changing all the time, it might be best to simply stick with you current approach of doing everything in JS, to keep things flexible. But my thinking is that since you're basically hardcoding things like the table headers in JavaScript, you're better off hardcoding it the markup where it belongs, rather than generating it.</p>\n\n<p>And you can also make the coupling a little looser, by using some <code>data-*</code> attributes in the \"template\" table to declare their intended content.</p>\n\n<p>For instance, have this in the page markup</p>\n\n<pre><code><table>\n <thead>\n <tr>\n <th>Name</th>\n <th>Command</th>\n </tr>\n </thead>\n\n <tbody>\n <!-- hidden row template -->\n <tr class=\"template\">\n <td data-property=\"name\"></td>\n <td data-property=\"com\"></td>\n </tr>\n </tbody>\n</table>\n</code></pre>\n\n<p>Then, on the JS-side, do something like:</p>\n\n<pre><code>var tbody = $(\"tbody\"),\n template = tbody.children(\".template\").removeClass(\".template\").remove(), // removed, but still in memory\n newRow, item;\n\nfor(var i = 0, l = deviceArray.commands.length ; i < l ; i++) {\n item = deviceArray.commands[i];\n newRow = template.clone();\n newRow.children(\"[data-property]\").each(function () {\n var cell = $(this),\n prop = cell.data(\"property\");\n cell.text(item[prop]);\n });\n newRow.appendTo(tbody);\n}\n</code></pre>\n\n<p>That should populate table nicely.</p>\n\n<p>Of course, for such a simple two-column table, it might be overkill. Still, if you need to populate more tables like this, you can create a pretty generic function that you just pass a \"scaffold\" element like the empty table above plus a data array, and use that anywhere it's needed.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-18T14:22:13.780",
"Id": "26322",
"ParentId": "26319",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-18T08:58:34.840",
"Id": "26319",
"Score": "1",
"Tags": [
"javascript",
"jquery"
],
"Title": "How can I improve my code which dynamically populates a section of a page?"
}
|
26319
|
<p>I'm writing a <a href="https://github.com/tarrsalah/jdk-manager" rel="nofollow">bash script</a> to manage multiple <code>JDKs</code>, the script is very simple, you have to choose a directory when you store all the jdk's, and the script maintain a <code>symlink</code> to the current <code>jdk'. The</code>JAVA_HOME<code>is always pointing to the</code>symlink`.</p>
<p>In order to use the script you have to source the <code>jdk-manager.bash</code> in <code>.bash_profile</code> or <code>.profile</code></p>
<p>The script is used by calling <code>jdk</code> function from the command line.</p>
<hr>
<p><strong>Questions</strong>:</p>
<ul>
<li>is there any security issues in the script ?</li>
<li>is there any way to implement the same functionality without sourcing the shell file in a <code>dotfile</code> ?</li>
</ul>
<hr>
<pre><code>#! /usr/bin/env bash
#set -u
#set -e
#to modify
JDK_ROOT="$HOME/local" # change it to the directory that contain the jdk's
JDK_PATTERN="[0-9]\.[0-9]\.+([0-9])?(_+([0-9]))"
CURRENT_JDK="$JDK_ROOT/.current_jdk"
SESSION=0;
# colors
textred=$(tput setaf 1)
texttyellow=$(tput setaf 3)
textreset=$(tput sgr0)
textgreen=$(tput setaf 2)
########################################################################""
# functions
########################################################################"
# ascii art
_print_java_ascii() {
printf ${texttyellow}"
_ _ _
(_) __| | | __ _ __ ___ __ _ _ __ __ _ __ _ ___ _ __
| |/ _ | |/ /____| _ _ \ / _ | _ \ / _ |/ _ |/ _ \ __|
| | (_| | <_____| | | | | | (_| | | | | (_| | (_| | __/ |
_/ |\__ _|_|\_\ |_| |_| |_|\__ _|_| |_|\__ _|\__ |\___|_|
|__/ |___/
"${textreset}
}
_is_jdk() {
return `[[ "$1" == jdk${JDK_PATTERN} ]]`
}
# init the current symlink
_init_current() {
if [[ ! -L $CURRENT_JDK ]];
then
ln -s /dev/null $CURRENT_JDK
fi
}
_get_current_jdk() {
basename `readlink -f $CURRENT_JDK`
}
# list all available jdks in the JDK_ROOT directory
_ls_jdks() {
for file in $(ls $JDK_ROOT)
do
if `_is_jdk "$file"`
then
if [[ $file == `_get_current_jdk` ]]
then
printf "${textgreen} > $file\n"
else
printf "${textreset} $file\n"
fi
fi
done
}
_set_current_jdk() {
jdk="jdk$1"
if `_is_jdk $jdk` && [[ -d "$JDK_ROOT/$jdk" ]]
then
rm "$CURRENT_JDK"
ln -sf "$JDK_ROOT/$jdk" "$CURRENT_JDK"
printf "${textgreen} INFO: ${textreset}Updating the \$JAVA_HOME to $JDK_ROOT/${textgreen}`_get_current_jdk`${textreset} .\n\n";
_ls_jdks;
else
printf "${textred} ERROR: ${textreset} there is no $jdk in $JDK_ROOT \n"
fi
}
########################################################################""
# main
########################################################################"
export JAVA_HOME=$CURRENT_JDK;
export PATH="$JAVA_HOME/bin:$PATH"
jdk() {
if [[ $SESSION -eq 0 ]]
then
_print_java_ascii;
SESSION=1;
fi
_init_current;
if [[ $# -eq 0 ]]
then
_ls_jdks;
else
_set_current_jdk $1
fi
}
</code></pre>
|
[] |
[
{
"body": "<p>Let's see:</p>\n\n<ul>\n<li>There's no need to use <code>return</code> in the last statement of a function. By default, the return code of the last command is returned anyway.</li>\n<li>Using backticks for evaluation is deprecated - you should use <code>$(command args)</code> instead. It is also more readable.</li>\n<li><a href=\"http://mywiki.wooledge.org/BashGuide/Practices\" rel=\"nofollow\">Use More Quotes™</a>. The current script does not handle even whitespace in file names, much less newlines or <code>-</code> at the beginning.</li>\n<li>Indent consistently, otherwise it's difficult to follow the code.</li>\n<li>Are you sure you need to initialize the symlink?</li>\n<li><a href=\"http://mywiki.wooledge.org/ParsingLs\" rel=\"nofollow\">Don't parse <code>ls</code> output</a>.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-28T14:19:28.720",
"Id": "26708",
"ParentId": "26320",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "26708",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-18T12:52:15.130",
"Id": "26320",
"Score": "2",
"Tags": [
"bash",
"linux",
"shell",
"unix"
],
"Title": "Bash script to manage multiple Java Development Kits installations"
}
|
26320
|
<p>I wrote a C++ <a href="http://en.wikipedia.org/wiki/Parsing_expression_grammar" rel="nofollow">PEG</a> packrat parser generator and would love to get some feedback on the code and/or syntax. I currently use the <code><<</code> operator for defining grammar expressions and linking the handler functions that are called when a rule is matched. These functions can then store a value of an arbitrary C++ type in the corresponding node of the parse tree using the <code>value<type>()</code> function.</p>
<p>For example, a very simple math parser can be generated through the following source code:</p>
<pre><code>#include "IO.h"
#include "parserTools.h"
#include <cmath> //pow
using namespace llib;
std::map<std::string, double> variables;
void op(parser::info &lhs,parser::info &rhs,parser::info &r,const std::string &op){
if(op[0]=='+') r.value() = lhs.value<double>() + rhs.value<double>() ;
else if(op[0]=='-') r.value() = lhs.value<double>() - rhs.value<double>() ;
else if(op[0]=='*') r.value() = lhs.value<double>() * rhs.value<double>() ;
else if(op[0]=='/') r.value() = lhs.value<double>() / rhs.value<double>() ;
else if(op[0]=='^') r.value() = pow(lhs.value<double>() , rhs.value<double>());
}
void variable(parser::info &s){ s.value<double>()=variables[s.string()]; }
void negate(parser::info &s) { s.value()=-s[0].value<double>(); }
void set(parser::info &s) { variables[s[0].string()]=s[1].value<double>(); }
int main(){
peg::grammar math("Math");
math << "Math" << "Set | Expression" << parserTools::show("%v0\n");
math << "Set" << "Variable '=' Sum" << set << parserTools::pass(1);
math << "Expression" << "Sum" << parserTools::pass();
math << "Sum" << "Product ([+-] Product )*" << parserTools::leftbinary(op);
math << "Product" << "Exponent ([*/] Exponent)*" << parserTools::leftbinary(op);
math << "Exponent" << "Atomic ('^' Atomic )*" << parserTools::leftbinary(op);
math << "Atomic" << "Parentheses | Number | Negate | Variable" << parserTools::pass();
math << "Parentheses" << "'(' Expression ')'" << parserTools::pass();
math << "Negate" << "'-' Atomic" << negate;
math << "Variable" << "[a-zA-Z] [a-zA-Z0-9]*" << variable;
math << "Number" << parserTools::doubleGrammar() << parserTools::pass();
math.ignored=" \t";
math.setStart("Math");
parser p(math);
p.error=parserTools::genericError;
p.warning=parserTools::genericWarning;
while (1) {
std::string str;
IO << "> " >> str << str << " -> ";
if(str=="q") break;
else if(str!="") p.parse(str);
else IO << clearline << endl;
}
return 0;
}
</code></pre>
<p>The full code and documentation is available on <a href="https://github.com/TheLartians/LParser" rel="nofollow">GitHub</a> (though LParser is probably pretty boring name).</p>
<p>So any thoughts on the project? Is it something you would actually use?</p>
|
[] |
[
{
"body": "<pre><code>void op(parser::info &lhs,parser::info &rhs,parser::info &r,const std::string &op){\n</code></pre>\n\n<p>I think I'd prefer a more descriptive name than <code>r</code> here. I'm guessing it's intended to stand for \"result\", in which case I think I'd prefer to just name it <code>result</code>.</p>\n\n<pre><code> peg::grammar math(\"Math\");\n\n math << \"Math\" << \"Set | Expression\" << parserTools::show(\"%v0\\n\");\n</code></pre>\n\n<p>It's not immediately clear why you specify <code>Math</code> both when you create the grammar object <em>and</em> when you specify rules. I think the second is naming the top-level rule <code>Math</code>, but it's not clear what the parameter to the constructor accomplishes.</p>\n\n<pre><code> math << \"Set\" << \"Variable '=' Sum\" << set << parserTools::pass(1);\n</code></pre>\n\n<p>At least without some documentation on your parserTools, the meaning of the <code>pass(1)</code> isn't immediately obvious. Presumably this is (at least roughly equivalent to) a semantic rule that's executed when the associated pattern is matched. I can think of a couple of different things <code>pass(1)</code> might be intended to mean, but lac, context to even guess at which is likely to be accurate. Sufficient study of your documentation would undoubtedly make the meaning clear, but it wasn't immediately obvious.</p>\n\n<p>This is kind of a difficult situation: you're basically defining an EDSL, which means understanding the code pretty much requires learning the language you've defined. In other words, no matter how carefully or well written the code is, it's likely to be at least somewhat difficult to understand in isolation.</p>\n\n<p>Summary: looking at the code in isolation, the grammar rules are highly readable, but the (presumed) associated actions <em>much</em> less so.</p>\n\n<pre><code>math << \"Exponent\" << \"Atomic ('^' Atomic )*\" << parserTools::leftbinary(op);\n</code></pre>\n\n<p>At first glance, I'd have assumed that <code>leftbinary</code> was intended to signify a left-associative binary operator--but exponentiation is normally right-associative. I'm left uncertain whether:</p>\n\n<ol>\n<li>it's a bug,</li>\n<li>you intentionally changed it from right- to left-associative, or </li>\n<li>I've completely misinterpreted what <code>leftbinary</code> really means.</li>\n</ol>\n\n<hr>\n\n<pre><code> while (1) {\n std::string str;\n IO << \"> \" >> str << str << \" -> \";\n</code></pre>\n\n<p>I have mixed feelings about this mixture of input and output in the same expression. It does lead to relatively terse code, but requires unusual care in reading to keep track of which parts are input vs. output.</p>\n\n<p>Ultimately, I think it would probably be better to review the parser generator and the IO library separately. Here I'm really concentrating on the parser generator, but the design if the I/O library might well be worth examination and review in its own right.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-08T17:37:33.867",
"Id": "131692",
"Score": "0",
"body": "Completely right, I forgot about the right-associativeness of the exponentiation operator. I have re-written the project with your input in mind (and ditched the ParserTools concept). I've submitted a new codereview question [here](https://codereview.stackexchange.com/questions/72043/a-header-only-linear-time-c11-peg-parser-generator)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T16:55:28.840",
"Id": "43952",
"ParentId": "26324",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "43952",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-18T16:11:00.363",
"Id": "26324",
"Score": "10",
"Tags": [
"c++",
"parsing"
],
"Title": "A C++ PEG parser generator"
}
|
26324
|
<p>I have written this code to sort a list of numbers, in increasing order. </p>
<p>It is a combination of quick sort, insertion sort, and merge sort. I make the first element of the list a pivot, then I go through the list. If a number is less than or equal to the pivot, I "insert" the number in its <strong>appropriate position</strong> in the left list. Otherwise, it is inserted into right list. After I reach the end of the list I simply merge the left and right lists, since they are already sorted. </p>
<p>I would like to know the time complexity of this sorting method. I believe the best case scenario is \$O(n)\$. What would be the average time?</p>
<pre><code>#lang racket
(define (merge-lists l1 l2)
(cond ((null? l1) l2)
((null? l2) l1)
((<= (car l1) (car l2))
(cons (car l1) (merge-lists (cdr l1) l2)))
(else
(cons (car l2) (merge-lists l1 (cdr l2))))))
(define (insert elem lst)
(if (or (null? lst) (<= elem (car lst)))
(cons elem lst)
(cons (car lst) (insert elem (cdr lst)))))
(define (quick-sorter lst)
(if (null? lst)
'()
(let ((pivot (car lst)))
(letrec ((iter (lambda (l left-l right-l)
(cond ((null? l)
(merge-lists left-l right-l))
((<= (car l) pivot)
(iter (cdr l) (insert (car l) left-l) right-l))
(else
(iter (cdr l) left-l (insert (car l) right-l)))))))
(iter (cdr lst) '() '())))))
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-18T17:33:29.600",
"Id": "26326",
"Score": "4",
"Tags": [
"sorting",
"lisp",
"scheme",
"racket"
],
"Title": "Quick Insert Merge Sort"
}
|
26326
|
<p>Depending on your directory structure you may have name spaced class files in different directories (that isn't really part of the structure, i.e. lib/ or core/).</p>
<p>Symfony ClassLoader is awesome, but I wanted something lightweight. That just solves the problem above, so inspired by other frameworks implementations I did this class.</p>
<p>Yes, it uses PSR-0.</p>
<p>I'd like some improvements on how I can get a better structure, use best practises and just make the class loader get as good as it can be.</p>
<pre><code><?php
namespace MyPro;
class Autoloader
{
/**
*
* @var array
*/
protected $directories = array();
public function loadClass($class)
{
if ($class[0] == '\\') {
$class = substr($class, 1);
}
$class = str_replace(array('\\', '_'), DIRECTORY_SEPARATOR, $class). '.php';
foreach ($this->directories as $directory)
{
if (file_exists($path = $directory . DIRECTORY_SEPARATOR . $class))
{
require_once $path;
return true;
}
}
}
public function register()
{
spl_autoload_register(array($this, 'loadClass'));
}
public function addDirectories($directories)
{
$this->directories = (array) $directories;
}
public function getDirectories()
{
return $this->directories;
}
}
</code></pre>
<p>Example Use:</p>
<pre><code>require_once __DIR__ . '/lib/MyPro/Autoloader.php';
$autoloader = new MyPro\Autoloader();
$autoloader->addDirectories(array(
__DIR__ . '/controllers',
__DIR__ . '/lib',
));
$autoloader->register();
</code></pre>
<p>Example Controller:</p>
<pre><code><?php
namespace Controller;
class Test extends MyPro\Controller
{
public function index()
{
echo 'hello!';
}
}
</code></pre>
<p>--- Is this correct use of namespaces (if you thinking this as some sort of framework)</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-16T20:14:03.567",
"Id": "42699",
"Score": "0",
"body": "please define \"lightweight\""
}
] |
[
{
"body": "<p>One minor improvement would avoid an extra string concatenation while looping over the directories.</p>\n\n<pre><code>public function loadClass($class)\n{\n $class = str_replace(array('\\\\', '_'), DIRECTORY_SEPARATOR, $class). '.php';\n\n if ($class[0] != DIRECTORY_SEPARATOR) {\n $class = DIRECTORY_SEPARATOR . $class;\n }\n\n foreach ($this->directories as $directory)\n {\n if (file_exists($path = $directory . $class))\n ...\n</code></pre>\n\n<p>Note that this assumes a single-character directory separator.</p>\n\n<p>My only quibble with the class, and I understand you want something lightweight, is that there's no checking of the array passed to <code>addDirectories</code>. This shouldn't be too much of a problem since it will fail pretty quick if the parameter isn't an array or contains non-strings, but if that comes later during the execution the error will be harder to spot. I think you'll get a simple \"class not found\" error.</p>\n\n<p>Oh, and the method should be named <code>setDirectories</code> since it removes any existing directories, or it should append them to the existing array.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-18T21:46:51.523",
"Id": "26329",
"ParentId": "26327",
"Score": "2"
}
},
{
"body": "<p>You have a protected member within your class - <code>$directories</code> - which would normally contain the directories that the autoloader looks within when resolving a namespaced class to a file.\nWhen the <code>loadClass()</code> method executes, it iterates through this array.\nThis isn't a PSR-0 valid principle in my opinion, as it does not account for the current directory tree structure or anything within the include path.</p>\n\n<p>When you are adding extra paths that the autoloader should do resolving with, what you're technically doing is changing the include path for the class. A more elegant way to promote this behavior is well, to actually amend the include path:</p>\n\n<pre><code>/**\n * Adds an individual directory to the include path\n * @param string $dir\n */\naddDirectory($dir) {\n // check for a possible duplicate\n if (!strstr(get_include_path(), $dir)) {\n set_include_path(get_include_path() . PATH_SEPARATOR . $dir);\n }\n}\n\n/**\n * Adds multiple directories to the include path\n * @param array $dirs\n */\naddDirectories(array $dirs) {\n foreach($dirs as $dir) {\n $this->addDirectory($dir);\n }\n}\n</code></pre>\n\n<p>Now, when a directory is added, it's actually added to the actual include path for the PHP interpreter for the entire lifetime of the current script's execution. This may not be most efficient way to do it, but it <em>is</em> lightweight. \nNote that I've included two methods: One for single entires and one for multiple ones. This simplifies things, and creates a relationship within your own class. The getters can also be amended to perform similar logic, but I cannot see why one would need to have such methods.</p>\n\n<p>You'll also need to modify your <code>loadClass()</code> method to incorporate this change:</p>\n\n<pre><code>loadClass($class) {\n\n $class = str_replace(array('\\\\', '_'), DIRECTORY_SEPARATOR, ltrim($class, '\\\\')). '.php';\n\n if (!file_exists($class)) {\n throw new RuntimeException(\"Unable to load $class\");\n }\n\n require_once $class;\n}\n</code></pre>\n\n<p>As you'll notice, I've done the following to improve your method:</p>\n\n<ul>\n<li>Removed the if-statement that looks for a namespace separator at the first index of the <code>$class</code> variable. This is unneeded for the scope of this method and is replaced with <code>ltrim($class, '\\\\')</code>.</li>\n<li>Removed the foreach loop: as stated above, the include path has been modified to include the hinted directories. The autoloading procedure will now <em>also</em> look throughout the entire include path as intended for <code>include</code>. </li>\n<li>Modified the if-statement that checks for file existence. Please note that this does not attempt to differentiate directories on *nix filesystems. If the file does not exist, a <code>RuntimeException</code> is thrown. This is a better practice than just doing <em>nothing</em>. The return statement has also been removed, since you'll likely never need or be able to receive it.</li>\n</ul>\n\n<p>See: </p>\n\n<ul>\n<li><a href=\"https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md\" rel=\"nofollow\">https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md</a></li>\n<li><a href=\"http://php.net/manual/en/function.spl-autoload-register.php\" rel=\"nofollow\">http://php.net/manual/en/function.spl-autoload-register.php</a></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-20T20:41:12.013",
"Id": "26384",
"ParentId": "26327",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-18T18:21:13.020",
"Id": "26327",
"Score": "5",
"Tags": [
"php"
],
"Title": "Autoloader class"
}
|
26327
|
<p>I'm trying to solve a SPOJ problem, which is code SAMER08A at <a href="http://www.spoj.com/problems/SAMER08A/" rel="nofollow">this</a> link.</p>
<p>The problem is that when I ran my code in my IDE with all the examples given in the problem, the code works perfectly. But when running it in SPOJ, it exceeds the time limit of 2 seconds.</p>
<p>I am frustrated because I have worked so hard on it. I would love some advice and help.</p>
<pre><code>#include <vector>
#include <iostream>
#include <queue>
using namespace std;
typedef pair <int, int> dist_node;
typedef pair <int, int> edge;
const int MAXN = 500;
const int INF = 1 << 30;
vector <edge> g[MAXN];
int d[MAXN];
vector<int> p[MAXN];
int answer[MAXN];
int last_node;
vector<vector<int> > paths;
int dijkstra(int s, int n,int t){
for (int i = 0; i <= n; ++i){
d[i] = INF; p[s].push_back(-1);
}
priority_queue < dist_node, vector <dist_node>,greater<dist_node> > q;
d[s] = 0;
q.push(dist_node(0, s));
while (!q.empty()){
int dist = q.top().first;
int cur = q.top().second;
q.pop();
if (dist > d[cur]) continue;
for (int i = 0; i < g[cur].size(); ++i){
int next = g[cur][i].first;
int w_extra = g[cur][i].second;
if (d[cur] + w_extra < d[next]){
d[next] = d[cur] + w_extra;
p[next].clear();
p[next].push_back(cur);
q.push(dist_node(d[next], next));
}
else if(d[cur] + w_extra == d[next]){
p[next].push_back(cur);
}
}
}
return d[t];
}
void findpath (int t, int depth){
if(t == 0){
vector<int> camino;
for(int i = depth-1; i >= 0; --i){
camino.push_back(answer[i]);
}
camino.push_back(last_node);
paths.push_back(camino);
return;
}
for(int i = (int)p[t].size()-1; i >= 0; --i){
answer[depth] = p[t][i];
findpath(p[t][i], depth+1);
}
}
void findAlmostShortestPath(){
for(int k = 0; k<paths.size();k++){
vector<int> camino = paths[k];
for(int i = 0;i<camino.size()-1;i++){
int x = camino[i];
int y = camino[i+1];
for(int j = 0; j < g[x].size() ; j++){
if(g[x][j].first == y){
g[x][j].second =INF;
break;
}
}
break;
}
}
}
int main(){
int n,m;
int w,s;
bool seguir = true;
while(seguir){
cin>>n>>m;
cin>>w>>s;
last_node=s;
if(n == 0 & m == 0){
break;
}
for (int i = 0; i < m; ++i){
int u, v, w;
cin >> u >> v >> w;
g[u].push_back(edge(v, w));
}
int i;
i = dijkstra(w, n,s);
findpath(s, 0);
findAlmostShortestPath();
i = dijkstra(w, n, s);
if(i==INF){
i =-1;
}
cout<<i<<endl;
for(int i = 0; i < g[i].size(); i++){
g[i].clear();
}
}
return 0;
}
</code></pre>
<p>I would be so grateful if you could help me since I've worked on this for hours, and it's my first SPOJ problem that I have tried to solve.</p>
|
[] |
[
{
"body": "<p>Here's a partial/basic structured implementation of the problem. It works for the first two cases, but the last case comes back twice as large. I saw this question on SO and thought your version was highly over complicated and probably inefficient due to data structure choices. There isn't any reason to provide and pass around multi-dimensional vectors and such, and there's no doubt you could drop that priority_queue. </p>\n\n<p>Take a look at mine and see if you could simplify yours. Since your logic, I'm assuming, works you should be able to catch the last case without too much effort. I wasn't intending to finish it I just wanted to see if it could easily be done without such complexity. It isn't meant to replace yours, it's just to provide a second opinion on it. </p>\n\n<p>Take a look:</p>\n\n<p>Note: Some of the variable are there because of the problem distription.\n Some validations are missing because the test data didn't require them.</p>\n\n<pre><code>#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing std::cin;\nusing std::cout;\nusing std::vector;\nusing std::sort;\n\nconst int START = 0;\nconst int END = 1;\nconst int DIST = 2;\n\nvector<int> getPaths(int **, int, int, int);\nint getDistance(int **, int , int , int , int , int&);\n\nint main (void)\n{\n\n int input = 0;\n int n = 0, m = 0, s = 0, d = 0, u = 0, v = 0, p = 0; \n int shortestPath = 0;\n int nextShortestPath = 0;\n int **pathPtr;\n vector<int> allDistances;\n\n cin >> n;\n if (n >= 2 && n <= 500) {\n cin >> m;\n if (m >= 1 && m <= 100000) {\n cin >> s;\n cin >> d;\n pathPtr = new int*[m];\n for (int i = 0; i < m; ++i) {\n pathPtr[i] = new int[3];\n }\n for (int i = 0; i < m; ++i) {\n for (int j = 0; j < 3; ++j) {\n cin >> input;\n pathPtr[i][j] = input;\n }\n }\n allDistances = getPaths(pathPtr, m, s, d);\n sort(allDistances.begin(), allDistances.end());\n for (unsigned int i = 0; i < allDistances.size(); ++i) {\n if (allDistances[i] != 0) {\n shortestPath = allDistances[i];\n if (i + 1 < allDistances.size()) {\n nextShortestPath = allDistances[i + 1];\n break;\n } else {\n nextShortestPath = -1;\n break;\n }\n }\n }\n cout << nextShortestPath;\n }\n }\n cin.get();\n return 0;\n}\n\nvector<int> getPaths(int **paths, const int m, const int s, const int d) {\n vector<int> distances;\n int distance = 0;\n int shortest = 0;\n int tempShort = 0;\n for (int i = 0; i < m; ++i) {\n if (paths[i][START] == s) {\n distance = 0;\n if (paths[i][END] == d) {\n distances.push_back(paths[i][DIST]);\n } else {\n distances.push_back(getDistance(paths, i, i + 1, m, d, distance));\n }\n }\n }\n return distances;\n}\n\nint getDistance(int **paths, int i, int j, int m, int d, int &distance) {\n if (paths[j][START] == paths[i][END]) {\n distance += paths[i][DIST];\n if (paths[j][END] != d) {\n if (j < m) {\n distance += getDistance(paths, j, j + 1, m, d, distance);\n } else { \n distance = 0;\n }\n } else {\n distance += paths[j][DIST];\n }\n } else {\n getDistance(paths, i, j + 1, m, d, distance);\n }\n return distance;\n}\n</code></pre>\n\n<p>Let me know if it improved your running time any. Good Luck!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-20T23:04:38.277",
"Id": "40866",
"Score": "0",
"body": "Man, I have tried to fix the code so I can run it in Spoj but it is not wokring for me, can you give me any advice on how to improve my code without actually changing everything? Thanks a lot! :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T23:37:07.437",
"Id": "41052",
"Score": "0",
"body": "Unfortunately if you're not meeting the time constraints you almost have no choice. I think you should ask yourself, \"what is this priority_queue for?\" *It needs to be removed!* There isn't any reason to even care about any priority. The data sets are given starting at 0 and continuing. All paths must start at 0, so those and their paths are the only ones you're interested in. That was more of the point of my example which, by the way, took no time to do. Maybe you should look and see how I'm able to find the shortest path by only following paths that begin with 0."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T04:52:14.267",
"Id": "41063",
"Score": "0",
"body": "I just ran that code with the 3 test cases that they give in the problem, and it doesn't work with the last case :("
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T05:31:53.797",
"Id": "41065",
"Score": "0",
"body": "That's what I said. Read the post again. I just wrote what I was thinking would be an easy way to meet the requirements. You'll have to resolve that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T14:29:18.430",
"Id": "41097",
"Score": "0",
"body": "Oh i'm sorry! Gonna try that man :) Thanks a lot!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T19:33:29.360",
"Id": "41117",
"Score": "0",
"body": "No problem. I believe the issue comes from the last data set having the shortest path as a direct path to the destination and mine doesn't check for that. If you notice it returns exactly twice the actual next shortest distance so I think I should be breaking out somewhere."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-18T23:49:12.247",
"Id": "26330",
"ParentId": "26328",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-18T18:24:21.367",
"Id": "26328",
"Score": "7",
"Tags": [
"c++",
"optimization",
"graph"
],
"Title": "Find almost-shortest path more efficiently"
}
|
26328
|
<p>I am in the process of rewriting in C all the data structures that I learned about a few years ago to increase my understanding of data structures and the C language. The first one I'm doing is singly-linked-lists, and so I'm designing an API for them. I haven't written any of the implementation yet, but I want to get some feedback on my function prototypes to make sure what I'm doing is sensible and logical.</p>
<p>First some remarks:</p>
<ol>
<li><p>I expect that many people will suggest a typedef for the node struct, but this is a personal decision, and I prefer not to typedef structs.</p></li>
<li><p>I am most unsure about my choices for return types and values. I have two functions that return a pointer to the data variable of a removed node. These functions remove the node from the list, save a pointer to the data, and free the node. This means that the user is required to free the data that is returned. Is this bad form? I am unsure about how to do it in such a way that would allow the data to be returned statically, because that would require knowing the size of the data in advance, which cripples the usefulness of the library.</p></li>
<li><p>I want to make the API such that it supports all useful things that can be done with a singly-linked list, one of which is implementing a stack. One thing that bothers me about push/pop operations on a singly linked list is that it seems like some people have the notion in their heads that pushing/popping should only occur at the <em>end</em> of a list. A stack, being a last-in/first-out mechanism (LIFO), is not suited for singly-linked lists if you require that push/pop operations happen at the tail (the end). This is obviously because it would be very inefficient to use the tail instead of the head of the list because the last element can only be reached by traversing the list. The push/pop functions below imitate the behavior of a stack, but the operations happen at the front of the list. Is this a bad design? </p></li>
</ol>
<p>Here is an example of a list with elements:</p>
<p>[SENTINEL]->[0]->[1]->[2]->[3]->NULL</p>
<p>Each node is of type struct node. A struct node is a struct with a data and next field:</p>
<pre><code>struct node {
void *data;
struct node *next;
}
</code></pre>
<p>This implementation will use sentinel nodes to simplify boundary conditions. There is one sentinel node per list, standing at the front of the list.</p>
<p>An empty list contains one sentinel node that points to null, like so:
[SENTINEL]->NULL</p>
<p>A list is of type struct sllist. A struct sllist is has one sentinel field that contains a pointer to the sentinel node:</p>
<pre><code>struct sllist {
struct node *sentinel;
}
</code></pre>
<p>Finally, here is a list of operations and their associated function prototypes (with description):</p>
<pre><code> //create new list:
struct *sllist new_sllist();
//Returns a pointer to a new, empty sllist.
//destroy list:
void destroy_sllist(struct sllist *sllist);
//Frees the memory of the list struct and all associated nodes.
//insert after node:
int sllist_insert_after(struct sllist *sllist, struct *node, void *data);
//Adds a node after the passed node.
//If allocation fails, returns -1, otherwise returns 0.
//prepend node to the list:
int sllist_push(struct sllist *sllist, void *data);
//Adds a node to the front of the list. If allocation fails, returns -1, otherwise returns 0.
//Note that the front of the list is defined to be the first node after the sentinel node.
//extract after node:
void* sllist_extract_after(struct sllist *sllist, struct node *node);
//Removes a node from the linked list, save a pointer to the data, free the node
//(but do not the data itself), and return a pointer to the data so that it can be used.
//If the node doesn't exist in the list, returns NULL.
//extract first node:
void* sllist_pop(struct sllist *sllist);
//Same as extract after node, but restricted to the first node (first node after sentinel.)
//Analogous to sllist_push(), the name sllist_pop suggests usage as a stack.
//destroy after node:
void sllist_destroy_after(struct sllist *sllist, struct node *node);
//Removes from the list the node after the passed node and frees all associated memory.
</code></pre>
<p>Please let me know if anything seems glaringly out-of-place, strange, or poorly designed.</p>
|
[] |
[
{
"body": "<p>You say \"A <code>struct sllist</code> is has one sentinel field that contains a pointer to\nthe sentinel node:\" - does this mean that there is an empty node separate from\nthe <code>sllist</code> instance acting as a 'sentinel'? If so, this would seem unnecessary.\nAnd unless <code>struct sllist</code> is going to hold metadata (such as the end of the list, number of\nelements), I'm not sure that it is really necessary - you can just use a pointer to the first node.</p>\n\n<ul>\n<li><p>On return types, I don't see anything wrong with what you have.</p></li>\n<li><p>For the <code>_after</code> functions, where does the user get the necessary <code>struct\nnode*</code> pointer? None of the functions returns a <code>struct node*</code>. Perhaps you\nhave omitted some functions - such as <code>sllist_find</code> returning a <code>struct\nnode*</code>. Such a function would have to take a compare function as a parameter.\nAlso you are missing an 'append' function.</p></li>\n<li><p>On your question 2, the user must have allocated the data in the first place\nbefore adding it to the list (as you don't know its size) so it is reasonable\nto expect her to free it. Conceivably it might not have been dynamically\nallocated, so you can't safely free it.</p></li>\n</ul>\n\n<p>Do you intend the structs to be opaque (ie. the user doesn't get to see what\nis inside them)? In this case you might need a way to iterate through the\nlist. If the structs are not opaque, you are expecting/allowing the user to\ntraverse the list and to manipulate it without using your functions - this is\nasking for trouble (particularly if you do choose to maintain any metadata) and partially negates the usefulness for the library.</p>\n\n<hr>\n\n<p>Some details: there are a few misplaced stars (<code>new_sllist</code>,\n<code>sllist_insert_after</code>), you have inconsistent naming of <code>new_sllist</code> and\n<code>destroy_sllist</code> (all others start with 'sllist') and <code>new_sllist</code> is missing void\nparameter list.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-19T04:44:50.827",
"Id": "40779",
"Score": "0",
"body": "Well, about the sentinel node:\nI actually realized since I posted this that I should probably make the sllist struct more like this:\n\n`struct sllist {\n struct node *sentinel;\n struct node *tail;\n struct node *current\n unsigned int size;\n }`\n\nThe sentinel node is just a \"dummy\" node that points to the first real node. It is there to allow me to use insert_after to prepend to the list. Do you think it over-complicates things?\n\nAlso, I do want the structs to be opaque.\n\nCan you explain why my stars are wrong?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-19T04:45:48.550",
"Id": "40780",
"Score": "0",
"body": "I realize now that\n`int sllist_insert_after(struct sllist *sllist, struct *node, void *data); `\nshould probably be\n`int sllist_insert_after(struct sllist *sllist, struct node *node, void *data); `\n\nAlso, about the inconsistent naming: perhaps `sllist_create` and `sllist_destroy` would be more fitting?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-19T04:52:00.203",
"Id": "40781",
"Score": "0",
"body": "Also, the sentinel is not a separate instance."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-19T12:23:31.017",
"Id": "40794",
"Score": "1",
"body": "So it sounds as if `sentinel` is misnamed and should be called `head`, if all it does is point to the 1st node. That is not too complicated. `sllist_create/destroy` sound much better. ps. try compiling the header to find the errors :-)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-19T02:41:21.237",
"Id": "26332",
"ParentId": "26331",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-18T23:51:56.163",
"Id": "26331",
"Score": "2",
"Tags": [
"c",
"api",
"linked-list"
],
"Title": "Designing function prototypes for a singly-linked list API in C"
}
|
26331
|
<p>I am extracting data from a text file. Some of the lines from which I want to extract the data consist of a text description with single spaces, followed by a multiple-space gap preceding four fields containing the data, each separated by multiple spaces. A field might either contain the indicator "N/A" or else it will contain an integer < 10,000 (possibly comma-ed) such as 15 or 7,151 followed by a valid percentage in parentheses. The percentage will always have a single decimal point; for example, (0.0%) or (19.8%) or (100.0%) . If the field contains "N/A", then I want to write out "NA,NA" and if the field contains a number and percentage, then I want to write those two values out separated by a comma.</p>
<p>At the moment, I use the following regex to describe a single field:</p>
<pre><code>$naNumberGroup = qr/(N\/A|(([0-9]{1,3}(,[0-9]{3})*) \(([0-9]{1,2}\.[0-9])\%\)))/
</code></pre>
<p>and then the following code to get the various pieces from the current line, which is $line :</p>
<pre><code>if( $line =~ m/$naNumberGroup +$naNumberGroup +$naNumberGroup +$naNumberGroup/ ) {
if("N/A" eq $1) {
print "NA,NA";
} else {
print ",$3,$5";
}
if("N/A" eq $6) {
print ",NA,NA";
} else {
print ",$8,$10";
}
if("N/A" eq $11) {
print ",NA,NA";
} else {
print ",$13,$15";
}
if("N/A" eq $16) {
print ",NA,NA";
} else {
print ",$18,$20";
}
print "\n";
}
</code></pre>
<p>It seems horribly clumsy; for example, it's easy to make a mistake in counting the parentheses and getting the pairs of fields correctly referenced ... but I am unsure of even what sorts of things I should be looking at to improve it (assuming that's possible). I would appreciate some guidance or comment. Even, "it seems fine" would at least indicate that I shouldn't waste time on improving it!</p>
<p>An example line of text is:</p>
<pre><code>Adults who actively pursue work opportunities
197 (82.8%) 30 (12.6%) N/A N/A
</code></pre>
<p>The description at the beginning of the line changes depending on the data. The output that I want for this line is:</p>
<pre><code>197,82.8,30,12,6,NA,NA,NA,NA
</code></pre>
<p>Similarly, if the line were:</p>
<pre><code>Adults who actively pursue work opportunities
197 (82.8%) N/A 30 (12.6%) N/A
</code></pre>
<p>then I want the output:</p>
<pre><code>197,82.8,NA,NA,30,12.6,NA,NA
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-18T11:14:36.623",
"Id": "40784",
"Score": "2",
"body": "Can you provide sample input and expected output ? Also a single improvement to make your regex *shorter* would be to use `\\d` instead of `[0-9]`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-18T11:18:24.600",
"Id": "40785",
"Score": "2",
"body": "Can't you just split the string by `/\\s{2,}+(?!\\()/` pattern, then work with fields as normal arrays? As for groups mismatch, well, you can use named capture groups (with `?<name>` notation)."
}
] |
[
{
"body": "<p>Splitting is much better solution than regex, as someone already mentioned.</p>\n\n<pre><code>my $line = \"197 (82.8%) N/A 30 (12.6%) N/A\";\nmy $result = \n join \",\",\n map {\n tr|()%||d;\n $_ eq \"N/A\" ? qw(NA NA) : $_;\n }\n split /\\s+/, $line;\n\n print \"$result\\n\";\n</code></pre>\n\n<p>gives</p>\n\n<pre><code>197,82.8,NA,NA,30,12.6,NA,NA\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-18T18:16:55.570",
"Id": "40786",
"Score": "0",
"body": "Nice solution - simplifying the problem to: delete excessive characters and replace `N/A` to `NA NA`. Really nice."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-18T12:17:14.263",
"Id": "26334",
"ParentId": "26333",
"Score": "3"
}
},
{
"body": "<p>Using \"split\" is an option as other people have mentioned. However, using a regex has the added benefit of validating the input data while parsing, so is still worth considering depending on your use-case.</p>\n\n<p>A regex is better used in loop here since we're matching the same pattern repeatedly. And you should use non-capturing parentheses for the bits you're not interested in capturing. E.g. changing nothing else your code would look like this:</p>\n\n<pre><code>$naNumberGroup = qr/(N\\/A|(?:([0-9]{1,3}(?:,[0-9]{3})*) \\(([0-9]{1,2}\\.[0-9])\\%\\)))/;\nmy @outFields;\nwhile ($line =~ m/\\s\\s+$naNumberGroup/g) {\n if(\"N/A\" eq $1) {\n push @outFields, 'NA', 'NA';\n } else {\n push @outFields, $2, $3;\n }\n}\nprint join(',', @outfields),\"\\n\";\n</code></pre>\n\n<p>It's worth noting that your code as-is would preserve any commas in the input, therefore breaking your output. And \"100.0%\" isn't handled.</p>\n\n<p>If you're wanting to improve readability and maintainability of your regexes, here are some additional things worth changing:</p>\n\n<ol>\n<li>Use the /x modifier to improve readability/maintainability.</li>\n<li>Use more intermediate variables to build your regexes.</li>\n<li>Avoid having to escape slashes by using <code>qr{...}</code> instead of <code>qr/.../</code></li>\n</ol>\n\n<p>E.g. </p>\n\n<pre><code>my $numberGroup = qr{\n (?<number> [0-9,]+ ) # Number with optional commas\n [ ] # Single space\n \\( (?<percent> [0-9]+\\.[0-9] ) %\\) # Percentage in parens\n}x;\nmy $naNumberGroup = qr{\n [ ]{2,} # Two or more spaces\n (?: $numberGroup | N/A ) # No need to capture \"N/A\"\n}x;\nmy @outFields;\nwhile ($line =~ m/$naNumberGroup/xg) {\n my $number = $+{number} // 'NA';\n my $percent = $+{percent} // 'NA';\n $number =~ tr/,//d; # Strip commas\n push @outFields, $number, $percent;\n}\nif (scalar @outFields == 8) {\n print join(',', @outFields),\"\\n\";\n} else {\n # Description line, or invalid line. You may be able to use\n # another regex to determine which.\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-18T20:49:06.370",
"Id": "40788",
"Score": "1",
"body": "That's what longer regex should always look like! btw, `%` doesn't need backslashing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-18T20:55:35.330",
"Id": "40789",
"Score": "0",
"body": "Thanks - good point re `%` - I've updated the answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-19T05:51:59.767",
"Id": "40790",
"Score": "0",
"body": "Many thanks for all the suggestions. I knew about the 'split' command but have never used it, so the suggestions about how to use it in this context are very educational as well as directly helpful. The suggestions about how to improve the formulation and use of the regex itself are more along the lines of my original expectation, and also very helpful. Thanks again."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-18T20:34:07.600",
"Id": "26335",
"ParentId": "26333",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "26335",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-18T11:10:39.810",
"Id": "26333",
"Score": "2",
"Tags": [
"regex",
"perl"
],
"Title": "Trying to improve a working regex"
}
|
26333
|
<p>Every <code>Account</code> has its owner who is <code>Person</code> The bank has list of owners. I am not sure if my destructors are right and <code>delete bank</code> will delete all elements of <code>list<Account*>* v</code> nad the list itself. Please help.</p>
<pre><code>#include <iostream>
#include <vector>
#include <list>
using namespace std;
class Person{
public:
char* name;
int age;
Person(char* name, int age){
this->name = name;
this->age = age;
}
~Person(){
}
void show(){
cout<<name<<" "<<age<<" yo";
}
};
class Account{
public:
Person& owner;
double money;
Account(Person* owner, double money):
owner(*owner) , // this->owner = *owner;
money(money) { //Uninitialized reference member
}
void show(){
cout<<"\n-------------\n";
owner.show();
cout<<endl;
cout<<money<<"USD\n-------------";
}
~Account(){
}
};
class Bank{
public:
list<Account*>* v;
Bank(){
v = new list<Account*>();
}
Account* openNewAccount(Person* client, double money){
Account* r = new Account(client, money);
v->push_back(r);
return r;
}
void zmienWlasciciela(Person& o, Account* r){
r->owner = o;
}
void usunRachunek(Account* r){
cout<<"\n\n\nUSUNALEM"<<endl;
v->remove(r);
delete r;
}
void show(){
for (list<Account*>::iterator it = v->begin(); it != v->end(); ++it){
(*it)->show();
}
}
~Bank(){
delete v;
}
};
int main(){
Bank* bank = new Bank();
Person* thomas = new Person("thomas", 34);
Account* r1 = bank->openNewAccount(thomas, 64363.32);
Account* r2 = bank->openNewAccount(thomas, 41251.54);
Account* r3 = bank->openNewAccount(thomas, 3232.32);
bank->show();
Person* margaret = new Person("Margaret", 23);
bank->zmienWlasciciela(*margaret, r2);
cout<<"I have changed owner of account r2"<<endl;
bank->show();
cout<<"I have deleted account r3"<<endl;
bank->usunRachunek(r3);
bank->show();
delete bank;
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-19T13:02:24.657",
"Id": "40797",
"Score": "0",
"body": "No, it's wrong. But why on earth are you using a pointer to a `list`?"
}
] |
[
{
"body": "<p>Deleting the vector will only delete the pointers in the vector, not the things to which they point.</p>\n\n<p>You need to iterate though the vector deleting the accounts before deleting the vector.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-19T13:51:20.107",
"Id": "26340",
"ParentId": "26339",
"Score": "0"
}
},
{
"body": "<h2>General Comment on Style</h2>\n\n<p>This is probably not what you want.</p>\n\n<pre><code>Bank* bank = new Bank();\nPerson* thomas = new Person(\"thomas\", 34);\n</code></pre>\n\n<p>You actually want:</p>\n\n<pre><code>Bank bank;\nPerson thomas(\"thomas\", 34);\n</code></pre>\n\n<p>This creates automatic variables. That are properly destroyed automatically at the end of scope.</p>\n\n<p>It is very rare to use RAW pointers in C++ <code>Bank*</code> or <code>Person*</code>. When you dynamically allocate objects using <code>new</code> you want to make sure that the returned pointer is put into an object that controls their lifespan and garbage collects the values when you are finished using them.</p>\n\n<pre><code>std::shared_ptr<Bank> bank = new Bank; // This is the closest to a Java object \n // that C++ has. It allows multiple users\n // and it is correctly destroyed when nobody\n // has a reference to it anymore.\n</code></pre>\n\n<h2>Looking at the code:</h2>\n\n<p>Don't do this:</p>\n\n<pre><code>using namespace std;\n</code></pre>\n\n<p>I know all the shitty C++ books you read have it in. Its fine for 10 line long programs you type out of a book. But once you get past those programs it can cause problems with namespace pollution. Its thus a very bad habit and one you should break as soon as possible. See: <a href=\"https://stackoverflow.com/q/1452721/14065\">https://stackoverflow.com/q/1452721/14065</a></p>\n\n<h3>Person</h3>\n\n<p>Pointers are bad.</p>\n\n<pre><code> char* name;\n</code></pre>\n\n<p>Unless you do a lot of validation and know the ownership of the thing you are pointing at and it is not going to be cleaned up behind you then you should be very weary of using pointers. I have checked your code and you are fine in this simple program but this is not a good design outside of a small toy project. C++ also has its own string type <code>std::string</code> so you don't need to know or use C-String. So I would change this to</p>\n\n<pre><code> std::string name;\n</code></pre>\n\n<p>In constructors prefer to use the initializer list to initialize the members.</p>\n\n<pre><code> Person(char* name, int age){\n this->name = name;\n this->age = age;\n }\n</code></pre>\n\n<p>Second point about pointers here. Its not normal to pass pointers to around in C++ (this is very common in C but modern C++ you should basically never do it (with a few exceptions that you will work out when you have more experience)). Pass objects by reference if you want to retain ownership; otherwise pass a smart_pointer to transfer ownership of the object.</p>\n\n<p>In this case you want to pass a <code>std::string</code>. As you don't want to change the original but make your own copy pass a const reference (if you are in C++11 you may want to also add a move constructor (but this is advanced so don't worry about it)).</p>\n\n<p>So it should look more like:</p>\n\n<pre><code> Person(std::string const& name, int age)\n : name(name)\n , age(age)\n {}\n</code></pre>\n\n<p>If a destructor does not do anything then don't declare it.</p>\n\n<pre><code> ~Person(){\n }\n</code></pre>\n\n<p>Its fine to have a public <code>show()</code> method. But any method that does not change the state of the object should be declared as <code>const</code>. This allows you to call the object from const objects (useful technique later). And if you add a parameter so it can be any stream it makes it more versatile. But you should also declare a stream operator for your Person type. Thus you can stream your person just like any other type.</p>\n\n<pre><code> void show(std::ostream& out = std::cout) const {\n // ^^^^^ Does not change the state\n // so make the method const.\n // ^^^^^^^^^^^^^^^^^ Pass stream to print on.\n // You may want to print in other places.\n // rather than std::cout (like a file).\n\n out<<name<<\" \"<<age<<\" yo\"; // A few spaces to make it readable\n // would be nice.\n }\n\n// Pass person by const reference so the compiler\n// knows you are not going to modify the object.\n// This means you can only call const methods (so `show()` must be const.\nstd::ostream& operator<<(std::stream& stream, Person const& person)\n{\n person.show(stream);\n return stream;\n}\n\nint main()\n{ std::cout << Perons(\"Loki\", 962) << \"\\n\";\n}\n</code></pre>\n\n<h3>Account</h3>\n\n<p>This is fine.</p>\n\n<pre><code>Person& owner;\n</code></pre>\n\n<p>It means you have a reference to a person that is stored somewhere else. But you need to be careful of lifetimes. Make sure the <code>Person</code> object is still alive while you are alive.</p>\n\n<p>Passing by pointer again.</p>\n\n<pre><code>Account(Person* owner, double money):\n</code></pre>\n\n<p>This is dangerous. Especially since you de-reference without checking. Since you are storing a reference. Pass the value in by reference.</p>\n\n<pre><code>Account(Person& owner, double money)\n : owner(owner)\n , money(money)\n{}\n</code></pre>\n\n<p>Make the <code>show()</code> method const and pass a stream.</p>\n\n<pre><code> void show(std::ostream& out = std::cout) const {\n // ^^^^^\n out<<\"\\n-------------\\n\" << owner << std::endl << money<<\"USD\\n-------------\";\n return out;\n}\n</code></pre>\n\n<p>Add a stream operator</p>\n\n<pre><code>std::ostream& operator<<(std::stream& stream, Account const& account)\n{\n account.show(stream);\n}\n</code></pre>\n\n<p>Destructor does nothing so remove it.</p>\n\n<pre><code> ~Account(){\n}\n</code></pre>\n\n<h3>Bank</h3>\n\n<p>Ok. Obviously a java (or java inspired language user).</p>\n\n<pre><code>list<Account*>* v;\n</code></pre>\n\n<p>You don't want to use pointers here. By making this a pointer you need to do all sorts of memory management (and make sure you obey the rule of three (look it up)). But you don't need to do that just make it a normal object and all those problems go away.</p>\n\n<p>list v;</p>\n\n<p>When the bank object is created. It automatically creates a list now. When the bank is destroyed it automatically cleans up its members (including the list). When the back is copied it automatically copies the accounts to the new Bank.</p>\n\n<p>Second; don't make the Account's inside the list pointers. Again you will need to manage the each object and control its lifespan. Much easier to put Account objects into the list.</p>\n\n<p>list v;</p>\n\n<p>There is also a principle called <code>Separation of Concerns</code>. Basically this says that an type should either be <code>Business Logic</code> or <code>Resource Management</code> you should not do both in the same type. Since <code>Bank</code> is obviously business logic you should not be doing resource management in the Bank. If you were using pointers then you would delegate the memory management of those pointers to anther type that would correctly do the clean up. C++ already has a whole bunch of smart pointers explicitly for managing pointers. </p>\n\n<p><strong>BUT</strong> in this situation I would defiantly sidestep the memory management by using automatic objects and make the changes I described above as <strong>ALL</strong> your memory management issues disappear. </p>\n\n<p>Remember use initializer list.</p>\n\n<pre><code>Bank(){\n v = new list<Account*>();\n}\n</code></pre>\n\n<p>But if you change the type as (described above) you don't need to do anything. The object automatically creates and initializes all members.</p>\n\n<p>Again passing pointers is bad: </p>\n\n<pre><code>Account* openNewAccount(Person* client, double money){\n Account* r = new Account(client, money);\n v->push_back(r);\n return r;\n}\n</code></pre>\n\n<p>If you return a pointer <code>Account*</code> you don't specify any ownership semantics. If you don't specify ownership semantics then you are very liable to leak as nobody knows who is supposed to clean up. In this situation the <code>Account</code> obviously belongs to the Bank object (The Bank will do the memory management). So here you should return a reference. This is an indication you can use the account. But the account will be managed by the Bank.</p>\n\n<pre><code>Account& openNewAccount(Person const& client, double money)\n{\n Account newAccount(client, money); // Create a new account.\n v->push_back(newAccount); // Not when you push objects into containers\n // they make a copy of the object.\n // So you have a copy of `newAccount`\n\n\n return v.last(); // return a reference to the last member of `v`\n // that you just pushed there via `push_back`\n // The user can now operate on the referenc\n // Also the reference will never be NULL\n // so the user needs to check for that.\n}\n</code></pre>\n\n<p>Pass by reference. You don't need to check for NULL</p>\n\n<pre><code>void zmienWlasciciela(Person& o, Account* r)\n\n// Becomes.\nvoid zmienWlasciciela(Person& o, Account& r){\n r.owner = o;\n}\n</code></pre>\n\n<p>Pass by reference (that's how it was given to you).</p>\n\n<pre><code>void usunRachunek(Account* r)\n\n// Becomes\nvoid usunRachunek(Account* r){\n cout<<\"\\n\\n\\nUSUNALEM\"<<endl;\n v.remove(r);\n}\n</code></pre>\n\n<p>Make <code>show()</code> const and take a stream</p>\n\n<pre><code>void show(std::ostream& out = std::cout ) const {\nfor (list<Account*>::iterator it = v.begin(); it != v.end(); ++it){\n (*it)->show(out);\n}\n</code></pre>\n\n<p>You could use a simple algorithm to copy the Account to the stream.</p>\n\n<pre><code>void show(std::ostream& out = std::cout ) const\n{\n // for this to work Account must have operator<< defined.\n std::copy(v.begin(), v.end(), std::ostream_iterator(out));\n}\n\n}\n</code></pre>\n\n<p>This is correct <strong>BUT NOT ENOUGH</strong> for your original definition where v is a pointer. If you use objects you don't need to do anything.</p>\n\n<pre><code>~Bank(){\n delete v;\n}\n</code></pre>\n\n<p>If you were using pointers then you also need to define a copy constructor and assignment operator to make sure you are not violating the rule of three. If you are using objects the compiler generated defaults work perfectly fine.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-19T16:10:48.090",
"Id": "26342",
"ParentId": "26339",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-19T12:46:26.037",
"Id": "26339",
"Score": "0",
"Tags": [
"c++"
],
"Title": "Does my classes contain right destructors"
}
|
26339
|
<p>I'm making a WordPress plugin that obfuscates the real file URL and forces the download of one of this 3 types of URL: </p>
<ul>
<li>Local: <code>http://example.com/wp-content/custom/filename.zip</code></li>
<li>Dropbox: <code>https://www.dropbox.com/s/DBOX-KEY/filename.zip?dl=1</code></li>
<li>Google Drive: <code>https://docs.google.com/uc?export=download&id=GDOCS-KEY</code></li>
</ul>
<p>The final URL that's provided to the user has a code which is checked against the database (<code>http://example.com/private/?download_file=SITE-KEY</code>). If correct, there are other checks in place and at the end the file is served through the script below with a <a href="http://php.net/manual/en/function.readfile.php" rel="nofollow"><code>read_file</code></a> to the real URL:</p>
<pre><code>$download_url = "LOCAL-GOOGLE-DROPBOX-URL";
@ob_end_clean(); //turn off output buffering to decrease cpu usage
// required for IE, otherwise Content-Disposition may be ignored
if ( ini_get( 'zlib.output_compression' ) ) ini_set( 'zlib.output_compression', 'Off' );
header( 'Content-Type: ' . $mime);
header( "Content-Disposition: attachment; filename=\"".$final_name."\";" );
header( "Content-Transfer-Encoding: binary" );
header( 'Accept-Ranges: bytes' );
header( "Cache-control: private" );
header( 'Pragma: private' );
header( "Expires: Mon, 26 Jul 1997 05:00:00 GMT" );
flush();
readfile( $download_url );
</code></pre>
<p>I'm inspecting the headers and response and there's no trace of the real URL.</p>
<p>Doubts: </p>
<ul>
<li>Is this really a "secure" method? </li>
<li>Can the real URL be <em>sniffed</em> by other means?</li>
</ul>
<p>For completeness, here are the inspection results for a Google Drive file:</p>
<blockquote>
<pre class="lang-none prettyprint-override"><code>Request URL:http://example.com/private/?download_file=1310819c43
Request Method:GET
Status Code:200 OK
Request Headers
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Host:example.com
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_4) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1366.0
</code></pre>
<p>Safari/537.22 FirePHP/4Chrome
X-FirePHP-Version:0.0.6</p>
<pre class="lang-none prettyprint-override"><code>Query String Parameters
pvdn_file:1310819c43
Response Headers
Accept-Ranges:bytes
Access-Control-Allow-Origin:http://example.com
Cache-control:private
Connection:Keep-Alive
Content-Disposition:attachment; filename="Test File";
Content-Transfer-Encoding:binary
Content-Type:image/png
Date:Sun, 19 May 2013 17:50:00 GMT
Expires:Mon, 26 Jul 1997 05:00:00 GMT
Keep-Alive:timeout=5, max=100
Pragma:private
Server:Apache
Transfer-Encoding:chunked
X-Pingback:http://example.com/xmlrpc.php
X-Powered-By:PHP/5.3.6
</code></pre>
</blockquote>
|
[] |
[
{
"body": "<p>The server is fetching the contents of the URL and then sending it to the user. Unless you accidentally output the URL, via an error or similar, there is no way the user could see it. The server is effectively sitting between them and the remote server.</p>\n\n<p>If you can, it would probably be better to host the files locally otherwise you will be using twice the bandwidth and also have the risk that one of the remote servers might go down.</p>\n\n<p>As long as the user can't specify the remote URL or edit the contents of it, it should be secure.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T12:32:55.467",
"Id": "26421",
"ParentId": "26343",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "26421",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-19T18:01:51.350",
"Id": "26343",
"Score": "1",
"Tags": [
"php",
"security",
"url",
"plugin"
],
"Title": "WordPress plugin for obfuscating a file URL"
}
|
26343
|
<p>I wrote some piece of code which reads and write multiple data structures on a file
using C++. I would be grateful to get your feedback on what you think about the code (it works at least when I tested). Thanks. </p>
<pre><code>#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;
// data structure to be written to a file
struct WebSites
{
char SiteName[100];
int Rank;
}s1,s2,s3,s4;
int _tmain(int argc, _TCHAR* argv[])
{
strcpy(s1.SiteName, "www.ppp.com");
s1.Rank = 0;
strcpy(s2.SiteName, "www.rrr.com");
s2.Rank = 111;
strcpy(s3.SiteName, "www.code.com");
s3.Rank = 123;
strcpy(s4.SiteName, "www.yahoo.com");
s4.Rank = 14;
// write
fstream binary_file("c:\\test.dat",ios::out|ios::binary|ios::app);
binary_file.write(reinterpret_cast<char *>(&s1),sizeof(WebSites));
binary_file.write(reinterpret_cast<char *>(&s2),sizeof(WebSites));
binary_file.write(reinterpret_cast<char *>(&s3),sizeof(WebSites));
binary_file.write(reinterpret_cast<char *>(&s4),sizeof(WebSites));
binary_file.close();
// Read data
fstream binary_file2("c:\\test.dat",ios::binary|ios::in| ios::ate );
int size = binary_file2.tellg();
for(int i = 0; i<size/sizeof(WebSites); i++)
{
WebSites p_Data;
binary_file2.seekg(i*sizeof(WebSites));
binary_file2.read(reinterpret_cast<char *>(&p_Data),sizeof(WebSites));
cout<<p_Data.SiteName<<endl;
cout<<"Rank: "<< p_Data.Rank<<endl;
}
binary_file2.close();
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<p>The trouble with writing binary blobs is that they lead to brittle storage.</p>\n\n<p>The stored objects have a tendency to break over time as the assumptions you make about the hardware no longer hold true (in this case that the <code>sizeof(int)</code> is constant and the endianess of <code>int</code> will not change).</p>\n\n<p>It has become more standard therefore to use a method know as serialization. In this you convert the object to a format that is hardware agnostic (and usually human readable).</p>\n\n<p>Note: Binary blobs have advantages. But you must weigh those against the brittleness. Therefore your first choice should be serialization (unless you have specific requirements that prevents this). Then look at binary Blobs only after you have shown that serialization has too much overhead (unlikely for most situations, but it is a possibility).</p>\n\n<p>In C++ you would do this using the <code>operator<<</code> and <code>operator>></code>.</p>\n\n<p>I would re-write your code as:</p>\n\n<pre><code>struct WebSites\n{\n std::string siteName;\n int rank;\n\n WebSite()\n : siteName(\"\")\n , rank(0)\n {}\n\n WebSite(std::string const& siteName, int rank)\n : siteName(siteName)\n , rank(rank)\n {}\n void swap(WebSites& other) throws()\n {\n std::swap(rank, other.rank);\n std::swap(siteName, other.siteName);\n }\n};\nstd::ostream& operator<<(std::ostream& stream, WebSites const& data)\n{\n stream << data.rank << \" \" \n << data.siteName.size() << \":\" \n << data.siteName;\n return stream;\n}\nstd::istream& operator>>(std::istream& stream, WebSites& data)\n{\n WebSite tmp;\n std::size_t size;\n if (stream >> tmp.rank >> size)\n {\n tmp.siteName.resize(size);\n if (stream.read(tmp.siteName[0], size)\n {\n data.swap(tmp);\n }\n }\n return stream;\n}\n</code></pre>\n\n<p>Now you can write your code like this:</p>\n\n<pre><code>int _tmain(int argc, _TCHAR* argv[])\n{\n WebSite s1(\"www.ppp.com\", 0); \n WebSite s2(\"www.rrr.com\", 111);\n WebSite s3(\"www.code.com\", 123);\n WebSite s4(\"www.yahoo.com\", 14);\n\n // write\n fstream binary_file(\"c:\\\\test.dat\",ios::out|ios::binary|ios::app);\n binary_file << s1 << s2 << s3 << s4;\n binary_file.close();\n\n // Read data\n fstream binary_file2(\"c:\\\\test.dat\",ios::binary|ios::in| ios::ate );\n WebSites p_Data;\n while(binary_file2 >> p_Data)\n { \n cout << p_Data.SiteName << endl;\n cout << \"Rank: \"<< p_Data.Rank << endl;\n }\n binary_file2.close();\n\n // Read data into a vector\n fstream binary_file3(\"c:\\\\test.dat\",ios::binary|ios::in| ios::ate );\n std::vector<WebSites> v;\n\n std::copy(std::istream_iterator<WebSites>(binary_file3),\n std::istream_iterator<WebSites>(),\n std::back_inserter(v)\n );\n binary_file3.close();\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-20T13:07:16.260",
"Id": "40825",
"Score": "0",
"body": "thanks I will study your code a bit later though."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-17T09:49:31.367",
"Id": "42733",
"Score": "0",
"body": "Hey Loki, what you described is serialization right? Do you have some links which explain this concept further?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-24T14:23:27.330",
"Id": "43205",
"Score": "0",
"body": "Loki I asked a question related to your suggestion above: http://stackoverflow.com/questions/17277070/doing-serialization-using-streams-c -- your feedback would be very useful. thanks"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-24T22:24:30.550",
"Id": "43234",
"Score": "0",
"body": "@user1999360: Yes this is serialization."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-25T09:07:00.663",
"Id": "43259",
"Score": "0",
"body": "Loki, what would you do if the struct `Websites` had one member variable of type `std:string` and other member variable of type `std:wstring`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-25T23:25:54.040",
"Id": "43297",
"Score": "0",
"body": "I would serialize both to UTF-8 for transport. Personally I serialize strings by prefixing with the byte length. Thus making deserialization easy. Then you convert the UTF-8 back to std::string and std::wstring a simple conversion to your internal representation."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-01-07T10:36:21.653",
"Id": "215512",
"Score": "1",
"body": "+1 for \"Binary blobs have advantages. But you must way those against the brittleness.\" I have several situations where I absolutely need data in a particular per-byte format, but it's definitely not the norm for most programmers using basic (non-byte) types."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-20T01:46:10.787",
"Id": "26351",
"ParentId": "26344",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-19T20:12:22.463",
"Id": "26344",
"Score": "5",
"Tags": [
"c++",
"file"
],
"Title": "Writing/reading data structure to a file using C++"
}
|
26344
|
<blockquote>
<p><strong>Note #2</strong>: This was a post from a while back. Although the top rated answer is <em>useful</em> (generally), I'm looking for something more specific to this issue including routing / architecture. I've even tried a bounty, which failed. As I don't have enough rep to keep adding bounties, I'll leave it open until someone decides to post :)</p>
<p><strong>Note #1</strong>: My code currently works well and I've progressed further than this - however I feel that this router is, frankly, crap, and I'm looking for honest opinions and constructive criticism.</p>
</blockquote>
<p>I'm in the process of creating my own framework for educational purposes, and for fun! This question pertains to the routing of my application using the front controller pattern.</p>
<h2>.htaccess</h2>
<p>Every request hits my .htaccess file which, using Apache's <code>mod_rewrite</code>, routes all requests through to my index.php file using <code>?url=</code>.</p>
<pre><code><IfModule mod_rewrite.c>
# -------------------------------------------------------------------------
# This file forwards all requests through to index.php as long as the
# request is not for a file or directory. This uses ?url and index.php
# internally, so any requests including these add an __iserror=1 which the
# framework picks up in the routing and redirects to a 404 error page.
# -------------------------------------------------------------------------
# Turn mod_rewrite on (please make sure it's enabled in Apache)
RewriteEngine On
# Block direct access to "index.php" and query strings with "?url="/"&url="
RewriteCond %{QUERY_STRING} !^__iserror=1$
RewriteCond %{THE_REQUEST} ^(\S+)\ +/(\S+)\/index\.php\b [OR]
RewriteCond %{THE_REQUEST} (?:&|\?)url=
RewriteRule .* /framework/index.php?__iserror=1 [L]
# As long as we're not requesting access to a file...
RewriteCond %{REQUEST_FILENAME} !-f
# And we're also not requesting access to a directory...
RewriteCond %{REQUEST_FILENAME} !-d
# Route everything through /framework/index.php
RewriteRule .* /framework/index.php?url=$0 [L,QSA]
# -------------------------------------------------------------------------
</IfModule>
</code></pre>
<p>So the .htaccess passes the request to index.php with <code>?url=<request></code>, and an optional <code>is_error=1</code> set if a user has manually appended <code>?url=</code> or <code>&url=</code> into the url as a GET parameter.</p>
<h2>The Router</h2>
<p>The code I'm showing here is <strong>not</strong> for the actual dispatching of the request to the correct controller / method - it's for the <em>parsing</em> of the request to get the actual data. This is where I am foremost looking for suggestions.</p>
<pre><code>/**
* Parses URL for routing purposes. Shows 404 if __iserror found in URL.
* Sets up default controller and action is none specified. Also handles
* any user defined routes in Core/CustomRoutes.php
*
* @return \Core\Router Instance of self for method chaining
*/
public function resolvePath()
{
/** __isserror check **/
/** Passed in via htaccess if URL contains index.php or ?url= **/
if (!empty($_GET['__iserror']))
{
header("HTTP/1.0 404 Not Found");
include('404.php');
exit();
}
$qs = $_SERVER['QUERY_STRING'];
/** If no controller requested, use defaults **/
if (empty($qs))
{
/** If already logged in, use dashboard controller **/
if (\Models\Session::checkSession())
{
$controller = Config::$defaultLoggedInController;
}
else
{
$controller = Config::$defaultController;
}
$action = Config::$defaultAction;
}
/** Strip out any GET vars **/
if (!empty($qs))
{
$query = explode('&', $qs);
/** Remove url if exists **/
foreach ($query as $key => $q)
{
if (strstr($q, 'url='))
{
unset($query[$key]);
}
}
/** Remove getVars from $query (not $qs, used elesewhere) **/
$remove = implode('&', $query);
if ($remove !== '')
{
$remove = sprintf('%s%s', '&', $remove);
$qs = str_replace($remove, '', $qs);
}
$getVars = array();
foreach ($query as $pair)
{
if (strstr($pair, '='))
{
list($key, $value) = explode('=', $pair);
$getVars[$key] = $value;
}
}
$this->getVars = $getVars;
/** Parse for controller / action **/
$request = array_filter(explode('/', $qs));
/** Only Controller Specified **/
if (count($request) === 1)
{
$controller = str_replace('url=', '', $request[0]);
$action = Config::$defaultAction;
}
/** Controller & Action Specified **/
if (count($request) >= 2)
{
$controller = str_replace('url=', '', array_shift($request));
$action = array_shift($request);
/** Remaining Params **/
if ($request)
{
foreach ($request as $param)
{
$this->params[] = $param;
}
}
}
}
/** Are there any user defined routes? If so, parse for them **/
/** Note: This is just a file containing an array, and it allows
/login to be mapped to /home/login, for example **/
if (isset($_SERVER['REDIRECT_URL']))
{
$customRoute = str_replace(PATH_ROOT, '', $_SERVER['REDIRECT_URL']);
if (array_key_exists($customRoute, customRoutes()))
{
$customRoute = array_values(array_filter(explode('/', customRoutes()[$customRoute])));
$controller = isset($customRoute[0]) ? $customRoute[0] : false;
$action = isset($customRoute[1]) ? $customRoute[1] : false;
}
}
/** Finally, set everything up at the end **/
$this->controller = $controller;
$this->action = $action;
/** Allow Method Chaining **/
return $this;
}
</code></pre>
<p>Hopefully the comments I placed are useful - they're pretty self explanatory. I want to know if there's a better way of getting from request to <code>$this->controller</code> / <code>$this->action</code>.</p>
<h2>Main Questions</h2>
<p>Firstly, the bloody thing is massive, and there are already issues with GET parameters in this (I have added to this code over time and not really properly re-factored it, so now it's just a mess). If I add <code>?x=</code> to the url, I get a missing <code>$controller</code> and missing <code>$action</code> PHP error. I know I can fix this, but it feels like it'll just be a patch, and I really think the thing needs being written properly.</p>
<p>Before I get on with the rest of the framework (currently implementing a proper dependency injection container and making the whole thing very modular / easily testable), I <em>really</em> want to get this working properly.</p>
<p>Any suggestions, criticisms or even complete overhauls (within reason) will be very welcome.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-20T10:26:29.650",
"Id": "40813",
"Score": "0",
"body": "Split it up in more functions."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-20T10:32:07.020",
"Id": "40815",
"Score": "0",
"body": "That's it? Any suggestions on the functions?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-20T11:24:19.450",
"Id": "40817",
"Score": "0",
"body": "It's just a comment not an Answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-20T11:30:10.290",
"Id": "40818",
"Score": "0",
"body": "@AlucardTheRipper Of course. So, in response to your comment, any suggestions on the functions (i.e. what for, etc)."
}
] |
[
{
"body": "<p>The first thing I notice is that you are using the superglobals directly in your class. Normally you want to inject a request object into the class which contains all the info about the request.</p>\n\n<p>The next thing I notice is the use of static methods, e.g.:</p>\n\n<pre><code>\\Models\\Session::checkSession()\n</code></pre>\n\n<p>and</p>\n\n<pre><code>Config::$defaultLoggedInController\n</code></pre>\n\n<p>Which not only makes you method / class hard to test, but also hard to maintain both for somebody else as for the future you. It makes it very hard to see the class / method has those dependencies by looking at the signatures.</p>\n\n<p>I think if you leave the request parsing to your request object you not only clean up this method / class, but you are also following <a href=\"http://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow\">SRP</a> better.</p>\n\n<p>In general it would be nice to <a href=\"http://nikic.github.io/2011/12/27/Dont-be-STUPID-GRASP-SOLID.html\" rel=\"nofollow\">GRASP</a> <a href=\"http://en.wikipedia.org/wiki/SOLID_%28object-oriented_design%29\" rel=\"nofollow\">SOLID</a>. To improve both readability and maintainability.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-20T11:49:08.787",
"Id": "40819",
"Score": "0",
"body": "From what you're saying, I need to do the following?:\n\n(1) Pass in the $_SERVER superglobal to the class via DI. \n(2) Pass in the defaults via DI.\n(3) Do *something* ?? with the Session Model... (also pass it in via DI, and lose the 'static')\nIf these are all correct, apart from the aforementioned architectural differences, is there anything code-wise specifically for the parsing you could suggest / help clean up? :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-20T11:58:06.667",
"Id": "40820",
"Score": "1",
"body": "You shouldn't pass in the `SERVER` superglobal directly, but an instance of a request class. Also I don't get why you would want to parse the querystring manually when your request class can simply leverage the `$_GET` superglobal."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-20T11:41:28.000",
"Id": "26360",
"ParentId": "26345",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "26360",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-19T20:46:08.460",
"Id": "26345",
"Score": "3",
"Tags": [
"php",
"mvc",
"url-routing"
],
"Title": "PHP MVC - Custom Routing Mechanism"
}
|
26345
|
<p><a href="http://projecteuler.net/problem=5" rel="nofollow">Project Euler problem 5</a> asks:</p>
<blockquote>
<p>What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?</p>
</blockquote>
<p>I'm learning Ruby by going through Project Euler problems, and though I got the following code right (as in the answer given by it), I'm not sure if I'm doing things quite the "Ruby way". Hence, I wanted the community's opinion of my code to better understand alternatives to my code (using the same algorithm please!), so that I don't become used to writing "C++ using Ruby!"</p>
<pre><code>def prime? x
(2..x-1).each { |y| return false if x % y == 0 }
true
end
def primes_upto n
p = Array.new
(2..n-1).each {|x| p.push(x) if prime? x}
return p
end
upto = 20 # The upper limit of the LCM range
primes = primes_upto upto
range = Array.new(upto) {|i| i + 1}
lcm = 1
primes.each do |i|
flag = true
while flag and range.length > 0
range.each do |x|
if x % i == 0
flag = true
break
else
flag = false
end
end
if flag
lcm *= i
range.map! {|y| y % i == 0? y/i : y}
end
range.delete(1)
range.compact!
end
end
print "\nLCM of 1..", upto, " = ", lcm
</code></pre>
<p>In particular, I would like to take advantage of ruby's built-in operators on Array, to reduce the size of the code, as well as make it less of an if-then, while structure that I've seen in C++ programs. </p>
<p>The algorithm I've used can be found <a href="http://en.wikipedia.org/wiki/Least_common_multiple#A_method_using_a_table" rel="nofollow">here</a> (if its not obvious from the code!)</p>
|
[] |
[
{
"body": "<p>Definitely your code looks like C directly translated to Ruby. Let's refactor the first two methods:</p>\n\n<pre><code>def prime?(n)\n (2..n-1).none? { |x| n % x == 0 }\nend\n\ndef primes_upto(n)\n (2..n-1).select { |x| prime?(x) }\nend\n</code></pre>\n\n<p>Of course <code>prime?</code> should be checking only 2 and odd numbers until <code>sqrt(x)</code> as candidates. Although you probably should be using the library in the core: <a href=\"http://www.ruby-doc.org/stdlib-1.9.3/libdoc/prime/rdoc/Prime.html\" rel=\"nofollow\">Prime</a>.</p>\n\n<p>Calculating the <code>lcd</code> using a table is a possible way to do it, granted, but having the standard formula <code>lcm(a, b) = a * b / gcd(a, b)</code>, and <code>gcd</code> being easily calculated with <a href=\"http://en.wikipedia.org/wiki/Euclidean_algorithm\" rel=\"nofollow\">Euclides algorithm</a>, well, I don't see why you'd choose that other way. </p>\n\n<p>Anyway, note that to get the <em>lcm</em> of three numbers you can do <code>lcm(a, b, c) = lcm(a, lcm(b, c))</code> (you get the idea for <em>N</em> numbers), and since Ruby >= 1.9 has <a href=\"http://ruby-doc.org/core-2.0/Integer.html#method-i-lcm\" rel=\"nofollow\">Integer#lcm</a>, you could simply write a left fold of the range:</p>\n\n<pre><code>(1..20).reduce(:lcm) #=> 232792560\n</code></pre>\n\n<p>BTW, that's how you could implement <code>Integer#lcm</code> in 1.8, a direct translation of the formulas:</p>\n\n<pre><code>class Integer\n def gcd(b)\n b == 0 ? self : b.gcd(self % b)\n end\n\n def lcm(b)\n (self * b) / self.gcd(b) \n end\nend\n</code></pre>\n\n<p>A final advice: project-euler is about maths. When doing maths you should try to use expressions (functional programming) instead of statements and change of state (imperative programming). Try to do these problems without any of these: <code>each</code>, <code>var = some_initial_value</code>, <code>push</code>, <code>bang_methods!</code>, <code>break</code>, <code>return</code>, <code>*=</code>, <code>+=</code>, <code>delete</code>, <code>while</code>, ... Instead, you should be using: <code>map</code>, <code>select</code>, <code>reduce</code>, <code>detect</code>, <code>zip</code>, <code>any?</code>, <code>all?</code>, <code>flatten</code>, <code>take_while</code>, <code>lazy</code> (Ruby 2.0)... More on <a href=\"https://code.google.com/p/tokland/wiki/RubyFunctionalProgramming\" rel=\"nofollow\">functional programming with Ruby</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-20T01:47:21.770",
"Id": "40804",
"Score": "0",
"body": "I seem to be getting the following error in Ruby 1.8, when running the last line in irb:\n>> (1..20).reduce(:lcm)\nNoMethodError: undefined method `lcm' for 1:Fixnum\n from (irb):1:in `reduce'\n from (irb):1:in `each'\n from (irb):1:in `reduce'\n from (irb):1"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-20T07:54:22.910",
"Id": "40811",
"Score": "0",
"body": "@TCSGrad. This method was added in Ruby 1.9. Are you using 1.8 for some reason? it's ancient... anyway, I'll add an implementation to the answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-20T15:41:38.090",
"Id": "40841",
"Score": "0",
"body": "I have the second edition of the Pickaxe book, which covers Ruby 1.8 - in addition, the default version of the Ruby in my system is 1.8 - so, didn't bother upgrading *both* of them :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-20T15:42:39.283",
"Id": "40843",
"Score": "0",
"body": "I'm glad you edited the answer - the final paragraph *is* the kind of feedback I was hoping for!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-20T22:19:48.123",
"Id": "40864",
"Score": "0",
"body": "`require 'prime'` enables `Prime.each(20) do |i|;flag = true;#etc`. No need to implement `prime?` (`11.prime?` works) or `primes_upto`."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-19T22:32:52.507",
"Id": "26347",
"ParentId": "26346",
"Score": "7"
}
},
{
"body": "<p>In Ruby, you can use this magic:</p>\n\n<pre><code>ns=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]\n\nputs ns.inject(:lcm)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T22:08:07.923",
"Id": "64083",
"Score": "0",
"body": "could you please elaborate?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T08:08:38.683",
"Id": "64117",
"Score": "1",
"body": "Why not `(1..20).inject(:lcm)`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-03T08:46:26.640",
"Id": "64122",
"Score": "0",
"body": "Ofcourse you can use range."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T21:24:01.687",
"Id": "38450",
"ParentId": "26346",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "26347",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-19T21:35:40.960",
"Id": "26346",
"Score": "4",
"Tags": [
"ruby",
"project-euler"
],
"Title": "Lowest Common Multiple of 1 to n in Ruby"
}
|
26346
|
<p>The idea behind this is mainly educational but I might even consider using it in reality if turns out to be good. Here's my first try at implementing smart pointers:</p>
<pre><code>template<typename T>
class smart_pointer{
T* pointer;
std::size_t *refs;
void clear(){
if (!--*refs){
delete pointer;
delete refs;
}
}
public:
smart_pointer(T* p = NULL)
: pointer(p), refs(new std::size_t(1))
{}
smart_pointer(const smart_pointer<T>& other)
: pointer(other.pointer), refs(other.refs)
{
++*refs;
}
~smart_pointer(){
clear();
}
smart_pointer<T>& operator=(const smart_pointer<T>& other){
if (this != &other){
clear();
pointer = other.pointer;
refs = other.refs;
++*refs;
}
return *this;
}
smart_pointer<T>& operator=(T* p){
if (pointer != p){
pointer = p;
*refs = 1;
}
return *this;
}
T& operator*(){
return *pointer;
}
const T& operator*() const{
return *pointer;
}
T* operator->(){
return pointer;
}
const T* operator->() const{
return pointer;
}
std::size_t getCounts(){
return *refs;
}
};
</code></pre>
<p>I have tested this under valrind and its clean. Also, to see how much the "smartness" makes things slower, I did the following test:</p>
<pre><code>struct foo{
int a;
};
template<typename pointer_t>
class bar{
pointer_t f_;
public:
bar(foo *f)
:f_(f)
{}
void set(int a){
f_->a = a;
}
};
int main()
{
foo *f = new foo;
typedef smart_pointer<foo> ptr_t;
// typedef boost::shared_ptr<foo> ptr_t;
// typedef foo* ptr_t;
bar<ptr_t> b(f);
for (unsigned int i = 0; i<300000000; ++i)
b.set(i);
// delete f;
return 0;
}
</code></pre>
<p>Here is some timing between my implementation, boost, and raw pointers: (code compiled with <code>clang++ -O3</code>)</p>
<pre><code>typedef smart_pointer<foo> ptr_t;
real 0m0.006s
user 0m0.001s
sys 0m0.002s
typedef boost::shared_ptr<foo> ptr_t;
real 0m0.336s
user 0m0.332s
sys 0m0.002s
typedef foo* ptr_t;
real 0m0.006s
user 0m0.002s
sys 0m0.003s
</code></pre>
<p>My implementation seems to be running almost as fast as raw pointers, which I think is a good sign. What worries me here is why Boost is running slower. Have I missed something in my implementation that is important and I might get into trouble for later?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-03-27T07:58:48.420",
"Id": "153257",
"Score": "0",
"body": "I have a question regarding incrementing the count. what if the smart pointer sp was originally pointed to something else, and you do a sp=sp1. In this case you need to decrease the old count first."
}
] |
[
{
"body": "<blockquote>\n <p>So the idea behind this is mainly educational...</p>\n</blockquote>\n\n<p>Cool. Always good to try and understand how things work under the covers.</p>\n\n<blockquote>\n <p>...but I might even consider using it in reality if turns out to be good.</p>\n</blockquote>\n\n<p>Please rethink this. Smart pointer implementations are <strong>incredibly</strong> difficult to get right. Scott Myers, of <em>Effective C++</em> fame, famously tried to implement a <code>shared_ptr</code>. After feedback from something like 10 iterations, it was <strong>still wrong</strong>.</p>\n\n<p>Let's go through a few things here.</p>\n\n<pre><code>smart_pointer(T* p = NULL)\n : pointer(p), refs(new std::size_t(1))\n</code></pre>\n\n<p>This constructor should be <code>explicit</code> to avoid implicit type conversions through construction.</p>\n\n<p>Your <code>operator=(T* p)</code> leaks. Here's a small example:</p>\n\n<pre><code>int main()\n{\n int *x = new int(5);\n {\n smart_pointer<int> sp(x);\n sp = new int(6);\n } // sp destroyed here \n\n std::cout << *x << \"\\n\"; // This should have been deleted but wasn't\n}\n</code></pre>\n\n<p>To convince yourself that this is the case, modify your <code>clear()</code> method:</p>\n\n<pre><code>void clear(){\n if (!--*refs){\n std::cout << \"deleteting \" << *pointer << \" at \" << pointer << \"\\n\";\n delete pointer;\n delete refs;\n }\n}\n</code></pre>\n\n<p>This will print out \"deleting 6 at <code><some memory address></code>\". </p>\n\n<p>Here's just a small rundown of what <code>boost::shared_ptr</code> (or <code>std::shared_ptr</code>) provides that is missing here:</p>\n\n<ul>\n<li>Constructors allowing a <code>Deleter</code>, which is used instead of a raw <code>delete</code>.</li>\n<li>Constructor allowing construction from <code><template Tp1> shared_ptr(Tp1 * ...)</code> where <code>Tp1</code> is convertible to type <code>T</code>.</li>\n<li>Copy constructor allowing construction from a <code>shared_ptr</code> with convertible template type <code><T1></code>. </li>\n<li>Copy constructor taking <code>weak_ptr</code>, <code>unique_ptr</code>.</li>\n<li>Move constructor and assignment operator.</li>\n<li>Usage of <code>nothrow</code> where it is required to be.</li>\n<li><code>reset</code>, which will replace the currently managed object.</li>\n<li>All the non-member operators like <code>operator<</code>, <code>operator==</code>, etc that allow containers and algorithms to work correctly. For example, <code>std::set</code> will not work correctly with your pointer class, neither will things like <code>std::sort</code>. </li>\n<li>A specialization of <code>std::swap</code>.</li>\n<li>A specialization of <code>std::hash</code>. Your pointer class won't work correctly with <code>std::unordered_set</code> or <code>std::unordered_map</code>. </li>\n<li>explicit operator bool conversion for <code>nullptr</code> tests, so that one can write <code>if (<some_shared_ptr>) { ... }</code>.</li>\n<li>Utility functions like <code>std::make_shared</code> which you should pretty much always use when creating a <code>shared_ptr</code>.</li>\n</ul>\n\n<p>The big pain point, and the reason why <code>boost::shared_ptr</code> or <code>std::shared_ptr</code> will be slower is the fact that they are thread-safe. Your <code>smart_ptr</code> when accessed by multiple threads could very easily delete the pointer it holds before another class is done with it, leading to dereferencing of a <code>delete</code>d object, and thus undefined behaviour. Furthermore, all of the <code>atomic</code> operations are specialized for <code>shared_ptr</code>.</p>\n\n<p>The above is not an exhaustive list.</p>\n\n<p>I don't write this to discourage you, but merely to try and reinforce the fact that writing something like this is a lot of work. It is very technical, and really, really easy to get wrong. In terms of the standard library, <code>shared_ptr</code> may be one of the most difficult things to write correctly.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-05T09:05:38.837",
"Id": "49015",
"Score": "1",
"body": "I think we should hold an \"everyone write a shared pointer day\"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-03T17:10:43.820",
"Id": "68744",
"Score": "5",
"body": "I would like to add that OP's implementation allocates the reference counter on the heap separately from the subject data. This can (if used very frequently) be a source of memory fragmentation, it is generally good to avoid small heap allocations not to mention the overhead of allocating 4 bytes is like 32 bytes or something. Also if the subject data and reference counter would be allocated together in a struct one would get better data locality and improved cache behavior. These two reasons are the reasons why std::make_shared<>() exists and is preferred for creation of smart pointers."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-20T03:58:06.277",
"Id": "26356",
"ParentId": "26353",
"Score": "33"
}
}
] |
{
"AcceptedAnswerId": "26356",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-20T02:34:14.580",
"Id": "26353",
"Score": "27",
"Tags": [
"c++",
"memory-management",
"pointers",
"boost"
],
"Title": "Efficient smart pointer implementation in C++"
}
|
26353
|
<p>I'm relatively new to jQuery and am trying to learn best practices/design patterns with JavaScript. Came across <a href="http://addyosmani.com/resources/essentialjsdesignpatterns/book/" rel="nofollow">this link</a> and decided to try and put it to something useful.</p>
<p>So far I've made a notifications menu dropdown using <a href="http://baijs.nl/tinyscrollbar/" rel="nofollow">TinyScrollBar</a> where the user can remove an individual notification. Once removed, the height of the dropdown updates until there are no more.</p>
<p><a href="http://jsfiddle.net/pSpBM/3/" rel="nofollow">Here</a> is a demo of what I have so far.</p>
<p>I would like to know ways on how I can improve my JavaScript.</p>
<p>JS</p>
<pre><code>var TEST = TEST || {};
/* Notifications */
TEST.notif = {};
TEST.notif._notifOpen = false;
TEST.notif._el = null;
TEST.notif._sum = 0;
TEST.notif._defaultVPHeight = 350;
TEST.notif.init = function(){
this._el = $('#notifications');
$('.notif-trigger').on('click',function(e){
TEST.notif.toggleNotifications();
return false;
});
// when you click outside the notification menu
// hide the notifications
$('html').on('click',function(e){
if( TEST.notif._notifOpen ) {
TEST.notif.hideNotifications();
}
});
// set initial notifications scrollbar height
this._el.tinyscrollbar( {size: TEST.notif._defaultVPHeight} );
};
TEST.notif.showNotifications = function(){
var $el = this._el,
$close = $('.notif-close'),
$li = $('.notif-list li a');
// show notificatoins and update scrollbar position
$el.show().tinyscrollbar_update();
// stop propagation
$li.on('click',function(e){ e.stopPropagation(); });
// remove list-item
$close.on('click', function(e){
// store
var liHeight, newH, overviewH;
// store individual list-item height
liHeight = $(this).parent().height();
// remove the list-item you clicked
$(this).parent().remove();
// store the new height TEST the viewport
newH = TEST.notif._defaultVPHeight - liHeight;
// get height TEST actual contents
overviewH = $('.overview').height();
// set new defaultH
TEST.notif._defaultVPHeight = newH;
// update scrollbar
$el.tinyscrollbar_update();
// once scrollbar is disabled, start changing the viewport height
if( $('#notifications .scrollbar').hasClass('disable') && $('.notif-list li').length > 1 ){
$('#notifications .viewport').height( overviewH );
} else if( $('.notif-list li').length == 1 ) {
$('.notif-list li.empty').show();
}
return false;
});
this._notifOpen = true;
};
TEST.notif.hideNotifications = function(){
this._el.hide();
this._notifOpen = false;
};
TEST.notif.toggleNotifications = function(){
this._notifOpen ? this.hideNotifications() : this.showNotifications();
};
/* init */
$(document).ready(function(){
TEST.notif.init();
});
</code></pre>
|
[] |
[
{
"body": "<p>From a once over:</p>\n\n<ul>\n<li><p>Review your comments, some of them just take up space and are not very valuable:</p>\n\n<pre><code>// update scrollbar\n$el.tinyscrollbar_update();\n</code></pre></li>\n<li>Indentation ( this might be because of copy pasting ) is off in your code, making it hard(er) to read</li>\n<li><code>TEST.notif</code> is a mouthful, I would just go for <code>notifications</code></li>\n<li><code>_el</code>, <code>_sum</code>, <code>_defaultVPHeight</code> should all loose their underscore, they dont make sense. Also I would go either for the Spartan <code>e</code> or the full out <code>element</code>.</li>\n<li><code>TEST.notif._notifOpen</code> -> why <code>notifOpen</code>, it's already part of an object called <code>notif</code>, just call it <code>open</code></li>\n<li>Use lowerCamelCase consistently: <code>tinyscrollbar_update</code> -> <code>tinyScrollbarUpdate</code></li>\n</ul>\n\n<p>Other than that, your code is well structured and easy to follow.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T19:34:18.833",
"Id": "47178",
"ParentId": "26355",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-20T03:27:06.717",
"Id": "26355",
"Score": "4",
"Tags": [
"javascript",
"jquery",
"design-patterns"
],
"Title": "Notifications dropdown with TinyScroll"
}
|
26355
|
<p>I have a producer consumer that simulates the interaction of threads controlling a hardware device. </p>
<p>I have 1 thread controlling the device, 1 thread reading, and 1 thread outputting. The read is synchronous on the thread while the controlling is asynchronous. </p>
<p>My producer is the thread controlling the device and my consumer is a thread that processes the data. Often the consumer takes about the same amount of time as the producer (ideal), but sometimes it takes more time.</p>
<p>The hope is that the producer should not produce more than the consumer can process. This is partly due to hardware overflow, the consumer will free a buffer on the device, and partly due to visual latency.</p>
<p>I think the producer should be responsible for regulating the rate of production. I implemented this regulation using a sleep timeout.</p>
<p><strong>I am wondering if this is the best way to do it.</strong></p>
<p>My heuristic for success is the time output of the redraw command, which should be roughly <code>ConsumerTime*8</code> (maybe 400).</p>
<pre><code>#include <cstdlib>
#include <thread>
#include <condition_variable>
#include <iostream>
#include <atomic>
#include <chrono>
//UTILITY
//
using namespace std;
#if !defined(WIN32)
#include <unistd.h>
void
_sleep (int ms)
{
usleep (ms * 1000); //convert to microseconds
}
#endif
long long
timestamp ()
{
auto now = std::chrono::system_clock::now ();
auto duration = now.time_since_epoch ();
auto millis = std::chrono::duration_cast<std::chrono::milliseconds>(duration).count ();
return millis;
}
//REDRAW
//
bool killRedraw;
bool drawIt;
long long last;
void
redraw ()
{
cout << "Starting drawing thread" << endl;
last = timestamp ();
while (!killRedraw)
{
if (drawIt)
{
long long now = timestamp ();
cout << "I drew it:" << now - last << endl;
last = now;
drawIt = false;
}
_sleep (15);
}
}
//PRODUCER
//
atomic<int> balance;
bool killProducer;
void
produce ()
{
cout << "Made one:" << ++balance << endl;
}
void
producer ()
{
balance = 0;
cout << "Starting producer thread" << endl;
while (!killProducer)
{
_sleep (40);
produce ();
while (balance > 1)
{
_sleep (10);
}
}
}
//CONSUMER
//
bool killConsumer;
void
consume ()
{
cout << "Ate one:" << --balance << endl;
}
void
consumer ()
{
cout << "Starting consumer thread" << endl;
while (!killConsumer)
{
int basetime = 35;
int noise = rand () % 20;
_sleep (basetime + noise);
consume ();
static int cycle = -1;
if ((cycle = ++cycle % 8) == 7)
{
drawIt = true;
}
}
}
//Main
//
int
main (int argc, char** argv)
{
//
// Important metric is the "draw it" time, which should be about 8*50
//
killProducer = false;
std::thread tP (producer);
killConsumer = false;
std::thread tC (consumer);
killRedraw = false;
drawIt = false;
std::thread tD (redraw);
_sleep (10000);
killProducer = true;
killConsumer = true;
killRedraw = true;
tD.join ();
tP.join ();
tC.join ();
//
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<p>I have some minor things to point out:</p>\n\n<ul>\n<li><p>There is not a <em>single</em> empty line in this code, and this essentially looks like globals, functions, and comments stacked on top of each other. You should have each type separated so that the code is easier to read (especially with the function names and return types on separate lines).</p></li>\n<li><p>Since you're using C++11, you should be using <a href=\"http://en.cppreference.com/w/cpp/header/random\" rel=\"nofollow noreferrer\"><code><random></code></a> in place of <code>std::rand</code>. It has been determined that <a href=\"http://channel9.msdn.com/Events/GoingNative/2013/rand-Considered-Harmful\" rel=\"nofollow noreferrer\"><code>rand()</code> is harmful</a> and should no longer be used in C++11.</p></li>\n<li><p>Unless I'm misunderstanding the use of multithreading here, I don't think you should be using any global variables, as they're prone to bugs. If that's the case, then you should just be passing them to functions as needed. If not, then at least put them all towards the top (they're already global, so it doesn't make a difference to have them in different places outside the functions).</p></li>\n<li><p>You don't need to be using <code>std::endl</code> everywhere. It doesn't appear that you're needing to flush the buffer each time, which can also affect performance. Instead, output a <code>\"\\n\"</code> to produce a newline without also flushing the buffer.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-08T19:10:38.477",
"Id": "99477",
"Score": "0",
"body": "Thanks for the feedback, although these things weren't really the focus of my question, rather they are in there to ensure the thing compiles. Also the booleans should probably be atomic..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-08T19:35:46.057",
"Id": "99478",
"Score": "0",
"body": "@Mikhail: I understand, but we're allowed to comment on any aspect of the code. This was also an older question, so it probably would've stayed unseen had I not said anything."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-08T13:49:42.950",
"Id": "56442",
"ParentId": "26357",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-20T05:33:57.927",
"Id": "26357",
"Score": "8",
"Tags": [
"c++",
"performance",
"design-patterns",
"multithreading",
"c++11"
],
"Title": "Producer consumer that simulates the interaction of threads controlling a hardware device"
}
|
26357
|
<p>I have a simple task: </p>
<blockquote>
<p>Given a sequence of real numbers, replace all of its members larger
than Z by Z and count the number of replacements.</p>
</blockquote>
<p>I solved this task using Scala, but my code looks like imperative-style code. I want to make my code more functional. How can I rewrite my program so it becomes functional-style code?</p>
<pre><code>def main(args : Array[String]) {
println("Enter Z number: ")
val z = readDouble();
println("Enter the length of sequence: ")
val lenght = readInt();
var seq: List[Double] = List();
// Filling sequence
for (i <- 1 to lenght) {
println("Enter sequence item № " + i)
val item = readDouble();
seq = item :: seq;
}
// number of replacements
var substituteCount = 0;
//replacing all numbers larger Z by Z
seq = seq.map(x => {if (x > z){substituteCount+= 1; z} else x})
println("Replacement count: " + substituteCount)
println("New sequence: " + seq.reverse.mkString(" "))
}
</code></pre>
|
[] |
[
{
"body": "<p>Let's split this up a bit; firstly, let's put the sequence filling code in its own function:</p>\n\n<pre><code>def populateSequence(length: Int): IndexedSeq[Double] = {\n for {\n i <- 1 to length\n _ = println(\"Enter sequence item ? \" + i)\n item = readDouble()\n } yield item\n}\n</code></pre>\n\n<p>This utilizes the a combination of <code>for</code> and <code>yield</code> - in this case, this returns an <code>IndexedSeq[Double]</code>, but don't worry, you can treat this like a <code>List</code> (or simply convert it to one with a <code>.toList</code> if you really want to.</p>\n\n<p>Our code structure then looks like this:</p>\n\n<pre><code>def main(args: Array[String]) {\n println(\"Enter Z number: \")\n val z = readDouble();\n\n println(\"Enter the length of sequence: \")\n val length = readInt();\n\n val seq = populateSequence(length) \n</code></pre>\n\n<p>Ok, where to from here? Well, in this case, instead of modifying <code>substituteCount</code> as we go, I'd rather just calculate it up front:</p>\n\n<pre><code>val substituteCount = seq count (_ > z)\n</code></pre>\n\n<p>To get our modified <code>List</code> (or <code>IndexedSequence</code>), we can use another for expression. Again, one thing to remember is that both <code>for</code> and <code>if</code> are expressions in Scala, so we can do this:</p>\n\n<pre><code>val modified = for {\n v <- seq\n item = if (v > z) z else v\n} yield item\n</code></pre>\n\n<p>We can then print everything as usual:</p>\n\n<pre><code>println(\"Replacement count: \" + substituteCount)\nprintln(\"New sequence: \" + modified.mkString(\" \"))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-20T14:05:54.277",
"Id": "40833",
"Score": "0",
"body": "Thank you, very nice, especially this statement: `val substituteCount = seq count (_ > z)` :) But does `val modified =...` is better than using `map` method as in my code? I thought that the only one place in my code written in true functional style is usage of `map` method :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-20T14:47:38.613",
"Id": "40837",
"Score": "1",
"body": "`map` and `for`-expressions are actually exactly the same - under the covers, `for` gets converted into a `map`. But yeah, whichever way you prefer really - using `map` there is totally fine too."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-20T13:21:23.603",
"Id": "26366",
"ParentId": "26362",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "26366",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-20T12:11:01.103",
"Id": "26362",
"Score": "3",
"Tags": [
"functional-programming",
"scala"
],
"Title": "Replacing a sequence of real numbers with another sequence"
}
|
26362
|
<p>To generate faces of a Minecraft-like world from a three dimensional array, I developed the following meshing algorithm. The faces are given vertices and indices. A vertex consists of a position in space, a normal vector and a texture coordinate. Indices point to vertices to consecutively define faces.</p>
<p>Those variables are used:</p>
<pre><code>// dimensions of the world
#define SIZE 32
// voxel grid representing the world, where 0 means air
uint8_t data[SIZE][SIZE][SIZE];
// results are stored in those vectors
vector<float> positions, normals, texcoords;
vector<unsigned int> elements;
</code></pre>
<p>This is the algorithm:</p>
<pre><code>int n = 0;
for(int X = 0; X < SIZE; ++X)
for(int Y = 0; Y < SIZE; ++Y)
for(int Z = 0; Z < SIZE; ++Z)
{
if(data[X][Y][Z])
{
uint8_t tile = clamp((int)data[X][Y][Z], 0, TILES_U * TILES_V - 1);
for(int dim = 0; dim < 3; ++dim) { int dir = -1; do {
ivec3 neigh = Shift(dim, ivec3(dir, 0, 0)) + ivec3(X, Y, Z);
if(Inside(neigh, ivec3(0), ivec3(SIZE) - 1))
if(data[neigh.x][neigh.y][neigh.z])
goto skip;
{
for(float i = 0; i <= 1; ++i)
for(float j = 0; j <= 1; ++j)
{
vec3 vertex = vec3(X, Y, Z) + vec3(Shift(dim, ivec3((dir+1)/2, i, j)));
positions.push_back(vertex.x); positions.push_back(vertex.y); positions.push_back(vertex.z);
}
/*
* the normal vector is not important for this question
*
* vec3 normal = normalize(vec3(Shift(dim, ivec3(dir, 0, 0))));
* for(int i = 0; i < 4; ++i)
* {
* normals.push_back(normal.x); normals.push_back(normal.y); normals.push_back(normal.z);
* }
*/
/*
* texture coordinates are not important for this question
*
* vec2 coords(tile % TILES_U, tile / TILES_U);
* vec2 position = coords * GRID;
* texcoords.push_back(position.x + GAP); texcoords.push_back(position.y + GAP);
* texcoords.push_back(position.x + GRID.x - GAP); texcoords.push_back(position.y + GAP);
* texcoords.push_back(position.x + GAP); texcoords.push_back(position.y + GRID.y - GAP);
* texcoords.push_back(position.x + GRID.x - GAP); texcoords.push_back(position.y + GRID.y - GAP);
*/
if(dir == -1) {
elements.push_back(n+0); elements.push_back(n+1); elements.push_back(n+2);
elements.push_back(n+1); elements.push_back(n+3); elements.push_back(n+2);
} else {
elements.push_back(n+0); elements.push_back(n+2); elements.push_back(n+1);
elements.push_back(n+1); elements.push_back(n+2); elements.push_back(n+3);
}
n += 4;
}
skip: dir *= -1; } while(dir > 0); }
}
}
</code></pre>
<p>And here are the two helper functions.</p>
<pre><code>bool Inside(ivec3 Position, ivec3 Min, ivec3 Max)
{
if(Position.x < Min.x || Position.y < Min.y || Position.z < Min.z) return false;
if(Position.x > Max.x || Position.y > Max.y || Position.z > Max.z) return false;
return true;
}
ivec3 Shift(int Dimension, ivec3 Vector)
{
if (Dimension % 3 == 1) return ivec3(Vector.z, Vector.x, Vector.y);
else if (Dimension % 3 == 2) return ivec3(Vector.y, Vector.z, Vector.x);
else return Vector;
}
</code></pre>
<p>As you can see, the algorithm uses a <code>goto</code> statement to skip faces which adjacent blocks first, are inside the world bounds and second, are not filled with air. Those faces shouldn't be generated since they are not visible to the player.</p>
<p>How can I restructure the statement to not use <code>goto</code> anymore?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-20T13:50:39.070",
"Id": "40831",
"Score": "0",
"body": "I'm confused, I may be missing something here but why did you feel you needed the `goto` in the first place? I see only one use and its use precedes the block it is skipping. Couldn't you just combine the logic that determines the `goto` and use it as the `if` condition for the block?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-20T22:35:37.213",
"Id": "40865",
"Score": "0",
"body": "I don't know how that should be done. It is important that the algorithm checks if the block is inside the world first, because otherwise the following look up in the data array would be out of range."
}
] |
[
{
"body": "<p>First of all, the way you're formatting your code is horribly confusing.</p>\n\n<pre><code>if(Inside(neigh, ivec3(0), ivec3(SIZE) - 1))\n if(data[neigh.x][neigh.y][neigh.z])\n goto skip;\n\n{\n ...\n}\n</code></pre>\n\n<p>The block here looks a lot like it's in the <code>if</code> condition but it's not (it's just a C-like block without any condition attached to it). I really suggest using braces for your <code>ifs</code> to avoid confusion. Another confusing part is <code>for(int dim = 0; dim < 3; ++dim) { int dir = -1; do {</code>: when I see a for loop, I don't expect to see another loop at the end of it.</p>\n\n<p>Now, about your question. Some languages (such as Java) support naming loop, which allows you to break to outer loops. This doesn't exist in C++, and the best option is to use a goto.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T08:47:58.120",
"Id": "40876",
"Score": "0",
"body": "The code formatting is necessary. Without that isolated code block the `goto` statement throws compiler warnings since variable declarations could be skipped. The `for` loop with nested `do while` iterates over all six sides of a cube. Can't I get rid of the nested conditionals at all?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T08:57:18.197",
"Id": "40879",
"Score": "0",
"body": "I'm not against the isolated block, but you should also put braces around the two ifs. I don't think there's an easy way to avoid the conditionals, no. (Well of course you can put them together: `if(A && B)`)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T09:09:31.537",
"Id": "40882",
"Score": "0",
"body": "Is there anything against putting them together? I just asked [another question](http://stackoverflow.com/questions/16666125/is-an-if-statement-guaranteed-to-not-be-evaluated-more-than-necessary) whether the second condition could be evaluated even if the first resolved to false. Because that would cause and out of bounds error."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T07:06:31.747",
"Id": "26406",
"ParentId": "26363",
"Score": "3"
}
},
{
"body": "<p>I may be missing some deep reason here, but it looks like you've got an if-condition that already does exactly what you need, except that you're using it to feed a GOTO instead of to (not) execute the defined code block.... Shouldn't you do something like:</p>\n\n<pre><code>if (!(Inside(neigh, ivec3(0), ivec3(SIZE)-1) && data[neigh.x][neigh.y][neigh.z]))\n{\n ...\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T18:31:33.527",
"Id": "40941",
"Score": "0",
"body": "Thanks. I wasn't sure if the second condition is guaranteed to not get evaluated if the first condition is false. But I found out."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T18:19:00.847",
"Id": "26448",
"ParentId": "26363",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "26448",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-20T12:28:15.503",
"Id": "26363",
"Score": "3",
"Tags": [
"c++",
"algorithm",
"minecraft"
],
"Title": "Meshing algorithm for generating faces in Minecraft"
}
|
26363
|
<p>I'm using sql server and I'm trying to update certain columns in a table but before it updates the data, I want to insert the data into another table.</p>
<p>This is my code</p>
<pre><code>declare @table1 table (Id int, Name varchar(100))
declare @temp table (Id int, Name varchar(100), CreatedOn datetime default getdate())
insert into @table1 values (1, 'Albert')
insert into @table1 values (2, 'Alex')
insert into @table1 values (3, 'Alas')
insert into @table1 values (4, 'Bob')
update @table1
set Name = 'B' + Name
output Deleted.Id, Deleted.Name, getdate() into @temp
where Name like 'A%'
select * from @table1
select * from @temp
</code></pre>
<p>Above code seems to be working correctly. Please let me know if I have to change anything.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T19:19:34.180",
"Id": "40945",
"Score": "0",
"body": "Is this happening on a set schedule, or every time the data is being updated?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T16:33:35.643",
"Id": "41182",
"Score": "0",
"body": "Not actually a schedule nor every time when data is updated... its a custom script. its executed when something bulk has to be deactivated."
}
] |
[
{
"body": "<p>You don't need to change anything as long as the code performs what you need. If you want to insert records to another table on <em>every</em> update (and not only in this place) you should probably take a look at <a href=\"http://msdn.microsoft.com/en-us/library/ms189799.aspx\" rel=\"nofollow\">triggers</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-20T13:04:57.223",
"Id": "40824",
"Score": "0",
"body": "actually I need this data only for this script... I so might not be going for triggers. thank you for the suggestion."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-20T12:44:21.120",
"Id": "26365",
"ParentId": "26364",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-20T12:28:28.760",
"Id": "26364",
"Score": "2",
"Tags": [
"sql",
"sql-server"
],
"Title": "Archiving data while running update statement"
}
|
26364
|
<p>I wrote the following code to read a config file line by line and split each line into 2 parts and store them separately. The split is done on the basis of a delimiter <code>=</code>:</p>
<pre><code>std::ifstream configfile(path_string.c_str());
std::string line;
std::vector<std::string> linesOfConfigFile;
while (std::getline(configfile, line))
linesOfConfigFile.push_back(line);
configfile.close();
std::string currentItem;
char delimeter = '=';
std::vector<std::string> RHS;
std::vector<long long> LHS;
bool flag = false;
for (int i =0; i<linesOfConfigFile.size(); i++)
{
std::stringstream singleLine(linesOfConfigFile[i]);
while(std::getline(singleLine, currentItem, delimeter))
{
if(flag == true)
{
RHS.push_back(currentItem);
flag = false;
}
else if (flag == false)
{
long long orderbookId = 0;
<some library class>::toNumeric(currentItem, orderbookId);
LHS.push_back(orderbookId);
flag = true;
}
}
}
for(int i=0; i<RHS.size(); i++)
StorageMap.insert( std::pair<long long, std::string>( LHS[i], RHS[i]) );
</code></pre>
<p>The review comment I got was this: </p>
<blockquote>
<p>The below code can be written in a better way, Need not use a Boolean flag to differentiate RHS and LHS. The outer for loops should be sufficient. </p>
</blockquote>
<p>I cannot understand what difference he wishes to have. Can someone please help me? </p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-20T15:10:54.080",
"Id": "40839",
"Score": "1",
"body": "Have you tried asking him?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T07:01:42.770",
"Id": "40874",
"Score": "1",
"body": "As an aside: when branching on booleans, you don't have to explicitly test whether they're true or false. Instead: `if (flag) { ... } else { ... } flag = !flag`. Note that flipping flag state is a common operation and can be done outside the conditional."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-20T09:18:32.430",
"Id": "42987",
"Score": "1",
"body": "what you did is an Antipattern: you perform a test with predictable outcome. You *know* that first comes LHS, and then comes RHS. Your code should reflect this explicitly, not pretend that LHSs and RHSs come in all kinds of different orders. They don't. The change here would be *loop unrolling* - performing two `getline`s on each step, first with a `\"=\"` `delimiter`, the second without it. Thus the code will explicitly and clearly reflect the nature of the situation; the knowledge won't be hidden in the obscure mechanics of `getline` stopping on end-of-line too, having failed 2 find the delim."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-21T05:26:46.447",
"Id": "43053",
"Score": "0",
"body": "@WillNess Thanks, why don't you add that as an answer."
}
] |
[
{
"body": "<blockquote>\n <p>I wrote the following code to read a config file line by line and split each line into 2 parts and store them separately.</p>\n</blockquote>\n\n<p>So there are two parts on each line, the stuff before the <code>=</code>, which is stored as a <code>string</code>, and the stuff after the <code>=</code>, which shall be parsed as an integer and stored as a <code>long long</code>.</p>\n\n<p>Thus you can handle each line on its own completely, without using a flag to determine at which part of the line you currently are:</p>\n\n<pre><code>for (int i =0; i<linesOfConfigFile.size(); i++)\n{\n std::stringstream singleLine(linesOfConfigFile[i]);\n\n // get first part of the line\n std::getline(singleLine, currentItem, delimeter);\n // store it\n RHS.push_back(currentItem);\n\n // Now get the next part of the line\n std::getline(singleLine, currentItem, delimeter);\n // parse it\n long long orderbookId = 0;\n <some library class>::toNumeric(currentItem, orderbookId);\n // and store the result\n LHS.push_back(orderbookId);\n\n // done with this line :D\n}\n</code></pre>\n\n<p>This supposes of course that the config file is well-formed, and the format requires that each <code>name = value</code> is on a separate line.</p>\n\n<p>If the config file is malformed, or the file format is not as simple, this version may fail where yours wouldn't (for example</p>\n\n<pre><code>name =\nvalue\n</code></pre>\n\n<p>would work with yours), but neither version does robust error handling, and both would fail on most malformed inputs. Config files can generally be assumed to follow the required format, so the absence of error handling probably isn't a serious problem.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T12:31:12.350",
"Id": "41156",
"Score": "0",
"body": "when I call `std::getline(singleLine, currentItem, delimeter);` for the second time; wont it again return me the same string it returned the first time ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T13:09:16.987",
"Id": "41161",
"Score": "0",
"body": "No, `singleLine` is a `stringstream`, it keeps trace of what it has already used, and delivers the next item each call (while there is one, of course)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-20T14:32:39.987",
"Id": "26372",
"ParentId": "26368",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "26372",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-20T13:41:14.470",
"Id": "26368",
"Score": "2",
"Tags": [
"c++",
"strings"
],
"Title": "Splitting and storing config file lines"
}
|
26368
|
<p>I've dabbled with PHP for a couple of years, I can generally get what I need done and I've been teaching myself PDO. The problem is I want to set it up with classes but i'm not really sure how to. </p>
<p>Below is my code, which takes data from a form, does some rough checking to see if the email is right and the fields are full. It works but it's gotten to a point where I can't take it further without breaking it or getting confused and i want to add things such as validation. </p>
<p>So what i'm asking for is can some show me how to create a basic connection class that outputs acouple of records from a database, this would help me a lot if anyone could.</p>
<pre><code><?php
try{
$host = "localhost";
$dbname = "db";
$user = "user";
$pass = "pass";
$odb = new PDO("mysql:host=" . $host . ";dbname=" . $dbname, $user, $pass);
$odb->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo "I'm afraid I can't do that.";
file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND);
}
if($_SERVER["REQUEST_METHOD"] == "POST"){
if (isset($_POST['firstname']) && !empty($_POST['lastname']) && filter_var($_POST['email'],FILTER_VALIDATE_EMAIL) && !empty($_POST['phone'])){
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$q = "INSERT INTO jobform(firstname, lastname, email, phone) VALUES (:firstname, :lastname, :email, :phone);";
$query = $odb->prepare($q);
$results = $query->execute(array(
":firstname" => $firstname,
":lastname" => $lastname,
":email" => $email,
":phone" => $phone,
));
} else {
#echo $errMsg;
}
}
?>
</code></pre>
|
[] |
[
{
"body": "<p>I know you're asking for \"a basic connection class\", but you really need a few classes. Currently, your code has all of these (tightly-coupled) responsibilities:</p>\n\n<ul>\n<li>Database access</li>\n<li>Error reporting</li>\n<li>Form validation</li>\n<li>Data persistence</li>\n<li>And I assume you're rendering output as well</li>\n</ul>\n\n<p>To move past the difficulties you're facing, you need to separate these concerns into loosely-coupled objects. The prevailing architectural pattern to accomplish this is with the <a href=\"https://stackoverflow.com/a/883031/400550\">MVC pattern</a>, but this is out of the scope of your question.</p>\n\n<p>With this in mind, I would start with trying to isolate database access. To decouple your data from the rest, you need to put all of your database access in a separate class or set of classes. Here, there are two key patterns: object-relational mapping (ORM) and the <a href=\"http://msdn.microsoft.com/en-us/library/ff649690.aspx\" rel=\"nofollow noreferrer\">database repository</a>. </p>\n\n<p>With ORM, you essentially try to hydrate database records into PHP objects – if you want to create a new record in the database, you create a PHP object and call a method to persist it to the database; if you want to update a record, you fetch a record, convert it to a PHP object (<a href=\"https://stackoverflow.com/questions/4929243/clarifying-terminology-hydrating-an-entity-fetching-properties-from-the-db\">hydration</a>), update the PHP object, then persist it; to delete, you either obtain a reference to a record or create a dummy PHP object, call a method to delete this record, then call another method to persist this change.</p>\n\n<p>ORM has a lot of surface area; it typically relies on a database abstraction layer, requires you to write a new class for every type of record you'd like to persist, and can confuse beginners when you throw relations into the mix. While this definitely takes some investment, it provides a path to a lot of other benefits: code reuse, testing, automatic schema generation, migrations, validation, etc.</p>\n\n<p>Another pattern for data persistence is the database repository. Here, all you're doing is wrapping your queries in methods and grouping these methods into classes based on which records the queries operate on. For instance, a <code>UserRepository</code> class might have the following methods: <code>UserRepository::createUser()</code>, <code>UserRepository::getUserById()</code>, <code>UserRepository::getUsersByZipcode()</code>, <code>UserRepository::updateUser()</code>, <code>UserRepository::deleteUser()</code>. Each one of these methods would accept a set of PHP parameters (arrays or ORM object and integers), perform database queries based on this data, and return the results (possibly hydrating them).</p>\n\n<p>ORM and database repositories work very well together. I've personally used <a href=\"http://www.doctrine-project.org/projects/orm.html\" rel=\"nofollow noreferrer\">Doctrine 2's ORM</a> and <a href=\"http://www.doctrine-project.org/projects/dbal.html\" rel=\"nofollow noreferrer\">DBAL</a> as well as <a href=\"https://github.com/auraphp/Aura.Sql\" rel=\"nofollow noreferrer\">Aura SQL's DBAL</a> and would recommend both. I personally would start with creating a connection object with Aura SQL, then create your own class called UserRepository with the methods I listed above. Instantiate the UserRepository class by passing the AuraSQL connection object to it's constructor, then call <code>UserRepository::createUser()</code> to persist the user data from your form. After this, I would consider how to improve your form validation and look into using a template system like <a href=\"http://twig.sensiolabs.org/\" rel=\"nofollow noreferrer\">Twig</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T18:37:45.963",
"Id": "26486",
"ParentId": "26374",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-20T15:08:42.190",
"Id": "26374",
"Score": "3",
"Tags": [
"php",
"classes",
"pdo"
],
"Title": "How do I refactor this basic form handler"
}
|
26374
|
<p>I'm learning Scala and functional programming. Can I make it more functional?</p>
<pre><code>class Student(val firstname: String, val lastname: String) {
override def toString: String = firstname + " " + lastname
}
class ClassRoom {
var rows: List[Array[Student]] = List[Array[Student]]()
var total: Int = _
def addRow(row: Array[Student]) = {
rows = row :: rows
total += row.length
}
def print = rows.foreach(r => r.foreach(println))
}
</code></pre>
|
[] |
[
{
"body": "<p>A couple of small things to start.</p>\n\n<pre><code>var rows: List[Array[Student]] = List[Array[Student]]()\n</code></pre>\n\n<p>This line can be simplified slightly by doing this instead:</p>\n\n<pre><code>var rows: List[Array[Student]] = List.empty\n</code></pre>\n\n<p>Unless you are caching the <code>total</code> for performance reasons, you could calculate it as needed with something like this:</p>\n\n<pre><code>def total: Int = rows.map(_.length).sum\n</code></pre>\n\n<p>That would simplify <code>addRow()</code> to this:</p>\n\n<pre><code>def addRow(row: Array[Student]) = rows = row :: rows\n</code></pre>\n\n<hr>\n\n<p>One of the tenets of functional programming is the use of immutable data. <code>ClassRoom</code> is not very functional from this perspective: both <code>rows</code> and <code>total</code> are mutable. If you wanted to take a pure functional approach, all members would be <code>val</code> and functions like <code>addRow()</code> would return a new <code>ClassRoom</code> instead of modifying itself. For example:</p>\n\n<pre><code>class ClassRoom(val rows: List[Array[Student]]) {\n def total: Int = rows.map(_.length).sum\n def addRow(row: Array[Student]) = new ClassRoom(row :: rows)\n def print = rows.foreach(_ foreach println)\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-20T22:06:46.697",
"Id": "26389",
"ParentId": "26376",
"Score": "4"
}
},
{
"body": "<p>Use a case classes as replacement of the normal Student and room class:</p>\n\n<pre><code> case class Student(firstname: String, lastname: String) \n case class ClassRoom(rows: List[Array[Student]]) \n</code></pre>\n\n<p>Case classes are:</p>\n\n<ol>\n<li>Immutable by default</li>\n<li>Generate toString, hashCode & equal by default. No typing needed</li>\n<li>Incredible compact syntax. I'm not aware of anything shorter</li>\n<li>Fit well with functional style </li>\n</ol>\n\n<p>Read more on: <a href=\"http://www.scala-lang.org/node/107\" rel=\"nofollow\">http://www.scala-lang.org/node/107</a> </p>\n\n<p>For more functional sytle, try to avoid empty / null references. Instead do this:</p>\n\n<ol>\n<li>Mutate only parameter</li>\n<li>Avoid side effects in functions to keep them pure. </li>\n<li>Combine simple functions to form complex functions. </li>\n</ol>\n\n<p>1) Mutate only parameter:</p>\n\n<p>Instead of changing a variable, you only modify a parameter and return\nthe modified parameter. This is thread-safe as long as all used local fields\nand data-structures are immutable (val) and the function is without side-effects.</p>\n\n<p>2) Side effects are:</p>\n\n<ol>\n<li>Reassigning a variable</li>\n<li>Modifying a data structure in place</li>\n<li>Setting a field on an object (case classes have no setter!) </li>\n<li>Throwing an exception or halting with an error</li>\n<li>Printing to the console or reading user input</li>\n<li>Reading from or writing to a file</li>\n<li>Drawing on the screen</li>\n</ol>\n\n<p>Essentially, functional programming has the idea of a \"pure\" core that is a bunch of pure functions only mutating parameters without any side effects and a very thin access layer, sometimes called IO layer of impure functions handling all sorts of IO like file reading or user interface interaction. </p>\n\n<p>3) Combine simple functions.</p>\n\n<p>Simple function are, for instance, a sum or size function. Calculating \nthe let's say average is the sum off all values divided by the number\nof all elements. A functional style would be to nest the the sum\nfunction inside the average function but keeping both pure. For instance:</p>\n\n<pre><code> def avg(values: Array[Double], nrElements): Double = values.sum / nrElements\n</code></pre>\n\n<p>In this case, sum is a standard function of Scakla Array. This function is pure\nbecause it has no mutable fields, it only mutatates parameters and it has no side other side effects.</p>\n\n<p>Back to your example, if you want to interact with your Student and Room case class, pass either one of them, or both to a function do whatever you want to do\nby mutating the classes / collections by using only immutable fields.</p>\n\n<p>So, beginning with the calculation of the total numbers of students, you make\na function that takes the collection as parameter calculates the total number\nand returns it. Like so: </p>\n\n<pre><code> def total(c : ClassRoom)= c.rows.map(_.length).sum\n</code></pre>\n\n<p>For performance, and sum over lists always suck in terms of performance, use lazy val that means, the function gets called only if the field gets accessed the first time and then stores the value in it. In other words, you write:</p>\n\n<pre><code> val s1 = Student(\"Linus\", \"T.\")\n val s2 = Student(\"Bill\", \"G.\") \n val s3 = Student(\"Larry\", \"E.\")\n val r1 = Array(s1)\n val r2 = Array(s2,s3)\n\n val prog101 = ClassRoom(List(r1,r2))\n\nlazy val size = total(prog101)\n</code></pre>\n\n<p>Let's say you want to print the class one by one student. This is an impure fuction because it prints to the system console. Ok in this case you pass \nthe class to function like so:</p>\n\n<pre><code> //@IMPURE: prints to console\n def printClass(c : ClassRoom) = c.rows.flatten.foreach(println)\n</code></pre>\n\n<p>Which you use in a familiar way:</p>\n\n<pre><code> printClass(prog101)\n</code></pre>\n\n<p>Now, lets say you want to print out the class size. in this case, you can \nre-use the size function we already know like so: </p>\n\n<pre><code> def printClassSize(c : ClassRoom) = println(total(c))\n</code></pre>\n\n<p>which you can use, just like the previous function:</p>\n\n<pre><code> printClassSize(prog101)\n</code></pre>\n\n<p>So what are the lessons learned? </p>\n\n<ol>\n<li>Functional programing uses immutable data-structures</li>\n<li>Functions should be simple and pure</li>\n<li>Complex functions are built from simple functions </li>\n</ol>\n\n<p>Full source code of the example is on github: </p>\n\n<p><a href=\"https://gist.github.com/marvin-hansen/5802829\" rel=\"nofollow\">https://gist.github.com/marvin-hansen/5802829</a> </p>\n\n<p>Additional material worth reading:</p>\n\n<p>1) eBook google: \"Functional Programming in Scala\" (Manning publisher)</p>\n\n<p>2) FREE coursera material, google: \"Functional Programming Principles in Scala\" </p>\n\n<p>Hope that helps\nm</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-18T05:30:31.797",
"Id": "27498",
"ParentId": "26376",
"Score": "1"
}
},
{
"body": "<ol>\n<li>The Student class is better implemented as a case class</li>\n<li>The addRow method should return another instance of the ClassRoom class</li>\n<li>Use foldLeft (or another higher-order function like map) to compute the total</li>\n<li>Use toString instead of .foreach(println) to avoid side-effects...</li>\n<li>You can use companion object for convenient purposes</li>\n</ol>\n\n<p>Here it is:</p>\n\n<pre><code>case class Student(fname: String, lname: String)\n\nclass ClassRoom(val rows: List[List[Student]]) {\n def addRow(row: List[Student]) = ClassRoom(row :: rows)\n def total = rows.foldLeft(0)( _ + _.length)\n override def toString = rows.map(_.mkString(\"\\n\")).mkString(\"\\n\")\n}\n\nobject ClassRoom {\n def apply(rows: List[List[Student]]) = new ClassRoom(rows)\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-21T12:06:41.857",
"Id": "28780",
"ParentId": "26376",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "26389",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-20T16:34:36.563",
"Id": "26376",
"Score": "3",
"Tags": [
"functional-programming",
"scala"
],
"Title": "Adding students to rows in a classroom"
}
|
26376
|
<p>I want to write my database access code for a Snap application in a way that makes the queries easy to test from the <code>ghci</code> repl, while also working within the Snap context. My solution so far is to define a HasPostgres instance for IO and to write all my DB access functions following the pattern of <code>allUsers</code> in the code snippet below. Am I doing this correctly?</p>
<pre><code>{-# LANGUAGE OverloadedStrings #-}
module Database where
import Core
import Control.Applicative
import Database.PostgreSQL.Simple.FromRow (field, fromRow)
import Database.PostgreSQL.Simple.ToRow (toRow)
import Database.PostgreSQL.Simple.ToField (toField)
import Snap.Snaplet.PostgresqlSimple
import Data.Pool
import qualified Database.PostgreSQL.Simple as P
import Data.Text (Text)
import qualified Data.Text as T
import Control.Monad.CatchIO
instance FromRow User where
fromRow = User <$> field <*> field
instance ToRow User where
toRow (User a b) = [toField a, toField b]
allUsers :: (HasPostgres m) => m [User]
allUsers = query_ "SELECT user_id, email from users"
instance HasPostgres IO where
getPostgresState = do
let stripes = 1
let idle = 5
let resources = 20
let ci = P.ConnectInfo "localhost" 5432 "choi" "" "testDatabase"
pool <- createPool (P.connect ci) P.close stripes (realToFrac (idle :: Double)) resources
return $ Postgres pool
</code></pre>
|
[] |
[
{
"body": "<p>Yes, this looks good to me. I've done exactly the same thing to facilitate debugging in my projects. However, I would recommend that you put the IO instance in some special module where all your debugging code lives. You really do not want instances like this making their way into any other code because it is akin to making a global statement that IO always has a test database available at localhost on port 5432.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T15:40:02.340",
"Id": "26439",
"ParentId": "26378",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "26439",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-20T16:02:27.627",
"Id": "26378",
"Score": "5",
"Tags": [
"haskell",
"postgresql",
"snap-framework"
],
"Title": "HasPostgres instance for IO with Snap framework"
}
|
26378
|
<p>I've wrote this script to fetch and format content from my DB. It also counts how many result there are and separates them into pages. I'm barely learning PHP and MySQL so I don't know much about performance.</p>
<pre><code>function fetch_content($section, $subsection, &$count, $page = 0){
$section = substr($section, 0,8);
$subsection = substr($subsection, 0,8);
require_once("system/config.php");
//Initiate connection
$mysqli = new mysqli($db_host, $db_user, $db_password, $db_database);
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') '. $mysqli->connect_error);
}
//Select page
$limit = 2;
$start = $page * $limit ;
//select query
if($section == 'home' || ($section != 'home' && $subsection == NULL)){
$selection = "WHERE section = ?";
}
else
$selection = "WHERE section = ? AND subsection = ?";
//Fetch data
$stmt = $mysqli->stmt_init();
$qry= "SELECT * FROM public
$selection
ORDER BY id DESC LIMIT ?,?";
$stmt->prepare($qry);
if($section == 'home' || ($section != 'home' && $subsection == NULL))
$stmt->bind_param("sss", $section, $start , $limit);
else
$stmt->bind_param("ssss", $section, $subsection, $start , $limit);
$stmt->execute();
$result = $stmt->get_result();
//Format the data
while( $row = $result->fetch_assoc()){
format_home($row, $mysqli);
}
$stmt->close();
//Count result
$stmt = $mysqli->stmt_init();
$qry= "SELECT COUNT(*) AS count FROM public $selection";
$stmt->prepare($qry);
if($section == 'home' || ($section != 'home' && $subsection == NULL))
$stmt->bind_param("s", $section);
else
$stmt->bind_param("ss", $section, $subsection);
$stmt->execute();
$result = $stmt->get_result();
$count = $result->fetch_assoc();
$count = $count['count'];
$stmt->close();
//close connection
$mysqli->close();
}
</code></pre>
|
[] |
[
{
"body": "<p>I would make a single file with the MySQL server connection, so you can use the same connection in other functions, etc..</p>\n\n<p>Also you should pass string variables directly.</p>\n\n<pre><code>$stmt->prepare(\"SELECT COUNT(*) AS count FROM public $selection\");\n</code></pre>\n\n<p>Did you know, that you can check every single called function if a error occurred?\nFor example:</p>\n\n<pre><code>if(!($stmt->execute()) {\n die('Unable to execute!'. $mysqli->error);\n}\n</code></pre>\n\n<p>The next point is, why do you execute another query to count the result rows?\nIn the mysqli_stmt object $num_rows. <a href=\"http://php.net/manual/en/mysqli-stmt.num-rows.php\" rel=\"nofollow\">http://php.net/manual/en/mysqli-stmt.num-rows.php</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T19:21:01.490",
"Id": "41032",
"Score": "0",
"body": "I tried using stmt->num_rows; as $count = stmt->num_rows but its returning 0, Idk if I'm calling it incorrectly"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T19:21:58.023",
"Id": "41034",
"Score": "0",
"body": "//Format the data\n\n while( $row = $result->fetch_assoc()){\n\n format_home($row, $mysqli);\n\n }\n\n $count = $stmt->num_rows;\n $stmt->close();"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T09:52:56.727",
"Id": "26416",
"ParentId": "26381",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-20T20:01:40.330",
"Id": "26381",
"Score": "3",
"Tags": [
"php",
"sql",
"pdo"
],
"Title": "Fetching and formatting content from a database"
}
|
26381
|
<p>How do you guys think I can improve the code for collision detection on my website <a href="http://asteroidfield.eu5.org" rel="nofollow">asteroidfield.eu5.org</a>? The current code is </p>
<pre><code>var dx = Math.abs(c1.getcx() - c2.getcx());
var dy = Math.abs(c1.getcy() - c2.getcy());
var dist = Math.sqrt((dx * dx) + (dy * dy));
if (dist - (c1.getR() + c2.getR()) <= 0) {
if (done === false && invinc !== true) {
game_over = true;
done = true;
}
}
</code></pre>
<p>C1 refers to the player sprite, and C2 is the enemy sprite. Getcx is essentially collecting the X location of the edge of what is essentially a collision detection circle, and gety does the same, but collects the Y location. GetR returns the radius of the collision detection circle.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T19:38:29.993",
"Id": "40947",
"Score": "0",
"body": "Was it running too slowly? How fast you detect a collision between two objects is not as important as being able to deal with thousands of them. In your case you do not have too many of the asteroids. By the way, there are some UI usability improvements that you can look into - the menu for selecting difficulty and a spaceship was not very intuitive (hard to find) and clunky. In professional games the implementation may be harder but the menus are slicker - you get all the info you want on screen, and you can often cycle through options with <=, => or other keys. Difficulty can be a combo box"
}
] |
[
{
"body": "<p>One thing you can improve on is the getting of the absolute value. In some browsers, bitwise absolute is faster than <code>Math.abs</code>. <a href=\"http://jsperf.com/absolute-value-speed/3\" rel=\"nofollow\">But it depends on the browser's implementation</a>.</p>\n\n<pre><code>//bitwise absolute\nfunction abs(n){\n return (n^(n>>31))-(n>>31);\n}\n</code></pre>\n\n<p>You could also factor this part out into a variable for readability. The result of this is a boolean. The explanation will be in the next part:</p>\n\n<pre><code>//foo true if less than or equal to 0, false if greater\nvar foo = dist - (c1.getR() + c2.getR()) <= 0; \n</code></pre>\n\n<p>Also, in this bit of code, since <code>done</code> and <code>invinc</code> are boolean, there's no point comparing them to <code>true</code> and <code>false</code>. You can use them directly in the condition. </p>\n\n<pre><code>if (done === false && invinc !== true) //when false, and not true (false)\n\nif (!done && !invinc) //when not true (false) and not true (false)\n</code></pre>\n\n<p>In JS, assignment operations \"spill left\". You can do the following, assigning <code>true</code> to <code>done</code> and \"spill\" the same value over to <code>game_over</code>.</p>\n\n<pre><code>game_over = done = true;\n</code></pre>\n\n<p>Also, due to the structure of the code, the previous only happens when our condition assigned to <code>foo</code> is less than or equal to zero or <code>true</code>. So let's modify the condition to this:</p>\n\n<pre><code>if(foo && !done && !invinc) game_over = done = true;\n</code></pre>\n\n<p>So in the end, your code will look like this:</p>\n\n<pre><code>var dx = Math.abs(c1.getcx() - c2.getcx());\nvar dy = Math.abs(c1.getcy() - c2.getcy());\nvar dist = Math.sqrt((dx * dx) + (dy * dy));\nvar foo = dist - (c1.getR() + c2.getR()) <= 0;\n\nif (foo && !done && !invinc) game_over = done = true;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T18:26:56.213",
"Id": "40940",
"Score": "0",
"body": "Thank you for you help, but that didn't really improve the accuracy. I updated the original post with context. The full JS file is also available here: http://asteroidfield.eu5.org/_js/main.js"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T19:40:10.923",
"Id": "40949",
"Score": "0",
"body": "@user2350334, what is wrong with the accuracy? This site is mainly for improving something that already works. Your problem might be with a timer or with modeling the bounding box of a spacecraft."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T20:28:08.270",
"Id": "40952",
"Score": "0",
"body": "@Leonid I am trying to improve the collision detect function-it works fine currently, but as I previously mentioned, it basically uses two collision detect circles. The problem is that since the asteroids have different sizes, it is hard to create an accurate collision detect function for all of them. Try taking a look at the JS file for more details."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T22:36:23.803",
"Id": "40963",
"Score": "1",
"body": "@user2350334, Take a look at the accepted answer for http://stackoverflow.com/questions/8968591/circle-polygon-intersections Basically you need to hard-coded a polygon that outlines the shape of each spaceship well. You can then test whether each of the line segments intersects with a given circle. Alternatively, you may cheat and pick n equally-spaced and tightly packed points on the outside of the spaceship. Hard-code that list for each spaceship. Then check whether any of the points lies inside of a circle. That test will run quickly because you are just comparing R w distance to the center"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T22:41:31.593",
"Id": "40964",
"Score": "1",
"body": "@user2350334, for speed purposes you may take a shortcut - come up with a big bounding sphere that fully encompasses all of your space ships. Then quickly check whether that bounding sphere intersects with any of the asteroids. If it does not, then the space ship is 100% safe. If the bounding sphere intersects with some asteroids, then only finely inspect the intersection with asteroids that are \"suspects\", e.g. their bounding spheres intersected. These are standard approaches to collision detection in gaming. So, your question did not belong at this codereview site to begin with."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T19:37:00.883",
"Id": "41118",
"Score": "0",
"body": "Thanks for your help, I will try to sort out those problems in time."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-20T23:26:18.840",
"Id": "26393",
"ParentId": "26382",
"Score": "3"
}
},
{
"body": "<p>Rather than doing math with coordinates, you might try this:</p>\n\n<pre><code>var board = [\"0x0\",\"0x1\",\"0x2\",\"0x3\",\n \"1x0\",\"1x1\",\"1x2\",\"1x3\",\n \"2x0\",\"2x1\",\"2x2\",\"2x3\",\n \"3x0\",\"3x1\",\"3x2\",\"3x3\",\n \"4x0\",\"4x1\",\"4x2\",\"4x3\"]; //Grid-based game board\n\nvar player = {\n \"x\": 0,\n \"y\": 0,\n \"location\": \"0x0\"\n};\n\nvar enemy = {\n \"x\": 0,\n \"y\": 0,\n \"location\": \"0x0\"\n};\n\nif (player.location == enemy.location){\n //Do things\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-06-27T18:49:58.570",
"Id": "133220",
"ParentId": "26382",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-20T20:06:01.023",
"Id": "26382",
"Score": "4",
"Tags": [
"javascript",
"html5",
"collision",
"canvas"
],
"Title": "Collision detection accuracy"
}
|
26382
|
<p>I need to speed up this code: it creates a multilinear function. I considered the below methods but no idea which with the largest benefit.</p>
<ul>
<li>replacing dummy variables with things such as anonymous functions</li>
<li>having all code in the same file (my instructor's hint)</li>
<li>improving the looping: getting rid of num2str</li>
<li>other?</li>
</ul>
<p>I need to repeatedly create this kind of initialisations and I am trying to get it as fast as possible. It may be that the reason for the slowness of my code lies somewhere else, not this code, say it if you think so! There may be some elegant functional way to write this fast and more compactly. I already know that the whole code is probably slow because of the mlfnneg but in order to speed it up I need to make sure the bug is not early ie on this code aka during the initialisation of test-cases.</p>
<p><img src="https://i.stack.imgur.com/yZJVa.png" alt="enter image description here"></p>
<pre><code> %Creating a mlf to check the negativity of the multilinear function
% Example: 0<x_i<i/Density
lbs_str=containers.Map; % I need variables here only to initialise mlf at the end
ubs_str=containers.Map;
terms=containers.Map;
for i = 1:100
i=num2str(i); % possible to make this more elegant? contairers.Map requires string
lbs_str(i)=0;
ubs_str(i)=i/100;
terms(i)=struct('coeff',1,'vars',{{i}});
% Tested catstruct [1] to append new terms to the mlf_terms but not intended:
% it does not do {terms('1'), terms('2'),...} aka {terms.values}
end
lbs=mlfpoint(lbs_str);
ubs=mlfpoint(ubs_str);
mlf_terms=struct('const',0,'terms',{terms.values});
mlf=mlfcreate(mlf_terms);
mlfnneg(lbs,ubs,mlf)
</code></pre>
|
[] |
[
{
"body": "<p>You should be able to prevent casting to a string 100 times.</p>\n\n<p>First create all strings in a cell array, then just loop over the strings.</p>\n\n<hr>\n\n<p>Though it does not show up on the profiler, this looks higly dubious:</p>\n\n<pre><code>i=num2str(i)\nubs_str(i)=i/100;\n</code></pre>\n\n<p>Now you will get the character code of <code>'i'</code> and divide that by 100. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-26T12:43:21.170",
"Id": "30257",
"ParentId": "26385",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-20T20:48:50.550",
"Id": "26385",
"Score": "1",
"Tags": [
"optimization",
"functional-programming",
"matlab"
],
"Title": "Speeding up repetitive initialisation with structured data?"
}
|
26385
|
<p>I am unit testing this role provider. I have a few asserts in the code for my test. I am sure there are more test I could preform. Does anyone have any suggestions for more test for this role of the membership provider?</p>
<pre><code>[TestMethod]
public void TestDeleteUserAccess()
{
try
{
string sRoleName = "TestRole";
string sUsername = "test.user";
// Use a known user for relationships
AsaMembershipProvider prov = this.GetMembershipProvider();
MembershipUser user = prov.GetUser(sUsername, false);
// Create a new role
AsaRoleProvider roleProv = this.GetRoleProvider();
roleProv.CreateRole(sRoleName);
// Verify that role exists
bool bRoleExists = roleProv.RoleExists(sRoleName);
Assert.IsTrue(bRoleExists);
// Add users to that role
string[] usernames = new string[] { sUsername };
string[] roleNames = new string[] { sRoleName };
roleProv.AddUsersToRoles(usernames, roleNames);
// Verify that user is in role
bool bRelationExists = roleProv.IsUserInRole(sUsername, sRoleName);
Assert.IsTrue(bRelationExists);
// Check various methods for finding role information
string[] matchUsernames = roleProv.FindUsersInRole(sRoleName, "userx");// find constant
foreach (string matchUsername in matchUsernames)//if match.length = 0 then roles were returned
{
Trace.WriteLine("Found in role " + sRoleName + ", user " + matchUsername + ". ");//check something instead of trace
}
string[] matchRoleNames = roleProv.GetRolesForUser(sUsername);
foreach (string matchRoleName in matchRoleNames)
{
Trace.WriteLine("Found for user " + sUsername + ", role " + matchRoleName + ". ");
}
// Remove user from the role
roleProv.RemoveUsersFromRoles(usernames, roleNames);
// Verify that user is no longer in the role
bRelationExists = roleProv.IsUserInRole(sUsername, sRoleName);
Assert.IsFalse(bRelationExists);
// Delete the role
roleProv.DeleteRole(sRoleName, true);
// Verify that no longer exists
bRoleExists = roleProv.RoleExists(sRoleName);
Assert.IsFalse(bRoleExists);
}
catch (Exception ex)
{
LogMessage(ex);
Assert.Fail(ex.Message);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T11:48:22.263",
"Id": "40890",
"Score": "0",
"body": "You are not doing unit testing here. Do you want to do unit test or do you want to test that `AsaMembershipProvider` implements `MembershipProvider` correctly? In any case you are asserting too much for one test."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T13:15:40.800",
"Id": "40899",
"Score": "0",
"body": "The objective is to make sure AsaMembershipProvider implements MembershipProvider correctly."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T13:39:25.460",
"Id": "40900",
"Score": "0",
"body": "Check [Implementing a Membership Provider](http://msdn.microsoft.com/en-us/library/f1kyba5e%28v=vs.100%29.aspx). Basic idea is for each **member** in the \"Required MembershipProvider Members\" table you should write several tests, covering each testable specification from the **description** column. You can look at [here](http://code.ingres.com/ingres/drivers/dot_net/roles/main/TestIngresAspNetProviders/) for an idea of how should test cases look. But it has a restrictive license, so do not use any code directly."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T14:54:15.937",
"Id": "40915",
"Score": "0",
"body": "Another word of caution with the linked example, they use `DbUnit` for populating the data source for each test. I strongly suggest you clean up your data source, such that it is empty for the start of each test and any change to the data source is visible to the reader of the test without reading an external xml file hundreds of lines long."
}
] |
[
{
"body": "<p>I am going to suggest a few improvements.</p>\n\n<p>Most of the principles for code quality apply just as well to test code as it does to production code:\nYour tests should follow <strong>Single Responsibility Principle</strong>. A test should ascertain one feature; such that any change or discovery or addition of a feature does not cause you to fix many unrelated tests. Ideally any bug introduced will cause one test to fail and that test failure will direct the programmer to the cause of the bug.</p>\n\n<p>You should use <strong>Intention Revealing Names</strong>. The names of your tests should tell the reader of the tests what is being tested.</p>\n\n<p>For example <a href=\"http://msdn.microsoft.com/en-us/library/8fw7xh74%28v=vs.100%29.aspx\" rel=\"nofollow\">Implementing a Role Provider</a> says: \"<em>CreateRole method;\nTakes as input the name of a role and adds the specified role to the data source for the configured ApplicationName.</em>\" One test case for that spec could be:</p>\n\n<pre><code> public void WhenICreateARoleItExists() {\n roleProv.CreateRole(A_VALID_ROLE_NAME);\n\n Assert.IsTrue(roleProv.RoleExists(A_VALID_ROLE_NAME));\n }\n</code></pre>\n\n<p>This code is derived from your first assertion. Notice removal of code related to other assertions made the test more readable.</p>\n\n<p>You can initialize your <em>System Under Test</em> in a <code>[SetUp]</code> method and assign it to a field, here <code>roleProv</code>, so that common initialization code does not clutter the reader's view. You should also extract repeated constant values, here <code>A_VALID_ROLE_NAME</code>, to <code>const</code> members, and name them as descriptive as you can.</p>\n\n<p>You should also test that what your system should not do. For example, the document says : \"You should throw a ProviderException if the specified role name already exists for the configured ApplicationName.\"</p>\n\n<pre><code> public void MultipleRolesCannotBeCreatedWithSameName() {\n var sameName = A_VALID_ROLE_NAME;\n roleProv.CreateRole(sameName);\n\n Assert.Throws<ProviderException>(delegate {roleProv.CreateRole(sameName);});\n }\n</code></pre>\n\n<p>Any unexpected exception should not be caught and indicates a broken test. Your test runner should , and most probably does, log its message and stack trace. Any expected exception should not cause the test to fail. You can remove your try/catch above.</p>\n\n<p>I noticed that you write the values to the <code>Trace</code> if a collection is returned from a tested method. That is totally useless. If a test does not <code>Assert</code>, it is not a test. A test should fail when the functionality it is testing is not working. </p>\n\n<pre><code> // Names are just to give you an idea\n public void WhenIAddSomeUsersToSomeRolesTheirRolesIncludeAllOfThoseRoles() {\n // Given some users\n var userNames = new string[] { A_VALID_USER_NAME, ANOTHER_VALID_USER_NAME};\n foreach(var userName in userNames) {\n createUserWithName(userName);\n }\n\n // And some roles\n var roleNames = new string[] { A_VALID_ROLE_NAME, ANOTHER_VALID_ROLE_NAME};\n foreach(var roleName in roleNames) {\n createRoleWithName(roleName);\n }\n\n // When I add those users to those roles\n roleProv.AddUsersToRoles(userNames, roleNames);\n\n // Each users roles contain all of those roles\n // This could be done more idiomatically by someone more familiar with C#\n foreach(var userName in userNames) {\n Assert.That(roleNames, Is.SubsetOf(roleProv.GetRolesForUser(sUsername)));\n }\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T12:24:58.673",
"Id": "26468",
"ParentId": "26388",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "26468",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-20T21:58:37.007",
"Id": "26388",
"Score": "4",
"Tags": [
"c#",
"unit-testing"
],
"Title": "Unit test provider roles"
}
|
26388
|
<p>I want to adopt good coding habits now. the below code was written under tight constraints. We don't do assignment post mortems in class to discuss "real world" best practices -- we just get letter grades with little or no feedback. What are some examples of good questions I can ask myself to determine when code that works for an assignment would be re-written in real world applications?</p>
<p>(I'm also very interested in memory management, which we haven't covered in class. Any memory management tips re: the below code would be super-appreciated!)</p>
<p>Note: this is a finished assignment; I'm not looking for help to complete it, just help to develop good habits as early as possible.</p>
<p><strong>Assignment</strong>: </p>
<ul>
<li>simulate 5,500 craps games and print out the results. </li>
<li>other than <code>main()</code>, use only one function -- <code>dice_roll()</code>. All calculations are inline.</li>
<li>the assignment covers, <code>enums</code>, output precision and <code>rand()</code> and <code>srand()</code> functions.</li>
<li>use <code>enum</code> to define WIN, LOSE, and CONTINUE to give the results for each roll.</li>
<li>use <code>const</code> data sizes: <code>int SIZE</code> and <code>int ROLLS</code>.</li>
</ul>
<p>Please feel free to provide any comments/questions as you see fit.</p>
<pre><code>#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <ctime>
// this is what will hold our data during the games
struct nodeType
{
int num_rolls;
int win;
int loss;
nodeType* link;
};
// these pointers will be used to traverse and perform operations
// on the nodes as we figure out what to do with them
nodeType *first, *last, *current, *trailCurrent, *newNode, *temp;
int roll_dice();
int main()
{
enum gameOutcome { CONTINUE, WIN, LOSE };
gameOutcome game_result;
const int MAX_GAMES(5500);
int sum, point, roll;
first = NULL; // start of our list
last = NULL; // end of our list
srand(time(0)); // give rand() new seed
for (int i = 1; i <= MAX_GAMES; ++i) // this for loop simulates all games
{
sum = roll_dice();
newNode = new nodeType; // create new node for this game
newNode->link = NULL; // make sure it doesn't point to anything
switch (sum) // first roll test
{
case 7:
game_result = WIN;
roll = 1;
case 11:
game_result = WIN;
roll = 1;
break;
case 2:
game_result = LOSE;
roll = 1;
case 3:
game_result = LOSE;
roll = 1;
case 12:
game_result = LOSE;
roll = 1;
break;
default:
game_result = CONTINUE;
point = sum;
roll = 1;
break;
} // end of switch
while (game_result == CONTINUE) // if no win/lose after 1st roll
{
sum = roll_dice();
++roll;
if (sum == point)
game_result = WIN;
else if (sum == 7)
game_result = LOSE;
}
// these assignments prepare our node fields to accept the
// game outcome data
newNode->num_rolls = roll;
newNode->win = 0;
newNode->loss = 0;
if(game_result == WIN)
newNode->win = 1; // adds one win for unique # of rolls
else
newNode->loss = 1; // adds one loss for unique # of rolls
if(first == NULL) // if empty list creates list on first roll
{
first = newNode;
last = newNode;
}
else
{
current = first; // starts search at beginning of list
int found(0); // use for list elem search
while (current != NULL && found < 1) // search to insert ascending order
{
if (current->num_rolls == roll) // has a game w/ this number of rolls
{ // been played?
if (game_result == WIN)
current->win += 1; // if so add one win to that "row"
else
current->loss += 1; // if so add one loss to that "row"
found = 1;
}
else if (current->num_rolls > roll) // if game's #rolls is < than some
found = 2; // #rolls in the list
else
{
trailCurrent = current;
current = current->link; // advances the search one node
}
} // end of while
if (found == 1)
delete[] newNode; // if #rolls for complete game already exists,
// delete this node. this is like "deduping" a
// database to first normal form
else if (current == first) // inserts node at beginning of list
{
newNode->link = first;
first = newNode;
}
else
{
trailCurrent->link = newNode; // inserts node in middle of list
newNode->link = current;
if (current == NULL) // if it's the biggest #rolls so far
last = newNode; // insert node at end of list
} // end of last else
} // end of 1st else
} // end of main for loop
int sum_wins(0), sum_loss(0);
current = first; // set to first node in list before iterating over it
while (current != NULL) // print results and sum wins/losses
{
std::cout << std::setw(4) << current->win << " games won and "
<< std::setw(3) << current->loss << " games lost on roll "
<< current->num_rolls << std::endl;
sum_wins += current->win; // summing wins for use below
sum_loss += current->loss; // summing losses for use below
current = current->link;
}
// calculate the odds based on game results
std::cout << std::setiosflags(std::ios::fixed | std::ios::showpoint)
<< "\nodds of winning are " << sum_wins << " / "
<< sum_wins + sum_loss << " = " << std::setprecision(2)
<< 100.0 * sum_wins / (sum_wins + sum_loss) << "%." << std::endl;
// calculate avg num rolls per game
double avg_length(0);
current = first;
while (current != NULL)
{
avg_length += (current->win + current->loss) * current->num_rolls;
current = current->link;
}
std::cout << "avg num rolls/game is " << std::setprecision(2)
<< avg_length / 5500.00 << " rolls." << std::endl;
while (first != NULL) // destroy list
{
temp = first;
first = first->link;
delete[] temp;
}
last = NULL;
std::cout << "press RET to exit";
std::cin.get();
return 0;
} // end of int main()
int roll_dice()
{
return (rand() % 6) + (rand() % 6) + 2;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T01:42:07.620",
"Id": "40868",
"Score": "6",
"body": "well i know the program constraints limited you to only having 1 method. Real world says that is a bad habbit to have. Even worse is they want you to use the main method... Ugh my skin is crawling. Having one large method always screams refactor. There is nothing wrong with having many methods that only have 3-4 lines in them. It makes it easier to find bugs, and easier to read."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T01:44:20.113",
"Id": "40869",
"Score": "1",
"body": "second thing i see is inconsistent white spaces. What I mean by that is you want to be consistant with lines in between blocks of statements. Normally when you have to do that you would pull out that line block and make a method for it. It tells me that you naturally want to break it up into somethign that is easier to read. That is good. It's also general practice to not have a whitespace between your if and else statement."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T01:58:36.590",
"Id": "40870",
"Score": "3",
"body": "To answer your question about What questions you should ask your self. The one I use the most is, `Will I remember what this method does next month?` Next is `Can I make this easier to read?` another `Is my method doing more than 1 thing?`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T23:06:34.177",
"Id": "41049",
"Score": "0",
"body": "@RobertSnyder, thx for the feedback. those seem like some great questions to ask. also, what do you think about automated checkers, like this -- http://google-styleguide.googlecode.com/svn/trunk/cpplint/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-25T03:40:50.803",
"Id": "63329",
"Score": "0",
"body": "@d3vin why would you want to purposefully make your code as broken as Google's?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T08:31:25.133",
"Id": "70345",
"Score": "0",
"body": "@Cubbi - If you believe using Google's style guide/automated checker is counterproductive perhaps you could make an argument or link to a reputable source."
}
] |
[
{
"body": "<p>There are a number of things you want to ask yourself. The first is, \"in the real world, do these requirements make sense?\". In this case, the answer is an emphatic \"No\". </p>\n\n<blockquote>\n <p>other than main(), use only one function -- <code>dice_roll()</code>. all calculations are inline.</p>\n</blockquote>\n\n<p>This is a terrible requirement, and whoever wrote this assignment needs to be whacked with the common sense bat. It is teaching really bad practice right from the get go. It is never desirable to have a giant <code>main</code> function. </p>\n\n<p>The second question to ask is, \"Am I using <code>C++</code> or am I using <code>C</code> with <code>std::cout</code> instead of <code>printf</code>?\". Likely this is not your fault - any teacher who decides to make a student bundle all their code into the <code>main</code> function is doing a dubious job at best.</p>\n\n<p>Let's tackle both of these. If you want to learn, I'm going to say throw away some of these requirements. The real requirement of the program is:</p>\n\n<blockquote>\n <p>simulate 5,500 craps games and print out the results.</p>\n</blockquote>\n\n<p>Here, the requirement itself leads to a relatively easy breakup of the program structure. We'll keep it simple, and say we want 4 functions in total:</p>\n\n<ul>\n<li>A function to simulate dice rolls - <code>roll_dice()</code> (which already exists)</li>\n<li>A function to simulate the games and store the results in some kind of data structure - let's call it <code>run_simulation</code>. This will take as a parameter the number of games to play.</li>\n<li>A function to calculate and print statistics based on games. This will take the data structure from the previous function. </li>\n<li><code>main</code>, which will co-ordinate the above functions.</li>\n</ul>\n\n<p>One of the nice things about C++ is the rich set of data structures available in the standard library. These generally perform memory management for you. It isn't listed in the requirements, but from your code, you want something that will store the number of wins/losses for a given number of rolls in sorted order. </p>\n\n<p>Again, I'm not sure how much experience you have with data structures, however, the standard library has a good fit for this requirement: a <code>std::map</code>. A map stores key/value pairs in an efficient way, so that key lookup is fast. </p>\n\n<p>Ok, so we'll start as before: defining our <code>enum</code> and something to store our game data - call it (unimaginatively) <code>game_data</code>:</p>\n\n<pre><code>#include <iostream>\n#include <iomanip>\n#include <cstdlib>\n#include <ctime>\n#include <map> // <--- Additional include so we can use `std::map`\n\nenum game_outcome { CONTINUE, WIN, LOSE };\n\nstruct game_data\n{\n int win;\n int loss;\n\n game_data()\n : win(0),\n loss(0)\n { } \n\n game_data(int w, int l)\n : win(w),\n loss(l)\n { }\n};\n</code></pre>\n\n<p>Above, we've defined some constructors for our <code>game_data</code> type. Now, we'll define our <code>map</code> type:</p>\n\n<pre><code>typedef std::map<int, game_data> result_list;\n</code></pre>\n\n<p>This says the type <code>result_list</code> is a map from integers to keys. Here, the <code>int</code> key will be the number of rolls. A nice thing about <code>map</code> is that it stores things in <strong>sorted order</strong> - so our sorting comes for free.</p>\n\n<pre><code>int roll_dice()\n{\n return (rand() % 6) + (rand() % 6) + 2;\n}\n\nresult_list run_simulation(int num_games)\n{\n result_list results;\n static game_outcome outcome[] = {CONTINUE, CONTINUE, LOSE, LOSE, CONTINUE, CONTINUE, \n CONTINUE, WIN, CONTINUE, CONTINUE, CONTINUE, WIN,\n LOSE};\n\n for(int i = 0; i < num_games; ++i) {\n\n int roll = 1;\n int sum = roll_dice();\n game_outcome out = outcome[sum];\n\n while (out == CONTINUE) {\n int point = sum;\n sum = roll_dice();\n ++roll;\n if(sum == point) {\n out = WIN;\n }\n else if(sum == 7) {\n out = LOSE;\n }\n }\n game_data& d = results[roll];\n (out == WIN) ? ++d.win : ++d.loss;\n } \n\n return results;\n}\n</code></pre>\n\n<p>Firstly, we've replaced the <code>switch</code> statement with an array lookup, which makes the code a bit more concise and arguably less error prone (it's easy to forget <code>break</code> at the end of switch statements). The <code>while</code> loop is mostly unchanged, other than some reordering. What has mostly changed is the replacement of a lot of code with the two lines:</p>\n\n<pre><code>game_data& d = results[roll];\n(out == WIN) ? ++d.win : ++d.loss;\n</code></pre>\n\n<p>Lookup in a <code>map</code> can be done using <code>[]</code> syntax (much like arrays). If the key doesn't exist in this case, it is inserted. Thus, we lookup the data by <code>rolls</code>. For example, if <code>rolls</code> was 3, this would find the <code>game_data</code> class that sits in the map with the previous results for 3. Then, we simply increment the correct <code>win</code> or <code>loss</code> based on the outcome.</p>\n\n<p>Now, we need to write a function that will take what is in the map and print out some information from what is in it: let's call it <code>result_statistics</code>.</p>\n\n<pre><code>void result_statistics(const result_list& results, int num_games)\n{\n int wins = 0;\n int losses = 0;\n double avg_length = 0;\n\n for(auto const & p : results) {\n std::cout << std::setw(4) << p.second.win << \" games won and \" \n << std::setw(3) << p.second.loss << \" games lost on roll \"\n << p.first << \"\\n\";\n wins += p.second.win;\n losses += p.second.loss;\n avg_length += (p.second.win + p.second.loss) * p.first;\n }\n int total_games = wins + losses;\n std::cout << std::setiosflags(std::ios::fixed | std::ios::showpoint) \n << \"\\nodds of winning are \" << wins << \" / \"\n << total_games << \" = \" << std::setprecision(2)\n << 100.0 * wins / total_games << \"%.\" << \"\\n\";\n std::cout << \"avg num rolls/game is \" << std::setprecision(2)\n << avg_length / num_games << \" rolls.\" << \"\\n\";\n\n}\n</code></pre>\n\n<p>The print code is mostly the same.</p>\n\n<p>Finally, our new <code>main</code> function:</p>\n\n<pre><code>int main()\n{\n const int kGames = 5500;\n srand(time(nullptr));\n result_list r = run_simulation(kGames);\n result_statistics(r, kGames);\n}\n</code></pre>\n\n<p>Note how we can now follow (at least at a high level) the flow of the code. We define the total number of games, seed our random generator, run the simulations, and calculate the statistics from those runs. Breaking things up in this way makes things much easier to reason about and follow in the code.</p>\n\n<p>Even if some (or most) of this doesn't make sense to you yet, I think the main things to take away from this are that if you get told to shove everything into a <code>main</code> function, do it for your assignment if that is what is required. Afterwards, go back and split it up into smaller functions, each one having a specific, well defined, singular purpose. Compare the code from the two. Which one is easier to understand? Investigate the standard library, teach yourself as much as you can about it (basic containers are probably the most important thing for now). Finally, look at the assignment specs. Do they all make sense? Do they lead to more or less readable code? What would you do differently if you had free-reign?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T23:01:42.580",
"Id": "41047",
"Score": "0",
"body": "this is fantastic. thx for the feedback. much of what you included is new to me -- i.e. initializer lists in structures, maps, recursion -- and i'd like the opportunity to review and perhaps post some questions as comments. is that cool w/ you?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T23:04:34.153",
"Id": "41048",
"Score": "0",
"body": "also, i'm wondering if in your enum it would make sense to do this -- `static game_outcome outcome[] = {LOSE = 2, LOSE, CONTINUE, ... }` -- or if that just adds unnecessary complexity."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T01:46:22.860",
"Id": "41055",
"Score": "1",
"body": "@d3vin Sure, ask away. Unfortunately, you can't do the above with arrays like you can with an `enum` - it won't compile."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T03:08:29.400",
"Id": "26399",
"ParentId": "26395",
"Score": "22"
}
}
] |
{
"AcceptedAnswerId": "26399",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-20T23:59:32.307",
"Id": "26395",
"Score": "16",
"Tags": [
"c++",
"game"
],
"Title": "Simulating craps games"
}
|
26395
|
<p>I just have a somewhat simple question on coding practices. I have never written a large application before and I am currently working on building a game engine in JavaScript. The part that confuses me is what the best method of organization is in this particular case.</p>
<p>I have my base engine class, <code>Engine</code>, a graphics class, <code>GFXSystem</code>, and I eventually plan on adding a physics system class. I am utilizing the entity component model, so each object in the game world is represented as an entity and various data classes, called components, are added to an entity to represent its state and allow it to do things.</p>
<p>Some components need to report to the <code>GFXSystem</code> so that it knows to include them when it renders to the screen. The engine class is the all encompassing class that keeps track of both the entities and the graphics system, and calls the update method each frame to run update on each component on each entity and tells the <code>GFXSystem</code> to draw the next frame. An engine will always have one <code>GFXSystem</code>.</p>
<p>I started off exposing both the engine and the graphics system to window. I decided against this and then tried letting the engine have a reference to the graphics system and instead had the entity store a reference to the engine it was attached to. This then resulted in the components having to call the following to tell the GFX system that it needed to be rendered, which seems wrong:</p>
<pre><code>this.entity.engine.gfx.addToDraw(this)
</code></pre>
<p>Is that really how I should be doing things or is there some better structure I could follow? Not all components even need to do anything outside their own data.</p>
<p>Here is a sample of some of my code, bear with me, it is a bit hastily done since I am still in the initial stage of writing things just to get it to work.</p>
<pre><code>var Engine = function(){
this.graphics = new GFXSystem();
this.keyboard;
this.keys;
this.mouse;
this.__entityList = new EntityList();
//window.engine = this;
//window.renderer = this.__renderer;
this.start = function(){
this.graphics.start();
this.keyboard = new Keyboard();
this.keys = new Keys();
this.mouse = new Mouse();
}
this.update = function(time){
for(var handle = this.__entityList.head; handle != null; handle = handle.next){
handle.entity.updateComponents(time);
}
this.graphics.update(time);
};
this.addEntity = function(entity){
this.__entityList.Add(entity);
entity.engine = this;
};
};
</code></pre>
<p><strong>Graphics</strong></p>
<pre><code>var GFXSystem = function(){
this.renderer = null;
this.width = document.body.clientWidth;
this.height = document.body.clientHeight;
this.camera = null;
this.scene = null;
this.__list = new EntityList();
this.start = function(){
this.renderer = new THREE.WebGLRenderer({antialias: true});
this.renderer.setSize(this.width, this.height);
document.body.appendChild(this.renderer.domElement);
this.renderer.setClearColorHex(0xeeeeee, 1.0);
this.renderer.clear();
//this.camera = new THREE.PerspectiveCamera(45, this.width/this.height, 1, 10000);
//this.camera.position.z = 300;
this.scene = new THREE.Scene();
}
this.update = function(time){
/*
this.camera.position.x = Math.sin(time/1000)*300;
this.camera.position.y = 150;
this.camera.position.z = Math.cos(time/1000)*300;
*/
// you need to update lookAt on every frame
this.renderer.render(this.scene, this.camera.camera);
}
this.registerEntity = function(entity){
this.__list.Add(entity);
this.scene.add(entity.getComponent('render').model);
}
this.removeEntity = function(entity){
this.__list.Remove(entity);
this.scene.remove(entity.getComponent('render').model);
}
}
</code></pre>
<p><strong>Component</strong></p>
<pre><code>var RenderComponent = function(model){
this.model = model;
this.start = function(){
var pos = this.entity.getComponent('position');
model.position.x = pos.x;
model.position.y = pos.y;
model.position.z = pos.z;
this.entity.engine.graphics.renderer.registerEntity(this.entity);
};
this.update = function(time){
var pos = this.entity.getComponent('position');
model.position.x = pos.x;
model.position.y = pos.y;
model.position.z = pos.z;
};
this.stop = function(){
this.entity.engine.graphics.removeEntity(this.entity);
};
};
RenderComponent.prototype = new Component();
</code></pre>
<p>My old code set <code>window.graphics = this.graphics</code> and <code>window.engine = this.engine</code> inside of the engine's start method.</p>
|
[] |
[
{
"body": "<p>First of all, it's a bit surprising that you roll your own <code>EntityList</code>. I would expect an normal array to be more efficient and natural, at least when starting.</p>\n\n<p>A good mindset when thinking about coupling between parts of your code is to think about the specific problem of testing your code for correctness. It's a very real problem than you can solve, while \"having code that looks properly designed\" is not useful in itself.</p>\n\n<p>The first thing is that you should not expose global variables to <code>window</code> as it will make your code impossible to test: those variables will taint everything interesting in your code. The current code is still very much tied to the way the entity stores the engine, and the way your engine stores graphics. I've heard a lot of praise about the entity component model, but unfortunately I don't know how it's tested.</p>\n\n<p>A related issue to think about first is the way you model requirements between different parts of your code: take a look at the <a href=\"http://addyosmani.com/resources/essentialjsdesignpatterns/book/#modulepatternjavascript\" rel=\"nofollow\">module pattern</a> and consider using something like RequireJS to make dependency handling easier to manage.</p>\n\n<p>I guess there's no good way to separate the rendering part of the component from the graphics system, so it's OK to have coupling here, but avoid relying on knowing graphics/engine when you don't have to.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T07:55:24.150",
"Id": "26459",
"ParentId": "26396",
"Score": "3"
}
},
{
"body": "<p>You should be modifying <code>prototype</code>, instead of assigning <code>this.method</code> inside your constructor. Your constructor runs every time you instantiate your class; you're effectively rerunning the entire class definition, every time. Each instance of your class will have it's own set of functions, completely with all the associated overhead.</p>\n\n<p>This:</p>\n\n<pre><code>var Engine = function(){\n // ... \n this.start = function(){\n // ...\n }\n\n this.update = function(time){\n // ...\n };\n}\n</code></pre>\n\n<p>Should be this:</p>\n\n<pre><code>var Engine = function () {\n\n};\n\nEngine.prototype.start = function () {\n\n}\n\nEngine.prototype.update = function () {\n\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T20:31:28.903",
"Id": "26491",
"ParentId": "26396",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T00:32:32.290",
"Id": "26396",
"Score": "4",
"Tags": [
"javascript",
"object-oriented",
"graphics",
"entity-component-system"
],
"Title": "Game engine utilizing a custom graphics system"
}
|
26396
|
<pre><code>def _getCallerLogger():
caller = inspect.currentframe().f_back.f_back
name = "{}-{}".format(caller.f_globals['__name__'], caller.f_code.co_name )
logger = logging.getLogger(name)
return logger
log = lambda msg : _getCallerLogger().debug(msg)
info = lambda msg: _getCallerLogger().info(msg)
warning = lambda msg: _getCallerLogger().warning(msg)
error = lambda msg: _getCallerLogger().error(msg)
critical = lambda msg: _getCallerLogger().critical(msg)
</code></pre>
<p>I have the above logging code in my application so I can just call <code>log</code> from anywhere and it will print the file and where the log method was called from. </p>
<p>Would there be anything wrong with this in the long run? </p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T12:20:50.793",
"Id": "40891",
"Score": "1",
"body": "why not `log = _getCallerLogger().debug`? why dont' you set the logger in a variable instead of creating a new one 5 times?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T12:39:18.277",
"Id": "40893",
"Score": "0",
"body": ":) Might have over thought it on the day"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T12:42:54.353",
"Id": "40895",
"Score": "0",
"body": "Well that also wouldn't work because I call these methods from all over the code base and in that case _getCallerLogger() would only be called once."
}
] |
[
{
"body": "<p>The logging module already supplies a function name to log messages. If you want to include the function name in your log message just set the appropriate formatter with <code>%(funcName)s</code> in the format string on your log handler with: <a href=\"http://docs.python.org/2/library/logging.html#logging.Handler.setFormatter\" rel=\"nofollow\">http://docs.python.org/2/library/logging.html#logging.Handler.setFormatter</a></p>\n\n<p>See also <a href=\"http://docs.python.org/2/library/logging.html#logrecord-attributes\" rel=\"nofollow\">http://docs.python.org/2/library/logging.html#logrecord-attributes</a></p>\n\n<p>The typical usage is to create a global <code>log</code> variable in your module like</p>\n\n<pre><code>logger = logging.getLogger(__name__)\n</code></pre>\n\n<p>and use that logger within functions in that module. But creating a separate logger for every single function is excessive.</p>\n\n<p>I (just now) realized this is a pretty old question, but if you're still interested I can provide a full working example.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-31T01:40:38.727",
"Id": "38349",
"ParentId": "26400",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T03:40:28.697",
"Id": "26400",
"Score": "3",
"Tags": [
"python",
"logging"
],
"Title": "Any side effects from this Python logging code?"
}
|
26400
|
<p>I was asked to do a code review for the following block of code. It implemented a bug fix to prevent some values being added to some drop down lists depending on the user's domain, in an ASP.NET WebForms app. The three lines adding items to the lists were from the pre-bug-fix code (not part of the fix), so I didn't review it.</p>
<pre><code> //Only add corporate AD domain if the user is a member of it.
string domainName = "";
if (Thread.CurrentPrincipal == null)
{
//"Missing the thread identity";
}
else if (Thread.CurrentPrincipal.Identity.Name.IndexOf("\\") < 0)
{
//"No domain detected leave domain name blank.";
}
else
{
domainName = Utils.GetUserDomain(Thread.CurrentPrincipal).ToUpper();
}
if (domainName == Config.AppSettings.Domain.ToUpper())
{
domainUserDropDownList.Items.Add(new ListItem(Config.AppSettings.Domain, Config.AppSettings.Domain));
domainOfficeDropDownList.Items.Add(new ListItem(Config.AppSettings.Domain, Config.AppSettings.Domain));
domainTypeDropDownList.Items.Add(new ListItem(Config.AppSettings.Domain, Config.AppSettings.Domain));
}
</code></pre>
<p>I reviewed the code and suggested changing the code to the following:</p>
<pre><code> //Only add corporate AD domain if the user is a member of it.
var currentPrincipal = Thread.CurrentPrincipal;
var hasDomain = currentPrincipal != null && currentPrincipal.Identity.Name.Contains("\\");
var domainName = hasDomain ? Utils.GetUserDomain(currentPrincipal) : null;
if (string.Equals(domainName, Config.AppSettings.Domain, StringComparison.OrdinalIgnoreCase))
{
domainUserDropDownList.Items.Add(new ListItem(Config.AppSettings.Domain, Config.AppSettings.Domain));
domainOfficeDropDownList.Items.Add(new ListItem(Config.AppSettings.Domain, Config.AppSettings.Domain));
domainTypeDropDownList.Items.Add(new ListItem(Config.AppSettings.Domain, Config.AppSettings.Domain));
}
</code></pre>
<p>When the original developer saw the changes, he agreed with some of it (change of IndexOf to Contains, and ToUpper to String.Equals for case insensitive search), but not all of it. His main complaint was that the new code was more difficult to read and understand, and that the if blocks were clearer than the ternary operator. We weren't able to come to a point of agreement.</p>
<p>Could you please review both the original and new code and suggest improvements to either. Also, please point out any problems in the new code, especially where you think it is worse than the original code.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T08:53:38.673",
"Id": "40877",
"Score": "1",
"body": "What does `Utils.GetUserDomain()` do when it's passed `null` or principal without a domain? Wouldn't it make sense to change that?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T00:52:34.490",
"Id": "40966",
"Score": "0",
"body": "@svick - I'm not sure what it does exactly. It was existing code and outside of scope for the code I was reviewing. Both sets of code prevent a principal without a domain being passed into `GetUserDomain`."
}
] |
[
{
"body": "<p>Disclaimer: I'm not too familiar with C#.</p>\n\n<p>The modified form has expressions that are a little too complex for me, but either would be ok. My only comment is that the initial comment line is screaming for some notice:</p>\n\n<pre><code>// Only add corporate AD domain if the user is a member of it.\n</code></pre>\n\n<p>Why not take all the tests and put them into a function?</p>\n\n<pre><code>if ( IsMemberOfCorporateDomain( Thread.CurrentPrincipal ) ) ...\n</code></pre>\n\n<p>Then, depending on how you both feel about early exits:</p>\n\n<pre><code>private bool IsMemberOfCorporateDomain( IPrincipal currentPrincipal )\n{\n if ( currentPrincipal == null ) return false;\n if ( !currentPrincipal.Identity.Name.Contains(\"\\\\\") ) return false;\n\n var domainName = Utils.GetUserDomain(currentPrincipal);\n return string.Equals( domainName, Config.AppsSettings.Domain, StringComparison.OrdinalIgnoreCase )\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T15:17:19.030",
"Id": "40918",
"Score": "4",
"body": "+100. This is what self documenting code is. The advantages of this approach: 1. Now you know the 'semantics' of the code without having to read the actual code. 2. If for some reason there is a bug in the function and it throws an Exception, the last function in stack trace will be 'IsMemberOfCorporateDomain'. It immediately makes it clear about what went wrong. 3. Helps tremendously when reading the code. Let's me get to the meat of the program i.e. updating the drop down lists."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T15:22:56.800",
"Id": "40919",
"Score": "0",
"body": "Here's how I would do it: http://codereview.stackexchange.com/a/26435/4405"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T00:58:26.877",
"Id": "40967",
"Score": "0",
"body": "Good point. This is essentially the _Extract Method_ refactoring."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T07:21:22.680",
"Id": "26408",
"ParentId": "26401",
"Score": "16"
}
},
{
"body": "<p>Both solutions have their merits. The original code is very easy to read, well commented and employs good use of vertical space. Beyond the points you already mentioned, I find that the conditional feels backwards. It may have been easier to read as</p>\n\n<pre><code>if (we have a domain name) {\n domainName = ...;\n} else {\n // nope\n}\n</code></pre>\n\n<p>i.e. we test for the positive case, not for negations. Hiding the important part in an <code>else</code> is dubious.</p>\n\n<p>Your code does this, but presents two rather cluttered lines. It is slightly more self-documenting, but lacks visual structure. We can add parens to make the <code>?:</code> stand out more:</p>\n\n<pre><code>(hasDomain) ? (Utils.GetUserDomain(currentPrincipal)) : (null)\n</code></pre>\n\n<p>Or, preferably, use an if-statement again:</p>\n\n<pre><code>var domainName = \"\";\nif ( currentPrincipal != null\n && currentPrincipal.Identity.Name.Contains(\"\\\\\") // must detect a domain\n) {\n domainName = Utils.GetUserDomain(currentPrincipal);\n}\n</code></pre>\n\n<p>This splits the condition across multiple lines, thus making them easy to grok. Specifically, the formatting emphasizes operator precedence. On the right of each part of the condition, space for comments remains. I prefer <code>\"\"</code> over <code>null</code> (self-documenting), but you may have style guides that mandate one solution.</p>\n\n<p>How the closing paren of the condition is formatted is an open question. I've shown the solution I use, but indenting the <code>) {</code> by two spaces may be preferable, or even splitting them across two lines:</p>\n\n<pre><code>if ( condA\n && condB\n )\n{\n ...;\n}\n</code></pre>\n\n<p>You may have style guides which mandate a certain style.</p>\n\n<p>The <code>currentPrinciple</code> variable is a valuable addition, as it simplifies the remaining code.</p>\n\n<p>The not-reviewed code is sightly painful:</p>\n\n<ol>\n<li>it should use a loop to perform the same action on multiple objects.</li>\n<li>it should have been vertically aligned when no loop is used.</li>\n<li><code>domainXDropDownList</code> is reverse Hungarian Notation. The prefix <code>domain</code> indicates you may want to use an object with properties <code>User</code>, <code>Office</code> and <code>Type</code>. The suffix <code>DropDownList</code> is type information that should rather be expressed by the type system, so maybe another class.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T07:46:55.190",
"Id": "26409",
"ParentId": "26401",
"Score": "3"
}
},
{
"body": "<p>First of all I am reviewing your changes only, as per FAQ. \"How to do a codereview\" might be a question more suitable for <a href=\"http://programmers.stackexchange.com\">programmers SE</a>.</p>\n\n<p>Glenn has already pointed out that the newly added code should be extracted to another method(+1). I suggest a different signature. Before the method had no knowledge of thread or user principles, therefore it need not now either. And pulling the domain name from configuration in two different places is not a good idea.</p>\n\n<pre><code> string corporateDomain = Config.AppSettings.Domain;\n\n if (canAddDomain(corporateDomain))\n {\n domainUserDropDownList.Items.Add(new ListItem(corporateDomain, corporateDomain));\n domainOfficeDropDownList.Items.Add(new ListItem(corporateDomain, corporateDomain));\n domainTypeDropDownList.Items.Add(new ListItem(corporateDomain, corporateDomain));\n }\n\n private canAddDomain(string domain) {\n IsMemberOfDomain(Thread.CurrentPrincipal, domain)\n }\n// where IsMemberOfDomain is as Glenn implemented except domain is extracted as a parameter\n</code></pre>\n\n<p>As a next step refactoring these should probably be extracted as fields: <code>Thread.CurrentPrincipal.Identity.Name</code>, <code>Config.AppSettings.Domain</code></p>\n\n<p>That many dots and dependence on static properties makes your code untestable. Any bugs cannot be detected until it is pushed to production and when a bug occurs it would not be clear whether it is a configuration error or a programming error.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T22:14:30.083",
"Id": "40961",
"Score": "0",
"body": "I totally agree with caching the `corporateDomain` value, but as stated in the question, that part of the code wasn't under review. It is part of the existing mess :) Thank you for the suggestion though. If I were writing the original code I would have done it your way too."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T08:18:54.380",
"Id": "26411",
"ParentId": "26401",
"Score": "3"
}
},
{
"body": "<ul>\n<li><p>I would extract a static method named <code>GetDomainNameIfPresent()</code> (<code>GetDomainNameOrNull()</code> might also be a good name for that).</p></li>\n<li><p>I would extract another method: <code>AddDomainFromAppSettingsToDropDownLists()</code></p></li>\n</ul>\n\n<p>By extracting these methods, you get a more self-documenting code (that nedds less comments) and that is more likely to be re-used instead of re-written.</p>\n\n<p>But looking at the bigger picture, you might want to take advantage of MVVM and data binding (WPF). Then you would not operate on the <code>Items</code> property of the <code>ComboBox</code>es, but on the collection(s) that are bound to their <code>ItemsSource</code> property.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T08:19:57.660",
"Id": "26412",
"ParentId": "26401",
"Score": "0"
}
},
{
"body": "<pre><code>//These two lines of code tells you exactly what's happening without burying\n//you with the details. It almost reads like plain English instead of code.\nif(IsMemberOfCorporateDomain(Thread.CurrentPrincipal))\n AddCorporateDomainToDropDowns();\n\n\nprivate void AddCorporateDomainToDropDowns()\n{ \n //I don't think you need to set both Text and Value, \n //check http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listitem.aspx\n\n domainUserDropDownList.Items.Add(new ListItem(Config.AppSettings.Domain));\n domainOfficeDropDownList.Items.Add(new ListItem(Config.AppSettings.Domain));\n domainTypeDropDownList.Items.Add(new ListItem(Config.AppSettings.Domain));\n}\n\nprivate bool IsMemberOfCorporateDomain(IPrincipal principal)\n{\n var domainName = GetDomainName(principal);\n\n return domainName != null && domainName.Equals(Config.AppSettings.Domain, StringComparison.OrdinalIgnoreCase);\n}\n\n//This function's only job is to get domain name from a given principal.\n//This will allow you to use this function elsewhere if needed. \nprivate string GetDomainName(IPrincipal principal)\n{\n if(principal == null || principal.Identity == null || principal.Identity.Name == null)\n return null;\n\n if(principal.Identity.Name.Contains(\"\\\\\"))\n return null;\n\n return Utils.GetUserDomain(principal.Identity.Name);\n}\n</code></pre>\n\n<p>That's how I would do it. As I wrote in my comment elsewhere, the advantages are:</p>\n\n<ol>\n<li>The code becomes self documenting. Now you know the 'semantics' of the code without having to read the actual code. </li>\n<li>If for some reason there is a bug in a function (say GetDoaminName) and it throws an Exception, the last function in stack trace will be 'GetDomainName'. It immediately makes it clear where the problem is.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T16:53:14.567",
"Id": "40935",
"Score": "0",
"body": "Welcome to Code Review and thanks for your answer! In general, feel free to explain your choices a bit more."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T17:05:22.707",
"Id": "40938",
"Score": "0",
"body": "@QuentinPradet For some reason, I am not able to format the code anymore. Could you please help?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T18:25:22.250",
"Id": "40939",
"Score": "0",
"body": "It's great as it is, isn't it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T19:39:54.093",
"Id": "40948",
"Score": "0",
"body": "@QuentinPradet Well, I figured out how to fix it. But thanks for checking! :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T19:55:07.693",
"Id": "40950",
"Score": "0",
"body": "@SolutionYogi, why would you return null from GetDomainName? What's wrong with string.Empty?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T22:48:25.723",
"Id": "40965",
"Score": "0",
"body": "`private void AddCorporateDomainToDropDowns()` is too repetitive for my taste. I do not know what the remedy would be, but I do not like that repetition - it does not scale."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T01:11:40.897",
"Id": "40968",
"Score": "0",
"body": "@SolutionYogi - `IsMemberOfCorporateDomain` is at risk of a `NullReferenceException` if `GetDomainName` returns null. `String.Equals` would fix that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T01:18:19.337",
"Id": "40969",
"Score": "0",
"body": "@SolutionYogi - I like how your solution has changed the main code to `if(IsMemberOfCorporateDomain(Thread.CurrentPrincipal))\n AddCorporateDomainToDropDowns();`. That is awesome, very compact and readable. However, overall, your code listing is now much larger than either of the original code pieces. That bit makes me a little uneasy. I do like the code more readable, but I also prefer less code too."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T03:53:45.340",
"Id": "40973",
"Score": "0",
"body": "@GiddyUpHorsey Sorry, I missed that NRE. I fixed that problem. BTW, I don't think the code listing is much larger. Mainly, I am doing additional check that principal.Identity and principal.Identity.Name is not null either because I don't see any guarantees in docs that they won't be null. Personally, if I had two choices, few more lines of code v/s readability, I will pick the later. Remember, you read code way more often than you write it. Additionally, I also care about how my stack trace looks like when an Exception occurs."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T03:54:54.110",
"Id": "40974",
"Score": "1",
"body": "@JeffVanzella Personally, I like to use Code Contracts to mark methods as Null or Not Null returning so that static analysis can check for errors during compile time itself. Returning string.Empty won't help the static analyzer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T03:55:26.253",
"Id": "40975",
"Score": "0",
"body": "@Leonid Could you clarify what you mean by `IsMemberOfCorporateDomain` being repetitive?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T17:56:07.367",
"Id": "41022",
"Score": "0",
"body": "@SolutionYogi, not what I wrote. I find `someDropDownList.Items.Add(new ListItem(Config.AppSettings.Domain));` x 3 repetitive."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T18:02:15.390",
"Id": "41024",
"Score": "0",
"body": "@Leonid Oh, I see. But there are three drop downs. There is no way to avoid writing three lines of code to populate three drop downs."
}
],
"meta_data": {
"CommentCount": "13",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T15:24:04.163",
"Id": "26435",
"ParentId": "26401",
"Score": "5"
}
},
{
"body": "<p>I normally format my ternary expressions (for the purposes of readability) as follows:</p>\n\n<pre><code>var hasDomain = currentPrincipal != null &&\n currentPrincipal.Identity.Name.Contains(\"\\\\\");\n\nvar domainName = hasDomain ? \n Utils.GetUserDomain(currentPrincipal) : \n null;\n</code></pre>\n\n<p>Perhaps this is an acceptable compromise?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T16:00:36.777",
"Id": "26440",
"ParentId": "26401",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "26435",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T04:30:52.757",
"Id": "26401",
"Score": "10",
"Tags": [
"c#"
],
"Title": "Is the new version of this code more difficult to read and understand than the original? How can it be improved?"
}
|
26401
|
<p>This is the second submission for Code Review for this project, but since the API changed considerably I felt it should not be attached to the original post. To see the original post and comment see <a href="https://codereview.stackexchange.com/questions/26268/potential-problems-with-this-templating-technique">Potential Problems with this templating technique</a>.</p>
<p>First off the goals motivation for this technique is to reduce the number of iterative includes of a template there by bypassing a lot of the I/O bottle neck that can occur, especially in I/O bound environments. </p>
<p>Overwhelmingly the biggest eyesore in the previous implementation was the use of <code>file_get_contents</code> and <code>create_function</code> to create the rendering function. I have sidestepped that in this implementation that creating a stream wrapper that does the dirty work of creating an anonymous function out of an included file.</p>
<p>I have also addressed some security issues that where brought up by jailing the source of template variables to the contents of developer specified directories. </p>
<p><strong>Overview of the Technique</strong></p>
<p>User will create an instance of the Template Processor (<code>Templar</code>), add Template root paths and then call one of the render methods passing in a template file and an array of variables which will be <code>extract</code>ed into the scope of the rendering function.</p>
<p><strong><em>Example</em></strong></p>
<pre><code>$tp = new Templar();
$tp->addTemplateDirectory(APPLICATION_PATH."/templates");
$tp->displayTemplate("page.phtml", array("who"=>"world","excitement_level"=>4));
</code></pre>
<p>A typical Template would look like this</p>
<pre><code><p>Hello <?= $who ?><?php
for($x = 0; $x<$excitement_level; $x++) echo "!"
?></p>
<p><?= $this->render("/template/motd.phtml"); ?></p>
</code></pre>
<p>Which as you would expect would result in...</p>
<pre><code><p>Hello world!!!!</p>
<p>Today is a good day.</p>
</code></pre>
<p>This use case provides no real benefit vs. native <code>include</code>, the benefit is realized when you iteratively call a template, say like outputting rows of a of a database result set, say of 500 results. The include method would result in 500 file system reads whereas this template system nets us 1. Performance that I noticed on a side by side comparison is of the two techniques was that it ran in 1/7th of the time and consumed at it's peak a little over half the amount of memory. </p>
<p><strong>Templar.php</strong></p>
<pre><code>class Templar {
protected $templateCache;
protected $templatePaths;
public function __construct(){
$this->templateCache = array();
$this->templatePaths = array();
// make sure the stream wrapper is registered
if (!in_array("templar.template", stream_get_wrappers())){
stream_register_wrapper("templar.template", "Templar_StreamWrapper");
}
}
/**
* Add a directory to the path cache
*
* @param string $path The path to the template
* @return Templar fluent interface
**/
public function addTemplatePath($path){
// Make sure the directory ends in exactly one DIRECTORY_SEPARATOR
$path = rtrim($path,DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR;
// if the path doesn't exist the fail silently
if (file_exists($path)){
$this->templatePaths[] = $path;
}
return $this;
}
/**
* Add Template Paths to the template
*
* @param array $paths
* @return Templar fluent interface
**/
public function addTemplatePaths($paths){
foreach($paths as $path){
$this->addTemplatePath($path);
}
}
/**
* Creates a template function
*
* @param string $path The path to the template
* @return callable the compiled function
* @throws Templar_Exception if the template can't be found or parsed
**/
protected function createTemplate($path){
// Jail the template resolution to directories under the template directories - per Sébastien Renauld @ Stackoverflow
// Make sure template exist in one of the template directories -- no ../ paths and no //
if (strpos($path, "..") !== false || strpos($path, "//") !== false) {
throw new Templar_Exception("Templates must exist in one of the template directories");
}
$path = ltrim($path, DIRECTORY_SEPARATOR);
if (!file_exists($path)) {
foreach($this->templatePaths as $testPath){
if (file_exists($testPath . $path)){
$targetPath = realpath($testPath . $path);
break; // break out of if and foreach;
}
}
// if I make it here and I don't have a valid template there a problem
if (!$targetPath){
throw new Templar_Exception("Could not load template [" . $path . "]");
}
}
$template = new Templar_Template($this, include('templar.template://'.$targetPath));
$this->templateCache[$path] = $template;
}
/**
* Returns an instance of a template function
*
* @param string $path The Path to the Template
* @return Callable The template function
**/
public function getTemplateFunction($path){
if (!array_key_exists($path, $this->templateCache)){
$this->createTemplate($path);
}
return $this->templateCache[$path];
}
/**
* Returns a rendered Template
*
* @param string $template Path to the template
* @param array $data
* @return string The renderer Template
**/
public function renderTemplate($template, $data = array()){
return $this->getTemplateFunction($template)->render($data);
}
/**
* Outputs a rendered Template
*
* @param string $template Path to the template
* @param array $data
* @return string The renderer Template
**/
public function displayTemplate($template, $data = array()){
$this->getTemplateFunction($template)->display($data);
}
}
</code></pre>
<p><strong>Templar/Template.php</strong></p>
<pre><code>class Templar_Template {
protected $processor;
protected $tmplFunction;
public function __construct(Templar $processor, $tmplFunction){
if (!is_callable($tmplFunction)) {
throw new Templar_Exception("Passed a [".gettype($tmplFunction)."] to Template Constructor expecting [Callable]");
}
$this->processor = $processor;
$this->tmplFunction = $tmplFunction->bindTo($this);
$that = $this;
}
public function __invoke(array $data){
$this->display($data);
}
public function display($data = array()){
$c = $this->tmplFunction;
return $c($data);
}
public function render($data = array()){
ob_start($data);
$this->display($data);
return ob_get_clean();
}
public function renderTemplate($template, $data = array()){
return $this->processor->renderTemplate($template, $data);
}
public function displayTemplate($template, $data = array()){
$this->processor->displayTemplate($template, $data);
}
}
</code></pre>
<p><strong>Templar/StremWrapper.php</strong> - The base of which was shamelessly stolen from Zend Frameworks' <code>Zend_View_Stream</code> class. </p>
<pre><code>class Templar_StreamWrapper {
/**
* The head matter for the callback function
**/
protected $functionHead = '<?php return function($__data){extract($__data);unset($__data);?>';
/**
* The foot matter for the callback function
**/
protected $functionFoot = '<?php };';
/**
* Current stream position.
*
* @var int
*/
protected $_pos = 0;
/**
* Data for streaming.
*
* @var string
*/
protected $_data;
/**
* Stream stats.
*
* @var array
*/
protected $_stat;
/**
* Opens the script file and converts markup.
*/
public function stream_open($path, $mode, $options, &$opened_path)
{
// get the view script source
$path = str_replace('templar.template://', '', $path);
if (strpos($path, "//") != false){
throw new Templar_Exception("Local Urls Please [".$path."]");
}
$template = trim(file_get_contents($path));
// expand the <?= to <?php echo if the server doesn't support it.
if (phpversion() < '5.4.0' && !ini_get('short_open_tag')){
$template = str_replace("<?=", "<?php echo");
}
// allow production code to opt out of static analysis
if (!(defined("TEMPLAR_DISABLE_STATIC_TEMPLATE_ANALYSIS") && TEMPLAR_DISABLE_STATIC_TEMPLATE_ANALYSIS == true)){
$toks = token_get_all($template);
$openTags = count(array_filter($toks, function($tok){ return $tok[0] != T_OPEN_TAG && $tok[0] != T_OPEN_TAG_WITH_ECHO; }));
$closeTags = count(array_filter($toks, function($tok){ return $tok[0] != T_CLOSE_TAG; }));
if ($openTags != $closeTags){
throw new Templar_Exception("Opening/Closing Tag Mismatch in template [".$path."] (".$openTags." vs ".$closeTags.")");
}
}
$this->_data = $this->functionHead.file_get_contents($path).$this->functionFoot;
/**
* If reading the file failed, update our local stat store
* to reflect the real stat of the file, then return on failure
*/
if ($this->_data === false) {
$this->_stat = stat($path);
return false;
}
$this->_stat = stat($path);
return true;
}
/**
* Included so that __FILE__ returns the appropriate info
*
* @return array
*/
public function url_stat()
{
return $this->_stat;
}
/**
* Reads from the stream.
*/
public function stream_read($count)
{
$ret = substr($this->_data, $this->_pos, $count);
$this->_pos += strlen($ret);
return $ret;
}
/**
* Tells the current position in the stream.
*/
public function stream_tell()
{
return $this->_pos;
}
/**
* Tells if we are at the end of the stream.
*/
public function stream_eof()
{
return $this->_pos >= strlen($this->_data);
}
/**
* Stream statistics.
*/
public function stream_stat()
{
return $this->_stat;
}
/**
* Seek to a specific point in the stream.
*/
public function stream_seek($offset, $whence)
{
switch ($whence) {
case SEEK_SET:
if ($offset < strlen($this->_data) && $offset >= 0) {
$this->_pos = $offset;
return true;
} else {
return false;
}
break;
case SEEK_CUR:
if ($offset >= 0) {
$this->_pos += $offset;
return true;
} else {
return false;
}
break;
case SEEK_END:
if (strlen($this->_data) + $offset >= 0) {
$this->_pos = strlen($this->_data) + $offset;
return true;
} else {
return false;
}
break;
default:
return false;
}
}
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T05:44:18.380",
"Id": "26403",
"Score": "1",
"Tags": [
"php",
"template"
],
"Title": "Templating engine that uses closures to eliminate iterative includes"
}
|
26403
|
<p>I am a huge proponent of self-documenting code (when at all possible). I prefer to have code be self evident by the very nature of the names of the variables, methods, etc.</p>
<p>For instance:</p>
<pre><code>if (TheSky.IsBlue && TheGrass.IsGreen)
BeHappy();
</code></pre>
<p>I have run into a situation that has defied all attempts to name the method in a way that illustrates what it does. The problem is that the method is required to do two things.</p>
<p>I have a class that must maintain its own state, however it must have a method that both verifies a condition, and changes the state via a thread safe lock to prevent race conditions.</p>
<p>It basically looks like the code below:</p>
<pre><code>public class TimeWindow
{
private static object lockObject = new object();
private DateTime Timestamp;
private int WindowCounter;
// What do I call this? CanWeDoSomething() implies that it is merely
// calculating a true/false state, not mutating state.
//
// I don't want to call it
// CanWeDoSomethingAndDecrementItIfWeActuallyDoIt() as that is
// just too annoying, and it messes up the self-documenting nature
// since if (CanWeDoSomethingAndDecrementItIfWeAcutallyDoIt()) describes
// two actions, but only one of them is a Boolean condition, so it doesn't
// really fit in with the if statement.
public bool CanWeDoSomething(int WindowSeconds) {
lock(lockObject) {
if ((DateTime.Now - TimeStamp).TotalSeconds > WindowSeconds) {
Timestamp = DateTime.Now;
WindowCounter = 0;
}
if (WindowsCounter < 10) {
++WindowCounter;
return true;
}
return false;
}
}
}
</code></pre>
<p>As you can see, I have to perform the test (to retrieve the Boolean) and modify state at the same time. If I didn't do this, then a race condition is possible where the value can be changed by another thread in between checking it's value and mutating its state.</p>
<p>The naming is important because if it implies no state change, then people call the method multiple times without realizing that it also changes state.</p>
<p>Can anyone suggest a name that adequately documents what the method is doing, without making it overly complex? The name should indicate that it's mutating the object as well as performing an action that is a Boolean state.</p>
<p>Alternatively, if you can suggest a better way to accomplish this in a thread safe manner that would work better, that would be good too.</p>
|
[] |
[
{
"body": "<p>I would call this method <code>AcquireTimeSlot</code> or similar, since the main action here is actually capturing a timely-limited resource. Result of the method specifies whether resource has been acquired or not. You may also call it <code>TryAcquireTimeSlot</code> to highlight the fact that acquisition may fail.</p>\n\n<p>As a side note - you can rewrite the code without locks in case if that's the only place you use the <code>lockObject</code>. It will be a bit more verbose though...</p>\n\n<pre><code>public class TimeWindow\n{\n private static readonly object _lockObject = new object();\n private long _timestampTicks;\n private int _windowCounter;\n\n private void CheckWindowExpiration(int windowSeconds)\n {\n long timestampTicks = _timestampTicks;\n while (TimeSpan.FromTicks(DateTime.Now.Ticks - timestampTicks).TotalSeconds > windowSeconds)\n {\n if (Interlocked.CompareExchange(ref _timestampTicks, DateTime.Now.Ticks, timestampTicks) == timestampTicks)\n {\n _windowCounter = 0;\n break;\n }\n\n timestampTicks = _timestampTicks;\n }\n }\n\n public bool TryAcquireTimeSlot(int windowSeconds)\n {\n CheckWindowExpiration(windowSeconds);\n\n int windowCounter = _windowCounter;\n while (windowCounter < 10)\n {\n if (Interlocked.CompareExchange(ref _windowCounter, windowCounter + 1, windowCounter) == windowCounter)\n return true;\n\n windowCounter = _windowCounter;\n }\n\n return false;\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T09:05:07.877",
"Id": "40880",
"Score": "2",
"body": "1. I would go with the `Try-` naming. Similar .Net methods use that naming convention (e.g. those from `System.Collections.Concurrent`). 2. I wouldn't use `Interlocked` here unless the lock was too slow. Code that uses `lock` is much easier to understand and also much easier to get right."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T09:58:14.560",
"Id": "40885",
"Score": "0",
"body": "@svick agree, I added `Interlocked` version as an example of lock-free implementation. It's always good to know your options :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T15:00:31.320",
"Id": "40917",
"Score": "0",
"body": "Out of curiosity, why did you choose to do the math via ticks? It seems like there are more conversions involved there."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T22:33:36.140",
"Id": "40962",
"Score": "1",
"body": "@MystereMan There are no `Interlocked` methods for `DateTime`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T08:44:35.273",
"Id": "40989",
"Score": "0",
"body": "yep, @svick is right, I had to switch to ticks in order to use atomic operations on it."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T08:52:01.680",
"Id": "26413",
"ParentId": "26407",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "26413",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T07:12:39.620",
"Id": "26407",
"Score": "5",
"Tags": [
"c#"
],
"Title": "Function that tests and mutates"
}
|
26407
|
<p>I am required to read the following text from a keyboard (<code>stdin</code>). Please note that it will be entered by the user from the keyboard in this format only.</p>
<pre><code> #the total size of physical memory (units are B, KB, MB, GB)
512MB 2 #the following are memory allocations
{
abc = alloc(1KB);
{
y_ = alloc(128MB);
x1= alloc(128MB);
y_ = alloc(32MB);
for (i = 0; i < 256; i++) abc[i] =alloc(512kB);
x1 = alloc(32MB); x2 = alloc(32MB); x3 = alloc(32MB);
x1.next = x2, x2.next = x3, x3.next = x1;
}
abc = alloc(256MB);
}
</code></pre>
<ul>
<li><p>A line beginning with the <code>#</code> sign is considered a comment and is ignored.</p></li>
<li><p>The first two allocations are physical memory size and number of generations.</p></li>
<li><p>A global bracket will be opened and it may be followed by a line called</p>
<pre><code>abc = alloc(1KB);
</code></pre>
<p>where <code>abc</code> is the object name and 1KB is the memory size allocated.</p></li>
<li><p><code>x1.next = x2</code>, where <code>x1</code> points to <code>x2</code>.</p></li>
<li><p>The <code>for</code> loop is entered in this format and it can have a same-line command or can have nested <code>for</code> loops.</p>
<pre><code>for (i = 0; i < 256; i++) abc[i] =alloc(512kB);
</code></pre></li>
</ul>
<p>I have the following code that somewhat takes care of this. I want to know how to improve on it.</p>
<pre><code>#include <iostream>
#include <algorithm>
#include <string>
#include <iomanip>
#include <limits>
#include <stdio.h>
#include <sstream>
using namespace std;
using std::stringstream;
string pMem,sGen, comment,val,input,input_for,id_size,id,init_str1, init_str2, inc_str, id_dummy,s_out,sss, id_dummy1;
int gen=0, pMem_int=0,i=0, gBrckt =0,cBrckt=0, oBrckt=0, id_size_int,v1,v2, for_oBrckt=0,for_cBrckt=0,y=0, y1=0, g=0;
unsigned long pMem_ulong =0, id_size_ulong;
char t[20], m[256], init1[10],init2[10],inc[10];
unsigned pos_start, pos,pos_strt=0,pos_end=0;
string extract(string pMem_extract);
unsigned long toByte(int pMem_int_func, string val);
void commentIgnore(string& input);
void func_insert();
void func_insert_for();
stringstream out;
void commentIgnore_for(string& input_for);
int main()
{
/* Reading the input main memory and num of generations */
/* Ignoring comment line */
cin >> pMem;
if(pMem == "#") {
cin.clear();
pMem.clear();
getline(cin,comment);
cin >> pMem;
}
if(pMem == "#") {
cin.clear();
pMem.clear();
getline(cin,comment);
cin >> pMem;
}
if(pMem == "#") {
cin.clear();
pMem.clear();
getline(cin,comment);
cin >> pMem;
}
/* Reading input generations */
cin>> sGen;
if(sGen == "#") {
cin.clear();
sGen.clear();
getline(cin,comment);
cin >> sGen;
}
if(sGen == "#") {
cin.clear();
sGen.clear();
getline(cin,comment);
cin >> sGen;
}
if(sGen == "#") {
cin.clear();
sGen.clear();
getline(cin,comment);
cin >> sGen;
}
/* Convert sGen and physical memory to int and report error if not a number */
gen = atoi(sGen.c_str());
if(gen ==0) {
cerr << "Generation must be a number"<<endl;
exit(0);
}
pMem_int = atoi(pMem.c_str());
// cout<< gen<<" "<<pMem_int<<endl;
/* Now that the number from pMem is removed, get its unit B,MB,KB */
extract(pMem); /* returns val(string) */
/* convert the given physical memory to Byte. input: pMem_int*/
toByte(pMem_int, val); /* return(pMem_ulong)*/
// move pMem_ulond to another location to keep address intact
/* read rest of the inputs */
/* Ignore comment lines before the global bracket */
cin >> input;
if(input == "#"){
cin.clear();
input.clear();
getline(cin,comment);
cin >> input;
}
if(input == "#"){
cin.clear();
input.clear();
getline(cin,comment);
cin >> input;
}
if(input == "#"){
cin.clear();
input.clear();
getline(cin,comment);
cin >> input;
}
if(input.compare("{") ==0)
gBrckt=1;
else {
cerr<< "Syntax error\n";
exit(0);
}
/* Clearing the input stream for next input */
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cin.clear();
input.clear();
//cout<<"input: "<<input<<endl;
while( getline(cin,input)) {
if(input == "CTRL-D")
break;
commentIgnore(input);
//cout<<"inputloop: "<<input<<endl;
/* If input = '{' or '}'*/
if(input.compare("{") ==0)
oBrckt = oBrckt + 1;
if (input.compare("}") ==0)
cBrckt = cBrckt + 1;
if (((input.find("alloc"))!= string::npos) && (input.find("alloc") < input.find("for"))) {
func_insert();
//call the allocate function here with name: id, size: id_size_ulong
}
if ((input.find("for")) != string::npos) {
sscanf(input.c_str(), "for (%s = %d; %s < %d; %[^)])", init1, &v1, init2, &v2, inc);
init_str1 = init1, init_str2 = init2, inc_str = inc;
cout<<init1<<" ="<< v1<<" "<<init_str1<<" < " << v2<< " "<< inc_str<<endl;
cout << input <<endl;
if(init_str1 != init_str2) {
cerr << "Error!\n";
exit(0);
}
if ((input.find("alloc"))!= string::npos) {
// unsigned pos = (input.find("alloc"));
if((input.find(";")) != string::npos) {
pos_start = (input.find(")")+1);
string alloc_substr = input.substr(pos_start);
cout<<"Substring alloc: "<< alloc_substr<<endl;
func_insert();
//call the allocate function here with name: id, size: id_size_ulong
}
else {
cerr << "ERROR: SYNTAX\n";
exit(0);
}
}
// cin.ignore();
while(getline(cin,input_for)) {
commentIgnore_for(input_for);
if ((input_for.find("{") != string::npos)) {
pos = input_for.find("{");
for_oBrckt = for_oBrckt+1;
string for_brckt = input_for.substr(pos,pos);
cout<< "Found: " << for_oBrckt<<endl;
}
if ((input_for.find("}") != string::npos)) {
pos = input_for.find("}");
for_cBrckt = for_cBrckt+1;
string for_brckt = input_for.substr(pos,pos);
cout<< "Found: " << for_cBrckt<<endl;
}
if (((input_for.find("alloc"))!= string::npos) && (input_for.find("alloc") < input_for.find("for"))) {
func_insert_for();
//call the allocate function here with name: id, size: id_size_ulong
}
if(for_oBrckt == for_cBrckt)
break;
}
cout<<"out of break"<<endl;
}
if (((input.find(".next"))!= string::npos) && (input.find(".next") < input.find("for"))) {
func_insert();
//call the allocate function here with name: id, size: id_size_ulong
}
if(((cBrckt-oBrckt)) == gBrckt)
break;
}
}
/*---------------------- Function definitions --------------------------------*/
/* Function to extract the string part of physical memory */
string extract(string pMem_extract) {
i=0;
const char *p = pMem_extract.c_str();
for(i=0; i<=(pMem_extract.length()); i++) {
if (*p=='0'|| *p=='1'|| *p=='2'|| *p=='3'|| *p =='4'|| *p=='5'|| *p=='6'|| *p=='7'|| *p=='8'|| *p=='9')
*p++;
else {
val = pMem_extract.substr(i);
return(val);
}
}
}
/* Convert the physical memory to bytes. return(pMem_ulong);*/
unsigned long toByte(int pMem_int_func, string val)
{
if (val == "KB")
pMem_ulong = (unsigned long) pMem_int_func * 1024;
else if (val == "B")
pMem_ulong = (unsigned long) pMem_int_func;
else if (val == "GB")
pMem_ulong = (unsigned long) pMem_int_func * 1073741824;
else if (val == "MB")
pMem_ulong = (unsigned long) pMem_int_func * 1048576;
else {
cerr<<"Missing the value in memory, B, KB, MB, GB\n";
exit(0);
}
return(pMem_ulong);
}
/*Ignoring comment line*/
void commentIgnore(string& input)
{
unsigned found = input.find('#');
if (found!=std::string::npos)
input= input.erase(found);
else
return;
return;
}
void func_insert() {
sscanf(input.c_str(), "%s = alloc(%[^)]);", t, m);
id =t;
id_size =m;
cout<<"Tag: "<<id <<" Memory: "<<id_size<<endl;
extract(id_size); /* Separates B,MB,KB and GB of input, returns val*/
id_size_int = atoi(id_size.c_str());
/* Convert object size to B */
toByte(id_size_int, val); /* return(pMem_ulong) */
id_size_ulong = pMem_ulong;
}
void func_insert_for() {
sscanf(input_for.c_str(), "%s = alloc(%[^)]);", t, m);
id =t;
id_size =m;
if(!((id.find("[")) && (id.find("]")) != string::npos)) {
cout<<"Tag: "<<id <<" Memory: "<<id_size<<endl;
extract(id_size); /* Separates B,MB,KB and GB of input, returns val*/
id_size_int = atoi(id_size.c_str());
/* Convert object size to B */
toByte(id_size_int, val); /* return(pMem_ulong) */
id_size_ulong = pMem_ulong;
// allocate here
return;
}
else {
if(inc_str.find("++"))
y1 =1;
if(inc_str.find("="))
{
sss = inc_str.substr(inc_str.find("+") +1);
y1 = atoi(sss.c_str());
cout<<"y1:"<<y1<<endl;
}
pos_strt = id.find("[");
pos_end = id.find("]") -1;
cout<<"Positions start and ebd: " << pos_strt<<pos_end<<endl;
id_dummy = id.substr(0,pos_strt);
id = id_dummy;
cout<<"Tag: "<<id_dummy <<" Memory: "<<id_size<<endl;
extract(id_size); /* Separates B,MB,KB and GB of input, returns val*/
id_size_int = atoi(id_size.c_str());
/* Convert object size to B */
toByte(id_size_int, val); /* return(pMem_ulong) */
id_size_ulong = pMem_ulong;
//allocate here
cout<<"v1: " << v1 << " " << v2<<endl;
// g = 0;
for(y = v1; y < v2; y= y+y1) {
// allocate here
}
}
return;
}
void commentIgnore_for(string& input_for)
{
unsigned found = input_for.find('#');
if (found!=std::string::npos)
input_for= input_for.erase(found);
else
return;
return;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T07:51:37.037",
"Id": "40875",
"Score": "0",
"body": "Also i am required to make it whitespace compatible. What it means is that input can be entered in one line as well. like two allocations in one line. Which i dont think i have taken care of."
}
] |
[
{
"body": "<ul>\n<li><p>With this much code, you definitely should avoid using <code>using namespace std</code>. More info about that can be found <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">here</a>.</p></li>\n<li><p>You have <em>a lot</em> of global variables, and you shouldn't have any. They're generally discouraged as they can be modified <em>anywhere</em> within the program. This can introduce bugs, and it'll just make maintenance more painful. Only use them when you have no other choice.</p>\n\n<p>Otherwise, in this procedural code, just pass to variables to functions as needed. That'll limit the variables scopes to which entity needs them, and it'll vastly improve your code. Based on the rest of the code, it looks like you've declared most of the variables in global. This is either lack of awareness of global variables, or some kind of laziness with handling variables.</p></li>\n<li><p>Keep your use of indentation and whitespace consistent. Four spaces is customary for indentation, and there should be whitespace between operators and after commas.</p></li>\n<li><p>Don't leave commented-out code present; it just clutters your code. If there's a specific reason for doing that in certain places, specify that; otherwise, leave it out.</p></li>\n<li><p>Instead of having all those function prototypes, have <code>main()</code> defined below each of the functions. That way, they'll already be recognized by <code>main()</code> when you need to call them from there.</p></li>\n<li><p><code>void</code> functions don't need an explicit <code>return</code> at the end; they'll always return there. However, you'll still need it if you need to exit from the function prematurely.</p></li>\n<li><p>For the input blocks in <code>main()</code>, have each different one in a different loop, rather than typing out each one. Don't Repeat Yourself (DRY).</p>\n\n<p>Each of those different blocks are done three times, so have a <code>for</code> loop for each one (using the first as an example):</p>\n\n<pre><code>for (int i = 0; i < 3; i++)\n{\n if(pMem == \"#\") {\n cin.clear();\n pMem.clear();\n getline(cin,comment);\n cin >> pMem;\n }\n}\n</code></pre>\n\n<p>Also, since you have <code>std::cin</code> and <code>std::getline</code> together, you should have <code>std::ignore</code> between them here, and in other similar instances.</p></li>\n<li><p>In <code>toByte</code>, there's no need for C-style casts. Use C++-style casts here, specifically with <code>static_cast<></code>:You don't need a C-style cast here:</p>\n\n<pre><code>pMem_ulong = static_cast<unsigned long>(pMem_int_func);\n</code></pre></li>\n<li><p>It doesn't make sense to call <code>exit(0)</code> after reporting an error. The <code>0</code> argument indicates successful termination, whereas <code>1</code> indicates failure.</p>\n\n<p>Moreover, since this is done in <code>main()</code>, just use <code>return 1</code>.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T00:56:09.100",
"Id": "44716",
"ParentId": "26410",
"Score": "5"
}
},
{
"body": "<p>I don't understand what your program is doing: you've defined what the input is, but haven't said what the output must be.</p>\n\n<p>Re. making it \"whitespace compatible\", your program is parsing input. Parsing is often done in two stages:</p>\n\n<ul>\n<li>A \"<a href=\"http://en.wikipedia.org/wiki/Lexical_analysis\">lexer</a>\" splits the input stream into 'tokens'</li>\n<li>A second-stage \"parser\" combines the tokens with a \"grammar\"</li>\n</ul>\n\n<p>Examples of the things (different types of thing) which I think could be 'one token' in the input stream are:</p>\n\n<ul>\n<li>Whitespace</li>\n<li>Comment</li>\n<li>Puntuation (e.g. '=', ';', '{', '++', etc.)</li>\n<li>Identifier, i.e. alphabetic first character followed by one or more alphanumerics (e.g. \"abc\", \"alloc\", \"x2\"</li>\n<li>Numbers (e.g. \"2\", \"256\")</li>\n<li>Memory (e.g. \"1KB\", \"512MB\")</li>\n</ul>\n\n<p>I think your code would be clearer if you did it in two stages:</p>\n\n<ul>\n<li>Inspect the stream of input characters and turned it into a list of \"tokens\"</li>\n<li>Parse the input list of tokens</li>\n</ul>\n\n<p>A \"token\" could be represented by a class and enum for example:</p>\n\n<pre><code>enum TokenType\n{\n Comment,\n Whitespace,\n Punctuation,\n ... etc ...\n}\n\nstruct Token\n{\n TokenType tokenType; // e.g. Memory\n std::string value; // e.g. \"512MB\"\n};\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T01:30:01.430",
"Id": "44718",
"ParentId": "26410",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T07:47:17.030",
"Id": "26410",
"Score": "5",
"Tags": [
"c++",
"strings",
"stream"
],
"Title": "Reading input from keyboard"
}
|
26410
|
<p>Is there a safer/ more readable way of using this code?
I gotta translate this code into a better , safer and more readable sample of code and get my onclick to work.(its currently called from another thread then what it is created from.)</p>
<pre><code>public class TemperaturePresenter
{
MainView _view;
// TODO ojoj det blev lite stökigt här
public TemperaturePresenter(){
_view = new MainView();
ThreadPool.QueueUserWorkItem(
delegate{
XmlDocument serverDoc = new XmlDocument();
serverDoc.Load("ServerUrls.xml");
var location = serverDoc.SelectSingleNode("//servers/server/url");
string serverUrl = location.InnerText;
var searchNode = serverDoc.SelectSingleNode("//servers/server/xpath");
var searchPath = searchNode.InnerText;
WebRequest req = WebRequest.Create(serverUrl);
var response = req.GetResponse();
var a = response;
Stream stream = response.GetResponseStream();
XmlDocument responseDoc = new XmlDocument();
responseDoc.Load(stream);
var temperatureNode = responseDoc.SelectSingleNode(searchPath);
string temperature = temperatureNode.Attributes["value"].Value;
SetTemperature(temperature);
});
}
void SetTemperature(string temperature) {
//if ( _view.InvokeRequired ){
// _view.Invoke( (Action<string>) SetTemperature, temperature);
// return;
//}
_view.Temperature = temperature;
}
public Form Form { get{ return _view; } }
</code></pre>
<p>Next page:</p>
<pre><code>public partial class MainView : Form
{
public MainView()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//fyll
throw new NotImplementedException("cant press on this button, yet!");
}
public string Temperature {
set {
tempLbl.Text = String.Format("{0} grader celcius", value);
Refresh();
}
</code></pre>
<p>Im thinking i need to do some "this.thread" stuff, but i dont know how.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T12:23:20.030",
"Id": "40892",
"Score": "0",
"body": "Safer, yes: you should be wrapping all creations of objects which implement `IDisposable` in a `using` statement. For example, `Stream`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T12:53:49.567",
"Id": "40896",
"Score": "0",
"body": "You should wrap `req.GetResponse()` in a try/catch, since it *will* throw a `WebException` eventually. Any service going through a network is not reliable."
}
] |
[
{
"body": "<p>Well, at first glance, i think it should be:</p>\n\n<ul>\n<li><p>Constructor shouldn't have any logic other than initialization. Any I/O, Threads .... operations would be better to start in custom method. So, in your case i will write:</p>\n\n<p>public TemperaturePresenter(){\n _view = new MainView();\n}</p></li>\n<li><p>delegate in your example very large, my opinion - it should be extracted as a new method</p></li>\n<li>Webrequest in Presenter? It depends, but I think it no so good. May be it would be better if you extract web-request logic as external dependency like ITemperatureProvider. Because now, it pull dependency on webserver file and file working into the presenter - it has some smell.</li>\n</ul>\n\n<p>At first glance that's all.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T11:10:18.323",
"Id": "26417",
"ParentId": "26415",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T09:40:38.017",
"Id": "26415",
"Score": "1",
"Tags": [
"c#"
],
"Title": "Is there a safer/ more readable way of using this code?"
}
|
26415
|
<p>I am attempting to develop an XML schema (XSD) to represent a set of unit tests for some code. (Specifically, I am testing Oracle PL/SQL stored procedures.)</p>
<p>I would like to have something that represents:</p>
<ul>
<li>the procedure itself</li>
<li>the data used for each test (both arguments to be supplied to the procedure, and data to be loaded into the database before beginning the test(s))</li>
<li>the expected result of each test</li>
</ul>
<p>Each procedure can have multiple tests, but I think I would like to only have the tests for one procedure in each XML file.</p>
<p>Below is the schema I have so far: any comments or suggestions would be welcomed!</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<schema targetNamespace="http://www.example.com/TestData"
elementFormDefault="qualified" xmlns="http://www.w3.org/2001/XMLSchema"
xmlns:tns="http://www.example.com/TestData">
<complexType name="ProcedureType">
<complexContent>
<extension base="tns:AbstractProcedureType">
</extension>
</complexContent>
</complexType>
<complexType name="FunctionType">
<complexContent>
<extension base="tns:AbstractProcedureType">
<attribute name="ReturnType" type="tns:DataTypeType"></attribute>
</extension>
</complexContent>
</complexType>
<complexType name="AbstractProcedureType" abstract="true">
<sequence>
<element name="PackageName" type="string" minOccurs="0" maxOccurs="1"></element>
<element name="Name" type="string" minOccurs="1" maxOccurs="1"/>
<element name="Arguments" type="tns:ArgumentsType"
minOccurs="1" maxOccurs="1" />
</sequence>
</complexType>
<complexType name="ArgumentType">
<attribute name="Name" type="string" use="required"/>
<attribute name="DataType" type="tns:DataTypeType"
use="required"/>
</complexType>
<simpleType name="DataTypeType">
<restriction base="string">
<enumeration value="VARCHAR2"/>
<enumeration value="NUMBER"/>
</restriction>
</simpleType>
<complexType name="TestType">
<sequence>
<choice maxOccurs="1" minOccurs="1">
<element name="Procedure" type="tns:ProcedureType"></element>
<element name="Function" type="tns:FunctionType"></element>
</choice>
<element name="Instance" type="tns:TestInstanceType"></element>
</sequence>
</complexType>
<complexType name="TestInstanceType">
<sequence>
<element name="Arguments" type="tns:ArgumentType"
maxOccurs="unbounded" minOccurs="0">
</element>
<element name="ExpectedResult"
type="tns:ExpectedResultType" maxOccurs="1" minOccurs="1">
</element>
</sequence>
</complexType>
<complexType name="ExpectedResultType">
<attribute name="Type" use="required">
<simpleType>
<restriction base="string">
<enumeration value="value"></enumeration>
<enumeration value="exception"></enumeration>
<enumeration value="null"></enumeration>
<enumeration value="nothing"></enumeration>
<enumeration value="query"></enumeration>
</restriction>
</simpleType>
</attribute>
</complexType>
<complexType name="ArgumentsType">
<sequence>
<element name="Argument" type="tns:ArgumentType" maxOccurs="1" minOccurs="0"></element>
</sequence>
</complexType>
<element name="Tests" type="tns:TestsType"></element>
<complexType name="TestsType">
<sequence>
<element name="Test" type="tns:TestType" maxOccurs="unbounded" minOccurs="0"></element>
</sequence>
</complexType>
</schema>
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li>I would move <code>PackageName</code> and <code>Name</code> elements of the <code>AbstractProcedureType</code> to attributes.</li>\n<li>I don't think you need an <code>AbstractProcedureType</code>, just have a <code>ProcedureType</code> and <code>FunctionType</code> derived from it.</li>\n<li>it's not clear why <code>ArgumentsType</code> may have either 0 or 1 argument... I would say that it should have <code>maxOccurs=\"unbounded\"</code></li>\n<li>I would make <code>Arguments</code> element optional in <code>ProcedureType</code> and <code>FunctionType</code> (<code>minOccurs=\"0\"</code>), and require at least one argument if the node is present.</li>\n</ul>\n\n<p>Now let's move to global changes...</p>\n\n<ul>\n<li>Since you want to have a single procedure/function per XML we can move the declaration of procedure right under the root node.</li>\n<li>I removed some of the named complextypes in favor of in-place type definitions</li>\n<li>You can add some referential constraints to XSD (e.g. argument names in test should match procedure/function declaration).</li>\n</ul>\n\n<p>As a result of these changes I've got the following XSD:</p>\n\n<pre><code><?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<schema targetNamespace=\"http://www.example.com/TestData\"\n elementFormDefault=\"qualified\" xmlns=\"http://www.w3.org/2001/XMLSchema\"\n xmlns:tns=\"http://www.example.com/TestData\">\n <element name=\"Tests\" type=\"tns:TestsType\">\n <key name=\"Argument.Name\">\n <selector xpath=\"tns:Procedure/tns:Arguments/tns:Argument | tns:Function/tns:Arguments/tns:Argument\" />\n <field xpath=\"@Name\" />\n </key>\n </element>\n <complexType name=\"TestsType\">\n <sequence>\n <choice maxOccurs=\"1\" minOccurs=\"1\">\n <element name=\"Procedure\" type=\"tns:ProcedureType\" />\n <element name=\"Function\" type=\"tns:FunctionType\" />\n </choice>\n <element name=\"Test\" type=\"tns:TestInstanceType\" minOccurs=\"0\" maxOccurs=\"unbounded\" />\n </sequence>\n </complexType>\n <complexType name=\"ProcedureType\">\n <sequence>\n <element name=\"Arguments\" minOccurs=\"0\" maxOccurs=\"1\">\n <complexType>\n <sequence>\n <element name=\"Argument\" minOccurs=\"0\" maxOccurs=\"unbounded\">\n <complexType>\n <attribute name=\"Name\" type=\"string\" use=\"required\" />\n <attribute name=\"DataType\" type=\"tns:DataTypeType\" use=\"required\" />\n </complexType>\n </element>\n </sequence>\n </complexType>\n </element>\n </sequence>\n <attribute name=\"PackageName\" type=\"string\" use=\"optional\" />\n <attribute name=\"Name\" type=\"string\" use=\"required\" />\n </complexType>\n <complexType name=\"FunctionType\">\n <complexContent>\n <extension base=\"tns:ProcedureType\">\n <attribute name=\"ReturnType\" type=\"tns:DataTypeType\" use=\"required\" />\n </extension>\n </complexContent>\n </complexType>\n <simpleType name=\"DataTypeType\">\n <restriction base=\"string\">\n <enumeration value=\"VARCHAR2\" />\n <enumeration value=\"NUMBER\" />\n </restriction>\n </simpleType>\n <complexType name=\"TestInstanceType\">\n <sequence>\n <element name=\"Argument\" minOccurs=\"0\" maxOccurs=\"unbounded\">\n <complexType>\n <attribute name=\"Name\" type=\"string\" use=\"required\" />\n <attribute name=\"Value\" type=\"string\" use=\"required\" />\n </complexType>\n <keyref name=\"Argument.Name.Exists\" refer=\"tns:Argument.Name\">\n <selector xpath=\".\" />\n <field xpath=\"@Name\" />\n </keyref>\n </element>\n <element name=\"ExpectedResult\" type=\"tns:ExpectedResultType\" maxOccurs=\"1\" minOccurs=\"1\" />\n </sequence>\n </complexType>\n <complexType name=\"ExpectedResultType\">\n <attribute name=\"Type\" use=\"required\">\n <simpleType>\n <restriction base=\"string\">\n <enumeration value=\"value\" />\n <enumeration value=\"exception\" />\n <enumeration value=\"null\" />\n <enumeration value=\"nothing\" />\n <enumeration value=\"query\" />\n </restriction>\n </simpleType>\n </attribute>\n </complexType>\n</schema>\n</code></pre>\n\n<p>What I would do next:</p>\n\n<ul>\n<li>Create several elements for different expected result types (query, exception, etc) and define corresponding attributes and elements on them</li>\n<li>You can also replace generic <code>Argument</code> with typed elements, that will allow you to define even more constraints on values of arguments in tests</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T13:14:35.217",
"Id": "40998",
"Score": "0",
"body": "Excellent - thanks so much for your help!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T13:08:04.590",
"Id": "26423",
"ParentId": "26418",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "26423",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T11:25:48.857",
"Id": "26418",
"Score": "3",
"Tags": [
"unit-testing",
"xml",
"oracle",
"plsql",
"xsd"
],
"Title": "XML schema for Database Unit Tests"
}
|
26418
|
<p>I'm working on an application, which tracks expenses. I have users, and each user can create his categories for the expenses (like Food, Bills, Transport, Drinks, Clothes) and then create expenses - each expense has one category (OneToMany relationship).</p>
<p>For example, the expense Banana is in the category Food for the user Faery. I also have months for each user. For example, for March 2013, user Faery has a budget of 500. For March 2013, user SuperCoolUser has a budget of 900 and so on.</p>
<p>Here are my entities:</p>
<p><strong>User.php</strong></p>
<pre><code>/**
* @ORM\Entity
* @ORM\Table(name="fos_user")
*/
class User extends BaseUser
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORM\OneToMany(targetEntity="Category", mappedBy="category")
*/
protected $categories;
/**
* @ORM\OneToMany(targetEntity="Expense", mappedBy="expense")
*/
protected $expenses;
public function __construct()
{
parent::__construct();
$this->categories = new ArrayCollection();
$this->expenses = new ArrayCollection();
}
// ...
}
</code></pre>
<p><strong>Category.php</strong></p>
<pre><code>/**
* @ORM\Table(name="category")
* @UniqueEntity(fields={"name", "user"})
*/
class Category
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORM\OneToMany(targetEntity="Expense", mappedBy="expense")
*/
protected $expenses;
public function __construct()
{
$this->expenses = new ArrayCollection();
}
/**
* @ORM\Column(type="string", length=100)
protected $name;
/**
* @ORM\ManyToOne(targetEntity="User", inversedBy="fos_user")
* @ORM\JoinColumn(name="fos_user_id", referencedColumnName="id")
*/
protected $user;
// ...
}
</code></pre>
<p><strong>Expense.php</strong></p>
<pre><code>/**
* @ORM\Table(name="expense")
*/
class Expense
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORM\ManyToOne(targetEntity="User", inversedBy="fos_user")
* @ORM\JoinColumn(name="fos_user_id", referencedColumnName="id")
*/
protected $user;
/**
* @ORM\ManyToOne(targetEntity="Category", inversedBy="category")
* @ORM\JoinColumn(name="category_id", referencedColumnName="id")
*/
protected $category;
/**
* @ORM\Column(type="string", length=100)
*/
protected $product;
/**
* @ORM\Column(type="string")
*/
protected $description;
/**
* @ORM\Column(type="float")
*/
protected $price;
/**
* @ORM\Column(type="date")
*/
protected $date;
// ...
}
</code></pre>
<p><strong>Month.php</strong></p>
<pre><code>/**
* @ORM\Table(name="month")
*/
class Month
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORM\Column(type="string")
*/
protected $name;
/**
* @ORM\ManyToOne(targetEntity="User", inversedBy="fos_user")
* @ORM\JoinColumn(name="fos_user_id", referencedColumnName="id")
*/
protected $user;
/**
* @ORM\Column(type="float")
*/
protected $budget;
/...
}
</code></pre>
<p>All of this looked fine to me, but I noticed that category, month, expense, all of these has a connection to User. I made this for the queries to be more convenient, but isn't it becoming too duplicated?</p>
<p>I have really little experience with databases and with programming, but I want the application to become nice and the code to be of good quality.</p>
<p>I want to know if this code is too problematic and connected and duplicated, or it's allowable. And if it's not please give me some advice or ideas on how to implement this better.</p>
|
[] |
[
{
"body": "<p>IMO this is great, it's nicely normalised. You're separating things logically into models.</p>\n\n<p>The only thing that's puzzling me is...what is your 'Month' entity for? None of your other Entities reference it?</p>\n\n<p>I don't know if:</p>\n\n<pre><code>/**\n * @ORM\\OneToMany(targetEntity=\"Expense\", mappedBy=\"expense\")\n */\nprotected $months;\n</code></pre>\n\n<p>Is meant to reference months? I'm guessing it is.</p>\n\n<p>The only thing I can think of is that you're using one model to satisfy two different entities : the categories model.</p>\n\n<p>If I were you I would split it into to things:</p>\n\n<pre><code>User_Categories\n</code></pre>\n\n<p>and</p>\n\n<pre><code>Expense_Categories\n</code></pre>\n\n<p>This is something I often do, and I've found it better than having one abstract category entity. Having more tables has almost no downsides from a programatic point of view.</p>\n\n<p>The only other thing I can think of really is, even if (as above) you meant to have a month entity, what is it for? It's actually a <em>budget</em> entity, not a month entity.</p>\n\n<p>Date/time models are already abstracted quite well in doctrine itself (just have a column [or two] specifying the date range), so having a <em>budget</em> entity makes much more sense, then you can specify arbitrary budget time periods instead of the monthly constraint.</p>\n\n<p>Hope this helps!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T06:01:25.480",
"Id": "40978",
"Score": "0",
"body": "The month entity really doesn't have references to the other entities. I just need a way the user to say how much money he has for the month so that when he enters his expenses, the app can tell him how much money he has left for the month. And I should remove the reference to months in the User controller. Thanks very much for your answer! It's really helpful! :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T16:19:15.770",
"Id": "26442",
"ParentId": "26420",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T11:51:40.950",
"Id": "26420",
"Score": "1",
"Tags": [
"php",
"database",
"doctrine",
"symfony2"
],
"Title": "Database \"design\" using Symfony2 and Doctrine2"
}
|
26420
|
<p>Doing database access in ViewModel is generally considered a bad practice. However, when you have a <code><select></code> in your view, you need to populate it using the ViewBag or the ViewModel (I prefer the ViewModel). This leads to the following code:</p>
<pre><code>public class NewUserViewModel
{
public string Username {get;set;}
public IEnumerable<SelectListItem> Cities {get;set;}
public User User // Helper to retrieve user
{
get { return new User() { Username = this.Username; }}
set { this.Username = value.Username; }
}
}
</code></pre>
<p>We now have to populate the Cities twice:</p>
<pre><code>public ActionResult New()
{
var vm = new NewUserViewModel();
vm.Cities = addressRepository.GetAllCities().Select(c => new SelectListItem() { Text = c.Name, Value = c.Id });
return View(vm);
}
[HttpPost]
public ActionResult Create(NewUserViewModel vm)
{
if(ModelState.IsValid)
{
userRepository.Add(vm.User);
return RedirectToAction("Index");
}
else
{
vm.Cities = addressRepository.GetAllCities().Select(c => new SelectListItem() { Text = c.Name, Value = c.Id }); // Copy this line
return View(vm);
}
}
</code></pre>
<p>I came up with an approach to solve this problem:</p>
<pre><code>public NewUserViewModel(AddressRepository addressRepository) {
this.Cities = addressRepository.GetAllCities().Select(c => new SelectListItem() { Text = c.Name, Value = c.Id });
}
</code></pre>
<p>I overrode the DefaultModelBinder to inject the Repository into the ViewModel.</p>
<pre><code>protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
{
return DependencyResolver.Current.GetService(modelType);
}
</code></pre>
<p>Now my controller is free:</p>
<pre><code>public ActionResult New()
{
// Is this bad too?
return View(DependencyResolver.Current.GetService<NewUserViewModel>());
}
public ActionResult Create(NewUserViewModel vm)
{
if(ModelState.IsValid)
{
userRepository.Add(vm.User);
return RedirectToAction("Index");
}
else
{
return View(vm);
}
}
</code></pre>
<p>If I think about it, having all the cities listed is ViewModel's job, not the controller's. This has one immediate downside: it fetches the <code>Cities</code> even when the <code>ModelState.IsValid</code>. However, that is not my concern. Is this bad practice? I won't do any more database access than this.</p>
|
[] |
[
{
"body": "<p>Yes I think its bad practise because you have introduced both complexity and dependencies when it simply isn't necessary. Its going to make your unit testing more difficult than it needs to be and it isn't the intended purpose of the your view models.</p>\n\n<p>Just create a private method in your controller that loads the data and populates the ListItems and call it where necessary. Agreed that it's not pretty but it will cause you less issues in the long run than what you are doing now. </p>\n\n<pre><code>public class AdminController : Controller\n{\n ...ctor etc...\n\n public ActionResult New()\n {\n var vm = new NewUserViewModel();\n PopulateListItems(vm);\n return View(vm);\n }\n\n [HttpPost]\n public ActionResult Create(NewUserViewModel vm)\n {\n if (ModelState.IsValid)\n {\n userRepository.Add(vm.User);\n return RedirectToAction(\"Index\");\n }\n else\n {\n PopulateListItems(vm);\n return View(vm);\n }\n }\n\n private static void PopulateListItems(NewUserViewModel vm)\n {\n vm.Cities = _addressRepository.GetAllCities().Select(c => new SelectListItem() { Text = c.Name, Value = c.Id });\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-06T15:10:29.770",
"Id": "404205",
"Score": "1",
"body": "5 years later, I agree with you :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T06:49:55.610",
"Id": "32226",
"ParentId": "26422",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "32226",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T12:53:16.450",
"Id": "26422",
"Score": "5",
"Tags": [
"c#",
"asp.net-mvc-4",
"dependency-injection"
],
"Title": "Select list items in ViewModel fetched using a Repository"
}
|
26422
|
<p>I'm quite new to javaScript and jQuery and wrote the following function to creat some dynamic tabs. I'd be very interested to know how professional programmers would improve this code.</p>
<p><a href="http://jsfiddle.net/8pLbt/" rel="nofollow">jsFiddle</a></p>
<p><strong>JavaScript</strong></p>
<pre><code>$(document).ready(function(){
function createVerticalTabs(options){
var container = options["container"];
var parentElement = options["parentElement"];
var childElement = options["childElement"];
var firstElement = options["firstElement"];
var tabClass = options["tabClass"];
var tabClassActive = options["tabClassActive"];
var closeOtherElements = options["closeOtherElements"]
var preventEvent = options["preventEvent"];
if(firstElement){
$(container+" "+childElement).not(":first").hide();
classToggle($(container+" "+childElement+":first").prev(parentElement), tabClass, tabClassActive);
}else{
$(container+" "+childElement).hide();
}
/* Click event */
$(container+" > "+parentElement).on("click", function(event){
if(preventEvent == true){
event.preventDefault();
}
/* Check if there're other active elements and close them if requested*/
if(closeOtherElements){
var otherActiveElement = $(this).parent().children(childElement);
if($(otherActiveElement).is(":visible")){
$(otherActiveElement).slideUp("slow");
classToggle($(otherActiveElement).prev(parentElement), tabClassActive, tabClass);
}
}
/* Show requested element */
var details = $(this).next(childElement);
if($(details).is(":visible")){
classToggle($(this), tabClassActive, tabClass);
$(details).slideUp("slow");
}else{
classToggle($(this), tabClass, tabClassActive);
$(details).slideDown("slow");
}
});
function classToggle(obj, remove, add){
return obj.removeClass(remove).addClass(add);
}
}
var options = {
container: ".testBox",
parentElement: "a",
childElement: "p",
tabClass: "title",
tabClassActive: "active",
firstElement: true,
closeOtherElements: true,
preventEvent: true
};
var options2 = {
container: ".testBox2",
parentElement: "h3",
childElement: "p",
tabClass: "title",
tabClassActive: "active",
firstElement: false,
closeOtherElements: false,
preventEvent: true
};
createVerticalTabs(options);
createVerticalTabs(options2);
});
</code></pre>
<p><strong>HTML</strong></p>
<pre><code><div class="testBox">
<a href="#">Anchor 1</a><p>Details of Anchor 1</p>
<a href="#">Anchor 2</a><p>Details of Anchor 2</p>
<a href="#">Anchor 3</a><p>Details of Anchor 3</p>
<a href="#">Anchor 4</a><p>Details of Anchor 4</p>
</div>
<div class="testBox2">
<h3>Anchor 1</h3><p>Details of Anchor 1</p>
<h3>Anchor 2</h3><p>Details of Anchor 2</p>
<h3>Anchor 3</h3><p>Details of Anchor 3</p>
<h3>Anchor 4</h3><p>Details of Anchor 4</p>
</div>
<div style="clear:both"></div>
</code></pre>
<p><strong>CSS</strong></p>
<pre><code>.testBox, .testBox2{ float:left; height:500px; margin:10px; }
.testBox a{ display:block; }
.testBox2 h3{ margin:0; padding:0; }
.title{ font-weight:bold; }
.active{ background:#333; border:#000 1px solid; color:#fff; }
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T14:03:31.093",
"Id": "40904",
"Score": "1",
"body": "Try not to write `== true`, it’s not a useful comparison."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T15:23:31.083",
"Id": "40920",
"Score": "0",
"body": "Really is not need to re map your options, especially manually. You can just use `options.tabClass` in your code"
}
] |
[
{
"body": "<ul>\n<li>I wouldn't change the entire code, but for performance you could compress the code.\n<a href=\"http://closure-compiler.appspot.com/\" rel=\"nofollow\">Closure compiler</a><br></li>\n<li>For a better UI I prefer twitters bootstrap (a sliding plugin included).\n<a href=\"http://twitter.github.io/bootstrap/\" rel=\"nofollow\">Bootstrap</a></li>\n<li>Use <strong>.click</strong> instead of <strong>.on('click')</strong></li>\n<li>Save variables you use often in a variable. For example $(otherActiveElement) or $(this)</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T14:02:47.620",
"Id": "40903",
"Score": "0",
"body": "a) Minification isn’t really a code improvement suggestion b) Bootstrap? c) What’s `.onlick` and why is `.on('click')` bad?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T14:05:16.490",
"Id": "40905",
"Score": "0",
"body": "sorry funny typing error. .click is faster than .on('click'), because 'click' is a string and have to be validated by the .on function"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T14:06:09.387",
"Id": "40906",
"Score": "0",
"body": "No, `click` is slightly faster to type. `click` with a function just calls `.on('click')` and isn’t any better performance-wise."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T14:07:17.763",
"Id": "40907",
"Score": "0",
"body": "Thanks for the closure compiler link. As rynah I'm interested in the difference between .onclick and .on('click')?\nBy the way UI frameworks aren't important for me here as I have a complex css file written by my own."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T14:12:26.027",
"Id": "40909",
"Score": "0",
"body": "Mhh, I think it's doesn't matter."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T14:12:52.513",
"Id": "40910",
"Score": "0",
"body": "Why do I got a thumb down?"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T13:51:07.497",
"Id": "26426",
"ParentId": "26424",
"Score": "0"
}
},
{
"body": "<p>I'm going to go through a few main points here about your code but don't be overwhelmed by the size of this book, I prefer to be on the side of too much information than too little.</p>\n\n<p><strong>- Cache your selectors:</strong> Probably the most important thing you can do for your code now. As a rule of thumb, if you use a selection more than once, you should cache it. What happens when you use <code>$(\"someElem\")</code> is jQuery queries the DOM to try and find elements that match. So imagine that every time you do that it runs a search. Would it be better if you could save the search results? This way you can look and play with them whenever you want without having to look for them again. Ex.:</p>\n\n<pre><code>//Something like this:\n\nvar childFound = $(container).find(childElement); \n/* Here I saved my search to a variable, which I use later.\nThis will return all \"p\" elements in \"container\".\nYou can filter more and get first element or all the others\nThe .find() method is just an example, there are countless others you can use\nto help you select the elements you want\nMethods like .map(), .each(), and .nextAll() will be increadibly useful for you */\n\n//Then use like this\nchildFound.hide();\n</code></pre>\n\n<p>You're on the right track by setting up the options variable. This concept will be vital when you start to develop plugins, if that's what you want to do.</p>\n\n<p><strong>- IIFE's:</strong> If you have your code in the footer (which you should be doing) what you'll want to do is wrap it in a IIFE. \"What the hell is that?\" you may ask. A basic syntax looks like this:</p>\n\n<pre><code>(function () {\n //Code goes in here.\n})();\n</code></pre>\n\n<p>You'll see several variations of this all over the internet as you read to find out more. The one I recommend you use in this case is like this:</p>\n\n<pre><code>;(function ($, window, document) {\n //Code goes here and the $ belongs to jQuery\n})(jQuery, window, document);\n</code></pre>\n\n<p>So lets break this down. The <code>;</code> in the front is a safety net against unclosed scripts, which can be common if you use plugins in Wordpress, or if you concat and minify your files it will protect you from your function becoming an argument.</p>\n\n<p>Then we pass in <code>$</code>, <code>window</code>, and <code>document</code>. We pass in <code>$</code> and at the bottom assign it to jQuery. So now in this function, no matter what value the <code>$</code> carried outside, in here it's jQuery. Then we pass in <code>window</code> and <code>document</code>. These are optional in your case, but a good idea since you do use references to <code>window</code> in your code. It saves <code>window</code> as a local variable, and also will be good when you minify your code as the <code>window</code> reference can be changed to something like <code>a</code> or <code>foo</code> automatically. If you don't use a <code>window</code> or <code>document</code> reference you can just remove them all together.</p>\n\n<p>Now keep in mind there might be times where you have to put your script in the header. Modernizr is an example of this. Then you'll probably end up using the <code>document.ready</code>. Don't sweat because all you have to do is this:</p>\n\n<pre><code>jQuery(document).ready(function( $ ) {\n //Code goes here and $ will belong to jQuery.\n});\n</code></pre>\n\n<p>I wouldn't rely on <code>$.noConflict</code> to protect your code from other libraries that use the <code>$</code> as well.</p>\n\n<p><strong>- Click Event Handler:</strong> As was mentioned before, there are several ways to set up your events. The ones that were mentioned were <code>.click()</code> and <code>.on(\"click\")</code>. The <code>.click()</code> method simply calls the <code>.on()</code> method and passes in the click. The <code>.on()</code> method is incredibly useful since you can use it to set up almost any kind of event - not only clicks. So yes, the one you are using now is \"the best\" because it saves you a function call. Now saving a single function call in your app won't be a significant increase in performance and you probably won't even notice it. Although arguing over such a small and possibly insignificant changes is really what we developers do best.</p>\n\n<p>Using the <code>.on()</code> method directly is hands down going to be faster, but there are many other things you could be spending your time on that will generate more significant performance results.</p>\n\n<p><strong>- Don't re-invent the wheel:</strong> I strongly believe that if there's a working solution out there by all means use it. There are tons of tabs and accordion plugins available I'm sure you can find one that fits your project. If you can't find an exact fit, you can still always tweak it and make it fit. jQuery it self has an entire UI package with tabs, accordions, sliders, and all kinds of cool stuff just ready and waiting to be used. Also the jQuery UI will let you use your own CSS files and customizations really easily. Making a whole new app from scratch should be done if absolutely necessary, or if you're trying to learn (which is your case). Back to the subject of learning, like you said, you are just starting out with jQuery, and with that I highly recommend this screencast by Jeffrey Way called <a href=\"https://tutsplus.com/course/30-days-to-learn-jquery/\" rel=\"nofollow\">30 Days to Learn jQuery</a>. He does a really good job of explain some basic principals as well as some more complex concepts.</p>\n\n<p>One thing in specific I'm going to point out is the following:</p>\n\n<pre><code>var details = $(this).next(childElement); //Details here is a jQuery object \n//You don't need to wrap it again, just use details.someMethod();\nif(details.is(\":visible\")){\n classToggle($(this), tabClassActive, tabClass);\n details.slideUp(\"slow\");\n}else{\n classToggle($(this), tabClass, tabClassActive);\n details.slideDown(\"slow\");\n}\n</code></pre>\n\n<p>When you cache a selection like you did there, the <code>.next()</code> gives you a new jQuery object with the results from the search which then are stored in <code>details</code>. So doing this: <code>$(details)</code> is the same as doing <code>$($(\"p\"))</code>. You're wrapping it twice. This is a common mistake with beginners and Jeffery, in that screencast, explains it much better than I ever could.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T11:29:45.760",
"Id": "40995",
"Score": "0",
"body": "Thank you for your detailed answer! These function is just to improve my JS/jQuery Skills and I'm aware of frameworks and plugins like jQuery UI. I'll check the screencast!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T15:20:42.837",
"Id": "26434",
"ParentId": "26424",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "26434",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T13:20:42.887",
"Id": "26424",
"Score": "1",
"Tags": [
"javascript",
"jquery"
],
"Title": "How to improve this jQuery code for tabs"
}
|
26424
|
<p>This method changes all URLs in the string into an HTML link. The goal is to not mutate the string passed in, which I believe is a good practice.</p>
<p>The <code>new_string</code> code in this method does not seem idiomatic.</p>
<pre><code>def autolink_string string
return if string.nil?
return '' if string.empty?
regex = /(\S+\.(com|net|org|edu|gov)(\/\S+)?)/
groups = string.scan regex
matches = groups.map &:first
new_string = string.clone
matches.each do |match|
new_string.gsub! match, "<a href='http://#{ match }'>#{ match }</a>"
end
new_string
end
</code></pre>
<p>How can I refactor to remove the <code>new_string</code>? Any other suggestions?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T14:27:17.257",
"Id": "40911",
"Score": "1",
"body": "This method needs some polishing indeed, but are you aware that there are gems for this task? https://github.com/tenderlove/rails_autolink"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T14:46:02.237",
"Id": "40913",
"Score": "0",
"body": "Yes, I did some research. This is not a rails project, and from what I could guess rails_autolink is only for Rails. I didn't find any other useful gems. It turns out that the regex is simple anyway."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T14:51:30.300",
"Id": "40914",
"Score": "0",
"body": "Ok. Let's see if somebody else answers (I am kind of hoarding the *ruby* tag lately ;-))"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T15:32:07.307",
"Id": "40921",
"Score": "1",
"body": "I don't know what kind of input you're dealing with, but here are some things to consider: What if the URL already includes \"http:\" (or something else)? What if there are \"bad\" chars after the domain, e.g. it's at the end of a sentence and followed by a period? What if the domain is a .co.uk, .io, or .museum or any one of the other [top-level domains](http://www.iana.org/domains/root/db)? What about chars that are illegal in URLs? What if the URL is uppercase? Robust URL detection is hard, but [here's a pretty good one](http://daringfireball.net/2010/07/improved_regex_for_matching_urls)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T15:50:02.783",
"Id": "40928",
"Score": "0",
"body": "@Flambino - I have a helper method to handle the case that it already includes http://. I omitted it for clarity. It does not match the punctuation after the URL. I don't care about .co.uk, .io, etc. I don't care about illegal URL chars. It works for uppercase. Thanks for the link."
}
] |
[
{
"body": "<p>You can use <code>gsub!</code> and block directly with a clone.</p>\n\n<pre><code>def autolink_string str\n unless str.empty?\n regex = /(\\S+\\.(com|net|org|edu|gov)(\\/\\S+)?)/\n str.clone.gsub!(regex) do |match|\n \"<a href='http://#{ match }'>#{ match }</a>\"\n end || str # Return str if no match\n end\nend\n</code></pre>\n\n<p>In console:</p>\n\n<pre><code>> str = \"this is a test abc.com\"\n> result = autolink_string str\n=> \"this is a test <a href='http://abc.com'>abc.com</a>\"\n> str\n=> \"this is a test abc.com\"\n> result\n=> \"this is a test <a href='http://abc.com'>abc.com</a>\"\n\n> autolink_string \"no url here\"\n=> \"no url here\"\n\n> autolink_string \"\"\n=> \"\"\n\n> autolink_string \"this is a test abc.com and test twitter.com\"\n=> \"this is a test <a href='http://abc.com'>abc.com</a> and test <a href='http://twitter.com'>twitter.com</a>\"\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T15:46:24.037",
"Id": "40927",
"Score": "0",
"body": "It seems that using `gsub` in the block is a good idea. However, I don't want to mutate the string."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T15:56:39.003",
"Id": "40930",
"Score": "0",
"body": "@BSeven, then just clone it, no more lines needed. Results are same."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T16:26:52.753",
"Id": "40933",
"Score": "0",
"body": "Works well, except that it returns nil if there are no matches: `autolink_string \"no url here\" => nil`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T16:38:51.617",
"Id": "40934",
"Score": "0",
"body": "@BSeven, nice point! It depends on your usages, sometimes nil is preferred when you already have \"str\" in hand. If you choose to return something, I've revised the code to return `str` if no matches."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T15:03:45.220",
"Id": "26432",
"ParentId": "26427",
"Score": "2"
}
},
{
"body": "<p>Some notes:</p>\n\n<ul>\n<li><p>About the double <code>return</code> at the beginning: note that you could write <code>return string if !string || string.empty?</code>. In any case, I wouldn't check this, if the caller sends a <code>nil</code> as argument it's his/her fault. IMO in dynamic languages it does not make much sense to check the types of the arguments.</p></li>\n<li><p>Again, about the double <code>return</code> at the beginning: ok, let's say that you really need to do this check. As it may be seen as a guard, it <em>may</em> be ok to write a inline <code>return</code>. However, as a rule of thumb, it's better to write full indented conditional expressions, they are much more clear (at the meager cost of a couple of lines and an indentation level).</p></li>\n<li><p><code>#{ match }</code> -> <code>#{match}</code>. Nobody puts those spaces.</p></li>\n<li><p><code>regex = /(\\S+\\.(com|net|org|edu|gov)(\\/\\S+)?)/</code>: This looks like a brittle regular expression to detect URLs. Also are you sure you won't get a <code>http://</code> here? Anyway, you'll know what you need...</p></li>\n<li><p><code>new_string.gsub!</code>: No need to do an in-place update. Use <code>String#gsub</code> with a block instead.</p></li>\n</ul>\n\n<p>So I'd simply write:</p>\n\n<pre><code>def autolink_string(string)\n regexp = /(\\S+\\.(com|net|org|edu|gov)(\\/\\S+)?)/\n string.gsub(regexp) { |url| \"<a href='http://#{url}'>#{url}</a>\" }\nend\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T17:04:08.240",
"Id": "40937",
"Score": "1",
"body": "OP should pick this answer, better than mine. `gsub` is the way to go, I used it before but failed due to something wrong."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T19:08:11.173",
"Id": "40943",
"Score": "1",
"body": "that's very nice of you :-) but your answer also shows two of my points: it uses real conditionals and `gsub` with blocks."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T16:39:34.050",
"Id": "26443",
"ParentId": "26427",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "26443",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T14:02:11.880",
"Id": "26427",
"Score": "3",
"Tags": [
"strings",
"ruby",
"url"
],
"Title": "Changing URLs into HTML links"
}
|
26427
|
<p>I wrote the following code as a way of plucking data from a n-depth JavaScript object.
It works a charm and even appends the parents of the the found item.</p>
<p>I was just wondering if you guys had any ideas on making it better.</p>
<pre><code>//#region function recursiveFind
function recursiveFind(data, key, childKey, match, result) {
///<summary>Returns JS obj and its parents based on a data set, key and match.</summary>
///<param name="data" type="Object" optional="false">the data object you want to find within</param>
///<param name="key" type="String" optional="false">the key for the data you want to match against eg. 'id' will look for data.id</param>
///<param name="childKey" type="String" optional="false">the data object you want to find within</param>
///<param name="match" type="Any" optional="false">the value you wish to search for</param>
///<returns type="Object">returns the found result</returns>
var parents = [];
var depth = 0;
var recurse = function (data, key, childKey, match, result) {
// Build Parents
depth++;
// Check this Object
if (data[key] === match) {
result = data;
}
else if (depth === 1) {
parents.push(data);
}
// If not found check children
if (result === undefined) {
if (data[childKey]) {
$.each(data[childKey], function (k, v) {
if (v[key] === match) {
result = v;
return false;
} else {
result = recurse(v, key, childKey, match, result);
if (result) {
parents.push(v);
return false;
}
}
});
}
}
// Set parents object into the result
if (result) {
result.parents = $.extend([], parents);
}
// Clean up parents object
depth--;
if (depth === 0) {
parents.length = 0;
}
return result;
};
return recurse(data, key, childKey, match, result);
}
//#endregion
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-11T20:13:02.913",
"Id": "52109",
"Score": "0",
"body": "You you add an example of use?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T19:52:52.447",
"Id": "62148",
"Score": "0",
"body": "Are you sure ` parents.length = 0;` works?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T10:58:27.943",
"Id": "62248",
"Score": "0",
"body": "@tomdemuyt yep, it is the preferred way of reseting an array in JavaScript http://stackoverflow.com/questions/1232040/how-to-empty-an-array-in-javascript"
}
] |
[
{
"body": "<p><strong>Overal</strong></p>\n\n<p>I think the code looks too busy just to find a key/value match in an object tree-structure, it took a while to figure out which part(s) bothered me.</p>\n\n<p><strong>Doing it twice</strong></p>\n\n<p>You are doing the matching twice, once with <code>(data[key] === match)</code> and once with <code>(v[key] === match)</code>, it would be cleaner to leave the second check to recursion.</p>\n\n<p><strong>Function in a function</strong></p>\n\n<p>I am assuming you use a function in a function to keep track of <code>depth</code> and <code>parents</code>, which isn't worth it. You can do this in a single function with an optional parameter.</p>\n\n<p><strong>Naming</strong></p>\n\n<ul>\n<li><code>match</code> -> <code>matchValue</code> because <code>match</code> sounds like a boolean to me</li>\n<li><code>childKey</code> - <code>childrenKey</code> because the key really points to an array</li>\n<li><code>result.parents</code> -> avoid this, what if the object already has a property called <code>parents</code> ?</li>\n</ul>\n\n<p><strong>Counter proposal</strong></p>\n\n<p>If you think about it, result can be considered the parent of key, so I would build a function that returns all parents in an array, if you wish you can then have <code>recursiveFind</code> call that.</p>\n\n<pre><code>function findParents( data, key, matchValue, childrenKey, parents )\n{\n var i , children , childrenCount;\n /* Prevent the need for an inner function by re-passing parents */\n parents = parents || [];\n parents.push( data )\n /* Return immediately if we find a match */\n if( data[key] === matchValue )\n return parents.reverse(); \n /* Are there children to inspect ? */\n if( !data[childrenKey] || !data[childrenKey].length )\n return false;\n children = data[childrenKey];\n childrenCount = children.length;\n /* See if any children have it ? */\n for( i = 0 ; i < childrenCount ; i++ )\n {\n if( parents = findParents( children[i] , key , matchValue , childrenKey , parents.slice() ) )\n return parents;\n }\n /* Fail.. */\n return false;\n}\n</code></pre>\n\n<p>Then <code>recursiveFind</code> becomes</p>\n\n<pre><code>function recursiveFind(data, key, childrenKey, match )\n{\n var parents = findParents( data , key, match ),\n result = parents.shift()\n result.parents = parents;\n return result;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-21T18:31:57.107",
"Id": "37887",
"ParentId": "26436",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T15:29:46.237",
"Id": "26436",
"Score": "4",
"Tags": [
"javascript",
"jquery",
"recursion",
"search"
],
"Title": "Recursive find function in JavaScript / jQuery"
}
|
26436
|
<p>I've created the following model for an academic project, and I'm wondering if this is a sensible way to manage a model:</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;
using System.Collections.ObjectModel;
using System.Windows.Forms;
namespace IceCreamShop
{
[Serializable]
public class Customer : ISerializable
{
private const string SAVE_FILE_NAME = @".\Customers.bin";
#region static model accessors
private static List<Customer> customers = new List<Customer>();
public static ReadOnlyCollection<Customer> Customers
{
get
{
return customers.AsReadOnly();
}
}
public static int Cardinality { get; private set; }
public static void saveCustomers(List<Customer> customers)
{
IFormatter formatter = new BinaryFormatter();
Stream stream = File.Open(SAVE_FILE_NAME, FileMode.Create);
formatter.Serialize(stream, customers);
formatter.Serialize(stream, Customer.Cardinality);
stream.Close();
}
public static void loadAllCustomers()
{
IFormatter formatter = new BinaryFormatter();
List<Customer> customers = new List<Customer>();
try
{
Stream stream = File.Open(SAVE_FILE_NAME, FileMode.OpenOrCreate);
if (stream.Length > 0)
{
customers = (List<Customer>)formatter.Deserialize(stream);
Customer.Cardinality = (int)formatter.Deserialize(stream);
}
stream.Close();
}
// Shouldn't happen during normal operation, pending any permissions/file write issues
catch (Exception ex)
{
throw ex;
}
if(customers.Count == 0)
{
// Dummy customer for patrons who don't want their data tracked
customers.Add(new Customer("nobody", "nobody"));
Customer.Cardinality = 1;
}
Customer.customers = customers;
}
#endregion
#region individual model data
private string firstName;
public string FirstName { get { return firstName; } }
private string lastName;
public string LastName { get { return lastName; } }
private int id;
public int ID { get { return id; } }
//Used externally to generate a new customer
public Customer(string firstName, string lastName)
{
this.id = Customer.Cardinality++;
this.firstName = firstName;
this.lastName = lastName;
}
#endregion
#region serialization
Customer(SerializationInfo info, StreamingContext context)
{
this.id = info.GetInt32("i");
this.firstName = info.GetString("j");
this.lastName = info.GetString("k");
}
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("i", this.id);
info.AddValue("j", this.firstName);
info.AddValue("k", this.lastName);
}
#endregion
}
}
</code></pre>
<p>An individual Customer consists of an id, first name and a last name. I realize there are still some issues to be ironed out, but I'm primarily wondering if it makes sense to use statics in this way.</p>
<p>This is part of an MVP-based project, which focuses on putting application logic in the controllers and data-based operations in the model with dumb views. </p>
|
[] |
[
{
"body": "<p>This smells slightly odd to me. Why would the class of customers know about what customers are actually participating in the model at the moment? Is there a need to even have knowledge of all the customers in the model overall? (Even in a simulation, you'd have that knowledge as part of the harness, not the customers themselves.)</p>\n\n<p>No, I'd instead model the collection of all potential customers as an instance of another class (the catchment? the clientele?) and would avoid having public static methods in any class at all. That collection might well just be a simple wrapper around a core collection class instance, but I'd be making it a proper member of the model simply because the collection of customers <em>is</em> a model participant. (Well, if it isn't then you have no reason to keep a list of all customers at all.) The other advantage of working this way is that you can then easily adapt to a growing business that opens a second shop far enough away from the first that virtually nobody goes to both shops…</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-20T21:20:59.503",
"Id": "40924",
"Score": "0",
"body": "Fair enough, sometimes I just want to scratch an itch. It's an interesting method, but I think you're right in that conceptually it confuses the subject quite a bit and wont extend well."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-20T20:49:15.130",
"Id": "26438",
"ParentId": "26437",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "26438",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-20T20:23:19.670",
"Id": "26437",
"Score": "2",
"Tags": [
"c#",
"design-patterns",
".net"
],
"Title": "Is this a sensible way to implement a model?"
}
|
26437
|
<p>I made a template pipe and filters to replace an old pipe and filters implementation that used inheritance and had a very heavy base class.</p>
<pre><code>#include <iostream>
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <list>
template <typename Data>
class pipeline {
typedef boost::function<Data(Data)> filter_function;
typedef std::list<filter_function> filter_list;
filter_list m_list;
public:
template<typename T>
void add(T t) {
m_list.push_back(boost::bind(&T::filter, t, _1));
}
Data run(Data data) {
typedef typename filter_list::iterator iter;
iter end = m_list.end();
for(iter it = m_list.begin(); it != end; ++it) {
data = (*it)(data);
}
return data;
}
};
struct foo {
int filter(int i) {
return i + 1;
}
};
int main(int argc, _TCHAR* argv[])
{
pipeline<int> pipe;
foo f;
pipe.add(f);
std::cout << pipe.run(0);
char c;
std::cin >> c;
}
</code></pre>
<p>Except the fact that <code>add()</code> is a template, are there any issues anyone sees with this approach?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-04-22T12:20:47.923",
"Id": "306342",
"Score": "0",
"body": "The answers really depend on what C++ standard you have access to. With C++11, you could throw boost away."
}
] |
[
{
"body": "<ul>\n<li><p>As <code>run()</code> is several lines long, it should be defined outside the class. Anything defined inside is automatically inlined.</p></li>\n<li><p>Depending on the size of <code>data</code> when passing by value, it may be best to pass it to <code>run()</code> by <code>const&</code>, modify a local copy, and return that. RVO should still kick in.</p></li>\n<li><p>Is there a significance to the name <code>foo</code> here? If not, it should be more accurate <em>and</em> start with a capital letter as it's a user-defined type. The capitalization also applies to <code>pipeline</code>.</p></li>\n<li><p><code>iter end = m_list.end();</code> seems pointless here. You can just use <code>m_list.end()</code> inside the loop statement.</p>\n\n<p>As <code>m_list</code> is not being modified inside the loop, you can instead use <code>cbegin()</code> and <code>cend()</code> for const-correctness.</p>\n\n<p>If you have C++11, you can use <a href=\"http://en.cppreference.com/w/cpp/language/auto\"><code>auto</code></a> to replace the defined iterator inside the loop statement.</p></li>\n<li><p>Your \"pause\" is okay, but you can also use <code>std::cin.get()</code> to do the same thing.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-04-22T12:22:41.057",
"Id": "306343",
"Score": "0",
"body": "`start with a capital letter as it's a user-defined type. The capitalization also applies to pipeline.` If you could provide a reference here, it would be a kick in the nuts for my colleagues, claiming that \"if STL does it, it's correct\"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-04-23T02:31:03.663",
"Id": "306493",
"Score": "1",
"body": "@Vorac: [This answer](http://stackoverflow.com/questions/13881915/why-does-the-stl-boost-c-coding-style-differ-so-much-from-everyone-elses) might help, which also includes a quote from Stroustrup."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-06T05:29:54.970",
"Id": "41035",
"ParentId": "26444",
"Score": "7"
}
},
{
"body": "<p>Using <code>std::vector</code> instead of <code>std::list</code> may be more efficient (both for speed and memory allocation).\nAdvantages are explained in answer to <a href=\"https://stackoverflow.com/questions/238008/relative-performance-of-stdvector-vs-stdlist-vs-stdslist\">this</a> question.</p>\n\n<p>Just change</p>\n\n<pre><code>typedef std::list<filter_function> filter_list;\n</code></pre>\n\n<p>to</p>\n\n<pre><code>typedef std::vector<filter_function> filter_list;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-04-14T12:58:17.353",
"Id": "160754",
"ParentId": "26444",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T16:50:05.600",
"Id": "26444",
"Score": "7",
"Tags": [
"c++",
"template",
"inheritance",
"boost"
],
"Title": "Generic pipe and filters"
}
|
26444
|
<p>I want to run a background job on my web server to do some database maintenance. I am looking at using <code>APScheduler</code> to do this.</p>
<p>I am planning on running the below code in a separate process to my main web server. I don't really want to tie the code to my web server.</p>
<p>Question: Is using <code>While True pass</code> at the end of a cron-like scheduler considered bad practice? How should it be done? (<code>time.sleep()</code>?)</p>
<pre><code>from apscheduler.scheduler import Scheduler
@sched.interval_schedule(days=1)
def tick():
# do a clean up job
while True:
pass
</code></pre>
|
[] |
[
{
"body": "<p><code>while True: pass</code> will consume 100 % of one CPU which is not something you want. I'm not familiar with APScheduler, but a quick look into <a href=\"http://pythonhosted.org/APScheduler/#scheduler-configuration-options\" rel=\"nofollow\">the docs</a> reveals a <code>daemonic</code> option:</p>\n\n<blockquote>\n <p>Controls whether the scheduler thread is daemonic or not.</p>\n \n <p>If set to False, then the scheduler must be shut down explicitly when\n the program is about to finish, or it will prevent the program from\n terminating.</p>\n \n <p>If set to True, the scheduler will automatically terminate with the\n application, but may cause an exception to be raised on exit.</p>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T16:52:38.930",
"Id": "41015",
"Score": "0",
"body": "I wasn't reading top correctly on my test. It really does use 100% of CPU. Thanks for the scheduler link to daemon mode - I missed that."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T08:28:10.393",
"Id": "26462",
"ParentId": "26445",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "26462",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T16:59:37.047",
"Id": "26445",
"Score": "2",
"Tags": [
"python"
],
"Title": "Leaving an APScheduler in a while True loop"
}
|
26445
|
<p>I am learning how to use the module unittest for test-driven development. Below is a simple yet practical example of an issue I will have many times: one single problem (e.g. an Abstract Data Type (ADT) describing a Data Type and an Operator on it), and various Data Structures (DS) implementing this ADT; in this case the problem of computing the number of elements smaller than an element x in a sorted array A (i.e. its "insertion rank"), and two solutions: <a href="http://en.wikipedia.org/wiki/Binary_search_algorithm" rel="nofollow">binary search</a> and <a href="http://en.wikipedia.org/wiki/Fibonacci_search_technique" rel="nofollow">Fibonacci search</a>. This codes "does the job" in that I can define the tests in one single place for all solutions, and the list of solutions in another one, but it does not seem elegant?</p>
<pre><code>import unittest
class InsertionRankTest(unittest.TestCase):
def generic_test(self,algorithm):
self.assertEqual(algorithm([1],0),0)
self.assertEqual(algorithm([1],1),0)
self.assertEqual(algorithm([1],2),1)
self.assertEqual(algorithm([0, 10, 20, 30, 40, 50, 60, 70, 80, 90],0),0)
self.assertEqual(algorithm([0, 10, 20, 30, 40, 50, 60, 70, 80, 90],40),4)
self.assertEqual(algorithm([0, 10, 20, 30, 40, 50, 60, 70, 80, 90],45),5)
self.assertEqual(algorithm([0, 10, 20, 30, 40, 50, 60, 70, 80, 90],100),10)
def test_all_inertionRankAlgorithms(self):
self.generic_test(binarySearchForInsertionRank)
self.generic_test(fibonacciSearch)
def binarySearchForInsertionRank(A,x):
"""Computes the insertion rank r of x in A in time logarithmic in
len(A).
"""
assert(A!=None)
if len(A)==0:
return 0
else:
m = len(A)//2
if x <= A[m]:
return binarySearchForInsertionRank(A[:m],x)
else:
return m+1+binarySearchForInsertionRank(A[m+1:],x)
def fibonacciSearch(A,x):
"""Computes the insertion rank r of x in A in time logarithmic in
r.
"""
assert(A!=None)
if len(A)==0:
return 0
l = 0
r = 1
while r < len(A) and A[r] < x:
r += l
l = r-l # i.e., former value of r
return l + binarySearchForInsertionRank(A[l:min(r,len(A))],x)
def main():
unittest.main(exit=False)
if __name__ == '__main__':
main()
</code></pre>
<p>Does one define a class for the ADT, a class for the tests, derives the class for the ADT for each DS, and <strong>derives the test classes again</strong>? (As a bonus question: can the same tools be used to measure and compare the performance (as measured by either the number of comparisons or the running time)? What is the best way to measure the performance of each solution on each test case?)</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T06:13:33.810",
"Id": "40979",
"Score": "0",
"body": "(I corrected the bonus question, please make sure I understood you correctly!)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T09:07:56.330",
"Id": "41076",
"Score": "0",
"body": "Thanks, seems I had pasted by mistake a sentence inside another. All corrected now :)"
}
] |
[
{
"body": "<p>Embrace Python's simplicity! This is a dynamic language, we care less about inheritance and complex data models and focus more on the actual problem. Of course, it has its drawbacks, but that's how it works.</p>\n\n<p>The answer your question: <strong>no, in Python, we wouldn't derive classes and so on but just write the code you wrote</strong>. It's still possible to define an abstract base class A with specific methods and extend it with a few implementations, but really think about the benefits before doing this.</p>\n\n<p>Note about the code: <a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">PEP 8</a> is a standard style guide important in the Python word: space between operators and no camelCase in variable names are the two that come to mind while reading your code.</p>\n\n<p>Finally, performance is another concern than unit testing (except if you find a reliable way to test for the complexity of your algorithms). I recommend the <code>timeit</code> module. It doesn't say how to test for complexity, but it's a good start to measure time spent in a method.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T13:36:03.543",
"Id": "40999",
"Score": "0",
"body": "Thanks: I don't need python's help to compute the (worst case) complexity of my algorithm, that's my job ;) I am more interested in timing python implementations on specific instances, timeit seems to be adequate. And I will read PEP8!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T13:56:28.137",
"Id": "41000",
"Score": "0",
"body": "I was thinking about checking it, not computing it. :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T06:53:04.243",
"Id": "26458",
"ParentId": "26446",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T17:15:56.767",
"Id": "26446",
"Score": "2",
"Tags": [
"python",
"unit-testing"
],
"Title": "Generic test serie for various solutions to the same algorithmic problem"
}
|
26446
|
<p>I am teaching myself Ruby and Ruby-on-rails, as part of this regimen I thought it would be a good idea to do some Ruby quiz exercises and so I started with the <a href="https://github.com/mathie/solitaire_cipher/blob/master/README.rdoc" rel="nofollow">solitaire cipher</a>. The basic functionality of decoding a properly formatted message is there but only just so. I've come to the realization that I've written this like Ruby has no object-oriented functionality, and instead it's a big imperative function full of clever expressions that make it hard to read.</p>
<p>At this point I would like to pad it out with a fuller feature set and "unclever" some of the logic, and I wanted to do so via TDD. Is this program hardly unit-testable because of it's imperative design?</p>
<p>As someone who wants to be a great ruby programmer, is it imperative that I refactor this code to utilize classes, methods and objects? If not, will unit-testing be of very limited value as a result? Am I overreacting and this is fine for what it was designed?</p>
<pre><code>input = String.new
input = ARGV[0].dup
def solitaire(input)
def decode(msg)
#Creates a hash with keys 1-54
abc = ('A'..'Z').to_a
alphaHash = Hash.new
alphaHash.default = ""
(1..54).to_a.each {|x| alphaHash[x] = (abc[x - 1])} #assigns 1-26 a letter in alphabetical order
abc.each {|x| alphaHash[abc.index(x) + 27] = x} #assigns letters in order to 27-52
#All non-joker card values 1-52 can be resolved to their letter
#Creates array in which each letter from msg is added as a number to the array, A = 1, B = 2 etc.
msg.delete! ' '
convertedMessage = Array.new
msg.each_char {|letter| convertedMessage << alphaHash.key(letter)}
#Create deck array, for this example in ascending numerical order; clubs, diamonds, hearts, spades
deck = (1..54).to_a
#Set indexes of two jokers
jkr_a_idx = deck.index 53
jkr_b_idx = deck.index 54
convertedKeys = Array.new
#This uses the solitaire cipher to generate the keys the message was encrypted with
while convertedKeys.length < convertedMessage.length
#Joker A down one card
jkr_a_idx = deck.index 53
jkr_a_idx += 1
#check if it returns to front of deck
if jkr_a_idx >= 54
jkr_a_idx -= 54 #Reset index to beginning of deck
jkr_a_idx += 1 #Joker can never be first card so it skips index 0
end
#Remove and insert Joker A at new index
deck.delete(53)
deck.insert(jkr_a_idx, 53)
#Joker B down two cards
jkr_b_idx = deck.index 54
jkr_b_idx += 2
#check if Joker B must return to front of deck
if jkr_b_idx >= 54
jkr_b_idx -= 54 #Reset index to beginning of deck
jkr_b_idx += 1 #Joker can never be first card so it skips index 0.
end
#Remove and insert Joker B at new index
deck.delete(54)
deck.insert(jkr_b_idx, 54)
#Triple cut around jokers, exchange cards above first joker with cards below second joker.
#determine top and bottom jokers
topJoker = deck.detect {|e| e == 53 or e == 54}
if topJoker == 53
bottomJoker = 54
end
if topJoker == 54
bottomJoker = 53
end
#Make the cuts
topCut = deck.slice!(0...deck.index(topJoker))
if bottomJoker != deck.last #if a joker is the last card, there is no bottom cut
bottomCut = deck.slice!((deck.index(bottomJoker) + 1)..-1) #cuts cards after bottom joker to the last one
deck.unshift bottomCut #Inserts the bottomCut at the front
deck.flatten!
end
deck << topCut
deck.flatten! #deck must be flattened as cuts are inserted as nested arrays
#Count cut: take last card's value, cut this many cards from top and insert before last card
if deck.last == 53 or deck.last == 54 #Either joker's value is always 53
countCut = deck.slice!(0...53) #If either joker is the last card, we cut 53 cards
else
countCut = deck.slice!(0...deck.last)
end
deck.insert(deck.index(deck.last), countCut) #inserts the countCut before the last card
deck.flatten!
#Take first card's value, count this many cards, convert the facing card to a letter, this is the letter for the keystream
if deck.first == 54 #All jokers get value 53
if deck[53] != 53 and deck[53] != 54 #If a joker is the facing card, there is no output to the keystream for this iteration
convertedKeys << alphaHash.key((alphaHash[deck[53]])) #Any other facing card is converted to a letter, then back to numeric
end
else
if deck[deck.first] != 53 and deck[deck.first] != 54 #Step is skipped if the facing card is a joker
convertedKeys << alphaHash.key((alphaHash[deck[deck.first]]))
end
end
end #while loop
decodedMessage = String.new
#Decodes the message
#Both convertedMessage and convertedKeys are numeric values 1-26
convertedMessage.each { |value|
#When decoding, subtract key from the encoded value for the decoded message
if convertedKeys[decodedMessage.length] >= value #If this operation is 0 or negative, add 26 to value
decodedMessage << alphaHash[((value + 26) - convertedKeys[decodedMessage.length])]
else
decodedMessage << alphaHash[(value - convertedKeys[decodedMessage.length])]
end
}
decodedMessage
end #decode
puts decode(input)
end
puts solitaire(input)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T19:14:06.233",
"Id": "40944",
"Score": "3",
"body": "IMO it's not imperative vs OOP (*typical* OOP is imperative) but procedural vs OOP. My answer is: yes, you have to do it more OO and, specially, more modular (this `decode` is humongous!). Also, I'd also write it in functional style (in the Functional Programming sense), no `each`, `<<`, `+=`, all that imperative stuff. Functional and OOP can coexist pretty well in fact."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T06:59:26.870",
"Id": "40983",
"Score": "0",
"body": "@tokland We're now waiting for one of your nice answers. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T07:56:09.263",
"Id": "40984",
"Score": "0",
"body": "Quentin: In my land we say something like \"Raise fame and go to sleep\". I am thinking about switching to phase 2 :-) On a serious note, @lutze: is this quiz written somewhere? it's not exactly pleasant to guess the specifications from code that needs a lot of review."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T14:02:52.230",
"Id": "41001",
"Score": "0",
"body": "Never use OOP until you need it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T16:56:11.500",
"Id": "41016",
"Score": "0",
"body": "@tokland Here is the text of the quiz, via this project's readme on github: https://github.com/mathie/solitaire_cipher/blob/master/README.rdoc . Unfortunately the original source is hard to find. Ruby Quiz has been abandoned and rehosted several times, current host's archives don't go back this far. I can verify that this appears to be the exact text as I originally read it. I would have posted it originally but without a good looking source I decided against it, hoping for someone familiar with it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T20:28:59.053",
"Id": "41041",
"Score": "1",
"body": "@lutze: ok, with those specifications is much, much easier to give sensible advice. Unfortunately there is a lot of code to be reviewed, usually that means you'll get no answers (too much work). I'll try to come up with something on the weekend."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T20:38:02.510",
"Id": "41044",
"Score": "1",
"body": "Don't use `or`, and `and`, use `||` and `&&`. They're not the same thing, `or` and `and` are not meant to be used as boolean operators."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T16:47:29.993",
"Id": "41183",
"Score": "1",
"body": "Also don't use `(x..y).to_a.each`, you're instantiating an array needlessly. Just use `(x..y).each` or `x.upto(y)`."
}
] |
[
{
"body": "<p>Some notes on your code:</p>\n\n<ul>\n<li><code>alphaHash = Hash.new</code>, <code>each</code>, <code>delete</code>, <code>+=</code>, ...: This shows that you think in imperative terms (init, update, remove, insert, destroy, change, ...), in Ruby is more idiomatic a functional style (see <a href=\"https://code.google.com/p/tokland/wiki/RubyFunctionalProgramming\" rel=\"nofollow\">this</a>) with immutable data structures.</li>\n<li><code>or</code>/<code>and</code> are used for flow control, for logic you should use <code>&&</code>/<code>||</code>.</li>\n<li>The real problem of your code is that is not declarative. You have a bunch of code put together doing things, but it's difficult to relate each step with the specifications (if you have to insert comments for that, it's a signal something is wrong). The way to solve this is by using abstractions (functions/methods) that capture the specifications. </li>\n</ul>\n\n<p>I'll show the skeleton of my solution, I think it's more useful than going into full detail (ask if you want to see the complete code). Note how every step (in <code>decode,</code>encode` and the deck re-arranging) has its own abstraction, the code is a composition of them:</p>\n\n<pre><code>class Deck < Array\n def move(card, offset)\n end\n\n def triple_cut_around(card1, card2)\n end\n\n def count_cut_last\n end\n\n def get_output_letter\n end\n\n def self.value_from_card(card)\n end\nend\n\nclass SolitaireCipher\n CharsToDigits = Hash[(\"A\"..\"Z\").map.with_index(1).to_a]\n DigitsToChars = CharsToDigits.invert\n\n def self.gen_keystream\n initial_cards = Deck.new((1..52).to_a + [:joker_a, :joker_b])\n ...\n shuffled_cards = cards.\n move(:joker_a, +1).\n move(:joker_b, +2).\n triple_cut_around(:joker_a, :joker_b).\n count_cut_last\n letter = shuffled_cards.get_output_letter\n [letter, shuffled_cards]\n ...\n end\n\n def self.chars_to_digits(chars)\n end\n\n def self.digits_to_chars(digits)\n end\n\n def self.encode(string)\n s0 = string.upcase.gsub(/[^A-Z]/, '')\n s = s0.ljust((s0.size / 5) * 5, \"X\")\n digits1 = chars_to_digits(s.chars)\n digits2 = chars_to_digits(gen_keystream.take(s.length))\n digits_encoded = digits1.zip(digits2).map { |d1, d2| (d2 + d1) % 26 }\n digits_to_chars(digits_encoded).each_slice(5).map(&:join).join(\" \")\n end\n\n def self.decode(string)\n end\nend\n\nencoded = SolitaireCipher.encode(\"Code in Ruby, live longer!\")\nputs encoded #=> GLNCQ MJAFF FVOMB JIYCB\ndecoded = SolitaireCipher.decode(encoded)\nputs decoded #=> CODEI NRUBY LIVEL ONGER\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-28T15:14:32.610",
"Id": "41400",
"Score": "0",
"body": "Thank you, this skeleton version is perfect. I appreciate your time learning the logic and all that of the cipher."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-25T18:59:11.457",
"Id": "26611",
"ParentId": "26449",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "26611",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T19:03:27.007",
"Id": "26449",
"Score": "4",
"Tags": [
"ruby"
],
"Title": "Is my solitaire cipher too imperative for an Object Oriented language like Ruby?"
}
|
26449
|
<p>I have implemented a doubly linked list in C++. I have tested it and everything works as expected, but I am not sure if my copy constructor and assignment operator perform a deep copy.</p>
<ol>
<li>Can someone tell whether I am doing a shallow or deep copy?</li>
<li>Just by looking at my code, does my destructor seem to work properly?</li>
<li>I think I am leaking memory. Can anybody confirm? I will run valgrind as soon as I get a chance.</li>
</ol>
<p></p>
<pre><code>#include <iostream>
template <typename T>
class list {
public:
list(); // constructor
list(const list &l); // copy constructor
list &operator=(const list &l); // assignment operator
~list(); // destructor
// Returns number of elements in the list
unsigned size();
// Returns true if the list is empty, false otherwise.
bool isEmpty() const;
// Inserts element to front of list
void insertFront(const T &val);
// Inserts element to the end of list
void insertBack(const T &val);
// Returns the values of the front element in the list
T front();
// Returns the value of the back element of the list.
T back();
// Deletes the front element of the list and returns its value
void removeFront();
// Deletes the back element of the list and returns its value
void removeBack();
// Prints each element of the list in order
void printForward();
// Prints each element of the list in reverse order
void printReverse();
private:
struct node {
node *next;
node *prev;
T value;
};
node *first; // The pointer to the first node
node *last; // The pointer to the last node
unsigned length; // holds number of elements in the list
// Initializes empty list
void createEmpty();
// Removes all of the elements in the list
void removeAll();
// Makes copy of all of the elements in the list
void copyAll(const list &l);
};
template <typename T>
void list<T>::createEmpty() {
first = nullptr;
last = nullptr;
length = 0;
}
template <typename T>
void list<T>::removeAll() {
while (!isEmpty()) {
removeFront();
}
}
template <typename T>
void list<T>::copyAll(const list &l) {
node *iterator = l.first;
while (iterator) {
T obj = iterator->value;
insertBack(obj);
iterator = iterator->next;
}
}
template <typename T>
unsigned list<T>::size() {
return length;
}
template <typename T>
bool list<T>::isEmpty() const{
return (first == nullptr && last == nullptr);
}
template <typename T>
void list<T>::insertFront(const T &val) {
length++;
node *newNode = new node;
new (&(newNode->value)) T(val);
newNode->next = first;
newNode->prev = nullptr;
if (isEmpty()) first = last = newNode;
else {
first->prev = newNode;
first = newNode;
}
}
template <typename T>
void list<T>::insertBack(const T &val) {
length++;
node *newNode = new node;
new (&(newNode->value)) T(val);
newNode->next = nullptr;
newNode->prev = last;
if (isEmpty()) first = last = newNode;
else {
last->next = newNode;
last = newNode;
}
}
template <typename T>
T list<T>::front() {
return first->value;
}
template <typename T>
T list<T>::back() {
return last->value;
}
template <typename T>
void list<T>::removeFront() {
if (isEmpty()) return;
length--;
node *removedNode = first;
first = first->next;
if (first) first->prev = nullptr;
else first = last = nullptr;
delete removedNode;
return;
}
template <typename T>
void list<T>::removeBack() {
if (isEmpty()) return;
length--;
node *removedNode = last;
last = last->prev;
if (last) last->next = nullptr;
else first = last = nullptr;
delete removedNode;
return;
}
template <typename T>
list<T>::list() {
createEmpty();
}
template <typename T>
list<T>::list(const list &l) {
createEmpty();
copyAll(l);
return;
}
template <typename T>
list<T>& list<T>::operator= (const list &l)
{
if (this != &l) {
removeAll();
copyAll(l);
}
return *this;
}
template <typename T>
list<T>::~list() {
removeAll();
}
template <typename T>
void list<T>::printForward() {
if (isEmpty()) {
std::cout << "List is empty\n";
return;
}
node *head = first;
while (head) {
std::cout << head->value << " ";
head = head->next;
}
std::cout << "\n";
}
template <typename T>
void list<T>::printReverse() {
if (isEmpty()) {
std::cout << "List is empty\n";
return;
}
node *tail = last;
while (tail) {
std::cout << tail->value << " ";
tail = tail->prev;
}
std::cout << "\n";
}
</code></pre>
|
[] |
[
{
"body": "<p>Use the copy and swap idium for assignment operator:</p>\n\n<pre><code>template <typename T>\nlist<T>& list<T>::operator= (const list &l)\n{\n if (this != &l) {\n removeAll();\n copyAll(l);\n }\n return *this;\n}\n\n// Easier to write as \ntemplate <typename T>\nlist<T>& list<T>::operator= (list l) // Pass by value to generate copy.\n{\n l.swap(*this); // Swap with parameter\n return *this;\n} // Parameter destroyed\n // Taking the old list with it.\n</code></pre>\n\n<p>The trouble with your versions is you are modifying the local object before you know that the copy has worked. This mean you are not in compliance with \"Strong Exception guarantee\" (you are only providing the basic guarantee).</p>\n\n<p>If you add a sentinel value then you can make your code much less complicated as you don't need to worry about NULL values.</p>\n\n<p>ie.</p>\n\n<pre><code>// No tail needed.\n// With a sentinel the list is circular.\n// head->prev == sentinal\n// head->prev->prev == tail\n// list is empty then => head->prev == head\n\nlist::list()\n{\n size = 0;\n head = new Node;\n head->next = head;\n head->prev = head;\n}\n\nvoid list::addHead(T val)\n{\n Node* n = new Node(val);\n n->next = head;\n n->prev = head->prev;\n\n n->prev->next = n;\n head->prev = n;\n\n head = n;\n ++size;\n}\n\nvoid list::removeHead()\n{\n if (size == 0)\n { return; // Empty list just contains the sentinal\n }\n Node* old = head;\n\n head = head->next;\n old->prev->next = head;\n head->prev = old->prev;\n --size;\n\n delete old;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T01:22:45.907",
"Id": "26453",
"ParentId": "26451",
"Score": "4"
}
},
{
"body": "<p>There's a few stylistic or design things that I noticed, but please pay special attention to the first two (<em>especially</em> the first item). The first two are not style or design related but rather actual bugs that are very likely to happen (well, the second one not so much).</p>\n\n<hr>\n\n<p><strong>NOTE:</strong> This item is a <strong>major bug</strong>. It's a \"this code could never actually be used\" level bug.</p>\n\n<p>Why are you placement-new'ing on top of the default-constructed element of <code>node</code>? This is unnecessary unless you're trying to get around some rather odd aversion to a copy constructor or assignment operator.</p>\n\n<p>If you're going to do it this way (and I highly suggest that you don't), you need to manually destruct the element (<code>(newNode->value).~T()</code>) before you placement new over it. </p>\n\n<p>To illustrate the problem, imagine that your're containing a type that sets up some kind of resources in its constructor. As the destructor never gets called for the initial member of <code>node</code> (the one that gets created when node is created), those resources will leak.</p>\n\n<p>I would just pass the object to node through a constructor and let the compiler work its magic before trying to unnecessarily placement-new things:</p>\n\n<pre><code>struct node {\n T value;\n node* next;\n node* prev;\nnode(const T& val, node* const next = nullptr, node* const prev = nullptr)\n : value(val), next(next), prev(prev)\n{ }\n};\n</code></pre>\n\n<hr>\n\n<p>When you're dealing with memory details, you must be very conscious of exceptions.</p>\n\n<p>In particular, if your <code>new</code> statements throw exceptions after your <code>length++</code> statements, the length is then incorrect. Luckily the solution is simple: just allocate the memory before incrementing <code>length</code>.</p>\n\n<hr>\n\n<p>Your indenting is inconsistent (4 spaces sometimes, and 2 spaces others)</p>\n\n<hr>\n\n<p>The void returns in removeFront and removeBack that do not affect control flow are a bit odd.</p>\n\n<hr>\n\n<p><code>front</code> and <code>back</code> could (and probably should) return a reference instead of a copy (as all of the standard library containers do). Note that you would then want two versions: a const one that returns a const reference, and a non-const one that returns a mutable reference.</p>\n\n<hr>\n\n<p>You've implemented more of a deque than a list. How do you iterate over the list?</p>\n\n<p>I suggest going the style of the standard library and making iterators.</p>\n\n<p>As this is just an academic exercise (if not, use std::list), there's no need to put in all of the effort, but if you wanted, you could even do standard style iterators: <a href=\"https://stackoverflow.com/questions/7758580/writing-your-own-stl-container/7759622#7759622\">this</a> and <a href=\"https://stackoverflow.com/questions/8054273/how-to-implement-an-stl-style-iterator-and-avoid-common-pitfalls\">this</a> should prove helpful if you go this route.</p>\n\n<p>This will allow you to iterate over the list, and, provided you write a <code>iterator insert(iterator, const T&)</code> method, your insertFront and insertBack methods become trivial (<code>insert(end(), value)</code> for example).</p>\n\n<hr>\n\n<p>Your printing methods don't particularly belong in the class.</p>\n\n<p>What if instead of printing a message when the list is empty, I want to do nothing? What if instead of a space separator, I want a newline? There's so many decisions that you've hard coded that it makes the method useless to a consumer of the class. Let consumers of the class handle output formatting.</p>\n\n<p>(Fun bonus with iterators: just <code>std::copy</code> into a <code>std::ostream_iterator</code> and you have your print methods already written.)</p>\n\n<hr>\n\n<p>createEmpty() shouldn't exist. That should be part of initialization lists.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T14:45:54.410",
"Id": "41003",
"Score": "0",
"body": "I would totally emphasis the point on the placement new problem. This is not just a design flaw but an actual bug. Without the call to `~T()` we have potential leak issues and undefined behavior."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T20:35:11.600",
"Id": "41042",
"Score": "0",
"body": "@LokiAstari Good point; I have edited to make it more clear that it's not only a bug but a rather serious one."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T00:07:53.003",
"Id": "41053",
"Score": "0",
"body": "Thanks for this. The printing statements were there so I could see what the list looks like. Kind of for debugging purposes. I use `createEmpty()` in the copy constructor. Should I just set those values myself?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T01:38:50.600",
"Id": "41054",
"Score": "0",
"body": "@OGH I should have explained that item a bit better. I'm just pushing (biased) style habits on you. With primitive types, it makes no difference, but with objects as members, assignment via initialization list constructs into the object rather than using the assignment operator. That means initialization list usage saves a wasted default construction and doesn't require a `operator=`. Also, with a reference as a member, you *must* use an initialization list. In this situation, neither of these reasons apply, but I like to always use initialization lists as a habit to make sure to avoid them."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T04:16:33.233",
"Id": "26456",
"ParentId": "26451",
"Score": "5"
}
},
{
"body": "<blockquote>\n <p>Can someone tell whether I am doing a shallow or deep copy?</p>\n</blockquote>\n\n<p>No.</p>\n\n<p>Shallow or Deep depends on T::operator=(). </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-09-20T19:41:12.423",
"Id": "63453",
"ParentId": "26451",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "26456",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T20:11:14.710",
"Id": "26451",
"Score": "9",
"Tags": [
"c++",
"c++11",
"linked-list",
"memory-management"
],
"Title": "Copy constructor and assignment operator for doubly linked list"
}
|
26451
|
<p>I just finished (re)reading <em>Clean Code</em>, and one of the ideas I learned was the SRP. However, I am not quite sure on what defines a "Single Responsibility." In the piece of code below, I have a <code>Note</code> class which I think may be doing too many things; it stores pitch and length, and converts these into a <code>Names</code> enum and a <code>Lengths</code> enum. Is this more than one responsibility, and if so, how should I define the classes instead? Other tips are welcome as well).</p>
<pre><code>public class Note {
public enum Lengths {
DOUBLE_WHOLE_NOTE(0.5f),
...
SIXTYFOURTH_NOTE(64);
private float length;
Lengths(float length) {
this.length = length;
}
public float getLength() {
return length;
}
private static final Map<Float, Lengths> lookup = new HashMap<Float, Lengths>();
static {
for (Lengths length : Lengths.values())
lookup.put(length.getLength(), length);
}
public static Lengths get(float length) {
return lookup.get(length);
}
}
public enum Names {
C(0),
...
REST(-1);
private final int number;
Names(int number) {
this.number = number;
}
public int getValue() {
return number;
}
private static final Map<Integer, Names> lookup = new HashMap<Integer, Names>();
static {
for (Names name : Names.values())
lookup.put(name.getValue(), name);
}
public static Names get(Integer value) {
return lookup.get(value);
}
}
private int pitch;
private float length;
public int getPitch() {
return pitch;
}
public void setPitch(int pitch) {
this.pitch = pitch;
}
public float getLength() {
return length;
}
public void setLength(float length) {
this.length = length;
}
private Note(int pitch, float length) {
this.length = length;
this.pitch = pitch;
}
public int getOctave() {
return (pitch / 12) - 5;
}
public Note.Names getNameOfNote() {
return Names.get(this.getPitch() % 12);
}
public Note.Lengths getLengthOfNote() {
return Lengths.get(this.getLength());
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T10:55:57.677",
"Id": "40992",
"Score": "1",
"body": "Here's a nice article that made practical SRP much clearer for me: https://sites.google.com/site/unclebobconsultingllc/one-thing-extract-till-you-drop Be sure to check the article comments too, where there are plenty of further ideas."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T15:34:44.070",
"Id": "41010",
"Score": "0",
"body": "Unlce Bob defines responsibility as 'a reason to change', so the SRP comes down to : a class should have only one reason to change. I think your classes are fairly safe in that department, but you may want to take a look at removing some [primitive obsession](http://c2.com/cgi/wiki?PrimitiveObsession)"
}
] |
[
{
"body": "<p>Although you put the three classes into one file, they are already three classes. So you already split the responsibility. Translating a float to a length is one \"responsibility\" and translating the pitch to a name is another. Seen from this angle everything is fine.</p>\n\n<p>SRP is a heuristic for good OO code. You won't go straight to hell if your class does two things. But if your class does 20 things you should consider a refactoring.</p>\n\n<p>If you have the feeling that your code is not readable or your file is too long, just extract the inner enum to standalone enum. In most cases it is no difference if you have an inner class/enum or a real one, so you should prefer the more readable solution.</p>\n\n<p>In addition to that, I would store the <code>length</code> as the enum at the note and translate it once in the setter (reused in the constructor) instead doing it every time in the getter. I'm also in doubt if I would offer an interface with a integer length getter and the enum length getter. Usually you want to force the caller to use the enum object, I guess.</p>\n\n<p>You should try to use <code>this</code> and the getters in a consistent way.</p>\n\n<p>Have you considered all the nasty pitfalls in using the float type? If you don't want to do any math I would prefer <code>String</code>, otherwise you might want to think about using <code>BigDecimal</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T10:15:32.937",
"Id": "40991",
"Score": "0",
"body": "Thanks mnhg, you've put my mind at ease and I'll get to work implementing your suggestions, but before that, I still have one question. What do you mean by float pitfalls? I know that are are not as precise as doubles, but I doubt that length will be used past .5 or .25. Is it still a problem?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T10:57:55.097",
"Id": "40993",
"Score": "0",
"body": "Float and doubles have the same issues. Check e.g. http://floating-point-gui.de/ . It really depends on what you are planing to do with this floats. Even adding then up might lead to a minor error and a comparison might fail."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T11:35:45.740",
"Id": "40996",
"Score": "0",
"body": "Alright, time to change to a BigDecimal, thanks for the catch."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T10:01:20.783",
"Id": "26464",
"ParentId": "26460",
"Score": "4"
}
},
{
"body": "<p>A word of caution for anyone who stumbles on this question: Just do <strong>not</strong> use <code>Float</code> or <code>Double</code> as <code>Map</code> keys.</p>\n\n<p>Do not use plurals as type names.</p>\n\n<p>See:</p>\n\n<pre><code>Cars audi = new Cars();\n</code></pre>\n\n<p>vs</p>\n\n<pre><code>Car bmw = new Car();\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T03:23:03.183",
"Id": "26506",
"ParentId": "26460",
"Score": "3"
}
},
{
"body": "<p>I would use more <a href=\"https://en.wikipedia.org/wiki/Musical_note\" rel=\"nofollow noreferrer\">standardized</a> names.</p>\n\n<p>The <code>length</code> is known as the <code>duration</code>. It can be a <code>float</code>. This way you also allow for non-powers of 2 (like triplets, dotted notes, fractional time signatures, etc.)</p>\n\n<blockquote>\n<pre><code> public float getLength() {\n\n return length;\n }\n</code></pre>\n</blockquote>\n\n<pre><code>public float getDuration() {\n\n return duration;\n }\n</code></pre>\n\n<hr>\n\n<p>The name of the note is generally either in <em>roman numeral</em> or <em>scientific pitch notation</em>. Your name is actually the latter. You could also add a helper <code>getPitchClass</code>. Note that the modular arithmic congruent operation is <code>(value % size + size) % size</code>. This allows for negative pitches. I noticed <code>C5</code> is pitch 0. So <code>B4</code> would be -1.</p>\n\n<blockquote>\n<pre><code>public Note.Names getNameOfNote() {\n\n return Names.get(this.getPitch() % 12);\n}\n</code></pre>\n</blockquote>\n\n<pre><code>public int getPitchClass() {\n\n return (this.getPitch() % 12 + 12) % 12;\n}\n\npublic Note.Names getScientificPitchClassName() {\n\n return Names.get(this.getPitchClass());\n}\n</code></pre>\n\n<hr>\n\n<p>The octave should get floored to allow also negative octaves. Since octave 5 is the zero point, octave 4 would be -1.</p>\n\n<blockquote>\n<pre><code>public int getOctave() {\n return (pitch / 12) - 5;\n}\n</code></pre>\n</blockquote>\n\n<pre><code>public int getOctave() {\n\n return Math.Floor(pitch / 12) - 5;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-24T16:13:33.427",
"Id": "220928",
"ParentId": "26460",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "26464",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T08:14:14.503",
"Id": "26460",
"Score": "5",
"Tags": [
"java",
"music"
],
"Title": "Note class for managing information on various musical notes"
}
|
26460
|
<p>I have a solution to the puzzle at <a href="https://kattis.csc.kth.se/problem?id=codes" rel="nofollow">https://kattis.csc.kth.se/problem?id=codes</a>.
What can I do to make my algorithm much much faster? What the algorithm does is take an N×K matrix and search for the minimum distance — that is, the least number of 1 for all the products of the matrix and a vector that ranges from 00001 to 11111 (where the top is 2<sup>K</sup> - 1). </p>
<pre><code>#include <iostream>
using namespace std;
void DataEntry(int &a, int &b, int** &matrix) {
cin >> a >> b;
matrix = new int*[a];
for (int i = 0; i < a; i++) {
matrix[i] = new int[b];
}
for (int i = 0; i < a; i++) {
for (int j = 0; j < b; j++) {
matrix[i][j] = -1;
cin >> matrix[i][j];
}
}
}
int* BinaryAdd(int* a, int* b, int tam) {
int* c;
int ac = 0;
c = new int[tam];
for (int i = tam - 1; i > -1; i--) {
c[i] = a[i] + b[i] + ac;
if (c[i] == 2) {
c[i] = 0;
ac = 1;
} else
ac = 0;
}
return c;
}
int* MultiplyMatrices(int** a, int* b, int tamF, int tamC) {
int * c;
c = new int[tamF];
for (int i = 0; i < tamF; i++) {
c[i] = 0;
for (int j = 0; j < tamC; j++) {
c[i] = c[i] + (a[i][j] * b[j]);
c[i] = c[i] % 2;
}
}
return c;
}
int MinimumDistance(int* a, int tam) {
int MD = 0;
for (int i = 0; i < tam; i++) {
if (a[i] == 1)
MD++;
}
return MD;
}
int pot(int a, int b) {
int c = 1;
for (int i = 1; i < b + 1; i++) {
c = a * c;
}
return c;
}
int main() {
int t = 0, n = 0, k = 0, d = -1, max = -1;
int ** lecc;
int * pro;
int * sal;
int * sol;
int * zero;
int * uno;
int * pro1;
cin >> t;
for (int p = 0; p < t; p++) {
DataEntry(n, k, lecc);
pro = new int[k];
uno = new int[k];
sal = new int[n];
zero = new int[n];
for (int i = 0; i < k; i++) {
pro[i] = 0;
}
for (int i = 0; i < k - 1; i++) {
uno[i] = 0;
}
uno[k - 1] = 1;
for (int i = 0; i < n; i++) {
zero[i] = 0;
}
pro1 = BinaryAdd(pro, uno, k);
pro = pro1;
max = pot(2, k);
sal = MultiplyMatrices(lecc, pro, n, k);
d = MinimumDistance(sal, n);
for (int i = 0; i < max - 1; i++) {
sal = MultiplyMatrices(lecc, pro, n, k);
pro1 = BinaryAdd(pro, uno, k);
pro = pro1;
int ad = MinimumDistance(sal, n);
if (ad < d)
d = ad;
}
cout << d << endl;
}
}
</code></pre>
<p>Edit: I give you a sample input and output </p>
<pre><code>Sample input Sample output
2
7 4
1 0 0 0
0 1 0 0
0 0 1 0 3
0 0 0 1 0
0 1 1 1
1 0 1 1
1 1 0 1
3 2
1 1
0 0
1 1
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T06:33:38.233",
"Id": "41069",
"Score": "0",
"body": "Can you give an example matrix and desired output?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T10:09:40.820",
"Id": "41081",
"Score": "0",
"body": "Can I divide the problem in thread? Is possible that?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T13:03:54.190",
"Id": "41160",
"Score": "1",
"body": "This is the problem in case it helps https://kattis.csc.kth.se/problem?id=codes"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T13:56:47.123",
"Id": "41168",
"Score": "1",
"body": "Sure, it's always possible to get some improvement with threading, but those problems are designed to be only solvable with the correct, non-naive algorithm."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-21T13:33:29.780",
"Id": "50459",
"Score": "0",
"body": "It seems like you are using a very brute force approach. Have you thought about using another algorithm instead of optimizing your algorithm?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-21T20:10:46.893",
"Id": "50463",
"Score": "0",
"body": "The variables should have better names than just letters (except for loop counters). I'm having a hard time reading this. Also, all the functions should start with a lowercase letter. They're not types."
}
] |
[
{
"body": "<p>I would consider use the <code>Eigen</code> library for matrix stuff. It is already optimized for that.</p>\n\n<p>Next consider using higher level contains instead of plan arrays. <code>std::vector</code> is a good choice. For a quick example of how <code>std::vector</code> will improve the run time consider <code>pro, uno, sal, and zero</code>. Right now they are all not efficient because your making a OS level requires for memory over and over. Instead create an <code>std::vector</code> and reserve the size you want if you know it in advance then simple clear the vector at the beginning of the loop and reuse the memory.</p>\n\n<p>Also your code is leaking memory like crazy. Stop using pointers Stop using <code>new[]</code> without <code>delete []</code>.</p>\n\n<hr>\n\n<p>I'm happy to hear you made a 7% improvement, but you missed the other parts of my suggestion.</p>\n\n<pre><code>int main(int argc, char *argv[]) {\n int t=0, n=0, k=0, d=-1, max=-1;\n vector< vector<int> > lecc(n, vector<int>(k));\n cin >> t;\n vector<int> sal; \n vector<int> uno;\n vector<int> pro;\n vector<int> pro1;\n //if you have an idea what the max capacity will be use `std::vector::reserve()`\n //This will avoid the time consuming task of allocating more capacity.\n\n for(int p=0; p<t; p++){\n\n lecc = EntradaDatos(n, k);\n //by resizing you might avoid a possible allocation of new space which \n //will saves alot of time.\n sal.resize(n, 0);\n uno.resize(k, 0);\n pro.resize(k, 0);\n pro1.resize(k, 0);\n</code></pre>\n\n<p>The first suggestion was to use <code>Eigen</code> for the matrix but if that's not possible consider using a 1D array implementation of a matrix. Here is an <a href=\"https://stackoverflow.com/a/13937325/942596\">example</a> array_2D using one vector. This will avoid page faults for small matrix which gives nice speed ups. Note this is limited to about 2GB(std::vector::max_size()) capacity. If your matrix need more than 2GB capacity this will not work.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T06:09:32.033",
"Id": "41066",
"Score": "0",
"body": "Thank you very much I will try to rewrite all the code using the vector."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T06:31:14.643",
"Id": "41068",
"Score": "0",
"body": "How would `std::vector` bring better performance? Of course they're more idiomatic C++ but saying they will solve the performance problem isn't helpful."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T09:50:52.507",
"Id": "41079",
"Score": "0",
"body": "I've modified the code and only drops from 0,53s to 0,491s so the change isn't very helpful"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T14:23:51.260",
"Id": "41095",
"Score": "0",
"body": "@QuentinPradet My entire point was std::vector allows for better memory management which can give a significant speed up if used correctly."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T14:27:27.243",
"Id": "41096",
"Score": "0",
"body": "@Trouner You missed my other suggestions. I updated the post. I hope this helps. I'm also happy you profiled it. Most people I encounter would just say \"I know arrays are more efficient than `std::vector`, I don't need to test it.\""
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T06:41:02.410",
"Id": "41141",
"Score": "0",
"body": "@ahenderson I come here because I need help so I try to see if your solution is better by myself. And thanks for all the help today I will try the other changes"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-21T20:21:06.083",
"Id": "50464",
"Score": "2",
"body": "@Trouner: If anything, follow his advice regarding the pointers. This is C++, and there are pointer implementations in the STL that improve on raw pointers typically used in C. To be honest, I almost mistook your code as C just by looking at the raw pointers."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T14:03:25.193",
"Id": "26471",
"ParentId": "26461",
"Score": "3"
}
},
{
"body": "<p>Considering that this is meant to be a puzzle, I'll write my review as a sequence of escalating hints.</p>\n\n<ol>\n<li>Everybody who is suggesting the use of threads or <code>std::vector</code> or matrix libraries is on the wrong track! How do you think error correction is implemented in your CD player or hard disk firmware? No threads or matrix libraries there, I assure you.</li>\n<li>Don't <em>simulate</em> the computer; <em>use</em> the computer.</li>\n<li>All operations are modulo 2. The puzzle guarantees <em>k</em> ≤ 16. Under these conditions, you can massively parallelize vector dot products. (Think SIMD or AltiVec, except you <em>don't</em> need SIMD or AltiVec.)</li>\n<li>I've added the <a href=\"/questions/tagged/bitwise\" class=\"post-tag\" title=\"show questions tagged 'bitwise'\" rel=\"tag\">bitwise</a> tag to this question.</li>\n</ol>\n\n<p>I'll conclude with a remark that you've basically written C code. The only thing that makes it C++ is your use of <code>iostream</code>. C++ can be much more expressive than that.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-22T19:10:03.557",
"Id": "50512",
"Score": "0",
"body": "You may eventually find [this](http://en.wikipedia.org/wiki/Hamming_weight) handy."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-22T17:13:50.367",
"Id": "31656",
"ParentId": "26461",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T08:17:08.317",
"Id": "26461",
"Score": "5",
"Tags": [
"c++",
"optimization",
"bitwise",
"edit-distance"
],
"Title": "Speed up a program to find the minimum Hamming distance"
}
|
26461
|
<p>I've made a program that goes through your download directory (or any other directory; you just have to change the path) and finds the files that matches your query then asks you to rename or remove the file of your choice.</p>
<p>I'd like to know how to make my program shorter.</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.h>
#define SIZE 100
void nEraser(char expression[]);
void cases(char entery[] ,int ans ,int ansN);
int main(void)
{
//DECLARATIONS
//----------------------------------------------------------------------------------------------
char fileNameContainer[SIZE] , entery[SIZE] , ans[3] , ansN[3] , *chrRes = NULL , fileNum[SIZE];
int i , finderChecker = 0 , lenght = 0 , n = 0 , number = 1 , ansNInt =0 , fileNumInt = 0 ;
DIR* directory = NULL;
struct dirent* theFile = NULL;
//----------------------------------------------------------------------------------------------
do
{
/*these variables need to be reinitialized after each 'y' answer*/
/*-----------------------------------------------------------------------------------*/
number = 1;
ansNInt = 0;
finderChecker=0;
n=0;
ans[3]="";
ansN[3] = "";
fileNameContainer[SIZE]= "";
fileNum[SIZE] = "";
/*-----------------------------------------------------------------------------------*/
directory = opendir("C:\\Users\\USER\\Downloads\\");//opening the targeted folder
if(directory == NULL)//always good to check
{
printf("error while trying to open this directory");
exit(-1);
}
do
{
printf("enter the name of the file you want to look for : ");
fgets(entery , sizeof(entery) , stdin);
/*the fgets function prints in addition to the carateres needed the \n which is a pain
in the ass so the following function removes the extra \n*/
nEraser(entery);
lenght = (int)strlen(entery);
if(lenght < 3)
{
printf("please enter a name that contains more than 3 caracters \n");
n++;
}
if(n == 5)
{
printf("you don't want to enter a valid name ? bye then ");
exit(1);
}
}
while(lenght < 3);
while((theFile = readdir(directory)) != NULL)//reading the fileNameContainer while there is something to read
{
strcpy(fileNameContainer,theFile->d_name);//copy the fileNameContainer name to fileNameContainer because its easier to deal with
/*changing the name of the file to lower case so that it maches the name entered by the user*/
for(i=0 ; fileNameContainer[i] != '\0' ; i++)
fileNameContainer[i] = tolower(fileNameContainer[i]);
/*this is where all the magic happens*/
if((chrRes = strstr(fileNameContainer,entery)) != NULL)
{
printf("%d- \" %s \"\n", number , fileNameContainer);
finderChecker++;
number++;
}
}
/*in case there is a match*/
if(finderChecker != 0)
{
printf("\n%d results in total\n\n" , finderChecker);
printf("what file do you want to modify , choose a number : ");
fgets(fileNum , sizeof(fileNum) , stdin);
nEraser(fileNum);
fileNumInt = strtol(fileNum , NULL , 10);
printf("what do you want to do with this files ?\n");
printf("1.rename\n2.remove\n3.nothing I just want to get the hell out of here\n");
fgets(ansN , sizeof(ansN) , stdin);
nEraser(ansN);
ansNInt = strtol(ansN , NULL , 10);
cases(entery , ansNInt , fileNumInt);
printf("would you like to perform another search ? y/n ");
fgets(ans , sizeof(ans) , stdin);
nEraser(ans);
if(strcmp(ans,"n") == 0 || strcmp(ans,"N") == 0)
break;
}
else
{
printf("we were unable to find this file , would you like to make another search ? y/n ");
fgets(ans , sizeof(ans) , stdin);
nEraser(ans);
}
if(closedir(directory) == -1)
exit(-2);
}
while(strcmp(ans,"y") == 0 || strcmp(ans,"Y") == 0);
getchar();
return 0;
}
void nEraser(char expression[])
{
int i , lenght = strlen(expression);
for(i=0 ; i<lenght ; i++)
{
if(expression[i] == '\n')
expression[i] = '\0';
}
}
void cases(char entery[] ,int ans , int ansN)
{
//---------------------------------------------------------------------------------------------------------------------------------
int i , number = 0;
struct dirent* filename = NULL;
DIR* directory = NULL;
char *chrRes = NULL , fileNameContainer[SIZE] , Path[SIZE] = "C:\\Users\\USER\\Downloads\\" , newFileName[SIZE] , removeAns[3];
//---------------------------------------------------------------------------------------------------------------------------------
directory = opendir(Path);
if(directory == NULL)//always good to check
{
printf("error while trying to open this directory");
exit(-1);
}
while((filename = readdir(directory)) != NULL)//reading the fileNameContainer while there is something to read
{
strcpy(fileNameContainer , filename->d_name);//copy the fileNameContainer name to fileNameContainer because its easier to deal with
for(i=0 ; fileNameContainer[i] != '\0' ; i++)
fileNameContainer[i] = tolower(fileNameContainer[i]);
chrRes = strstr(fileNameContainer,entery);
if(chrRes != NULL)
{
number++;
}
if(number == ansN)
break;
}
switch(ans)
{
case 1:
printf("what's the new file name ? : ");
fgets(newFileName , sizeof(newFileName) , stdin);
nEraser(newFileName);
strcat(Path , filename->d_name);
if(rename(Path, newFileName) == 0)
printf("the file %s (PATH : %s )was renamed successfuly , the new name is : %s\n" , filename->d_name , Path , newFileName);
else
printf("the renaming process didn't go well ...\n");
break;
case 2:
printf("are you sure you want to remove the file : %s ? y/n \n" , filename->d_name);
fgets(removeAns , sizeof(removeAns) , stdin);
nEraser(removeAns);
if(strcmp(removeAns , "y") == 0 || strcmp(removeAns , "Y") == 0)
{
strcat(Path , filename->d_name);
remove(Path);
}
break;
case 3:
break;
default :
printf("please enter a valid answer");
}
if(closedir(directory) == -1)
exit(-3);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T14:46:22.450",
"Id": "41004",
"Score": "2",
"body": "We'll only be able to answer if you show us the working code, as mentioned in the [faq#im-confused-what-questions-are-on-topic-for-this-site]. Otherwise, your question will be closed. Thanks!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T17:41:50.590",
"Id": "41018",
"Score": "2",
"body": "I suggest you compile your program with warnings enabled (eg -Wall for gcc/clang) and fix the warnings. Then paste the whole program into the question here, just like you did at pastebin. After pasting, select the whole program and use ctrl-k to indent it."
}
] |
[
{
"body": "<p>This code has too many issues to go through in detail. Here are some that\nstand out.</p>\n\n<p>Firstly, compiling the code leads to a page of warnings that you should have\ncaught yourself. Code such as</p>\n\n<pre><code>char fileNameContainer[SIZE] , entery[SIZE] , ans[3] , ansN[3] ...\n...\nans[3] = \"\";\nansN[3] = \"\";\netc\n</code></pre>\n\n<p>should give some warnings:</p>\n\n<pre><code>code.c:26:15: warning: incompatible pointer ...\ncode.c:26:9: warning: array index 3 is past the end of the array ...\n</code></pre>\n\n<p>If you had defined one variable per line (as is best practice) and initialized\nit immediately, there would have been no problem.</p>\n\n<pre><code>char fileNameContainer[SIZE] = \"\";\nchar entery[SIZE] = \"\";\nchar ans[3] = \"\";\nchar ansN[3] = \"\";\n</code></pre>\n\n<p>Secondly, you do not decompose the program into suitable functions. <code>main</code> and <code>cases</code> are much too long. Its component parts should be extracted into separate\nfunctions. <code>main</code> is typically quite short. </p>\n\n<p>Thirdly, you are converting file names to lower case for comparison, but some\nfielsystems are case sensitive. </p>\n\n<p>Minor tidbit, you <code>nEraser</code> function, which deletes the trailing \\n on a string\nis excessive. The standard function <code>strchr</code> will find the character for you\nso all you need is:</p>\n\n<pre><code>char *s = strchr(expr, '\\n');\nif (s) {\n *s = '\\0';\n}\n</code></pre>\n\n<p>There are many other issues, and maybe someone else will point some out. But\nyou can improve the program by correcting those above. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-02T14:15:14.080",
"Id": "36508",
"ParentId": "26470",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T13:37:18.047",
"Id": "26470",
"Score": "2",
"Tags": [
"optimization",
"c",
"algorithm",
"search",
"file"
],
"Title": "Use search query to find and modify files in directory"
}
|
26470
|
<p>I need a global data in my application. My application uses several threads to access and add items to my global variable. The global variable is a <code>ConcurrentDictionary</code> I choose to ensure data is added to the variable. What do you think about my approach?</p>
<pre><code>public class GlobalData
{
private static volatile GlobalData instance;
private volatile ConcurrentDictionary<string, object> _data = new ConcurrentDictionary<string, object>();
private static object syncRoot = new Object();
public static GlobalData Instance
{
get
{
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
instance = new GlobalData();
}
}
return instance;
}
}
public void Add(string id, object obj)
{
_data.TryAdd(id, obj);
}
public object Get(string id)
{
object value;
_data.TryGetValue(id, out value);
return value;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T14:51:36.920",
"Id": "41005",
"Score": "1",
"body": "Why do you think you need shared data? What are the threads doing with it? You have separate `Add` and `Get` methods, which means, dollars to dimes, you have a race condition."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T20:16:04.167",
"Id": "41039",
"Score": "0",
"body": "Read this for a recommended approach for creating singletons http://codereview.stackexchange.com/questions/79/implementing-a-singleton-pattern-in-c"
}
] |
[
{
"body": "<p>Yes, it can:</p>\n\n<ol>\n<li>First, you are mixing statics and non-statics in a confusing way. Please seperate those.</li>\n<li>A singleton should only be created once. Your class does not have a constructor, so it can be initialized everywhere. Give your class a private constructor. This why, only the class itself can instantiate one.</li>\n<li>You lock the creation of the GlobalData to prevent problems in a multi threaded environment. Why not put your initialization inside a static constructor or initialize the static field directly, which prevent any problems with multiple threads. This also gets rid of the <code>syncRoot</code>.</li>\n<li>The keyword <code>volatile</code> is only required on changing values in a multithreaded environment. Your reference to the <code>GlobalData</code> will never change after it has been initialized.</li>\n</ol>\n\n<p>Suggestion:</p>\n\n<pre><code>public class GlobalData\n{\n #region Static members\n\n private static readonly GlobalData instance = new GlobalData();\n\n public static GlobalData Instance\n {\n get\n {\n return instance;\n }\n }\n\n #endregion\n #region Instance members\n\n private readonly ConcurrentDictionary<string, object> _data = new ConcurrentDictionary<string, object>();\n\n private GlobalData()\n {\n }\n\n public void Add(string id, object obj)\n {\n _data.TryAdd(id, obj);\n }\n\n public object Get(string id)\n {\n object value;\n _data.TryGetValue(id, out value);\n return value;\n }\n\n #endregion\n} \n</code></pre>\n\n<p>While you are working on it, why not put all code inside a static class, removing the need for one instance and making your code much shorter?</p>\n\n<pre><code>static public class GlobalData\n{\n static private readonly ConcurrentDictionary<string, object> _data = new ConcurrentDictionary<string, object>();\n\n static public void Add(string id, object obj)\n {\n _data.TryAdd(id, obj);\n }\n\n static public object Get(string id)\n {\n object value;\n _data.TryGetValue(id, out value);\n return value;\n }\n} \n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T15:02:39.863",
"Id": "41008",
"Score": "0",
"body": "I like the second version. Can threads add data to the dictionary and retrieve the data at anytime. I see that the _data variable is read-only does that mean i can only add a value to it one?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T15:39:46.997",
"Id": "41011",
"Score": "1",
"body": "@Luke: The keyword `readonly` only says something about the reference to the object. It does not say anything about the values inside the object. In this case, when you have created a new dictionary, that reference cannot be modified (outside the constructor). But the contents of the dictionary can be modified."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T15:40:43.583",
"Id": "41012",
"Score": "1",
"body": "@Luke: The dictionary is a `ConcurrentDictionary` which means that the dictionary will synchronize all multithreaded operations. In this case, multiple readers are allowed, and one writer is allowed. Reads and writes cannot be combined, but the dictionary will manage that himself. Do not worry about that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-09T23:30:18.393",
"Id": "86825",
"Score": "0",
"body": "The access modifier comes first, it's `public static class GlobalData` - nice review nonetheless, +1 :)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T14:50:20.417",
"Id": "26473",
"ParentId": "26472",
"Score": "5"
}
},
{
"body": "<ul>\n<li><a href=\"https://stackoverflow.com/questions/137975/what-is-so-bad-about-singletons\">Singletons are evil</a></li>\n<li>Even if you do want to use it, use <code>Lazy<T></code> instead of manually doing double-checked locking</li>\n</ul>\n\n<p>Best solution would be to leverage <a href=\"http://en.wikipedia.org/wiki/Inversion_of_control\" rel=\"nofollow noreferrer\">IoC</a> container to inject dependencies you need.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T14:55:37.947",
"Id": "26475",
"ParentId": "26472",
"Score": "7"
}
},
{
"body": "<h2>Do not use singleton</h2>\n\n<h2>If you dare...</h2>\n\n<p>... and you are on .NET 4.0 use <code>Lazy<T></code></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T15:18:47.113",
"Id": "26477",
"ParentId": "26472",
"Score": "-2"
}
},
{
"body": "<p>I do something like this when I feel like singletons are the answer. I'm not sure if it's considered dependency injection, but it works pretty well for me. You can also swap out functionality easily, by writing a set Dependency function in the class that wants injections then calling it's functions.</p>\n\n<pre><code>public interface IExampleInterface\n{\n void Foo(int number);\n}\n\npublic class OldSingletonClassThatWillBeInjected : IExampleInterface\n{\n public OldSingletonClassThatWillBeInjected()\n {\n\n }\n\n public void Foo(int value)\n {\n Log(value);\n }\n}\n\npublic class ClassThatWantsInjection \n{\n IExampleInterface _injection;\n\n public ClassThatWantsInjection(IExampleInterface injection)\n {\n //Act on this variable through interface methods.\n _injection = injection; \n }\n\n public void TestInjection()\n {\n _injection.Foo(5643);\n }\n}\n\npublic class ProgramMain()\n{\n ClassThatWantsInjection _subject;\n OldSingletonClassThatWillBeInjected _oldSingleton;\n\n static void Main()\n {\n _oldSingleton = new OldSingletonClassThatWillBeInjected();\n //Send the old singleton-y class into the subject.\n _subject = new ClassThatWantsInjection(_oldSingleton);\n _subject.TestInjection();\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-31T22:25:58.013",
"Id": "30598",
"ParentId": "26472",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T14:21:29.170",
"Id": "26472",
"Score": "3",
"Tags": [
"c#",
"singleton"
],
"Title": "Global data singleton"
}
|
26472
|
<p>In my program I read several information's about the system. I read each categories like CPU, memory, services, software and so on with a own thread. The main program have to wait for the longest thread.</p>
<p>To implement this, I use <code>LINQ</code> and the <code>Join</code> function from <code>Thread</code>.</p>
<p>Here is a small part from my code:</p>
<pre><code>var culture = CultureInfo.CreateSpecificCulture("en-US");
var thread_list = new List<Thread>();
var c = new Computer();
var thrma = new Thread(() =>
{
c.Mainboard = new Mainboard().GetInformation();
});
thrma.CurrentUICulture = culture;
thrma.Start();
thread_list.Add(thrma);
var thrce = new Thread(() =>
{
c.ProcessorList = new CentralProcessingUnit().GetInformation();
});
thrce.CurrentUICulture = culture;
thrce.Start();
thread_list.Add(thrce);
...
var thrsvr = new Thread(() =>
{
DeviceService.ScanServices();
});
thrsvr.CurrentUICulture = culture;
thrsvr.Start();
thread_list.Add(thrsvr);
foreach (Thread t in thread_list)
{
t.Join();
}
// Everyone is done!
</code></pre>
<p>Each hardware device is derived from the Hardware class.</p>
<p>What do you think about the solution? Is there a "nicer" or better implementation? I would like to use a function, because the code is very similar, but I'm not sure how to do it. Any idea?</p>
<p>Thanks for your advices. </p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T14:57:36.083",
"Id": "41006",
"Score": "0",
"body": "Which .NET version are you using? Are these `Mainboard`, `CentralProcessingUnit` and `DeviceService` classes written by you or came from 3rd-party library?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T15:01:31.843",
"Id": "41007",
"Score": "0",
"body": "I use .Net 4. I wrote those classes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T15:48:09.600",
"Id": "41013",
"Score": "0",
"body": "I have forgotten to say, that the threads are running in a services."
}
] |
[
{
"body": "<p>It's better to use new asynchronous API since it provides more features for combining asynchronous tasks. </p>\n\n<p>Ideally <code>Mainboard</code>, <code>CentralProcessingUnit</code> and <code>DeviceService</code> should expose asynchronous API if a certain operation is not trivial, so (as you mentioned in comments you wrote them) I would implement asynchronous API for them first, e.g.:</p>\n\n<pre><code>public class Mainboard\n{\n public Task<string> GetInformationAsync()\n {\n //TODO: extract long-term operation into Task. Try not to span extra threads here\n }\n}\n</code></pre>\n\n<p>Then your method would look like:</p>\n\n<pre><code>Task.WaitAll(\n new Mainboard().GetInformationAsync().ContinueWith(task => c.Mainboard = task.Result),\n new CentralProcessingUnit().GetInformationAsync().ContinueWith(task => c.ProcessorList = task.Result),\n DeviceService.ScanServicesAsync());\n</code></pre>\n\n<p>If you decide not to implement async API the code can look like:</p>\n\n<pre><code>var c = new Computer();\n\nTask.WaitAll(\n Task.Factory.StartNew(() => c.Mainboard = new Mainboard().GetInformation()),\n Task.Factory.StartNew(() => c.ProcessorList = new CentralProcessingUnit().GetInformation()),\n Task.Factory.StartNew(() => DeviceService.ScanServices()));\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T15:33:48.837",
"Id": "41009",
"Score": "0",
"body": "Looks very nice! Is it possible to set the `CultureInfo` in the `Task`. The asynchronous API doesn't block the main program, right? Thanks!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T16:01:20.840",
"Id": "41014",
"Score": "0",
"body": "I would rather explicitly pass `CultureInfo` to methods that require it instead of relying on current thread CultureInfo."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T15:23:21.413",
"Id": "26478",
"ParentId": "26474",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "26478",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T14:50:20.357",
"Id": "26474",
"Score": "1",
"Tags": [
"c#",
"linq",
"multithreading"
],
"Title": "Optimize Implementation - Wait for all threads using LINQ"
}
|
26474
|
<p>I'm relatively new to bash scripting, and I'm wondering how I've done on this. Basically it's a script where if I'm in a github or bitbucket repository in my terminal, I can type <code>browse-repository</code> to open it up in the browser. I can also type something like <code>browse-repository issues</code> to visit the issues page, or <code>browse-repository issues 19</code> to see issue # 19 for the repository.</p>
<p>I alias the command as <code>br</code> to save on typing, and can type things like <code>br i 19</code> to get to the page for issue # 19.</p>
<p>I'm mainly looking for tips on organization and scope, and of course if there's any other improvements as well. I couldn't figure out any sort of namespacing, so i prefixed commands with <code>_browse_repository</code></p>
<p>The file as it currently stands is simple sourced from my <code>.bash_profile</code>, if that matters.</p>
<pre><code>#!/bin/bash -e
function browse-repository() {
local URL="https://$(git config remote.origin.url | sed 's/\.git//' | sed 's/https:\/\///' | sed 's/ssh:\/\///' | sed 's/git:\/\///' | sed 's/git@//' | tr ':' '/')"
if _browse_repository_is_bitbucket_repo "$URL" || _browse_repository_is_github_repo "$URL"
then
case "$1" in
"")
URL="$URL"
_browse_repository_go
;;
i|issues|-i|--issues)
if [[ -n $2 ]]
then
if _browse_repository_is_bitbucket_repo "$URL"
then
URL="$URL/issue/$2"
else
URL="$URL/issues/$2"
fi
else
URL="$URL/issues"
fi
_browse_repository_go
;;
p|pulls|-p|--pulls)
if _is_bitbucket_repo "$URL"
then
URL="$URL/pull-requests"
else
URL="$URL/pulls"
fi
_browse_repository_go
;;
w|wiki|-w|--wiki)
URL="$URL/wiki"
_browse_repository_go
;;
h|help|-h|--help)
_browse_repository_usage
;;
*)
_browse_repository_usage
;;
esac
else
case "$1" in
h|help|-h|--help)
_browse_repository_usage
;;
*)
echo "Not a valid bitbucket or github repository"
;;
esac
fi
}
_browse_repository_is_bitbucket_repo() {
[ "$URL" != "${URL#https:\/\/bitbucket.org\/}" ]
}
_browse_repository_is_github_repo() {
[ "$URL" != "${URL#https:\/\/github.com\/}" ]
}
_browse_repository_usage() {
cat <<EOF
usage: browse-repository [<command>] [<number>]
The following commands are performed on the current project.
Available commands:
-i --issues [<number>] Open issues, optionally pass a number to open a specific issue
-p --pulls Open pull requests, optionally pass a number to open a specific pull request
-w --wiki Open wiki
When no argument is supplied the main project page will be opened.
EOF
}
_browse_repository_go() {
open "$URL"
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T17:21:11.910",
"Id": "71132",
"Score": "0",
"body": "I saved your script and made it executable, and from a github Repository, i executed it but nothing happens.."
}
] |
[
{
"body": "<p>Some things:</p>\n\n<ul>\n<li>You don't need the <code>function</code> keyword to define a function.</li>\n<li>You can combine <code>sed</code> commands by separating them by <code>;</code>: <code>sed 's/\\.git//;s/https:\\/\\///;s/ssh:\\/\\///;s/git:\\/\\///;s/git@//'</code></li>\n<li>This can be shortened down to a single statement: <code>sed 's/\\(\\.git\\|https:\\/\\/\\|ssh:\\/\\/\\|git:\\/\\/\\|git@\\)//'</code></li>\n<li>Fortunately you can get rid of picket fences in <code>sed</code> by using a different separator: <code>sed 's#\\(\\.git\\|https://\\|ssh://\\|git://\\|git@\\)##'</code></li>\n<li>I'd use <code>getopt</code> or <code>getopts</code> for option handling. Which one to use is a bit of a religious issue, but <code>getopt</code> supports long options (<code>--help</code> and the like), while <code>getopts</code> is more portable.</li>\n<li>It is <a href=\"https://stackoverflow.com/a/673940/96588\">recommended</a> to use upper case only for variables exported in the shell, and lower case for other variables.</li>\n<li>This is maybe more of a personal preference, but rather than creating a <em>function</em> called I'd create a <em>script</em> with the same name and move the contents of the <code>browse-repository</code> function to the end of the script. That way there's no pollution of the function name space, and no need to source the script. Just put it for example at <code>/usr/local/bin/browse-repository</code> and run. An added advantage of this is that you don't need the function name prefixes anymore.</li>\n<li><p>I'm not sure how portable <code>open</code> is. On my system:</p>\n\n<pre><code>$ open http://www.example.org\nCouldn't get a file descriptor referring to the console\n</code></pre>\n\n<p>Alternatively you could use <code>x-www-browser</code>, but I fear that's even less portable (Debian & derivatives only IIRC). I don't know if there's something more portable available.</p></li>\n</ul>\n\n<p>All in all a very nice script.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-28T13:35:26.337",
"Id": "26705",
"ParentId": "26479",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "26705",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T15:35:57.170",
"Id": "26479",
"Score": "4",
"Tags": [
"bash"
],
"Title": "Simple bash script for opening a repository in the browser from the command line"
}
|
26479
|
<p>I've developed <a href="https://gist.github.com/vi/5628320" rel="nofollow">a script</a> to set up an encrypted tunnel between two Linux hosts, using <code>iproute2</code>, <code>ssh</code> and <code>setkey</code>.
The goal is to allow setting up ad-hoc secure tunnels with minimum of setup and dependencies.</p>
<p>Mirrored here:</p>
<pre><code>#!/bin/bash
# Setup encrypted IPv4 tunnel over IPv4 or IPv6 on two Linux nodes using SSH for tunnel setup.
# Requires only ipsec-tools, iproute2, ssh and necessry kernel modules locally and remotely.
# Warning: it flushes IPsec settings both locally and remotely.
# Don't use with other IPsec tunnnels.
# Sample usage:
# simplevpn -6 fc::1 fc::2 ssh -T root@fc::2
# fc::1 is your IPv6 address
# fc::2 is other peer's IPv6 address
# after successful run it should create tunnel named "simplevpn" locally and remotely
# and set up addresses 192.168.77.1 and 192.168.77.2 locally and remotely respectively
# Note: tested only once in my configuration. This is not a serious production-ready VPN solution.
# Implemented by Vitaly "_Vi" Shukela in 2013, License=MIT
MODE="ipip"
PROT="-4"
if [ "$1" == "-6" ]; then
shift;
MODE=ipip6
PROT="-6"
fi
SRC="$1"; shift
DST="$1"; shift
if [ -z "$1" ]; then
echo Usage: simplevpn [-6] source_ip destination_ip ssh_command_line
exit 1;
fi
set -e
KEY1=0x`dd if=/dev/urandom count=32 bs=1 2> /dev/null| xxd -p -c 64`
KEY2=0x`dd if=/dev/urandom count=32 bs=1 2> /dev/null| xxd -p -c 64`
true ${LOCALIP:="192.168.77.1"}
true ${REMOTEIP:="192.168.77.2"}
true ${DEVNAME:="simplevpn"}
# 4 is encapsulated IPv4 both in IPv4 an IPv6
setkey -c << EOF
flush;
spdflush;
spdadd $SRC $DST 4 -P out ipsec esp/transport//require ah/transport//require;
spdadd $DST $SRC 4 -P in ipsec esp/transport//require ah/transport//require;
add $SRC $DST esp 0x4444 -E rijndael-cbc $KEY1 ;
add $DST $SRC esp 0x4444 -E rijndael-cbc $KEY1 ;
add $SRC $DST ah 0x4445 -A hmac-sha256 $KEY2 ;
add $DST $SRC ah 0x4445 -A hmac-sha256 $KEY2 ;
EOF
modprobe ip6_tunnel
ip $PROT tunnel del $DEVNAME || true
ip $PROT tunnel add $DEVNAME mode $MODE local $SRC remote $DST
ip link set $DEVNAME up
ip -4 addr add $LOCALIP/32 dev $DEVNAME
ip -4 route add $REMOTEIP/32 dev $DEVNAME
"$@" << EOF
set -e
# the same as above, but "in" and "out" swapped
setkey -c << EOF2
flush;
spdflush;
spdadd $SRC $DST 4 -P in ipsec esp/transport//require ah/transport//require;
spdadd $DST $SRC 4 -P out ipsec esp/transport//require ah/transport//require;
add $SRC $DST esp 0x4444 -E rijndael-cbc $KEY1 ;
add $DST $SRC esp 0x4444 -E rijndael-cbc $KEY1 ;
add $SRC $DST ah 0x4445 -A hmac-sha256 $KEY2 ;
add $DST $SRC ah 0x4445 -A hmac-sha256 $KEY2 ;
EOF2
modprobe ip6_tunnel
ip $PROT tunnel del $DEVNAME || true
ip $PROT tunnel add $DEVNAME mode $MODE remote $SRC local $DST
ip link set $DEVNAME up
ip -4 addr add $REMOTEIP/32 dev $DEVNAME
ip -4 route add $LOCALIP/32 dev $DEVNAME
EOF
</code></pre>
<p>Are there any glaring errors? Do you have any suggestions (apart from not flushing entire security tables)? I'm primarily interested in security issues.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T15:03:09.673",
"Id": "41099",
"Score": "0",
"body": "Note: filed [a bug](https://bugzilla.kernel.org/show_bug.cgi?id=58691) reproduced with this script."
}
] |
[
{
"body": "<ul>\n<li>As far as I can tell, it checks if you provide too many options, but it doesn't check if you provide too few. This should be done before trying to do anything with <code>SRC</code> and <code>DST</code>. <code>set -o errexit -o nounset</code> as the first line would be prudent.\n<ul>\n<li><code>set</code> stuff is <em>not inherited by subshells</em>. So to make a failure in the <code>dd</code> command propagate you should start with <code>set -o errexit -o pipefail</code>. A simpler way to achieve the same effect would be to add <code>-o pipefail</code> to <code>set</code>, create a function with the <code>dd | xxd</code> commands, and use this directly instead of assigning to variables.</li>\n</ul></li>\n<li>What happens if <code>dd</code> fails, for whatever reason? For example, <code>dd() { echo foo; }</code> will override the command. Use <code>command dd</code> [sic] if you want to make sure it doesn't use shell builtins, aliases or functions.</li>\n<li>There's no <code>==</code> operator in POSIX <code>[</code> - AFAIK this only works by accident on some systems. You can either use Bash' <code>[[</code> or a single <code>=</code>.</li>\n<li><code>|| true</code> can hide issues with the preceding command. Either check first if the command should be run before trying (and not ignoring the error), or run the command and check if the exit code matches the one you expect.</li>\n<li><a href=\"http://mywiki.wooledge.org/BashGuide/Practices\" rel=\"nofollow\">Use More Quotes™</a></li>\n</ul>\n\n<p>I can't comment on the safety of the <code>KEYn</code> generation or <code>setkey</code> use.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-28T17:57:18.297",
"Id": "41408",
"Score": "0",
"body": "Thanks for the advices. The main concern is `setkey`. Can my tunnel _suddenly_ become uncrypted? Is the encryption applied correctly?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-28T17:59:39.647",
"Id": "41409",
"Score": "0",
"body": "Doesn't `set -e` dig into backticked command? If `dd` failed I expect the script to exit."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-29T08:18:13.007",
"Id": "41436",
"Score": "0",
"body": "@Vi. Updated with tips."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-29T08:19:03.523",
"Id": "41437",
"Score": "0",
"body": "@Vi. As I said, I can't really comment on the inner security issues. You may want to strip down to the bare minimum code and ask on [security.](http://security.stackexchange.com/)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-28T14:00:57.780",
"Id": "26706",
"ParentId": "26480",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T16:30:43.520",
"Id": "26480",
"Score": "3",
"Tags": [
"security",
"bash",
"linux",
"networking"
],
"Title": "Simple IPSec/tunnel setup script"
}
|
26480
|
<p>I am walking through a sample MVC4 ASP.NET tutorial available on PluralSight.com, by Scott Allen. I am in a section #5, Working with Data (part 2), "Listing Reviews".</p>
<p>This application has a database of restaurant reviews. I'm following a section right now in which Scott shows how to add links in the Restaurant view that will display a list of reviews for the selected restaurant.</p>
<p>There <em>was</em> a problem when clicking the link to display the reviews, encountered in the following cshtml file. The problem was that <code>Model.Reviews</code> in the parameters for <code>Html.Partial</code> method was <code>null</code> by default.</p>
<h2>Index.cshtml</h2>
<pre><code>@model OdeToFood.Models.Restaurant
@{
ViewBag.Title = "Index";
}
<h2>Reviews for @Model.Name</h2>
@Html.Partial("_reviews", Model.Reviews)
<p>
@Html.ActionLink("Create New", "Create")
</p>
</code></pre>
<p>Scott explained that the Model class <code>Restaurant</code>, listed below, will load all the properties except for Reviews, which are stored in another table somewhere else. He said there are many ways to fix the problem, but the <strong>easiest</strong> way to make EF load the reviews is to make the <code>Reviews</code> property <code>virtual</code>.</p>
<h2>Model class <code>Restaurant</code></h2>
<pre><code>public class Restaurant
{
public int Id { get; set; }
public string Name { get; set; }
public string City { get; set; }
public string Country { get; set; }
public ICollection<RestaurantReview> Reviews { get; set; }
}
</code></pre>
<p>He said that at run time, the EF creates a "wrapper" for the restaurant class that will intercept calls (I don't understand this) to the <code>Reviews</code> property so that when you get to the reviews in the view, The EF will load them up instead of being <code>null</code>.</p>
<p>My concern is that making a property <code>virtual</code> when you don't intend to override it, is bad coding practice. If so, what is the best coding practice here? I'm also wondering if the simplest solution is the best solution here.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T18:28:10.597",
"Id": "41027",
"Score": "0",
"body": "I'm not sure if your question fits here, because you're not actually asking for a review of your code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T18:37:19.493",
"Id": "41028",
"Score": "0",
"body": "@svick Yes, I was trying to decide that. I felt it might be relevant to Code Review as opposed to StackOverflow because I felt that the virtual property needed to be reviewed."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-06-30T03:49:59.440",
"Id": "173611",
"Score": "1",
"body": "`making a property virtual when you don't intend to override it, is bad coding practice` -- but it is being overridden by generated code."
}
] |
[
{
"body": "<p>EF will not create a wrapper around the <code>Restaurant</code> class! Instead it will derive from your <code>Restaurant</code> class and it will override that property (<code>public ICollection<RestaurantReview> Reviews</code>) because it needs to create a proxy or navigation property instead of an everyday property. If you don't specify that property as a virtual one, the EF can not create a navigation property over it and your relations will not work.</p>\n\n<p>I recommend you to check out this behavior through the debugger you will see classes with this kind of name: <code>Restaurant_HFUEOHUEOHHRRHRHRHHRHIFEFNSES355KL4KLH4KH3KLNEN3L3</code></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T18:17:14.870",
"Id": "26485",
"ParentId": "26481",
"Score": "5"
}
},
{
"body": "<p>I considered submitting this for migration to StackOverflow, but mentally justified it as being a meta-review of your own review. Thus I will take this as on opportunity to respond to your review.</p>\n\n<p>I'm not sure if leaving methods virtual is bad coding practice -- Java designers would take the opposite view.</p>\n\n<p>Previous comment aside, you are intending for the property to be overridden. To explain most simply would be to define the <a href=\"http://c2.com/cgi/wiki?DecoratorPattern\" rel=\"nofollow\">'wrapper' or 'decorator' pattern</a> which you indicated you didn't understand.</p>\n\n<p>Most basically, the pattern involves subclassing a type to add functionality, such as logging, authorization, or in this case creating lazy navigable properties. If EF automatically populated each complex property of an entity (and those properties complex properties ad infinitum), then most common object graphs would result in returning the entire repository. To avoid this, EF creates lazy properties to not load these details until they are first read. (This can be overridden by specifying a property as 'eager', but that is beyond this review.) EF generates a subclass of your entity to 'decorate' this laziness on your type which, in turn requires the property to be virtual.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-06-30T04:14:38.917",
"Id": "95180",
"ParentId": "26481",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T16:55:42.647",
"Id": "26481",
"Score": "2",
"Tags": [
"c#",
"performance",
"asp.net",
"entity-framework",
"asp.net-mvc-4"
],
"Title": "Making a property virtual to cause EF to load the property"
}
|
26481
|
<p>As an exercise, I've written quicksort algorithm in C using pointers. Please comment and help me find the cases where it breaks (if any).</p>
<pre><code>void qsort(int *, int, int);
void swap(int *, int *);
void qsort(int *v, int left, int right)
{
int i, *last;
if (right <= left)
return;
last = v + left; //choosing the first element as the pivot
for (i = left + 1; i <= right; i++)
if (*(v + i) < *(v + left))
swap(++last, v + i); //swapping the numbers < pivot
swap(v + left, last);
qsort(v, left, last - v - 1); //sub-array containing numbers < pivot
qsort(v, last - v + 1, right); //sub-array containing numbers >= pivot
}
void swap(int *i, int *j)
{
int temp;
temp = *i;
*i = *j;
*j = temp;
}
</code></pre>
|
[] |
[
{
"body": "<p>I'd make right an exclusive instead of inclusive upper bound, that is write <code>i < right</code> instead of <code>i <= right</code> and <code>last - v</code> instead of <code>last - v - 1</code>.</p>\n\n<p>This has the advantage of making the base call <code>qsort(v, 0, length)</code> instead of <code>qsort(v, 0, length - 1)</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T20:48:45.387",
"Id": "26494",
"ParentId": "26483",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T18:00:29.367",
"Id": "26483",
"Score": "4",
"Tags": [
"c",
"algorithm",
"array",
"sorting",
"quick-sort"
],
"Title": "Quicksort using pointers"
}
|
26483
|
<p>I made a class to perform tasks concurrently and have implemented it. From appearances and testing, everything seems to work. How can I improve this? I understand this is somewhat a broad question, so please let me know how I should narrow it down.</p>
<p>Here is the pseudocode:</p>
<p>The general idea is a single <code>Starter</code> spawns multiple <code>TaskWorker</code> to do the work. I want to start the loading process fairly early on and then block EDT until the completion of all <code>TaskWorker</code>.</p>
<pre><code>class ImproveMe {
private AtomicInteger incompleteTasksCount = new AtomicInteger( -1 );
/* SwingWorker has a limitation of 10 */
private static final int MAX_CONCURRENT_THREAD = 20;
private static ExecutorService threadPool = Executors.newFixedThreadPool( MAX_CONCURRENT_THREAD );
/* This just starts multiple TaskWorker */
class Starter extends SwingWorker {
Object doInBackground() {
incompleteTasksCount.getAndSet( -1 );
Tasks[] taskList = getTasks();
for ( Task task : taskList ) {
/* Track incomplete tasks */
if ( incompleteTasksCount.compareAndSet( -1, 1 ) {
incompleteTasksCount.incrementAndget();
}
threadPool.submit( new TaskWorker( task ) );
}
threadPool.shutdown();
}
}
/* Performs the actual work -- I don't care about the results since it will be cached elsewhere */
class TaskWorker implements Runnable {
Task t;
TaskWorker( Task t ) {
this.t = t;
}
void run() {
if ( t != null ) {
do stuff with 't'
}
synchronized( incompleteTasksCount ) {
if ( incompleteTasksCount.decrementAndGet() == 0 ) {
/* everything is done! */
incompleteTasksCount.notifyAll();
}
}
}
}
/* User will call this to start the loading */
public void startLoading() {
if ( !threadPool.isShutdown() ) {
Starter s = new Starter();
s.execute();
}
}
/* User will call this to ensure that everything has complete before continuing */
public void blockUntilDone() {
boolean cont = true;
if ( incompleteTasksCount.get() == 0 || threadPool.isTerminated() ) {
return;
} else if ( incompleteTasksCount.get() == -1 ) {
/* not loaded/started */
return;
}
while ( cont ) {
synchronized( incompleteTasksCount ) {
try {
incompleteTasksCount.wait();
} catch ( InterruptedException e ) {
e.printStackTrace();
cont = false;
} finally {
if ( incompleteTasksCount.get() == 0 ) {
cont = false;
}
}
}
}
}
}
</code></pre>
<p>In reality, <code>TaskWorker</code> calls <a href="http://docs.oracle.com/javase/6/docs/api/javax/print/PrintService.html" rel="nofollow noreferrer"><code>PrintService</code></a>.<a href="http://docs.oracle.com/javase/6/docs/api/javax/print/PrintService.html#getSupportedAttributeValues%28java.lang.Class,%20javax.print.DocFlavor,%20javax.print.attribute.AttributeSet%29" rel="nofollow noreferrer"><code>getSupportedAttributeValues(..)</code></a> because of the numerous printers and Java caches that so any future calls will return fairly quickly as compared to the first time (some of the network printers took 40+ seconds). I call <code>ImproveMe.startLoading()</code> somewhere fairly early in my program then before the actual program starts (e.g. GUI is shown), I use <code>ImproveMe.blockUntilDone()</code> to ensure everything is loaded.</p>
|
[] |
[
{
"body": "<p><code>SwingWorker</code> comes with all the control features you try to emulate here. It already uses an <code>ExecutorService</code> under the hood. I'm not sure why you want to increase the maximum pool size, but given that the code does not compile as given, makes me suspect you did not decide this, based on performance measuring.</p>\n\n<p>So here's what I did :</p>\n\n<ol>\n<li>Launching the workers is lightweight enough to not need\nto be run in a separate thread, so I inlined Starter. </li>\n<li>Keeping tabs on task progression is done through the <code>Future</code> that you get from\nan <code>ExecutorService</code>. <code>SwingWorker</code> exposes this by implementing <code>Future</code>\nitself. Waiting until a <code>SwingWorker</code> is done is as simple as calling its\n<code>get()</code> method, which will block until the task is done.</li>\n<li>You don't need the low level constructs <code>wait()</code> and <code>notifyAll()</code>. </li>\n<li>Properly handle <code>InterruptedException</code> : put it in your throws clause, or if you catch\nit, reset the <code>Thread</code>'s interrupted flag by calling\n<code>Thread.currentThread().interrupt();</code> so clients of your code know the thread has been\ninterrupted, and they can do their own cleanup.</li>\n<li><code>SwingWorker</code> uses generics to know the type of the result. Typically when no result is\ngiven, <code>Void</code> is chosen as a return type. (this makes a comment about not caring about\nthe return value superfluous).</li>\n<li>I've spent attention to the visibility modifiers, tightening it wherever possible,\nexposing only as much as is strictly needed.</li>\n<li><code>Future.get()</code> throws an ExecutionException if the underlying task execution\nthrew an exception. Your code had no means of dealing with those.</li>\n</ol>\n\n<p>Here's my refactoring of your code :</p>\n\n<pre><code>public class ImproveMe {\n private final List<SwingWorker> workers;\n\n public ImproveMe(Task[] tasks) {\n workers = new ArrayList<>(tasks.length);\n for (Task task : tasks) {\n workers.add(new TaskWorker(task));\n }\n }\n\n /* User will call this to start the loading */\n public void startLoading() {\n for (SwingWorker worker : workers) {\n worker.execute();\n }\n }\n\n /* User will call this to ensure that everything has complete before continuing */\n public void blockUntilDone() throws InterruptedException {\n for (SwingWorker worker : workers) {\n waitForWorker(worker);\n }\n }\n\n private void waitForWorker(SwingWorker worker) throws InterruptedException {\n try {\n worker.get(); // will block until the worker's task is done\n } catch (ExecutionException e) {\n throw new RuntimeException(e); // more appropriate exception handling here\n }\n }\n\n private static class TaskWorker extends SwingWorker<Void, Void> {\n private final Task t;\n\n TaskWorker( Task t ) {\n this.t = t;\n }\n\n public Void doInBackground() {\n if ( t != null ) {\n //do stuff with 't'\n }\n return null;\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T17:09:15.580",
"Id": "41111",
"Score": "0",
"body": "`SwingWorker` maximum of 10 is actually not enough for me and it's also shared with whatever `SwingWorker` that could exist at that point and time - it did originally start out as a `SwingWorker`. (1) Yes, I've thought about getting rid of the `Starter` class but kept it around for future if I do care about the results it generates. (2) I suppose I can track number of complete via a series of `isDone()` call. (3), (4), and (5) are good points. (6) Just pseudocode but I'll pay attention to that when I include code in the future."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T18:07:23.837",
"Id": "41114",
"Score": "0",
"body": "If you really must use more than 10 threads, you can replace `worker.execute()` by `service.execute(worker)`. But I'm not sure how you think you know you need more without actually measuring performance. (I hope you don't think that it is the maximum number of tasks)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T18:14:43.953",
"Id": "41115",
"Score": "0",
"body": "BTW : [*Premature optimization is the root of all evil.*](http://en.wikipedia.org/wiki/Program_optimization#When_to_optimize)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T18:18:01.247",
"Id": "41116",
"Score": "0",
"body": "In testing, I personally have 13 tasks. I have no idea what the average tasks size is going to be but I do not want to share the thread pool with `SwingWorker` nor do I want to create too many tasks at once hence why I have a fixed sized of threads that I'm using outside of `SwingWorker`. Some tasks returns in under a second and some takes more than 40 seconds to finish - it's unfortunately something that I can't control. Of course it's not the maximum number of tasks - it's the maximum number of concurrent tasks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T04:58:53.540",
"Id": "41135",
"Score": "0",
"body": "You may want to avoid sharing the pool (who else will submit tasks to it?) but you cannot avoid sharing memory and CPUs. In the end the overhead of your extra threads may harm performance rather than help it. That's why you should measure. That's really all I'm saying : measure before optimizing (and after, so you know it helped :) )."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T05:15:17.887",
"Id": "41137",
"Score": "0",
"body": "Well, my code is just a small part in the system - I have no control of what others do with `SwingWorker` but as far as my tasks goes, there's only me. It's hard to find the setup to measure since this is primarily dependent on the number of printers installed so I've been been going by rough estimates of my own results."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T06:28:40.893",
"Id": "26510",
"ParentId": "26484",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T18:12:06.343",
"Id": "26484",
"Score": "2",
"Tags": [
"java",
"concurrency"
],
"Title": "Performing tasks concurrently"
}
|
26484
|
<p>I have written a caching wrapper class for ConcurrentDictionary. Basically it has a timer that checks if items are expired and removes them. Since ConcurrentDictionary does not have RemoveAll method that takes a predicate as a parameter, it has to decide which ones are expired first, then remove them. The problem is an item can be unexpired (it may have sliding expiration and it is accessed) before it is removed. I have to do something to make sure my code is correct.</p>
<p>Here's the current implementation:</p>
<pre><code>private void CheckExpiredItems(object sender, ElapsedEventArgs e)
{
_timer.Stop();
IEnumerable<TKey> expiredItemKeys = _cachedItems.Where(item => item.Value.IsExpired)
.Select(item => item.Key)
.ToList();
foreach (TKey expiredItemKey in expiredItemKeys)
{
ICacheItem<TValue> expiredItem;
if (_cachedItems.TryRemove(expiredItemKey, out expiredItem))
{
if (expiredItem.IsExpired)
{
expiredItem.Expire();
}
else
{
_cachedItems.TryAdd(expiredItemKey, expiredItem);
}
}
}
_timer.Start();
}
</code></pre>
<p>It removes the expired items one by one while checking they are still expired. If it is not expired, it is added back only if there isn't a new item with the same key. However I'm still not sure if this code is correct. I would appreciate a few suggestions. If you want to take a look at the rest, it is on <a href="https://github.com/uhaciogullari/MemoryCacheT" rel="noreferrer">GitHub</a>.</p>
|
[] |
[
{
"body": "<p>First of all I'd suggest to remove <em>expired</em> business-logic from UI <code>event handler</code> (looks like <code>CheckExpiredItems</code> method belongs to some UI class). </p>\n\n<p>If you are focusing on some concurrent logic you can create your own collection class, having inner member of <code>ConcurrentDictionary</code> type. Then you can explicitly implement <code>RemoveExpiredItems</code> method and create <strong>unit-tests</strong> or even <strong>integration</strong> tests, covering the desired functionality (for example you can emulate mult-threaded environment and check if your collection removes only expired items and correctly restores unexpired ones).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T07:38:24.533",
"Id": "26513",
"ParentId": "26488",
"Score": "1"
}
},
{
"body": "<p>I know it's not a direct answer to your question, but I'm trying to get to the roots of the problem rather than giving correct answer to issue caused by potential misuse...</p>\n\n<p>In your code what you are actually trying to do is to write a cache with time-based expiration of items. Even though <code>ConcurrentDictionary</code> is thread-safe, it's not quite appropriate structure for frequent element scans like you do. Moreover, in your code you remove items, then add them back in case when they have been updated in the middle. It causes side effects for other threads that may try to read the value in-between.</p>\n\n<p>Correct solution would be to use a proper data structure. If by any chance you are using .NET 4.0 or later .NET has already provided you with proper solution - <a href=\"http://msdn.microsoft.com/en-us/library/system.runtime.caching.memorycache.aspx\" rel=\"noreferrer\"><code>MemoryCache</code> class</a>, otherwise I would recommend creating a lock-based class that maintains 2 indexes for entries - a <code>Dictionary</code> for storing key-value pairs, and a <code>SortedList</code> for storing expiration timestamp-key mapping. In this case you'll always know upfront when the next expiration will happen so timer can be set to specific <code>TimeSpan</code>, and you don't have to scan through all cache entries to find expired ones.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-31T14:05:02.040",
"Id": "386397",
"Score": "0",
"body": "At current time, you not need create separate key expiration storage, because ConcurrentDictionary enumerator is safe to use concurrently with reads and writes to the dictionary."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-22T16:09:51.500",
"Id": "389675",
"Score": "0",
"body": "There is a small problem in maintaining one indexing with timestamp-key mapping with SortedList. There is a high probability that 2 or more items can get added at the same time-fraction & it would end up in only adding 1 and skipping the others (as sorted list will not allow duplicate key)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-22T20:27:56.340",
"Id": "389676",
"Score": "0",
"body": "In the comment marked as Answer \"recommended maintaining 2 indexes for entries - a Dictionary for storing key-value pairs, and a SortedList for storing expiration timestamp-key mapping. SortedList<DateTime, ActualKey>\"\n\nIf 2 Items are added at the same time with the exact milliseconds, then only one Time would get added to the TimeStamp sorted list. How can this be solved?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-23T17:08:27.937",
"Id": "389850",
"Score": "0",
"body": "As I mentioned in the response, you should use locks to avoid concurrent modifications. The behaviour of the SortedList during concurrent modifications is not defined (https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.sortedlist-2?view=netframework-4.7.2#thread-safety). But my solution with 2 indexes is only relevant if you're on .NET 3.5 or earlier, which I hope is not the case."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-24T19:04:52.753",
"Id": "390094",
"Score": "0",
"body": "@almaz, below is how my add method looks like. \"timeKeyCollection\" is the SortedList. In the main program when I try to add elements in an for-loop (1000 items), it throws an exception saying that an Element with the same Key already exists. public void Add(T1 key, T2 value) { this.collection.TryAdd(key, value); lock (syncRoot) { timeKeyCollection.Add(DateTime.Now, key); } } To avoid this, I added a sleep interval to avoid this exception. Now when I simulate insertion of 1000 numbers it take more time & the increase is also quite significant & not acceptable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-25T20:39:15.940",
"Id": "390194",
"Score": "0",
"body": "It is not clear what are you trying to achieve here. Why do you use `ConcurentDictionary` if the next statement uses locks? Why do you add DateTime.Now instead of the time the value should expire?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-25T20:43:38.160",
"Id": "390195",
"Score": "0",
"body": "Just to answer your question about `ArgumentException`: `SortedList` doesn’t accept duplicate keys, so in order to track multiple items scheduled to expire at the same time you need to store all of them under a single key in `SortedList`. The most appropriate way to do that is via linked list"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T09:39:29.363",
"Id": "26521",
"ParentId": "26488",
"Score": "8"
}
},
{
"body": "<p>I just had to do something similar today. Take a look at <a href=\"http://blogs.msdn.com/b/pfxteam/archive/2011/04/02/10149222.aspx\" rel=\"nofollow\">this</a>.</p>\n\n<p>If your <code>ICacheItem<TValue></code> can have value semantics then you can just use the approach above to do something similar to this:</p>\n\n<pre><code>foreach (var p in collection)\n{\n if (p.Value.Expired())\n {\n if (!collection.TryRemove(p))\n {\n log.Debug(\"Did not remove item because it was changed.\");\n }\n }\n}\n</code></pre>\n\n<p>Indeed in my tests the log message was printed from time to time. Note that the value semantics are important. I overrode Equals for my class.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-10-23T21:55:43.160",
"Id": "108559",
"ParentId": "26488",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "26521",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T19:06:32.367",
"Id": "26488",
"Score": "8",
"Tags": [
"c#",
".net",
"multithreading",
"thread-safety"
],
"Title": "Correct way to delete elements from a ConcurrentDictionary with a predicate"
}
|
26488
|
<p>I'm new to Android. I was wondering if anyone had any suggestions. It's basically an <code>AsyncTask</code> to get a remote JSON array and put it into a native array.</p>
<p>Would be very grateful for suggestions.</p>
<pre><code>package com.example.test2;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Arrays;
import java.util.Hashtable;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends Activity {
private String strCategoryJsonUrl = "http://www.mydomain.com/categories.json";
getCategories myCategories;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myCategories = new getCategories();
myCategories.execute();
}//onCreate
private class getCategories extends AsyncTask<Integer, Integer, String>{
@Override
protected String doInBackground(Integer... intMyGuessLevel) {
String strJson = "";
try {
URL url = new URL(strCategoryJsonUrl);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
strJson = readStream(con.getInputStream());
} catch (Exception e) {
e.printStackTrace();
}
return strJson;
} //doInBackground
private String readStream(InputStream in) {
BufferedReader reader = null;
String strContent = "";
try {
reader = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = reader.readLine()) != null) {
strContent = strContent + line;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} //finally
return strContent;
} //readStream
protected void onPostExecute(String strResult) {
int i = 0;
String strValue = "";
TextView txtDebug = (TextView) findViewById(R.id.txtdebug);
String arrCategories[] = new String[1];
//parse JSON data
try{
JSONArray jArray = new JSONArray(strResult);
//JSONObject menu = jObject.getJSONObject("menu");
arrCategories = new String[jArray.length()];
for(i=0; i < jArray.length(); i++) {
JSONObject jObject = new JSONObject(jArray.get(i).toString());
strValue = jObject.getString("name");
//put value into array
arrCategories[i] = strValue;
}
//debug output the array
txtDebug.setText(Arrays.toString(arrCategories));
} catch (JSONException e) {
e.printStackTrace();
txtDebug.append("Error in categories json file \n");
txtDebug.append(String.valueOf(e));
} // catch
} //onPostExecute
} //getJsonContent
}
</code></pre>
|
[] |
[
{
"body": "<p>Don't open a resource in one place and close it in another. Keep the opening and closing of a resource localized to the same function (if you open it, you close it). This makes it easier to spot potential resource leaks.</p>\n\n<p>For example, an <code>InputStream</code> is being opened in <code>doInBackground()</code>, but it is being closed in <code>readStream()</code>. Since <code>doInBackground()</code> opened the resource, it should be responsible for closing it.</p>\n\n<hr>\n\n<pre><code>HttpURLConnection con = (HttpURLConnection)url.openConnection();\n</code></pre>\n\n<p>You are not using anything specific to <code>HttpURLConnection</code>, so there is no reason to cast it. This works just fine:</p>\n\n<pre><code>URLConnection con = url.openConnection();\n</code></pre>\n\n<hr>\n\n<pre><code>try {\n ...\n} catch (Exception e) {\n e.printStackTrace();\n}\n</code></pre>\n\n<p>Don't ignore exceptions. Either let them continue up to the caller, or handle them appropriately. The <code>readStream()</code> function is a good example of where the exception should continue to the caller. Declare it as throwing <code>IOException</code> and remove the exception handling:</p>\n\n<pre><code>private String readStream(InputStream in) throws IOException {\n String content = \"\";\n BufferedReader reader = new BufferedReader(new InputStreamReader(in));\n String line = null;\n while ((line = reader.readLine()) != null) {\n content += line;\n }\n return content;\n}\n</code></pre>\n\n<hr>\n\n<pre><code>JSONObject jObject = new JSONObject(jArray.get(i).toString());\n</code></pre>\n\n<p>This can be simplified to this:</p>\n\n<pre><code>JSONObject jObject = jArray.getJSONObject(i);\n</code></pre>\n\n<hr>\n\n<p>Declare variables closer to there they are used. For example, in <code>onPostExecute()</code>: <code>i</code>, <code>strValue</code> and <code>arrCategories</code> are all declared at the top of the function, but are only ever used inside the <code>try</code> block.</p>\n\n<pre><code>protected void onPostExecute(String strResult) {\n TextView txtDebug = (TextView)findViewById(R.id.txtdebug);\n try {\n JSONArray jArray = new JSONArray(strResult);\n String[] arrCategories = new String[jArray.length()];\n for (int i = 0; i < jArray.length(); i++) {\n JSONObject jObject = jArray.getJSONObject(i);\n arrCategories[i] = jObject.getString(\"name\");\n }\n txtDebug.setText(Arrays.toString(arrCategories));\n } catch (JSONException e) {\n e.printStackTrace();\n txtDebug.append(\"Error in categories json file \\n\");\n txtDebug.append(String.valueOf(e));\n }\n}\n</code></pre>\n\n<hr>\n\n<p>I would also like to see <code>onPostExecute()</code> broken down further. It is currently doing two things: parsing the JSON array and updating the UI. Move those into their own functions.</p>\n\n<hr>\n\n<p>I am not a big fan of the comments in this code. I do not believe they add any value, and are only a distraction while reading.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T15:59:57.177",
"Id": "26576",
"ParentId": "26489",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "26576",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T19:17:46.643",
"Id": "26489",
"Score": "4",
"Tags": [
"java",
"android"
],
"Title": "JSON AsyncTask refactoring to improve quality?"
}
|
26489
|
<blockquote>
<p>A generic <em>blocking queue</em> has the following properties:</p>
<ol>
<li>It is thread-safe.</li>
<li>It allows queuing and de-queuing of items of a certain type (T).</li>
<li>If a de-queue operation is performed and the queue is empty, the de-queuing thread waits indefinitely for an item to be queued and then
retrieves it (i.e. a de-queue operation cannot fail or return no
item).</li>
</ol>
</blockquote>
<p>Assuming we want to implement a client application that simulates the operation of such a queue.</p>
<p><img src="https://i.stack.imgur.com/vnEUf.jpg" alt="enter image description here"></p>
<p>The application allows the user to do the following:</p>
<ol>
<li><p><strong>Start a number of de-queuing worker threads by doing the following</strong>:</p>
<p>a. Specify the number of worker threads (w).</p>
<p>b. Press the "Start" button.</p>
<p>By pressing the "Start" button, w worker threads are created and start de-queuing and executing the tasks in the queue. Completed tasks display their results in the results list.
Each result shows the executing worker thread id and the result itself.</p></li>
<li><p><strong>Queue tasks by doing the following</strong>:</p>
<p>a. Choose a task type.</p>
<p>b. Initialize its parameters.</p>
<p>c. Specify the number of queuing threads (n) and the number queued tasks (t) for each thread.</p>
<p>d. Press the "Queue" button.</p>
<p>The user can queue 3 types of tasks (of course, many more tasks could be created) :</p>
<ul>
<li><p>A task that receives 2 integers as inputs, <strong><em>adds</em></strong> them and returns the result.</p></li>
<li><p>A task that receives 2 strings as inputs, <strong><em>concatenates</em></strong> them and returns the result.</p></li>
<li><p>A task that receives a string as an input and returns whether the <strong><em>string is a palindrome</em></strong>.</p></li>
</ul>
<p>Upon pressing the button, n threads are created, each creates t instances of the task and queues them all.</p></li>
</ol>
<blockquote>
<p>Some useful guidelines:</p>
<ol>
<li>Design the UI in WinForms or WPF, or whatever technology you're comfortable with.</li>
<li>Separate the different application layers (BL, UI, etc.)</li>
<li>Write code that allows easy addition of other task types to the system with minimal change to existing code.</li>
</ol>
</blockquote>
<p>The question is a request for code-review on the design of the classes, interfaces
and logic of the queue. The GUI design-part is not related to the question and not concerned, but is supplied as part of the code base, which contains about 800 lines of code and could <a href="https://github.com/rycle/BlockingTaskQueue" rel="nofollow noreferrer">be found here</a>.</p>
<p>I've chosen to use WinForms, since I'm not very familiar with other ways to design UI.</p>
<p><strong>Yet, the GUI is not the real question here, and it's absolutely off the topic for review.</strong></p>
<p>My idea was to divide the project into a few building blocks:</p>
<p><strong><em>Contracts assembly</em></strong>: general interfaces defining tasks and its parameters and events.</p>
<blockquote>
<p>ITask.cs</p>
</blockquote>
<pre><code>namespace Contracts
{
public class SingleOperandInput
{
public Object Operand;
}
public class TwoOperandsInput
{
public Object Operand1;
public Object Operand2;
}
public interface ITask
{
ResultBase ResultAction { get; set; }
void Run();
}
}
</code></pre>
<blockquote>
<p>IResult.cs</p>
</blockquote>
<pre><code>namespace Contracts
{
public interface IResult
{
void NotifyResult(Object result);
}
}
</code></pre>
<blockquote>
<p>ResultBase.cs</p>
</blockquote>
<pre><code>namespace Contracts
{
public abstract class ResultBase : IResult
{
// A delegate type for hooking up change notifications.
public delegate void ResultEventHandler(object sender, GeneralTaskEventArgs e);
// An event that clients can use to be notified whenever
// there's a result.
public event ResultEventHandler Changed;
public abstract void NotifyResult(object result);
// Invoke the Changed event
protected virtual void OnChanged(GeneralTaskEventArgs e)
{
if (Changed != null)
{
Changed(this, e);
}
}
}
}
</code></pre>
<blockquote>
<p>GeneralTaskEventArgs.cs</p>
</blockquote>
<pre><code>namespace Contracts
{
public abstract class GeneralTaskEventArgs : EventArgs
{
public Int32 SourceThreadId;
public Object Operand1;
public Object Operand2;
}
}
</code></pre>
<p><strong><em>Tasks assembly</em></strong>: concrete task implementations.</p>
<p>Here's just one example, since all other implementations have the same look:</p>
<blockquote>
<p>AddIntegers.cs</p>
</blockquote>
<pre><code>namespace Tasks
{
public class AddIntegers : ITask
{
public ResultBase ResultAction { get; set; }
private TwoOperandsInput _input;
public AddIntegers(Object op1, Object op2, Object resultAction)
{
ResultAction = resultAction as ResultBase;
_input = new TwoOperandsInput() { Operand1 = op1, Operand2 = op2 };
}
public void Run()
{
Int32 sum = Int32.Parse(_input.Operand1 as String) + Int32.Parse(_input.Operand2 as String);
ResultAction.NotifyResult(sum);
}
}
}
</code></pre>
<p><strong><em>Callbacks assembly</em></strong> - concrete task's callback implementations.</p>
<p>Meaning, what to do when a task finishes. A mapping between concrete tasks to concrete could be done in run-time, so they aren't coupled to the tasks assembly in any way!</p>
<blockquote>
<p>AddIntegersResult.cs</p>
</blockquote>
<pre><code>namespace Callbacks
{
public class AddIntegersEventArgs : GeneralTaskEventArgs
{
public readonly Int32 Result;
public AddIntegersEventArgs(Int32 sourceThreadId, Int32 result)
{
SourceThreadId = sourceThreadId;
Result = result;
}
public override string ToString()
{
return String.Format("Sum is {0}", Result);
}
}
public class AddIntegersResult : ResultBase
{
public override void NotifyResult(object result)
{
AddIntegersEventArgs args = new AddIntegersEventArgs(Int32.Parse(Thread.CurrentThread.Name), (Int32)result);
OnChanged(args);
}
}
}
</code></pre>
<p><strong><em>Blocking queue assembly</em></strong> - implements the task blocking queue.</p>
<blockquote>
<p>TaskQueue.cs</p>
</blockquote>
<pre><code>namespace BlockingTaskQueue
{
public static class TaskQueue
{
private static Int32 _threadCount = 0;
private static ConcurrentQueue<ITask> _queue = new ConcurrentQueue<ITask>();
private static List<Thread> _dequeueThreads = new List<Thread>(100);
public static void Enqueue(ITask task)
{
if (task == null)
{
throw new ArgumentNullException("task is null.");
}
_queue.Enqueue(task);
}
public static void Dequeue(Int32 workers)
{
for (Int32 i = 0; i < workers; i++)
{
Thread worker = new Thread(new ThreadStart(DequeueThreadFunc));
// Worker threads will not keep an application running after all foreground threads have exited.
worker.IsBackground = true;
worker.Name = Interlocked.Increment(ref _threadCount).ToString();
_dequeueThreads.Add(worker);
worker.Start();
}
}
public static void DequeueThreadFunc()
{
ITask task;
while (true)
{
if (_queue.IsEmpty)
{ // Wait indefinitely until there is something to de-queue.
Thread.Sleep(100);
}
else if (_queue.TryDequeue(out task))
{
task.Run();
}
}
}
}
}
</code></pre>
<p><strong><em>GUI assembly</em></strong> - The designer code to create the form isn't included.</p>
<blockquote>
<p>SimulatorForm.cs</p>
</blockquote>
<pre><code>namespace BlockingTaskQueue
{
public partial class MainForm : Form
{
public delegate void NewResultDelegate(GeneralTaskEventArgs args);
public NewResultDelegate _resultDelegate;
// Maps task descriptions to their concrete class from the tasks assembly.
private Dictionary<String, TaskObject> _taskDescriptionToObject;
private Dictionary<GeneralTaskEventArgs, String> _concreteEventArgsToTaskDescription;
//// TODO: extend to many assemblies in the configuration.
private Assembly _tasksAssembly;
private Assembly _callbacksAssembly;
public MainForm()
{
InitializeComponent();
_tasksAssembly = Assembly.LoadFrom(ConfigurationManager.AppSettings["TasksAssembly"]);
_callbacksAssembly = Assembly.LoadFrom(ConfigurationManager.AppSettings["CallbacksAssembly"]);
// TODO: implement a prefix for each task description, don't use Count!
_taskDescriptionToObject = new Dictionary<string, TaskObject>(ConfigurationManager.AppSettings.Count);
_concreteEventArgsToTaskDescription = new Dictionary<Type, string>(ConfigurationManager.AppSettings.Count);
foreach (var key in ConfigurationManager.AppSettings.AllKeys)
{
if (key != "TasksAssembly" && key != "CallbacksAssembly")
{
String[] concreteTypeNamesAndOperandsRequired = ConfigurationManager.AppSettings[key].Split(',');
Type taskConcreteType = _tasksAssembly.GetType(concreteTypeNamesAndOperandsRequired[0]);
Type taskCallbackType = _callbacksAssembly.GetType(concreteTypeNamesAndOperandsRequired[1]);
Type taskConcreteEventArgsType = _callbacksAssembly.GetType(concreteTypeNamesAndOperandsRequired[2]);
_taskDescriptionToObject.Add(key, new TaskObject(taskConcreteType, taskCallbackType, Int32.Parse(concreteTypeNamesAndOperandsRequired[3]),
"true" == concreteTypeNamesAndOperandsRequired[4]));
_concreteEventArgsToTaskDescription.Add(taskConcreteEventArgsType, key);
tasksComboBox.Items.Add(key);
}
}
_resultDelegate = new NewResultDelegate(AddResultToList);
}
private void startDequeueButton_Click(object sender, EventArgs e)
{
Int32 dequeueThreads;
// Sanity checks.
if (!Int32.TryParse(dequeueThreadsTextBox.Text, out dequeueThreads))
{
throw new ArgumentException("Expected a number as number of de-queuing worker threads.");
}
if (dequeueThreads < 1)
{
throw new ArgumentException("Expected at least 1 de-queuing worker threads.");
}
BlockingTaskQueue.TaskQueue.Dequeue(dequeueThreads);
}
private void queueButton_Click(object sender, EventArgs e)
{
Int32 queueingThreads;
Int32 tasksPerThread;
// Sanity checks.
if (!Int32.TryParse(queueThreadsTextBox.Text, out queueingThreads))
{
throw new ArgumentException("Expected a number as number of queuing worker threads.");
}
if (queueingThreads < 1)
{
throw new ArgumentException("Expected at least 1 queuing worker threads.");
}
if (!Int32.TryParse(tasksPerThreadTextBox.Text, out tasksPerThread))
{
throw new ArgumentException("Expected a number as the number of tasks each queuing thread will enqueue.");
}
if (tasksPerThread < 1)
{
throw new ArgumentException("Expected at least 1 tasks to be enqueued by each thread.");
}
// Create instances of the task and the result-action.
Object taskInstance = null;
Object resultInstance = null;
TaskObject taskObj = _taskDescriptionToObject[tasksComboBox.Text];
// Instantiate the concrete result class
if (!taskObj.RequiresInput)
{
resultInstance = Activator.CreateInstance(taskObj.ConcreteActionAndResult.Value);
}
if (taskObj.OperandsRequired == 1)
{
if (taskObj.RequiresInput)
{
SingleOperandInput soi = new SingleOperandInput() { Operand = operand1TextBox.Text };
resultInstance = Activator.CreateInstance(taskObj.ConcreteActionAndResult.Value, new Object[] { soi });
}
taskInstance = Activator.CreateInstance(taskObj.ConcreteActionAndResult.Key, new Object[] { operand1TextBox.Text, resultInstance });
}
else if (taskObj.OperandsRequired == 2)
{
if (taskObj.RequiresInput)
{
TwoOperandsInput toi = new TwoOperandsInput() { Operand1 = operand1TextBox.Text, Operand2 = operand2TextBox.Text };
resultInstance = Activator.CreateInstance(taskObj.ConcreteActionAndResult.Value, new Object[] { operand1TextBox.Text, operand2TextBox.Text });
}
taskInstance = Activator.CreateInstance(taskObj.ConcreteActionAndResult.Key, new Object[] { operand1TextBox.Text, operand2TextBox.Text, resultInstance });
}
else
{
throw new NotImplementedException("Not supporting more than 2 operands.");
}
((ITask)taskInstance).ResultAction.Changed += NewResult;
// Enqueue the task the amount of times specified, using the amount of threads specified.
EnqueueConcurrent(queueingThreads, tasksPerThread, taskInstance);
}
private void NewResult(object state, GeneralTaskEventArgs args)
{
if (InvokeRequired)
{
Invoke(_resultDelegate, new object[] { args });
}
else
{
_resultDelegate(args);
}
}
private void AddResultToList(GeneralTaskEventArgs args)
{
outputListBox.Items.Add(String.Format("{0} Result (Worker thread #{1})", _concreteEventArgsToTaskDescription[args.GetType()], args.SourceThreadId));
outputListBox.Items.Add(args.ToString());
}
private void EnqueueConcurrent(Int32 queueingThreads, Int32 tasksPerThread, Object task)
{
for (Int32 i = 0; i < queueingThreads; i++)
{
Thread queueingThread = new Thread(new ParameterizedThreadStart(EnqueueTasksThreadFunc));
EnqueingObject enqueueObj = new EnqueingObject() { Task = task, TasksToEnqueue = tasksPerThread };
queueingThread.Start(enqueueObj);
}
}
public static void EnqueueTasksThreadFunc(Object state)
{
EnqueingObject enqueueObj = state as EnqueingObject;
if (enqueueObj == null)
{
throw new ArgumentNullException();
}
for (Int32 i = 0; i < enqueueObj.TasksToEnqueue; i++)
{
// If this isn't a real ITask, a run-time exception will be thrown.
BlockingTaskQueue.TaskQueue.Enqueue((ITask)enqueueObj.Task);
}
}
private void tasksComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
Int32 operandsRequired = _taskDescriptionToObject[tasksComboBox.Text].OperandsRequired;
if (operandsRequired == 1)
{
if (operand2Label.Visible)
{
operand2Label.Visible = false;
operand2TextBox.Visible = false;
}
}
else if (operandsRequired == 2)
{
if (!operand2Label.Visible)
{
operand2Label.Visible = true;
operand2TextBox.Visible = true;
}
}
}
}
}
</code></pre>
<p>The complete working code base could be found in <a href="https://i.stack.imgur.com/vnEUf.jpg" rel="nofollow noreferrer">my implementation's github repository</a>.</p>
<p>Consumers of the contracts assembly may define their own tasks, callbacks and specific events as wished.</p>
<p>The Tasks assembly contains concrete task's implementation,</p>
<p>whilst the Callbacks assembly contain concrete callback's implementations,</p>
<p>but one concrete task isn't coupled to another concrete callback.</p>
<p>That is to say, <strong>during run time</strong>, whoever decides to map between a Task implementation and a Callback implementation, may choose a different mapping in the configuration.</p>
<p>All the consumer has to do in order to provide tasks with callback ability using a blocking queue is to bring a compiled Tasks assembly and Callbacks assembly, and provide their assembly file paths/assembly-signature in the configuration. </p>
<p>This is what I did in the <em>SimulatorView</em> form.</p>
<p>So the GUI's configuration,</p>
<blockquote>
<p>App.config</p>
</blockquote>
<pre><code><configuration>
<appSettings>
<add key="TasksAssembly" value="C:\Code\BlockingTaskQueue\TasksImplementation\bin\Debug\Tasks.dll"/>
<add key="CallbacksAssembly" value="C:\Code\BlockingTaskQueue\Callbacks\bin\Debug\Callbacks.dll"/>
<!-- key: defines the description of the task.
value: constructed as TASK_CLASS_NAME, CALLBACK_CLASS_NAME, EVENTARGS_CLASS_NAME, NUM_OPERANDS, REQUIRES_INPUT_BOOLEAN -->
<add key="Add Numbers" value="Tasks.AddIntegers,Callbacks.AddIntegersResult,Callbacks.AddIntegersEventArgs,2,false"/>
<add key="Concatenate Strings" value="Tasks.ConcatenateStrings,Callbacks.ConcatenateStringsResult,Callbacks.ConcatenateStringsEventArgs,2,false"/>
<add key="Is Palindrome" value="Tasks.PalindromChecker,Callbacks.PalindromCheckerResult,Callbacks.PalindromCheckerEventArgs,1,true"/>
</appSettings>
</configuration>
</code></pre>
<p>Which simply means that the both assemblies (Tasks, Callbacks) will be loaded</p>
<p>during run time and a mapping will be created such that "Add Numbers" operation</p>
<p>will activate a Tasks.AddIntegers task, that will end up calling a Callbacks.AddIntegersResult callback and use a Callbacks.AddIntegersEventArgs to supply data about the result.</p>
<p>Whoever subscribes on this event may use it's overriden ToString method to get the actual result from the whole operation.</p>
<p>I've chosen to use reflection in my implementation, although many IoC implementations such as </p>
<ul>
<li>Spring.NET</li>
<li>Castle Windsor</li>
<li>StructureMap</li>
<li>Autofac</li>
<li>Unity</li>
<li>Ninject</li>
</ul>
<p>(the list is actually pretty partial, <a href="https://stackoverflow.com/questions/1140730/net-di-containers-comparison">look there to elaborate</a>)</p>
<p>could probably save a programmer some time get going with reflection...</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T23:11:32.233",
"Id": "41050",
"Score": "0",
"body": "It looks like your question is “How would you do this?” That's not what this site is for, so your question is off-topic here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T08:19:49.020",
"Id": "41071",
"Score": "0",
"body": "No, my question isn't \"How would you do this?\".\nSince I've provided my code in my answer,\n\n\nhttps://github.com/rycle/BlockingTaskQueue"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T08:31:00.080",
"Id": "41074",
"Score": "0",
"body": "Its a pure codereview question, its just that it takes some 15 different source files to be pasted here, so I put my implementation in a link to be reviewed, but of course if you wish to think of other ways to accomplish this, then you should, but please, share as another answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T11:29:48.187",
"Id": "41083",
"Score": "0",
"body": "That's not how this works. If you want some code reviewed, you need to include the code in your question. And a link isn't enough, you need to actually include your code there. If you have too much code to put it there, then it's too much code to review."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T11:55:19.310",
"Id": "41085",
"Score": "0",
"body": "Is there a policy on how long it should be?\n\nWhoever understands and looks at this project could know that its the dividing of projects and logic that matters, rather than \"how to implement a palindrome checking method\",\nWhich I respect, of course there are code review questions about single methods checking.\n\nBut I think that a code reviewing site should be able to allow a slightly-bigger projects, that might contain even GUI. Of course, as users you may ignore/discourage/hate and move on, but as admins of this community, you're explicitly saying that you disallow that. How rude of you!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T12:03:54.673",
"Id": "41086",
"Score": "0",
"body": "There are some related questions about this [on meta](http://meta.codereview.stackexchange.com/), for example [Is it appropriate to post 1k+ lines of code?](http://meta.codereview.stackexchange.com/q/706/2041) or [How to get feedback on whole projects](http://meta.codereview.stackexchange.com/q/704/2041)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T14:34:08.600",
"Id": "41171",
"Score": "0",
"body": "After reading both the http://meta.codereview.stackexchange.com/questions/706/is-it-appropriate-to-post-1k-lines-of-code\narticle and http://codereview.stackexchange.com/faq#im-confused-what-questions-are-on-topic-for-this-site\n\nI've successfully answered \"Yes\" to 5 out of 6 of the rules above. The single foul was (1.). Instead of publishing portions of the code, I've included a link to it.\nThe entire code is not above 800 lines, including the designer's auto generated code.\n\nTo comply with the site's policy, I'll include integral parts of the code here,"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T14:36:38.270",
"Id": "41172",
"Score": "0",
"body": "And of course I'll leave the designer's auto generated code outside. \n\nTo my understanding, once the integral part of the code is published, a link to the project is legitimate.\nSo that whoever wants to wonder around the code or run it locally could also do this."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T15:29:58.160",
"Id": "41178",
"Score": "0",
"body": "You need to include the code in your *question*, not the answer. Answers are for the suggestions you're going to get, not for your code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T16:09:01.643",
"Id": "41179",
"Score": "0",
"body": "I've updated the question:\n\nIt now contains the integral part of the code, and it is a \"Yes-to-all-6-rules\" in http://codereview.stackexchange.com/faq#im-confused-what-questions-are-on-topic-for-this-site\n\nWould you please re-open it?\nThank you!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-26T19:53:56.663",
"Id": "41286",
"Score": "0",
"body": "Jeff Vanzella, svick, Winston Ewert\nCan anyone reopen this post?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-26T22:01:10.207",
"Id": "41296",
"Score": "0",
"body": "Me and two other people have already voted to reopen. Hopefully, it's now just a matter of time."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-18T14:41:29.097",
"Id": "425971",
"Score": "0",
"body": "@rycle The Thread.Sleep(..) should be rewritten into a ManualResetEvent.WaitOne(). It is also interesting to see how the Java platform implemented their blocking queue. https://github.com/openjdk-mirror/jdk7u-jdk/blob/master/src/share/classes/java/util/concurrent/ArrayBlockingQueue.java"
}
] |
[
{
"body": "<blockquote>\n <p><strong>This is a 10-in-1 question.</strong> This answer is taking a quick look at <code>SimulatorForm.cs</code>.</p>\n</blockquote>\n\n<p>What you mention at the end of your [epic] post, that you've chosen <em>reflection</em> but that you could have used an enumeration of IoC containers instead, leaves me perplexed.</p>\n\n<p><em>Inversion of Control</em> implies <strong>letting go of control</strong>. Your <code>MainForm</code> has an empty constructor that loads assemblies, fetches static configurations and populates a combobox. I think that's a lot to do for a constructor. I don't think usage of reflection is warranted here, at all. In fact I find it just obfuscates the intent. Go ahead, <em>inject your dependencies</em>! Your usage of reflection isn't too far off from some all-powerful <em>Service Locator</em> that can instantiate just about anything.</p>\n\n<p>Also maybe it's because I'm getting quite fond of <em>commands</em>, but I find you have a lot going on in those event handlers, beyond what would be the job of a <em>presentation layer</em> - i.e. deal with <em>presentation</em> concerns, delegating the <em>actual work</em> elsewhere. As a result, your code-behind feels bloated with mixed concerns:</p>\n\n<ul>\n<li><code>tasksComboBox_SelectedIndexChanged</code> is purely presentation stuff. That's good.</li>\n<li><code>EnqueueTasksThreadFunc</code> clearly belongs somewhere else, and it being <code>public</code> and <code>static</code> is kind of scary.</li>\n<li><code>EnqueueConcurrent</code> probably belongs in the same type as <code>EnqueueTasksThreadFunc</code>.</li>\n<li><code>queueButton_Click</code> and <code>startDequeueButton_Click</code> actually implement your \"business logic\".</li>\n</ul>\n\n<p>I realize event handlers are named after the objects that they handle events for, but still I would rename them so as to keep a consistent <em>PascalCasing</em> for all methods. The <code>objectName_EventName</code> convention feels like VB6 - you're free to name you handlers as you like them, e.g. \"OnQueueButtonClick\"</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T19:38:44.153",
"Id": "59135",
"Score": "0",
"body": "definitely a **10-IN-1** question"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T01:55:43.463",
"Id": "36095",
"ParentId": "26497",
"Score": "2"
}
},
{
"body": "<blockquote>\n <p>About <code>TaskQueue.cs</code></p>\n</blockquote>\n\n<p>I'm not a big multithreading guru (actually not a guru at anything), so <em>maybe</em> it's playing a part here, but I don't get <strong>why</strong> this class has to be <code>static</code>, along with all of its members.</p>\n\n<p>I think I would have tackled this class as a non-static class derived from <code>ConcurrentQueue</code> (which I believe has all the plumbing for thread-safety built-in).</p>\n\n<p>There's something about <code>static</code> classes that just raises a flag in my mind.</p>\n\n<blockquote>\n <p>About <code>AddIntegers.cs</code></p>\n</blockquote>\n\n<p>I find that's a rather bad name for a class, it looks like a method name (starts with a verb) - I <em>know</em> it's a <em>task</em> because I see <code>AddIntegers : ITask</code>, but it seems <code>AddIntegersTask</code> would be a [slightly] better name, especially if you make it a convention to end all classes that implement <code>ITask</code> with the word \"Task\".</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-26T02:28:05.943",
"Id": "36099",
"ParentId": "26497",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "13",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T22:15:16.177",
"Id": "26497",
"Score": "5",
"Tags": [
"c#",
"multithreading",
"winforms",
"generics",
"interface"
],
"Title": "Generic Task Blocking Queue"
}
|
26497
|
<p>I have the following function:</p>
<pre><code>def item_by_index(iterable, index, default=Ellipsis):
"""Return the item of <iterable> with the given index.
Can be used even if <iterable> is not indexable.
If <default> is given, it is returned if the iterator is exhausted before
the given index is reached."""
iterable_slice = itertools.islice(iterable, index, None)
if default is Ellipsis:
return next(iterable_slice)
return next(iterable_slice, default)
</code></pre>
<p>It should (and does) throw an exception if the <code>default</code> is not given and the iterator is exhausted too soon. This is very similar to what the built-in function <a href="http://docs.python.org/2/library/functions.html#next"><code>next</code></a> does.</p>
<p>Usually, one would probably use <code>None</code> as default value to make an argument optional. In this case, however, <code>None</code> is a valid value for <code>default</code> and should be treated differently from no argument. This is why I used <code>Ellipsis</code> as a default value. It sort of feels like an abuse of the <code>Ellipsis</code> object, though.</p>
<p>Is there a better way of doing this or is <code>Ellipsis</code> a good tool for the job? </p>
|
[] |
[
{
"body": "<p>I would argue the best option is to make an explicit sentinel value for this task. The best option in a case like this is a simple <code>object()</code> - it will only compare equal to itself (aka, <code>x == y</code> only when <code>x is y</code>).</p>\n\n<pre><code>NO_DEFAULT = object()\n\ndef item_by_index(iterable, index, default=NO_DEFAULT):\n ...\n</code></pre>\n\n<p>This has some semantic meaning, and means there is no potential overlap between a value a user wants to give and the default (I imagine it's highly unlikely they'd want to use Ellipses, but it's better to make as few assumptions as possible about use cases when writing functions). I'd recommend documenting it as such as well, as it allows the user to give a default/not using a variable, rather than having to change the call.</p>\n\n<pre><code>try:\n default = get_some_value()\nexcept SomeException:\n default = yourmodule.NO_DEFAULT\n\nitem_by_index(some_iterable, index, default)\n</code></pre>\n\n<p>As opposed to having to do:</p>\n\n<pre><code>try:\n default = get_some_value()\nexcept SomeException:\n item_by_index(some_iterable, index)\nelse:\n item_by_index(some_iterable, index, default)\n</code></pre>\n\n<p>The only downside it's not particularly clear what it is if you are looking at the object itself. You could create a custom class with a suitable <code>__repr__()</code>/<code>__str__()</code> and use an instance of it here.</p>\n\n<p>As of Python 3 <a href=\"http://www.python.org/dev/peps/pep-0435/\">enums have been added</a> - the default type of enum only compares equal on identity, so a simple one with only the one value would also be appropriate (and is essentially just an easy way to do the above):</p>\n\n<pre><code>from enum import Enum\nclass Default(Enum):\n no_default = 0\n</code></pre>\n\n<p>Thanks to metaclass magic, <code>Default.no_default</code> is now an instance of a <code>Default</code>, which will only compare equal with itself (not <code>0</code>, by default, enums are pure).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T23:29:20.767",
"Id": "26500",
"ParentId": "26499",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "26500",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T22:56:50.490",
"Id": "26499",
"Score": "6",
"Tags": [
"python"
],
"Title": "Optional argument for which None is a valid value"
}
|
26499
|
<p>I am making a web editor for fun and I was told that the way I was doing it (using PHP) would be a bad way. I also thought about it while I was making it, and in massive sums of data transfer it would be a bad idea to do it this way. I can't think of another way to do it and was looking for someone to help me improve it, by that I mean my save method I am using.</p>
<p><strong>Editor:</strong></p>
<pre class="lang-html prettyprint-override"><code><html>
<head>
<title>Web Editor</title>
<link href="controller.css" rel="stylesheet" />
<script type="text/javascript" src="script/editor.js"></script>
</head>
<body>
<div class="platform">
<div class="head">
<div class="file">
<p>File:
<div id="file">C:\hello.html</div>
</p>
</div>
</div>
<div class="hotbar">
<img src="images/save.png" class="hotbarImage" onClick="save()" />
</div>
<div class="editor">
<div contenteditable="true" style="height:100%; overflow:scroll;" id="editPad"></div>
</div>
</div>
</body>
</html>
</code></pre>
<p><strong>JS:</strong></p>
<pre class="lang-js prettyprint-override"><code>function save() {
var dir = document.getElementById("file").innerHTML;
var data = document.getElementById("editPad").innerHTML;
window.location = "save.php?dir=" + encodeURIComponent(dir) + "&data=" + encodeURIComponent(data);
}
</code></pre>
<p><strong>PHP:</strong></p>
<pre class="lang-php prettyprint-override"><code><?php
$dir = $_GET['dir'];
$data = $_GET['data'];
$lookFor = array("&lt;", "&gt;","<br>","<%2Fdiv>","<div>","</div>");
$replaceWith = array("<", ">", "", "", "","");
$newData = str_replace($lookFor,$replaceWith,$data);
$f = fopen(urldecode($dir),"w");
fwrite($f,urldecode($newData));
fclose($f);
?>
</code></pre>
<p>All of it is just a work in progress and I need more done. But for right now, is there a better way for me to save the file with massive sums of data being transferred?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T06:27:25.373",
"Id": "41067",
"Score": "0",
"body": "How much data do you expect per transfer?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T20:37:26.043",
"Id": "41122",
"Score": "0",
"body": "Up to a MB. That should probably be the largest amount."
}
] |
[
{
"body": "<ul>\n<li><p>I'd prefer a form with a textarea rather than a contenteditable element. Forms and text areas were built for that purpose.</p></li>\n<li><p>As for your save code, <code>GET</code> requests should not do anything on the server. It should only do what it was called to do, and that is to <em>get data</em>. I suggest you do a <code>POST</code> or <code>PUT</code> instead by using a form, or via AJAX.</p></li>\n<li><p>An advantage of AJAX compared to forms is that you won't leave your page. Similar to how you did it, you grab the data and send it to the server.</p></li>\n<li><p>Your editor is risky since it can write to an arbitrary file on the server (or worse, on the system). With this code, I can modify this PHP file itself and make it do all kinds of stuff. I suggest you do some research on how you can restrict where and what you can modify.</p></li>\n<li><p>You need a more robust approach in stripping HTML from the data than doing it manually. PHP has some built-in functions to do that for you, like <code>strip_tags</code>. There could be better solutions that I'm not aware of as well.</p></li>\n<li><p>Massive data? How much data do you expect you put in anyway? I suggest <em>polishing the implementation first</em> before optimizing for other stuff, like data size and so on.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T02:34:07.610",
"Id": "26504",
"ParentId": "26502",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T01:38:40.943",
"Id": "26502",
"Score": "3",
"Tags": [
"javascript",
"php",
"html"
],
"Title": "Transferring large amounts of data in web editor"
}
|
26502
|
<p>I am actually quite new to C++, although I have previously programmed in Java. Do you see any ways I can improve readability, maintainability and performance, and make it more object-oriented?</p>
<pre><code>/*
Control + 0 = enable aimbot
*/
#include "stdafx.h"
#include <math.h>
const float pi = 3.14159265358979f;
/*
* I am using int* as if it were the same thing as int**, int***, etc.
* Another more elegant looking method is to use int as if it were int*, int**, etc
* but it is more prone to undefined behaviour and I am more likely to get away with the first method.
* See: http://stackoverflow.com/questions/16256158/dereferencing-a-double-level-pointer-results-in-different-behaviour-from-derefer
*/
int* getClosestPointer(int** basePointer, int offsets[], int levels) {
for (int i = 0; i < levels; i++) {
basePointer = (int**) (*basePointer + offsets[i] / sizeof(int));
}
return (int*) basePointer;
}
/*
[Player base] = A
[A + 34] = X
[A + 38] = Y
[A + 3C] = Z
[A + 40] = Crosshair X
[A + 44] = Crosshair Y
[A + F4] = HP
[A + 154] = Grenades
*/
int playerBaseXOffsets[] = { 0x34 };
int playerBaseYOffsets[] = { 0x38 };
int playerBaseZOffsets[] = { 0x3C };
int playerBaseCXOffsets[] = { 0x40 };
int playerBaseCYOffsets[] = { 0x44 };
int playerBaseHPOffsets[] = { 0xF4 };
int playerBaseAmmoOffsets[] = { 0x368, 0x14, 0 };
int playerBaseGrenadesOffsets[] = { 0x154 };
typedef struct Player {
int** basePointer;
float* xPointer;
float* yPointer;
float* zPointer;
float* cXPointer;
float* cYPointer;
int* hpPointer;
int* ammoPointer;
int* grenadesPointer;
Player() {
}
Player(int** basePtr) {
basePointer = basePtr;
xPointer = (float*) getClosestPointer(basePointer, playerBaseXOffsets, sizeof(playerBaseXOffsets) / sizeof(playerBaseXOffsets[0]));
yPointer = (float*) getClosestPointer(basePointer, playerBaseYOffsets, sizeof(playerBaseYOffsets) / sizeof(playerBaseYOffsets[0]));
zPointer = (float*) getClosestPointer(basePointer, playerBaseZOffsets, sizeof(playerBaseZOffsets) / sizeof(playerBaseZOffsets[0]));
cXPointer = (float*) getClosestPointer(basePointer, playerBaseCXOffsets, sizeof(playerBaseCXOffsets) / sizeof(playerBaseCXOffsets[0]));
cYPointer = (float*) getClosestPointer(basePointer, playerBaseCYOffsets, sizeof(playerBaseCYOffsets) / sizeof(playerBaseCYOffsets[0]));
hpPointer = getClosestPointer(basePointer, playerBaseHPOffsets, sizeof(playerBaseHPOffsets) / sizeof(playerBaseHPOffsets[0]));
ammoPointer = getClosestPointer(basePointer, playerBaseAmmoOffsets, sizeof(playerBaseAmmoOffsets) / sizeof(playerBaseAmmoOffsets[0]));
grenadesPointer = getClosestPointer(basePointer, playerBaseGrenadesOffsets, sizeof(playerBaseGrenadesOffsets) / sizeof(playerBaseGrenadesOffsets[0]));
}
} Player;
Player players[32] = { };
/* Pythagorean's theorem (flavour for 3D) */
float getDistanceBetween(Player one, Player two) {
return sqrt(
(*(one.xPointer)-*(two.xPointer))*(*(one.xPointer)-*(two.xPointer))
+ (*(one.yPointer)-*(two.yPointer))*(*(one.yPointer)-*(two.yPointer))
+ (*(one.zPointer)-*(two.zPointer))*(*(one.zPointer)-*(two.zPointer))
);
}
int getNumberOfPlayers() {
return *((int*) ((UINT) GetModuleHandleW(0) + 0xE4E10));
}
Player* getClosestTarget() {
float smallestDistance;
int index = -1;
for (int i = 1; i < getNumberOfPlayers(); i++) {
if (*(players[i].hpPointer) > 0) {
float tempDistance = getDistanceBetween(players[0], players[i]);
if (index == -1 || tempDistance < smallestDistance) {
smallestDistance = tempDistance;
index = i;
}
}
}
if (index == -1) {
return NULL;
} else {
return &players[index];
}
}
/* Gets the crosshair horizontal angle in degrees. */
float getCX(Player me, Player target) {
float deltaX = *(target.xPointer) - *(me.xPointer);
float deltaY = *(me.yPointer) - *(target.yPointer);
if (*(target.xPointer) > *(me.xPointer) && *(target.yPointer) < *(me.yPointer)) {
return atanf(deltaX/deltaY) * 180.0f / pi;
} else if(*(target.xPointer) > *(me.xPointer) && *(target.yPointer) > *(me.yPointer)) {
return atanf(deltaX/deltaY) * 180.0f / pi + 180.0f;
} else if(*(target.xPointer) < *(me.xPointer) && *(target.yPointer) > *(me.yPointer)) {
return atanf(deltaX/deltaY) * 180.0f / pi - 180.0f;
} else {
return atanf(deltaX/deltaY) * 180.0f / pi + 360.0f;
}
}
/* Gets the crosshair vertical angle in degrees. */
float getCY(Player me, Player target) {
float deltaZ = *(target.zPointer) - *(me.zPointer);
float dist = getDistanceBetween(me, target);
return asinf(deltaZ/dist) * 180.0f / pi;
}
int main() {
bool aimbotEnabled = false;
Player* closestTargetPointer = NULL;
// [Base + DF73C] = Player 1 base
players[0] = Player((int**) ((UINT) GetModuleHandleW(0) + 0xDF73C));
int** extraPlayersBase = *((int***) ((UINT) GetModuleHandleW(0) + 0xE5F00));
while (true) {
// [Base + E5F00] = A
// [A + 0,4,8...] = Player 2/3/4... base
for (int i = 0; i < getNumberOfPlayers() - 1; i++) {
players[i + 1] = Player(extraPlayersBase + i * 4 / sizeof(int*));
}
if (GetAsyncKeyState(VK_CONTROL) && GetAsyncKeyState('0')) {
aimbotEnabled = !aimbotEnabled;
Sleep(500);
}
if (aimbotEnabled) {
closestTargetPointer = getClosestTarget();
if (closestTargetPointer != NULL) {
*(players[0].cXPointer) = getCX(players[0], *closestTargetPointer);
*(players[0].cYPointer) = getCY(players[0], *closestTargetPointer);
}
}
Sleep(10);
}
}
DWORD WINAPI Main(LPVOID lpParam) {
main();
return S_OK;
}
BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) {
if (ul_reason_for_call == DLL_PROCESS_ATTACH) {
DisableThreadLibraryCalls(hModule);
CreateThread(NULL, 0, &Main, NULL, 0, NULL);
}
return TRUE;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-14T07:18:13.177",
"Id": "44677",
"Score": "0",
"body": "At `getCX` there is some pieces of repeated code. I think it's best to eliminate it, maybe use another function. Otherwise looks good for me - but I'm not good in C and/or WinAPI."
}
] |
[
{
"body": "<ul>\n<li><p>This is C++, not C, so use <code><cmath></code> instead of <code><math.h></code>.</p></li>\n<li><p>This would look and function better with more <code>class</code>es, especially since it's a game. For instance, <code>Player</code> can become a class instead of a <code>struct</code> so that it can be kept <code>private</code>. There should also be a <code>Game</code> class to keep a collection of Players and handle the gameplay. You will simply initiate the game in <code>main()</code> by creating a Game object. Note that <code>main()</code> should not have access to anything within the game beyond the ability to start it.</p></li>\n<li><p>I agree with @Lstor about making an <code>std::vector</code> of <code>Player</code>s. This will also allow you to access each Player using the container's iterators. If you have C++11, you have two options, depending on whether or not your compiler supports <strong>range-based for-loops</strong>:</p>\n\n<p><em>If it does...</em></p>\n\n<pre><code>for (auto const& player : players)\n{\n std::cout << player;\n}\n</code></pre>\n\n<p><em>If it does not...</em></p>\n\n<pre><code>for (auto iter = players.cbegin(); iter != players.cend(); ++iter)\n{\n std::cout << *iter;\n}\n</code></pre>\n\n<p>In your game, you would be operating on this vector inside the Game class only. This is important because it shouldn't be exposed through the interface. You're free to define a display function (or overload <code>operator<<</code>), <strong>but you mustn't break encapsulation</strong>.</p></li>\n<li><p>The parameters in <code>getCX()</code> and <code>getCY()</code> should be const-refs since they're not modified:</p>\n\n<pre><code>float getCX(Player const& me, Player const& target) {}\nfloat getCY(Player const& me, Player const& target) {}\n</code></pre></li>\n<li><p>The <code>playerBaseOffset</code>s look like they should be <code>const</code>. I'd also prefer something more concise than single arrays, such as an <code>enum</code>. It could also be put into a <code>namespace</code> to avoid name collisions.</p></li>\n<li><p>The STL <em>should</em> especially be utilized to take advantage of smart pointers in place of raw pointers (the latter is more C-like). Beyond that, using the STL as much as possible will clean up your code considerably. As for pointers in general, use <code>nullptr</code> instead of <code>NULL</code> if you're using C++11.</p></li>\n<li><p>Regarding @Lstor's answer, include <code><cstddef></code> in order to use <code>std::size_t</code>.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T03:02:46.230",
"Id": "45981",
"Score": "0",
"body": "A `struct` is a class where default access is `public` instead of `private`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T03:04:37.277",
"Id": "45982",
"Score": "0",
"body": "@Lstor: Yeah, I wasn't clear enough. I'll fix it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T04:38:16.350",
"Id": "45994",
"Score": "1",
"body": "`for (auto const& player : players) { std::cout << player; }` :-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T04:39:48.290",
"Id": "45995",
"Score": "0",
"body": "@Lstor: I'll put that as another option (with specifics). ;-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T06:04:32.130",
"Id": "45998",
"Score": "1",
"body": "[gcc](http://gcc.gnu.org/projects/cxx0x.html), [msvc](http://msdn.microsoft.com/en-us/library/vstudio/hh567368.aspx), [icc](http://software.intel.com/en-us/articles/c0x-features-supported-by-intel-c-compiler) and [clang](http://clang.llvm.org/cxx_status.html) have [all supported range-based `for` loops](http://cpprocks.com/c11-compiler-support-shootout-visual-studio-gcc-clang-intel/) for a while."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T06:11:36.530",
"Id": "45999",
"Score": "0",
"body": "@Lstor: Right. Again, I still have MSVC2010, which doesn't support it. I'm still trying to determine the best way to upgrade compilers (preferably gcc)."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T22:49:13.157",
"Id": "29152",
"ParentId": "26503",
"Score": "4"
}
},
{
"body": "<p><strong>Your C++ is very C-like.</strong> I would start by taking advantage of C++:</p>\n\n<ul>\n<li><p>You will almost always want to use <code>std::vector</code> instead of arrays.</p>\n\n<p>For example:</p>\n\n<pre><code>std::vector<Player> players;\nplayers.reserve(32);\n</code></pre>\n\n<p>This will create a vector large enough to hold 32 <code>Player</code>s. If you ever need room for more, the vector will grow automatically when you add more players. By accessing elements using <code>players.at(index)</code>, you will get range-checking.</p>\n\n<p>To get the number of elements in a <code>vector</code>, you can use <code>players.size()</code> instead of using the <code>sizeof</code> array division hack.</p></li>\n<li><p>Your <code>struct</code> typedef-ing is a common idiom in C, because in C you need to qualify <code>struct</code> identifiers with <code>struct</code> in order to use them: <code>void foo(struct Bacon* bacon)</code>. In C++ you don't have to do this. I would therefore change your definition of <code>Player</code> to:</p>\n\n<pre><code>class Player {\npublic:\n // contents\n};\n</code></pre></li>\n<li><p>The variables in <code>Player</code> should normally be encapsulated. This means they should be defined in the <code>private</code> section of the class (above <code>public:</code>). If you need access to the variables from other functions or classes, then you can provide accessor functions:</p>\n\n<pre><code>class Player {\n int** basePointer;\npublic:\n int** getBasePointer() const { return basePointer; }\n};\n</code></pre></li>\n<li><p>If you really want to use your <code>struct</code> as <a href=\"http://en.wikipedia.org/wiki/Plain_Old_Data_Structures\" rel=\"nofollow noreferrer\">POD</a>, I recommend making the members <code>const</code> and making a copy every time your need to. This isn't a <em>must</em>, but reduces the chances of unintentional changes.</p></li>\n<li><p>In short, your class (a <code>struct</code> is a class) could and probably should be designed like a <em>class</em>, and not like POD.</p></li>\n<li><p>Like @Jamal points out, you can use <code>enum</code> for your offsets:</p>\n\n<pre><code>enum Offsets { playerBaseXOffset = 0x34, playerBaseYOffset = 0x38 /* ... */ };\n</code></pre>\n\n<p>If you are expecting to have more offsets of a kind later, use a <code>std::vector</code> instead:</p>\n\n<pre><code>std::vector<std::size_t> playerBaseXOffsets{ 0x34 }; // C++11 syntax.\n</code></pre>\n\n<blockquote>\n <p><strong>Note the <code>{</code> and <code>}</code> in the last example. <em>Using</em> <code>(</code> <em>and</em> <code>)</code> <em>instead compiles, but means something entirely different!</em></strong> (It will default-construct 0x34 = 52 objects.)</p>\n</blockquote></li>\n<li><p>I'm not sure if all your pointer fiddling is really necessary. If it's not, I recommend you avoid it. It is error prone, and some of the potential errors can be really hard to find. You risk forgetting to dereference a pointer if you're lucky; you get undefined behavior from <a href=\"https://stackoverflow.com/questions/98650/what-is-the-strict-aliasing-rule\">violating the strict aliasing rule</a> if you're not.</p></li>\n<li><p>Use symbolic, rather than literal, constants. For example:</p>\n\n<pre><code>const std::size_t player_one_base_offset = 0xDF73C;\nplayers[0] = Player((int**) ((UINT) GetModuleHandleW(0) + player_one_base_offset));\n</code></pre>\n\n<p>I'm sure you agree <code>player_one_base_offset</code> is much more readable and understandable than <code>0xDF73C</code>.</p></li>\n<li><p>I would normally recommend C++-style <code>static_cast<type>(object)</code> instead of your C-style <code>(type)object</code> casting, but in your case I think it would just reduce readability even more without giving much benefit.</p></li>\n</ul>\n\n<p>And finally, not directly code related: It's either <em>Pythagoras' theorem</em>, or the <em>Pythagorean theorem</em>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T03:54:43.007",
"Id": "45983",
"Score": "0",
"body": "+1. I did forgot to mention `std::vector` here (even after seeing many arrays), but I got the `enum`s."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T03:56:36.157",
"Id": "45984",
"Score": "0",
"body": "@Jamal In all fairness, you did recommend using the STL. I was just a little more concrete."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T04:00:17.873",
"Id": "45985",
"Score": "0",
"body": "True. Although, when looking at the Player array, I was more concerned about it being in a better place (`main()` or a Game class). I am quite lost in this design, but it'd be great to see it become more C++-like."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T04:04:26.483",
"Id": "45986",
"Score": "0",
"body": "By the way, what do you think about the `\"stdafx.h\"` in the code? I know it indicates a pre-compiled header under Visual C++ (I would know), but I'm not sure if it's even necessary."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T04:08:30.810",
"Id": "45988",
"Score": "1",
"body": "@Jamal In this case it's necessary for the WinAPI calls. For a program that by nature is platform-restricted like this, I see no harm in it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T04:09:31.143",
"Id": "45989",
"Score": "0",
"body": "I see. I tend to avoid it since it seems tacky and unnecessary (at least right now)."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T03:48:50.103",
"Id": "29159",
"ParentId": "26503",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T02:02:13.090",
"Id": "26503",
"Score": "11",
"Tags": [
"c++",
"beginner",
"ai"
],
"Title": "Aimbot for open-source FPS game Assault Cube"
}
|
26503
|
<p>How could this code be improved and have fewer repeated lines?</p>
<pre><code>vent.on("createAccountLayout:rendered", function() {
logger.info('createAccountLayout:rendered => CreateAccountLayoutController');
showRegion(['phoneNumberRegion', 'keyboardRegion', 'nextRegion', 'quitRegion']);
vent.trigger('createAccountLayout:setToNumericKeyboard');
});
vent.on('createAccountPhoneNumberView:nextStep', function() {
closeRegion(['phoneNumberRegion', 'keyboardRegion', 'nextRegion']);
showRegion(['nameRegion', 'keyboardRegion', 'nextRegion']);
vent.trigger('createAccountLayout:setToAlphaNumericKeyboard');
vent.trigger('createAccountLayout:disableNextButton');
});
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T02:52:23.780",
"Id": "41057",
"Score": "1",
"body": "If the code isn't that repetitive or that many, I suggest you leave it be. This is too little for a generic routine to be created."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T03:00:47.660",
"Id": "41059",
"Score": "0",
"body": "Noted. Though while coding this module, I realized that there's going to be more of those. So I want to simplify this before things gets out of hand."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T03:07:15.260",
"Id": "41060",
"Score": "1",
"body": "As far as I remember, I have answered a question of yours that holds the same pattern. You can apply a similar approach."
}
] |
[
{
"body": "<p>Answerifying what Joseph the Dreamer commented on, </p>\n\n<p>there is really not enough code to build a general routine out of, the code is fine as is. Though ideally you could add comments.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-16T22:47:24.303",
"Id": "47408",
"ParentId": "26505",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T02:46:48.480",
"Id": "26505",
"Score": "2",
"Tags": [
"javascript",
"backbone.js"
],
"Title": "Backbone Marionette code improvement 2"
}
|
26505
|
<h1>Background</h1>
<p>Breaking from MVC, I've implemented the following architecture:</p>
<pre><code>POST/GET ➤ PHP ➤ Database Calls ➤ XML ➤ XSLT ➤ HTML
</code></pre>
<p>All database interactions are relegated to the <code>call</code> method in the <code>Database</code> class, without exception. This adheres to the DRY principle. This design allows the following, which is a critical application feature:</p>
<pre><code>... ➤ XML ➤ XSLT ➤ LaTeX ➤ PDF
</code></pre>
<p>The same code that retrieves data to render as an interactive web page is exactly the same code <em>and</em> XML used to render a PDF. Eventually additional output formats will be required:</p>
<pre><code>... ➤ XML ➤ XSLT ➤ XML
... ➤ XML ➤ XSLT ➤ ASCII Text
</code></pre>
<p>Using this architecture, the same database functions can be used to generate completely different output formats.</p>
<h1>Common Code</h1>
<p>The code that makes database calls can do so in one of three ways:</p>
<pre><code>$this->call( "database_function", "c1, c2, c3", $v1, $v2, $v3 );
$this->call( "database_function", "c1, c2, c3" ) );
$this->call( "database_procedure" ) );
</code></pre>
<p>The parameters are variable arguments.</p>
<h1>Database Class</h1>
<p>My questions pertain to the database class itself:</p>
<pre><code><?php
use PDO;
use PDOException;
/**
* Used for interacting with the database. Usage:
* <pre>
* $db = Database::get();
* $db->call( ... );
* </pre>
*/
class Database extends Obj {
private static $instance;
private $dataStore;
/**
* Sets the connection that this class uses for database transactions.
*/
public function __construct() {
global $dbhost;
global $dbname;
global $dbuser;
global $dbpass;
try {
$this->setDataStore(
new PDO( "pgsql:dbname=$dbname;host=$dbhost", $dbuser, $dbpass ) );
}
catch( PDOException $ex ) {
$this->log( $ex->getMessage() );
}
}
/**
* Returns the singleton database instance.
*/
public function get() {
if( self::$instance === null ) {
self::$instance = new Database();
}
return self::$instance;
}
/**
* Call a database function and return the results. If there are
* multiple columns to return, then the value for $params must contain
* a comma; otherwise, without a comma, the value for $params is used
* as the return column name. For example:
*
*- SELECT $params FROM $proc( ?, ? ); -- with comma
*- SELECT $proc( ?, ? ) AS $params; -- without comma
*- SELECT $proc( ?, ? ); -- empty
*
* @param $proc Name of the function or stored procedure to call.
* @param $params Name of parameters to use as return columns.
*/
public function call( $proc, $params = "" ) {
$args = array();
$count = 0;
$placeholders = "";
// Key is zero-based (e.g., $proc = 0, $params = 1).
foreach( func_get_args() as $key => $parameter ) {
// Skip the $proc and $params arguments to this method.
if( $key < 2 ) continue;
$count++;
$placeholders = empty( $placeholders ) ? "?" : "$placeholders,?";
array_push( $args, $parameter );
}
$sql = "";
if( empty( $params ) ) {
// If there are no parameters, then just make a call.
$sql = "SELECT $proc( $placeholders )";
}
else if( strpos( $params, "," ) !== false ) {
// If there is a comma, select the column names.
$sql = "SELECT $params FROM $proc( $placeholders )";
}
else {
// Otherwise, select the result into the given column name.
$sql = "SELECT $proc( $placeholders ) AS $params";
}
$statement = $this->getDataStore()->prepare( $sql );
//$this->log( "SQL: $sql" );
for( $i = 1; $i <= $count; $i++ ) {
//$this->log( "Bind " . $i . " to " . $args[$i - 1] );
$statement->bindParam( $i, $args[$i - 1] );
}
$statement->execute();
$result = $statement->fetchAll();
$this->decodeArray( $result );
return $result;
}
/**
* Converts an array of numbers into an array suitable for usage with
* PostgreSQL.
*
* @param $array An array of integers.
*/
public function arrayToString( $array ) {
return "{" . implode( ",", $array ) . "}";
}
/**
* Recursive method to decode a UTF8-encoded array.
*
* @param $array - The array to decode.
* @param $key - Name of the function to call.
*/
private function decodeArray( &$array ) {
if( is_array( $array ) ) {
array_map( array( $this, "decodeArray" ), $array );
}
else {
$array = utf8_decode( $array );
}
}
private function getDataStore() {
return $this->dataStore;
}
private function setDataStore( $dataStore ) {
$this->dataStore = $dataStore;
}
}
?>
</code></pre>
<p>A <code>BaseController</code> class abstracts the persistence layer from subclasses as follows:</p>
<pre><code> protected function call() {
$db = Database::get();
return call_user_func_array( array( $db, "call" ), func_get_args() );
}
</code></pre>
<p>Thus subclasses can call <code>$this->call(...)</code> without knowing about the database.</p>
<h1>Example Usage #1</h1>
<p>The database functionality is used, for example as an AJAX request, as follows:</p>
<pre><code>class AjaxPhotographCategory extends Ajax {
function __construct() {
parent::__construct();
}
public function handleAjaxRequest() {
return $this->json( $this->call(
"get_photograph_category_list", "id, label, description" ) );
}
}
?>
</code></pre>
<h1>Example Usage #2</h1>
<p>Here is another example usage:</p>
<pre><code> private function exists( $cookie_value ) {
$result = $this->call( "is_existing_cookie", "existing", $cookie_value );
return isset( $result[0] ) ? $result[0]["existing"] > 0 : false;
}
</code></pre>
<p>The return line could be abstracted and simplified, but that's not an important detail.</p>
<h1>Example Usage #3</h1>
<p>The code to generate an XML document resembles (where <code>"x"</code> is the column name to hold XML content):</p>
<pre><code> private function getXml() {
$result = $this->call( "generate_account_xml", "x", $this->getId() );
return isset( $result[0] ) ? $result[0]["x"] : $this->getErrorXml( "account" );
}
</code></pre>
<h1>Example Usage #4</h1>
<p>Information is added to the database as follows:</p>
<pre><code> private function authenticate() {
$this->call( "authentication_upsert", "",
$this->getCookieToken(),
$this->getBrowserPlatform(),
$this->getBrowserName(),
$this->getBrowserVersion(),
$this->getIp()
);
}
</code></pre>
<p>Since this calls a stored procedure, the return value can be discarded. As <code>call</code> requires two values (database routine name and return column name) to precede the arguments passed into the database routine, the second parameter must be filled with <em>something</em> (hence <code>""</code>).</p>
<p>This could be abstracted by splitting <code>call</code> into <code>callProc</code> and <code>callFunc</code>, so I'd consider the extraneous empty string parameter to be a minor detail.</p>
<h1>Questions</h1>
<p>My questions are:</p>
<ul>
<li>What performance impacts or security issues may be encountered?</li>
<li>What improvements could be made to alleviate those issues?</li>
<li>How could the implementation be changed to ease maintenance?</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T05:27:07.523",
"Id": "41064",
"Score": "0",
"body": "Do I get this right that you are trying to move most of your logic to stored procedures?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T16:06:49.837",
"Id": "41105",
"Score": "0",
"body": "All persistence logic is in stored procedures already. The entire PHP code base has only three `SELECT` statements (shown). There are no `INSERT`, `UPDATE`, or `DELETE` statements in the code base and my plan is to keep it that way. My concern is around the performance and security impacts of the Database class."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T04:34:02.860",
"Id": "41134",
"Score": "2",
"body": "Although I'm getting OT here. Isn't this a maintenance and testing nightmare? I'm really interested in some sample procedures here?"
}
] |
[
{
"body": "<p>Here's my sniff at the first things I saw for the code (not the implementation).</p>\n\n<pre><code>public function __construct() {\n ...\n try {\n $this->setDataStore(\n new PDO( \"pgsql:dbname=$dbname;host=$dbhost\", $dbuser, $dbpass ) );\n }\n ...\n</code></pre>\n\n<p>Above, a class is instantiating a class, and not injecting dependencies.</p>\n\n<p>Pass arguments to the constructor with the dependencies that a class requires:</p>\n\n<pre><code>public function __construct(PDO $pdo) {\n $this->dataStore = $pdo;\n}\n</code></pre>\n\n<p>In addition, use the magic <code>__get()</code> and <code>__set()</code> methods instead of explicitly declared accessors to vastly improve readability and maintenance ease. <a href=\"http://www.php.net/manual/en/language.oop5.overloading.php\" rel=\"nofollow\">Here's the documentation</a>, remember it, and learn to love it.</p>\n\n<pre><code>public function __get(string $name) {\n // Logic/cases to check name for correct stores here.\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-25T06:13:45.657",
"Id": "41217",
"Score": "0",
"body": "Exposing the PDO class through the constructor would mean that any class wanting to use the Database class would need to know about PDO, which would defeat the purpose of a Database singleton."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-25T06:14:43.927",
"Id": "41218",
"Score": "0",
"body": "The `__get` and `__set` methods look interesting. If the `__get` method can be made `private`, that pattern will be quite handy."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-25T06:17:53.633",
"Id": "41219",
"Score": "0",
"body": "@DaveJarvis in PHP, magic methods must be public. You can control access inside that function, though, and keep all attributes private/protected"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-25T09:55:26.600",
"Id": "41225",
"Score": "1",
"body": "The magic methods are [3 times slower](http://www.garfieldtech.com/blog/magic-benchmarks). Although you should not start a premature optimization, you should be aware of this fact."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-25T09:57:27.280",
"Id": "41227",
"Score": "1",
"body": "Maybe you can replace your global variables by some kind of configuration object."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-25T17:57:38.150",
"Id": "41241",
"Score": "0",
"body": "@mnhg it's a trade-off for maintenance value; getters/setters for every single value (in my experience) turned into maintenance hell."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-26T22:13:58.257",
"Id": "41298",
"Score": "0",
"body": "The global variables are generated from a database. All constants are in a table, which gets exported as XML. The XML is then transformed into PHP, JavaScript, or XSLT as required. ;-)"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T22:48:12.043",
"Id": "26589",
"ParentId": "26507",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "26589",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T04:02:20.380",
"Id": "26507",
"Score": "6",
"Tags": [
"php",
"object-oriented",
"postgresql",
"delegates"
],
"Title": "Generic method for database calls"
}
|
26507
|
<p>The following is a small part of some code I am working on
Which is better/faster/nicer?</p>
<p>1.</p>
<pre><code>for (Future<Subscription> future : futures) {
try {
executorService.submit(new Updater(future.get()));
} catch (ExecutionException e) {
logger.error(e, e);
}
}
</code></pre>
<p>2.</p>
<pre><code> for (Future<Subscription> future : futures) {
try {
executorService.submit(new Updater(future));
//here future.get() will be called in the Updater constructor in its own thread
} catch (ExecutionException e) {
logger.error(e, e);
}
}
</code></pre>
<p>I am tempted to go with the second way as future.get() is called in its own thread and not in the main thread.</p>
|
[] |
[
{
"body": "<p>Your presumtion that the future.get() method is called in another thread is wrong. The constructor still executes in the same thread as the loop, its the run() method in the Updater class that is called in its own thread. Consider passing the whole future to the Updater and store a reference to the future internally. Then, once the value is really required (somewhere after the run method of Updater has been called), you can call get() on the future to retrieve its value.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T08:31:03.593",
"Id": "41075",
"Score": "0",
"body": "Thanks for the quick response. The question now becomes, Is calling future.get() in the run() method better/faster than calling it in the Constructor?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T17:04:54.187",
"Id": "41109",
"Score": "1",
"body": "its better to do it in the run() method :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T06:51:27.103",
"Id": "26511",
"ParentId": "26508",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "26511",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T06:02:07.680",
"Id": "26508",
"Score": "2",
"Tags": [
"java",
"multithreading"
],
"Title": "Best way to call future.get()"
}
|
26508
|
<pre><code>eval {
# here is put some code that may throw exception
1; # Why is the "1;" here ?
} or do {
my $error = $@;
# Handle error.
};
</code></pre>
<ol>
<li>Does the following style protect against $@ not being set
correctly ? </li>
<li>What does the following "1;" protect against?</li>
<li>Is the "or do{" better than the saying "if ($@){ " ? If so, why?</li>
</ol>
|
[] |
[
{
"body": "<p>Ad. 1. Yes and no - <a href=\"https://metacpan.org/module/Try::Tiny#BACKGROUND\" rel=\"nofollow noreferrer\">there are still some pitfalls</a> (please read further).</p>\n\n<p>Ad. 2. You must remember about returning truthy value from <code>eval</code> block because it evaluates to last value in block <strong>unless</strong> some code died, in which case <code>undef</code> is returned, so <code>1;</code> as last statement in <code>eval</code> block is important.</p>\n\n<p>You also have to localize <code>$@</code> somehow (<code>my $error = $@</code> in your example) because it's a global variable which can be changed silently (see Conclusion).</p>\n\n<p>Ad. 3. <code>if ($@)</code> can have one pitfall, i.e. it doesn't catch error when it's false:</p>\n\n<pre><code>eval {\n die '';\n do_something();\n};\nif ($@) {\n # ooops... we don't get here\n}\n</code></pre>\n\n<p>while <code>or do { }</code> block will always be activated in case of exception</p>\n\n<pre><code>eval {\n die '';\n do_something();\n 1;\n} or do {\n # caught!\n};\n</code></pre>\n\n<p><strong>Conclusion:</strong></p>\n\n<p>I personally use \"eval or do # process error\" style of catching errors but common and widely used alternative, which eleminates boilerplate code, is to use <a href=\"https://metacpan.org/module/Try::Tiny\" rel=\"nofollow noreferrer\"><code>Try::Tiny</code></a>. It's a simple, 0-dependency CPAN module which addresses <code>$@</code> issues. Its documentation (especially BACKGROUND section) is really worth reading as it answers some of your questions and with even more details.</p>\n\n<p>See also <a href=\"https://stackoverflow.com/questions/10364975/is-trytiny-still-recommended-for-exception-handling-in-perl-5-14-or-later\">this SO question</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T11:22:03.397",
"Id": "41082",
"Score": "1",
"body": "Great documented answer. I don't know Perl, but enjoyed reading it. :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T09:17:04.300",
"Id": "26520",
"ParentId": "26512",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "26520",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T07:20:33.433",
"Id": "26512",
"Score": "4",
"Tags": [
"exception-handling",
"perl"
],
"Title": "What changes, if any, are required to make the following Perl eval bullet proof?"
}
|
26512
|
<p><a href="http://brislink.github.io/Abstract/" rel="nofollow">My application</a>. The <a href="https://github.com/brislink/Abstract" rel="nofollow">repository</a> and the <a href="https://github.com/brislink/Abstract/blob/master/javascript/index.js" rel="nofollow">file</a> that needs review.</p>
<p>Here is the source code</p>
<pre><code>$(function () {
var draft = function (parsed, title) {
var self = this;
var wordCount = parsed.wordCount;
self.date = new Date(parsed.time).toDateString();
self.count = wordCount;
self.title = title;
self.plural = wordCount > 1;
self.trueDate = new Date(parsed.time);
};
var viewModel = function (drafts) {
var self = this;
self.drafts = ko.observableArray(drafts);
self.showEditor = ko.observable(true);
self.showTitle = ko.observable(true);
self.raw = ko.observable(true);
self.deleteDraft = function (draft, event) {
event.stopPropagation();
removeDraft(draft.title);
self.drafts.remove(draft);
};
self.showDrafts = function () {
self.showEditor(false);
self.showTitle(false);
renderSavedDrafts();
hideThis(["#previewContainer"]);
showThis(["#drafts"]);
};
self.newDraft = function () {
hideThis(["#previewContainer", "#drafts"]);
self.showTitle(true);
self.showEditor(true);
editArea.focus();
editArea.val('');
$("#title").text('');
};
self.showPreview = function () {
if (validateInputOnFousOut()) {
setHtmlinPreviewPane(getMarkdownText());
hideThis(['#plain']);
self.showEditor(false);
self.showTitle(true);
showThis(["#rawHtml", '#previewContainer']);
saveCurrentDraft();
$("#saveStatus").fadeIn().show().delay(1000).fadeOut();
}
};
self.hidePreview = function () {
hideThis(["#previewContainer"]);
self.showEditor(true);
editArea.trigger('autosize');
editArea.focus();
};
self.editDraft = function (draft) {
var title = draft.title;
var item = getDraftFromKey(title);
var parsed = JSON.parse(item);
hideThis(["#drafts"]);
editArea.val(parsed.text).trigger('autosize');
$("#title").text(title);
$("#wordCount").text(parsed.wordCount);
self.showEditor(true);
self.showTitle(true);
};
self.rawHtml = function (data, event) {
setRawHtml();
event.stopPropagation();
self.raw(false);
}
self.plain = function (data, event) {
setPlain();
event.stopPropagation();
self.raw(true);
}
};
function prepareInitialWorkSpace() {
var editArea = $("#editArea");
editArea.autosize();
$("#title").focus();
return editArea;
}
function hideThis(elements) {
for (var i = 0; i < elements.length; i++) {
$(elements[i]).hide();
}
}
function showThis(elements) {
for (var i = 0; i < elements.length; i++) {
$(elements[i]).show();
}
}
function getMarkdownText() {
return $("#editArea").val();
}
function getWordCount(text) {
return text.split(/\s+\b/).length;
}
function setHtmlinPreviewPane(markdownText) {
$("#wordCount").text('words: ' + getWordCount(markdownText));
$("#previewPane").html(markdown.toHTML(markdownText));
}
function setRawHtml() {
var pane = $("#previewPane");
pane.text(pane.html());
}
function setPlain() {
var pane = $("#previewPane");
pane.html(pane.text());
}
function getWordCountFromLabel(text) {
return text.match(/\d+/)[0];
}
function validateInputOnFousOut() {
var isTitleEmpty = $("#title").text().trim() === '';
var isDraftEmpty = $("#editArea").val() === '';
var hasTitileAndDraft = !isTitleEmpty && !isDraftEmpty;
return hasTitileAndDraft;
}
var initializeDrafts = new viewModel();
ko.applyBindings(initializeDrafts);
function loadSavedDrafts() {
return Object.keys(localStorage);
}
function sortedArray(data) {
return data.sort(function (a, b) {
a = new Date(a.trueDate);
b = new Date(b.trueDate);
return a < b ? -1 : a > b ? 1 : 0;
}).reverse();
}
function buildData(keys) {
var data = [];
for (var i = 0; i < keys.length; i++) {
var parsed = JSON.parse(localStorage[keys[i]]);
var initializeDraft = new draft(parsed, keys[i]);
data.push(initializeDraft);
}
return sortedArray(data);
}
function renderSavedDrafts() {
var array = buildData(loadSavedDrafts());
initializeDrafts.drafts(array);
}
function saveCurrentDraft() {
var key = $("#title").text();
var draft = {};
draft["time"] = new Date();
draft["text"] = getMarkdownText();
draft["wordCount"] = getWordCountFromLabel($("#wordCount").text());
localStorage.setItem(key, JSON.stringify(draft));
}
function getDraftFromKey(key) {
return localStorage.getItem(key);
}
function removeDraft(key) {
localStorage.removeItem(key);
}
var editArea = prepareInitialWorkSpace();
});
</code></pre>
<p>My main concern is that I have heavily mixed knockout and jquery. I need some tips to make my code less confusing and easier to understand. Any help will be appreciated.</p>
|
[] |
[
{
"body": "<p>I suggest you break down your application into concerns. Break them so that you separate your UI code, your IO code (read/write), your logic and your utilities. Then you could use a dependency system like <a href=\"http://requirejs.org/\" rel=\"nofollow\">Require</a> to manage these separated code into modules.</p>\n\n<p>Don't worry if you end up with multiple files. You can use their <a href=\"http://requirejs.org/docs/optimization.html\" rel=\"nofollow\">optimizer</a> after you got everything done.</p>\n\n<p>Also, you seem to use a few non-cross-brower-friendly APIs there (especially for IE), like <a href=\"http://kangax.github.io/es5-compat-table/#Object.keys\" rel=\"nofollow\"><code>Object.keys</code></a>, <a href=\"http://caniuse.com/namevalue-storage\" rel=\"nofollow\"><code>localStorage</code></a> and <a href=\"http://caniuse.com/json\" rel=\"nofollow\"><code>JSON</code></a>. Be sure <a href=\"http://html5please.com/\" rel=\"nofollow\">to check for safety and use polyfills if necessary</a> if you want to support such functionality for older (cough, IE, cough) and buggy browsers.</p>\n\n<p>As for your code, I have found a few weird parts that can be optimized.</p>\n\n<ul>\n<li><p>Organize your functions in the following manner:</p>\n\n<ol>\n<li>variable declarations</li>\n<li>function declarations</li>\n<li>all other stuff (in any order now)\n<ul>\n<li>function calls</li>\n<li>assignment operations</li>\n<li>etc.</li>\n</ul></li>\n</ol>\n\n<p><a href=\"http://jsfiddle.net/68yg3/1/\" rel=\"nofollow\">This is how the compiler sees your code</a>. To avoid any weirdness or hard to find variables (like <code>initializeDrafts</code> and <code>editArea</code>) in your code, just follow the format.</p></li>\n<li><p>Prefer function declarations over function expressions when necessary. The difference between the two in terms of syntax is:</p>\n\n<pre><code>function foo(){} //declaration\nvar foo = function(){}; //expression\n</code></pre>\n\n<p>There is what you call \"function and variable declaration hoisting\" in JavaScript where function and variable declarations are pulled up in the scope which results in the order discussed previously. </p>\n\n<p>However, function expressions are <em>assigment operations</em> and are not hoisted. They exist where they are assigned. So unlike a function declaration which can be used before they are declared (since the compiler pulls it up), function expressions cannot be used before it was assigned. </p>\n\n<p>A misplaced function expression could lead to errors, while a misplaced function declaration is bad practice (IMO). Stick to the order, it's better.</p></li>\n<li><p>When selectors are often reused, it's best you store the selector string into a variable for easy modification. What if you changed the <code>id</code> of the element, you wouldn't want to edit tens of selectors (Although you could do a Replace All, but with considerable amount of risk). </p>\n\n<p>So from your <code>viewModel</code>, you can do:</p>\n\n<pre><code>var viewModel = function (drafts) {\n\n var self = this;\n //cache selectors for easy modification\n var previewContainerSelector = '#previewContainer';\n var draftsSelector = '#drafts';\n ...\n\n self.showDrafts = function () {\n ...\n hideThis(previewContainerSelector);\n showThis(draftsSelector);\n };\n self.newDraft = function () {\n hideThis([previewContainerSelector, draftsSelector]);\n ...\n }\n ...\n</code></pre></li>\n<li><p>When an element is static throughout the lifetime of your page, it's not good to \"refetch\" them from the DOM everytime. Since they are static, they won't change and thus you can just store them in a variable for reference. </p>\n\n<p>So in modification of the one above, you can also cache the element instead:</p>\n\n<pre><code>var viewModel = function (drafts) {\n\n var self = this;\n //we can cache the jQuery objects of the elements instead\n var previewContainer = $('#previewContainer');\n var drafts = $('#drafts');\n ...\n\n self.showDrafts = function () {\n ...\n hideThis(previewContainer);\n showThis(drafts);\n };\n self.newDraft = function () {\n hideThis([previewContainer, drafts]);\n ...\n }\n ...\n</code></pre>\n\n<p>You can even cache them outside the <code>viewModel</code> so it's accessible from the other functions, constructors and operations. That way, you fetch it only once from the DOM.</p></li>\n<li><p>The jQuery functions <a href=\"http://api.jquery.com/jQuery/#jQuery-elementArray\" rel=\"nofollow\"><code>jQuery()</code> and <code>@()</code></a> (I know, they are the same thing), can accept a variety of arguments. Try to harness their power instead of doing it manually.</p>\n\n<p>You can pass in an array of selectors</p>\n\n<pre><code>function hideThis(elements) {\n var selectors = elements.join(',');\n $(selectors).hide();\n}\n\nhideThis(['#previewContainer','#drafts']);\n\n//you can even do:\n$(['#previewContainer','#drafts'].join(',')).hide();\n</code></pre>\n\n<p>An array of DOM elements</p>\n\n<pre><code>var previewContainer = document.getElementById('previewContainer');\nvar drafts = document.getElementById('drafts');\n\nfunction hideThis(elements) {\n $(elements).hide();\n}\n\nhideThis([previewContainer,drafts]);\n</code></pre>\n\n<p>An array of jQuery objects</p>\n\n<pre><code>var previewContainer = $('#previewContainer');\nvar drafts = $('#drafts');\n\nfunction hideThis(elements) {\n $.each(elements,function(){\n this.hide();\n });\n}\n\nhideThis([previewContainer,drafts]);\n</code></pre>\n\n<p>You can also use the special <a href=\"https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Functions_and_function_scope/arguments\" rel=\"nofollow\"><code>arguments</code></a> variable within each function which collects all arguments passed into the function into this variable. That way you don't need to construct an array of somethings. Just pass them in as normal arguments to the function, and access them via <code>arguments</code> like an array.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T03:21:27.000",
"Id": "41131",
"Score": "0",
"body": "Wow fantastic advice. Thanks. I especially like the one on passing multiple elements in jquery itself. That would save the effort of maintaining `hideThis(array)` . One question that I still have though is that I have mixed 2 libraries. That is I have jquery in knockout view models. I feel a bit uneasy about this. Is is okay should I try to spereate jquery from knockout completely?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T22:19:34.153",
"Id": "26550",
"ParentId": "26514",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "26550",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T07:44:16.207",
"Id": "26514",
"Score": "2",
"Tags": [
"javascript",
"jquery",
"knockout.js"
],
"Title": "Need suggestions to improve the code for an open source web based drafting application"
}
|
26514
|
<p>Using OpenMP, is it correct to parallelize a <code>for</code> loop inside a function "func" as follows?</p>
<pre><code>void func(REAL coeff, DATAMPOT *dmp, int a, int la, int b, int lb, REAL L)
{
int i,j,k;
REAL dx,dy,dz;
REAL dx2,dy2,dz2;
REAL r;
#pragma omp parallel for default(shared) private(k,i,j,dx,dy,dz,dx2,dy2,dz2,r) reduction(+:deltaE)
for(k=0; k<la*lb; ++k){
j=k/la+b;
i=k%la+a;
dx=fabs(part[i].x-part[j].x);
dy=fabs(part[i].y-part[j].y);
dz=fabs(part[i].z-part[j].z);
dx2=(dx<0.5?dx*dx:(1-dx)*(1-dx));
dy2=(dy<0.5?dy*dy:(1-dy)*(1-dy));
dz2=(dz<0.5?dz*dz:(1-dz)*(1-dz));
r=L*sqrt(dx2+dy2+dz2);
deltaE += coeff*((dmp+NSPES*part[i].s+part[j].s)->npot>1?
mpot(r,dmp+NSPES*part[i].s+part[j].s,((REAL)rand())/RAND_MAX):
(dmp+NSPES*part[i].s+part[j].s)->pot[0](r,(dmp+NSPES*part[i].s+part[j].s)->dp ) );
}
}
</code></pre>
<p>Where:</p>
<ul>
<li><code>REAL</code> is <code>double</code> (<code>#define REAL double</code>)</li>
<li><code>DATAMPOT *dmp</code> is a pointer to a struct containing (among others) some pointers to functions, such as <code>pot[0]</code></li>
<li><code>part</code> is a global array of <code>struct</code></li>
<li><code>deltaE</code> (variable for summation-reduction) is a <code>REAL</code> global variable</li>
</ul>
<p>I know that, for a correctness, a special treatment of function <code>rand()</code> is also required;
but apart from that, are there some other important (conceptual) correction to do on the above parallelization? Which is limited at only one directive row?</p>
|
[] |
[
{
"body": "<p>There is nothing wrong with your code, but it can be improved somehow.</p>\n\n<p>First, automatic variables, defined in a scope that is outer to the parallel region, are automatically <code>shared</code>. Therefore the <code>default(shared)</code> clause is redundant.</p>\n\n<p>Second, the loop counter <code>k</code> has <em>predetermined</em> sharing class of <code>private</code> - you can safely omit it. Also you should declare all variables in the scope where they are used. In your case all variables except <code>k</code> can be declared in the parallel region. Such variables have predetermined sharing class of <code>private</code>.</p>\n\n<p>If you follow both of the above points, your OpenMP directive will be greatly simplified:</p>\n\n<pre><code>void func(REAL coeff, DATAMPOT *dmp, int a, int la, int b, int lb, REAL L)\n{\n int k;\n\n #pragma omp parallel for reduction(+:deltaE)\n for (k = 0; k < la*lb; ++k) {\n int j = k/la+b;\n int i = k%la+a;\n\n REAL dx = fabs(part[i].x-part[j].x);\n REAL dy = fabs(part[i].y-part[j].y);\n REAL dz = fabs(part[i].z-part[j].z);\n REAL dx2 = (dx<0.5?dx*dx:(1-dx)*(1-dx));\n REAL dy2 = (dy<0.5?dy*dy:(1-dy)*(1-dy));\n REAL dz2 = (dz<0.5?dz*dz:(1-dz)*(1-dz));\n REAL r = L*sqrt(dx2+dy2+dz2);\n\n DATAMPOT *ptr = dmp + NSPES*part[i].s+part[j].s;\n\n deltaE += coeff*(ptr->npot>1 ?\n mpot(r,ptr,((REAL)rand())/RAND_MAX) :\n ptr->pot[0](r,ptr->dp));\n }\n}\n</code></pre>\n\n<p>If you can use C99 constructs in your code, then you can even move the declaration of <code>k</code> inside the <code>for</code> loop, i.e.:</p>\n\n<pre><code>#pragma omp parallel for reduction(+:deltaE)\nfor (int k = 0; k < la*lb; k++) {\n ...\n}\n</code></pre>\n\n<p>Also make sure that none of the functions called inside the loop have visible side effects, i.e. they don't modify some shared global state in an unexpected and unsynchronised way.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T16:23:35.793",
"Id": "41106",
"Score": "0",
"body": "Many thanks Hristo Iliev. What about the use of rand() function inside the parallel region? May be more correct to use something like this: #pragma omp parallel{ srand(int(time(NULL)) ^ omp_get_thread_num()); #pragma omp for /*for loop ...*/ }"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T16:57:41.597",
"Id": "41108",
"Score": "0",
"body": "I assumed that you know how to threat it. `rand()` is not thread-safe as it modifies a global RNG state. You should use a separate PRNG for each thread (e.g. use the re-entrant version where the state is supplied explicitly) or serialise the access to the PRNG in a critical section. Proper initialisation and decorrelation of multiple PRNGs is a completely separate (research) topic. You could use current time + some large prime number times the thread ID."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T13:16:21.880",
"Id": "26528",
"ParentId": "26515",
"Score": "3"
}
},
{
"body": "<ul>\n<li><p>Try to come up with a better function name than <code>func()</code>. You are the one who understands this code the most, so you should know how to give it a relevant name.</p></li>\n<li><p>Try not to use single-character names, unless they're for a simple <code>for</code>-loop. It's hard to tell what they're for, especially without comments. If this ends up making the <code>#pragma</code> line even longer, then you can just split it into separate lines with a <code>\\</code> at the end of each line.</p></li>\n<li><p>It's a little hard to read lines lacking whitespace:</p>\n\n<blockquote>\n<pre><code>dx2=(dx<0.5?dx*dx:(1-dx)*(1-dx));\n</code></pre>\n</blockquote>\n\n<p>It's difficult to see the entire ternary statement, so add more whitespace:</p>\n\n<pre><code>dx2 = (dx < 0.5 ? dx*dx : (1-dx)*(1-dx));\n</code></pre>\n\n<p>This concept should be applied everywhere, especially each statement in the loop.</p>\n\n<p>Going back to the ternary, consider using an <code>if</code>/<code>else</code> here instead. Sure, this is a short ternary, but that doesn't mean it should always be used, especially if it's harder to read carefully.</p>\n\n<pre><code>if (dx < 0.5)\n{\n dx2 = dx * dx;\n}\nelse\n{\n dx2 = (1-dx) * (1-dx);\n}\n</code></pre></li>\n<li><p>This formatting is a bit hard to read:</p>\n\n<blockquote>\n<pre><code> deltaE += coeff*((dmp+NSPES*part[i].s+part[j].s)->npot>1?\nmpot(r,dmp+NSPES*part[i].s+part[j].s,((REAL)rand())/RAND_MAX):\n(dmp+NSPES*part[i].s+part[j].s)->pot[0](r,(dmp+NSPES*part[i].s+part[j].s)->dp ) );\n</code></pre>\n</blockquote>\n\n<p>At least reformat it to something like this:</p>\n\n<pre><code>deltaE += coeff*((dmp+NSPES*part[i].s+part[j].s)->npot>1\n ? mpot(r,dmp+NSPES*part[i].s+part[j].s,((REAL)rand())/RAND_MAX)\n : (dmp+NSPES*part[i].s+part[j].s)->pot[0](r,(dmp+NSPES*part[i].s+part[j].s)->dp));\n</code></pre>\n\n<p>However, this may still be too lengthy for a ternary. You could still use a plain <code>if</code>/<code>else</code> if it would help more with readability.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-11-15T07:18:36.647",
"Id": "127768",
"Score": "0",
"body": "Nice, but I would firmly recommend an if-else instead of that ternary, and put spaces around operators."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-11-15T07:20:41.483",
"Id": "127769",
"Score": "0",
"body": "@janos: Yeah, I could add that. I was mostly using that as an example of lack of whitespace, but there were other instances of it."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-11-13T19:28:44.240",
"Id": "69770",
"ParentId": "26515",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "26528",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T07:44:42.807",
"Id": "26515",
"Score": "4",
"Tags": [
"c",
"openmp"
],
"Title": "OpenMP parallelization of a for loop with function calls"
}
|
26515
|
<p>I am summing the total <code>.outerHeight()</code> of multiple <code>div</code>s like this:</p>
<pre><code>var h = $('#div1').outerHeight() + $('#div2').outerHeight() + $('#div3').outerHeight() + $('#div4').outerHeight();
</code></pre>
<p>Is there any way to do this more efficiently?</p>
<p>I was considering something like this (but it doesn't work):</p>
<pre><code>$('#div1, #div2, #div3').outerHeight();
</code></pre>
|
[] |
[
{
"body": "<p>You'll have to add a class to the <code>div</code>s to be able to select them all</p>\n\n<pre><code><div id=\"div1\" class=\"sumdiv\"></div>\n<div id=\"div2\" class=\"sumdiv\"></div>\n</code></pre>\n\n<p>Then, use <code>$.each()</code> (<a href=\"http://api.jquery.com/each/\" rel=\"nofollow\">http://api.jquery.com/each/</a>)</p>\n\n<pre><code>var sum = 0;\n$( \".sumdiv\" ).each(function( index ) {\n sum += $(this).outerHeight()\n});\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T09:42:21.830",
"Id": "26522",
"ParentId": "26518",
"Score": "2"
}
},
{
"body": "<p>A more functional approach, but it requires the browser to support <a href=\"https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/Reduce\" rel=\"nofollow\"><code>.reduce()</code></a></p>\n\n<pre><code>var sum = $('#div1, #div2, #div3').map(function () {\n return $(this).outerHeight();\n}).get().reduce(function (sum, value) {\n return sum + value;\n}, 0);\n</code></pre>\n\n<p>Or</p>\n\n<pre><code>var sum = $('#div1, #div2, #div3').get().reduce(function (sum, element) {\n return sum + $(element).outerHeight();\n}, 0);\n</code></pre>\n\n<p>Alternatively, for cross-browser support, you can use <a href=\"http://underscorejs.org/\" rel=\"nofollow\">underscore.js</a></p>\n\n<pre><code>var sum = _.reduce($('#div1, #div2, #div3').get(), function (sum, element) {\n return sum + $(element).outerHeight();\n}, 0);\n</code></pre>\n\n<p>But Topener's answer is straightforward, so you might as well go with that.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T14:01:26.753",
"Id": "26572",
"ParentId": "26518",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T08:22:47.627",
"Id": "26518",
"Score": "1",
"Tags": [
"javascript",
"performance",
"jquery"
],
"Title": "Summing outerHeight of multiple divs"
}
|
26518
|
<p>I made this Javascript to hide, show and change some DIVs but I believe it's not really good code. Can you help me to make it better?</p>
<pre><code>function colorM(n) {
switch(n){
case 1:
document.getElementById("slideM1").style.backgroundColor="#009CFF";
document.getElementById("slideM1").className="show";
document.getElementById("slideM2").style.backgroundColor="silver";
document.getElementById("slideM3").style.backgroundColor="silver";
document.getElementById("slideM4").style.backgroundColor="silver";
document.getElementById("slideM5").style.backgroundColor="silver";
document.getElementById("slideM2").className="";
document.getElementById("slideM3").className="";
document.getElementById("slideM4").className="";
document.getElementById("slideM5").className="";
document.getElementById("slideC1").style.display="block";
document.getElementById("slideC2").style.display="none";
document.getElementById("slideC3").style.display="none";
document.getElementById("slideC4").style.display="none";
document.getElementById("slideC5").style.display="none";
break;
case 2:
document.getElementById("slideM2").style.backgroundColor="#009CFF";
document.getElementById("slideM2").className="show";
document.getElementById("slideM1").style.backgroundColor="silver";
document.getElementById("slideM3").style.backgroundColor="silver";
document.getElementById("slideM4").style.backgroundColor="silver";
document.getElementById("slideM5").style.backgroundColor="silver";
document.getElementById("slideM1").className="";
document.getElementById("slideM3").className="";
document.getElementById("slideM4").className="";
document.getElementById("slideM5").className="";
document.getElementById("slideC1").style.display="none";
document.getElementById("slideC2").style.display="block";
document.getElementById("slideC3").style.display="none";
document.getElementById("slideC4").style.display="none";
document.getElementById("slideC5").style.display="none";
break;
case 3:
document.getElementById("slideM3").style.backgroundColor="#009CFF";
document.getElementById("slideM3").className="show";
document.getElementById("slideM1").style.backgroundColor="silver";
document.getElementById("slideM2").style.backgroundColor="silver";
document.getElementById("slideM4").style.backgroundColor="silver";
document.getElementById("slideM5").style.backgroundColor="silver";
document.getElementById("slideM1").className="";
document.getElementById("slideM2").className="";
document.getElementById("slideM4").className="";
document.getElementById("slideM5").className="";
document.getElementById("slideC1").style.display="none";
document.getElementById("slideC2").style.display="none";
document.getElementById("slideC3").style.display="block";
document.getElementById("slideC4").style.display="none";
document.getElementById("slideC5").style.display="none";
break;
case 4:
document.getElementById("slideM4").style.backgroundColor="#009CFF";
document.getElementById("slideM4").className="show";
document.getElementById("slideM1").style.backgroundColor="silver";
document.getElementById("slideM2").style.backgroundColor="silver";
document.getElementById("slideM3").style.backgroundColor="silver";
document.getElementById("slideM5").style.backgroundColor="silver";
document.getElementById("slideM1").className="";
document.getElementById("slideM2").className="";
document.getElementById("slideM3").className="";
document.getElementById("slideM5").className="";
document.getElementById("slideC1").style.display="none";
document.getElementById("slideC2").style.display="none";
document.getElementById("slideC3").style.display="none";
document.getElementById("slideC4").style.display="block";
document.getElementById("slideC5").style.display="none";
break;
case 5:
document.getElementById("slideM5").style.backgroundColor="#009CFF";
document.getElementById("slideM5").className="show";
document.getElementById("slideM1").style.backgroundColor="silver";
document.getElementById("slideM2").style.backgroundColor="silver";
document.getElementById("slideM3").style.backgroundColor="silver";
document.getElementById("slideM4").style.backgroundColor="silver";
document.getElementById("slideM1").className="";
document.getElementById("slideM2").className="";
document.getElementById("slideM3").className="";
document.getElementById("slideM4").className="";
document.getElementById("slideC1").style.display="none";
document.getElementById("slideC2").style.display="none";
document.getElementById("slideC3").style.display="none";
document.getElementById("slideC4").style.display="none";
document.getElementById("slideC5").style.display="block";
break;
default:
document.getElementById("slideM1").style.backgroundColor="#009CFF";
document.getElementById("slideM1").className="show";
document.getElementById("slideM2").style.backgroundColor="silver";
document.getElementById("slideM3").style.backgroundColor="silver";
document.getElementById("slideM4").style.backgroundColor="silver";
document.getElementById("slideM5").style.backgroundColor="silver";
document.getElementById("slideM2").className="";
document.getElementById("slideM3").className="";
document.getElementById("slideM4").className="";
document.getElementById("slideM5").className="";
document.getElementById("slideC1").style.display="block";
document.getElementById("slideC2").style.display="none";
document.getElementById("slideC3").style.display="none";
document.getElementById("slideC4").style.display="none";
document.getElementById("slideC5").style.display="none";
break;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T09:09:13.690",
"Id": "41077",
"Score": "1",
"body": "For starters: Instead of clearing the `className` of every div that you want to hide, assign a class name that already has the `background-color: 'silver'` and `display: none`. That alone saves you a lot of lines."
}
] |
[
{
"body": "<p>Loop through the ID's instead of doing a switch. This should do the same as yours</p>\n\n<pre><code>function colorM(id){\n\n // if not a number\n if (!(!isNaN(parseFloat(n)) && isFinite(n))) id =1;\n // default for numbers\n if (id > 5 || id < 1) id = 1;\n\n for (var i = 1; i <= 5; i++){\n\n if (id == i){\n document.getElementById(\"slideM\" + i).style.backgroundColor=\"#009CFF\";\n document.getElementById(\"slideM\" + i).className=\"show\";\n document.getElementById(\"slideC\" + i).style.display=\"block\";\n }\n else {\n document.getElementById(\"slideM\" + i).style.backgroundColor=\"silver\";\n document.getElementById(\"slideM\" + i).className=\"\";\n document.getElementById(\"slideC\" + i).style.display=\"none\";\n }\n }\n}\n</code></pre>\n\n<p>Edit: added a check if <a href=\"https://stackoverflow.com/a/1830844/249710\">id is numeric</a> AND id is within range </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T11:47:00.397",
"Id": "41084",
"Score": "0",
"body": "That's almost perfect but I need also default state. Which is explained in default case."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T13:10:10.250",
"Id": "41093",
"Score": "0",
"body": "The default is the same as `1`? So make it in such a way that if you are trying to `default` it, (it is not any of the 5) it'll give `1` to the function"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T13:13:52.563",
"Id": "41094",
"Score": "0",
"body": "added a check in it!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T10:29:04.180",
"Id": "26523",
"ParentId": "26519",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "26523",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T08:56:02.900",
"Id": "26519",
"Score": "1",
"Tags": [
"javascript",
"dom"
],
"Title": "Better way to hide, change and show DIVs in Javascript"
}
|
26519
|
<p>I just wrote this code to concatenate two wide characters strings. Could someone please comment if it looks OK? (seems to work at least).</p>
<pre><code>SomeStringClass amount = Window->get_text();
wchar_t strAmount[100] = L"Amount: "; // I know I could remove 100 from here too
wchar_t *ptr = wcscat( strAmount, amount.c_str() );
SomeStringClass final;
final.set(ptr, 10 /* 10 is roughly due to length of Amount line 2*/ + amount.length());
</code></pre>
<p>Now, <code>final</code> contains what I wanted (e.g. "Amount: 123").</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T12:12:29.040",
"Id": "41087",
"Score": "0",
"body": "Why not just use `std::wstring`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T12:14:51.770",
"Id": "41088",
"Score": "0",
"body": "@Yuushi: Instead of SomeStringClass? (I'll consider that). Just I am programming on a device and it has its own support of strings in the form of SomeStringClass"
}
] |
[
{
"body": "<p>Firstly, avoid the non-<code>n</code> versions of <code>(w)str_</code> functions. You've got a buffer overflow just begging to happen here - if <code>amount.length() > 100 - 8</code>, it'll overflow your buffer, causing undefined behaviour and general bad times. Use <code>wcsncat</code> instead:</p>\n\n<pre><code>static const unsigned kstrMax = 100;\nwchar_t strAmount[kstrMax] = L\"Amount: \";\nwchar_t* ptr = wcsncat(strAmount, amount.c_str(), kstrMax - amount.length() - 1);\n</code></pre>\n\n<p>In fact, we have to be even <strong>more</strong> careful here, because there's still a bug in the above code (I left it in because I only caught it when modifying my example - it's easy to make mistakes). Say <code>amount.length() > kstrMax</code>, then you'd think the value <code>kstrMax - amount.length()</code> would be below zero, but being unsigned, it will silently overflow, and will instead be some very large positive value, hence we could still easily overwrite the buffer size with this if <code>amount</code> is large enough.</p>\n\n<pre><code>static const unsigned kstrMax = 100;\nunsigned currentBufferSize = kstrMax;\nwchar_t strAmount[kstrMax] = L\"Amount: \";\nif(amount.length() >= kstrMax - 8) {\n //find out the difference, remake your buffer and copy across\n currentBufferSize = newBufferSize;\n}\nwchar_t* ptr = wcsncat(strAmount, amount.c_str(), currentBufferSize - amount.length());\n</code></pre>\n\n<p>From the looks of it, the amount entered is meant to be a small numeric value. Never assume anything about input. Anything that a user touches must be sanitized before you blindly use it. </p>\n\n<p><code>std::wstring</code> would make this fiddling about go away:</p>\n\n<pre><code>std::wstring strAmount(\"Amount: \");\nstrAmount += amount.c_str();\nfinal.set(strAmount.c_str(), strAmount.size());\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T12:43:26.523",
"Id": "26527",
"ParentId": "26524",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T11:37:47.393",
"Id": "26524",
"Score": "1",
"Tags": [
"c++",
"strings"
],
"Title": "Concatenating wide character strings"
}
|
26524
|
<p>I need to implement a system of queueing that extracts elements equally from <code>x</code> queues to one single queue with <code>y</code> positions.</p>
<p>Let's say I have 5 queues, each with a number of elements and I need to extract elements from each of the 5 queues to build a new queue containing the extracted elements until the new queue is full.</p>
<p>For example:</p>
<ul>
<li><p>5 queues to a queue with 100 positions. I need to extract 20 elements from each queue. Ok, but if some of the 5 input queues have less than 20 elements, the resulting queue will have some empty elements.</p></li>
<li><p>51 queues to a queue with 100 positions. I need to extract 1 element from each queue. The input queues have for sure at least 1 element. But the resulting queue will have 49 empty positions. So I'll need to iterate the input queues to extract 1 element from each one, until I reach the max 100 positions of the resulting queue.</p></li>
</ul>
<p>I need this to implement a system of sending queues to send massive SMSs form web for our customers. In those example, the 51 queues are 51 different SMS, inside each of these queues there are all the mobile numbers to send the sms to.</p>
<p>I can send only <code>$this->QueueMax</code> sms every 2 minutes, so I have a script that takes a number of mobile phones from all sms to send and send all sms in parallel.</p>
<p>I've implemented this PHP script to manage the final queue: at the end, <code>$smsToSend</code> will tell me how many mobile numbers to extract for each SMS in the 'limit' field.</p>
<p>Is that alright? Will the script work fine?</p>
<p>But most of all, is there a less-complex method of doing this?</p>
<pre><code> $query = 'SELECT sms_id, COUNT(DISTINCT mobile) AS tot_mobile ';
$query.= 'FROM sms_queue ';
$query.= 'GROUP BY sms_id ';
$this->Dbh->query($query);
$smsToSend = array();
while($this->Dbh->next()) {
$smsToSend[$this->Dbh->Record['sms_id']] = array(
'tot' => $this->Dbh->Record['tot_mobile'],
'limit' => 0,
);
}
/* The queue to send is empty */
if( empty($smsToSend) ) {
$this->IsSending = false;
return false;
}
/* Total phone numbers to take from each sms queue */
$totSmsToSend = count($smsToSend);
/* There are more sms to send than empty positions in the send queue; send only the firsts "QueueMax" sms */
if( $totSmsToSend > $this->QueueMax ) {
$smsToSend = array_slice($smsToSend, 0, $this->QueueMax, true);
$totSmsToSend = $this->QueueMax;
}
$totMobilesFromEachSms = (int)floor($this->QueueMax / $totSmsToSend);
foreach( $smsToSend as $smsID => $info ) {
$smsToSend[$smsID]['limit'] = ($totMobilesFromEachSms >= $info['tot']) ? $info['tot'] : $totMobilesFromEachSms;
}
/* If there are some empty positions, iterate $smsToSend and take 1 mobile number foreach sms 'till covering all empty positions */
if( ($totMobilesFromEachSms * $totSmsToSend) < $this->QueueMax ) {
$i = $totSmsToSend + 1;
while(true) {
$check = false;
foreach($smsToSend as $smsID => $info) {
if( $info['limit'] >= $info['tot'] ) {
continue;
}
$check = true;
$smsToSend[$smsID]['limit']++;
$i++;
if( $i >= $this->QueueMax ) {
break 2;
}
}
/* Each sms has all its phone numbers correctly placed inside the send queue*/
if( !$check ) {
break;
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>First off, you're code looks nice, but it can be improved in places:</p>\n\n<ol>\n<li><p>I don't see why:</p>\n\n<pre><code> $totSmsToSend = count($smsToSend);\n</code></pre></li>\n</ol>\n\n<p>Is indented so far, you should fix that. There's quite a few elements that have been over indented.</p>\n\n<ol start=\"2\">\n<li><p>Your constant use of the word <code>Sms</code> like so, seems a bit silly, as it as an acronym, you should stick to <code>SMS</code> or <code>sms</code> but don't mix cases.</p></li>\n<li><p><code>$tot</code>, You shouldn't leave out two characters, just for the purpose of slimming when it makes it much less readable.</p></li>\n<li><p>Your code seems really forced, so I think it could be improved in the method it goes about doing.</p></li>\n</ol>\n\n<p>Your solution really just sounds like basic division:</p>\n\n<ol>\n<li><code>Y / X</code>, rounded down to a whole number</li>\n<li>For leftover positions in <code>Y</code> queue, transfer <code>X(1), X(2), ... X(X)</code> and go through until you fill up the queue.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-06-28T01:04:31.873",
"Id": "94951",
"ParentId": "26530",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T14:22:35.037",
"Id": "26530",
"Score": "3",
"Tags": [
"php",
"queue"
],
"Title": "Extract equally from X queues to one queue with Y elements"
}
|
26530
|
<p>Is there any way I can DRY up this Rails 4 routes.rb code?</p>
<pre><code> match '/oauth/apps/' => 'oauth/applications#index', :as => :oauth_applications, :via => :get
match '/oauth/apps/new/' => 'oauth/applications#new', :as => :new_oauth_application, :via => :get
match '/oauth/apps/new/' => 'oauth/applications#create', :via => :post
match '/oauth/apps/:id/' => 'oauth/applications#show', :as => :oauth_application, :via => :get
match '/oauth/apps/:id/edit/' => 'oauth/applications#edit', :as => :edit_oauth_application, :via => :get
match '/oauth/apps/:id/edit/' => 'oauth/applications#update', :via => :post
match '/oauth/apps/:id/destroy/' => 'oauth/applications#destroy', :as => :destroy_oauth_application, :via => :delete
</code></pre>
|
[] |
[
{
"body": "<p>Yes, use <code>namespace</code> and <code>resources</code>:</p>\n\n<pre><code>namespace :oauth do\n resources :apps, controller: \"applications\", as: :applications\nend\n</code></pre>\n\n<p>This is not 100% identical (the names of some of your routes have changed) but it is the way you <em>should</em> be building your routes, and you should change the rest of your app to reflect the change.</p>\n\n<p>The primary difference is your names for the <code>create</code> and <code>destroy</code> routes have gone away; these routes <em>shouldn't have names anyways</em>. When you want to create/destroy a model, you should be using <code>oath_applications_path</code>, with <code>method: :post</code> or <code>method: :delete</code>, not <code>oath_apps_new_path</code>/<code>destroy_oauth_application_path</code>.</p>\n\n<p>My way also uses the correct verb (PUT) for updates.</p>\n\n<p>Your <code>rake routes:</code></p>\n\n<pre><code> oauth_applications GET /oauth/apps(.:format) oauth/applications#index\n new_oauth_application GET /oauth/apps/new(.:format) oauth/applications#new\n oauth_apps_new POST /oauth/apps/new(.:format) oauth/applications#create\n oauth_application GET /oauth/apps/:id(.:format) oauth/applications#show\n edit_oauth_application GET /oauth/apps/:id/edit(.:format) oauth/applications#edit\n POST /oauth/apps/:id/edit(.:format) oauth/applications#update\ndestroy_oauth_application DELETE /oauth/apps/:id/destroy(.:format) oauth/applications#destroy\n</code></pre>\n\n<p>My <code>rake routes</code> (reordered to match yours):</p>\n\n<pre><code> oauth_applications GET /oauth/apps(.:format) oauth/applications#index\n new_oauth_application GET /oauth/apps/new(.:format) oauth/applications#new\n POST /oauth/apps(.:format) oauth/applications#create\n oauth_application GET /oauth/apps/:id(.:format) oauth/applications#show\nedit_oauth_application GET /oauth/apps/:id/edit(.:format) oauth/applications#edit\n PUT /oauth/apps/:id(.:format) oauth/applications#update\n DELETE /oauth/apps/:id(.:format) oauth/applications#destroy\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T11:45:51.930",
"Id": "41150",
"Score": "0",
"body": "Wow thank you for this. I never thought of doing it this way and I guess doing things the conventional way is better then anything else."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T20:42:36.910",
"Id": "26546",
"ParentId": "26531",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "26546",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T14:28:36.083",
"Id": "26531",
"Score": "3",
"Tags": [
"ruby",
"ruby-on-rails"
],
"Title": "Clean up Rails Routes"
}
|
26531
|
<p>Consider a process composed of three algorithms: <em>makeRuns</em>, <em>meld</em> and <em>traverse</em> (each taking the output of the previous one as input): it is interesting to test each separately. Now consider three (or more) instances (e.g. <em>singleton</em>, <em>twoPairs</em>, <em>SimplePair</em>): it is interesting to test the behavior of the three algorithms on each of those instances. The result can be described as an array of (say) 3*3 tests. Is the code below the correct implementation of such a test? (I find the result of the tests to be lacking in clarity.)</p>
<pre><code>import unittest, doctest
import insertionRank
##############################################################################
class TestMTDRAG(unittest.TestCase):
def test_singleton(self):
"""Basic example [1]."""
run = makeRuns([1])
self.assertEqual(run,[Node(1,1)])
graph = meld(run)
self.assertEqual(graph,Node(1,1))
lengths=traverse(graph)
self.assertEqual(lengths,[1,0])
def test_TwoPairsExample(self):
"""Two messages of distinct probabilities [1,2]."""
run = makeRuns([1,2])
self.assertEqual(run,[Node(1,1),Node(2,1)])
graph = meld(run)
self.assertEqual(graph,Node(3,1,[Node(1,1),Node(2,1)]))
lengths=traverse(graph)
self.assertEqual(lengths,[0,2,0])
def test_SimplePairExample(self):
"""Basic example of four equiprobable messages [1,1,1,1]."""
run = makeRuns([1,1,1,1])
self.assertEqual(run,[Node(1,4)])
graph = meld(run)
self.assertEqual(graph,
Node(4,1,
[Node(2,2,[Node(1,4),Node(1,4)]),
Node(2,2,[Node(1,4),Node(1,4)])
]))
lengths=traverse(graph)
self.assertEqual(lengths,[0,0,4])
##############################################################################
class Node(object):
"""
A node in a MTDRAG (Moffat-Turpin Directed Rooted Acyclic Graph).
"""
def __init__(self, weight, frequency, children=[], minDepth=None, nbPathsAtMinDepth=0, nbPathsAtMinDepthPlusOne=0):
assert frequency>0
self.weight = weight
self.frequency = frequency
self.children = children
self.minDepth= minDepth
self.nbPathsAtMinDepth = nbPathsAtMinDepth
self.nbPathsAtMinDepthPlusOne = nbPathsAtMinDepthPlusOne
def computeDepths(self,depthParent=-1,nd=1,ndp1=0):
assert self.frequency>0
if self.minDepth==None: # Node is not yet labeled
self.minDepth = depthParent+1
self.nbPathsAtMinDepth = nd
self.nbPathsAtMinDepthPlusOne = ndp1
elif self.minDepth == depthParent: # Node labeled at same depth as parent
self.nbPathsAtMinDepthPlusOne += nd
else:
assert(self.minDepth==depthParent+1) # Node labeled at depth + 1 of parent
self.nbPathsAtMinDepth += nd
self.nbPathsAtMinDepthPlusOne += ndp1
if self.nbPathsAtMinDepthPlusOne > 0:
maxDepth = depthParent+2
else:
maxDepth = depthParent+1
for child in self.children:
maxDepth = max( maxDepth,
child.computeDepths(depthParent+1,self.nbPathsAtMinDepth,self.nbPathsAtMinDepthPlusOne)
)
return maxDepth
def collectDepths(self,M):
assert self.frequency>0
if self.children == []:
M[self.minDepth] += self.nbPathsAtMinDepth
M[self.minDepth+1] += self.nbPathsAtMinDepthPlusOne
else:
for child in self.children:
child.collectDepths(M)
def __eq__(self,node):
assert self.frequency>0
if node == None:
return False
assert node.frequency>0
return self.weight==node.weight and self.frequency == node.frequency and self.children == node.children
def __str__(self):
assert self.frequency>0
if self.children == None:
return "("+str(self.weight)+", "+str(self.frequency)+")"
else:
return "("+str(self.weight)+", "+str(self.frequency)+", "+str(self.children)+")"
def __repr__(self):
assert self.frequency>0
return self.__str__()
def copy(self):
assert self.frequency>0
return Node(self.weight,self.frequency,self.children,self.minDepth,self.nbPathsAtMinDepth,self.nbPathsAtMinDepthPlusOne)
##############################################################################
def makeRuns(A):
"""Compresses a list of INTEGER weights into a list of nodes, in
sublinear time (if all weights are not distinct).
"""
A.sort() # Linear if already sorted
output = []
position = 0
while position < len(A):
weight = A[position]
frequency = insertionRank.fibonacciSearch(A[position:],weight+1)
output.append(Node(weight,frequency))
position += frequency
return output
def meld(leaves):
"""Moffat and Turpin's algorithm to simulate van Leeuwen's
algorithm on a compressed representation of a list of weights.
"""
assert(len(leaves)>0)
graphs = []
source = leaves
first = source[0]
while first.frequency>1 or len(leaves)+len(graphs)>=2:
if first.frequency>1:
graphs.append(Node(first.weight*2,first.frequency//2,[first,first]))
if first.frequency %2 == 1:
first.frequency = 1
else:
source.remove(first)
else: #first.frequency == 1 but len(leaves)+len(graphs)>=2
source.remove(first)
source = min(s for s in (leaves,graphs) if s)
second = source[0]
assert(second.frequency>0)
if second.frequency==1:
source.remove(second)
graphs.append(Node(first.weight+second.weight,1,[first,second]))
else:
extract = second.copy()
extract.frequency=1
second.frequency -= 1
graphs.append(Node(first.weight+extract.weight,1,[first,extract]))
source = min(s for s in (leaves,graphs) if s)
first = source[0]
return(first)
def traverse(graph):
"""Computes an array containing the depth of the leaves of the
graph produced by the algorithm meld().
"""
if graph==None:
return None
maxDepth = graph.computeDepths()
M = [0]*(maxDepth+2)
graph.collectDepths(M)
return M
##############################################################################
def main():
unittest.main()
if __name__ == '__main__':
doctest.testmod()
main()
##############################################################################
</code></pre>
|
[] |
[
{
"body": "<p>You have recognized that each of the tree functions can be tested separately. In the context of unit testing this means that each function is a \"unit\". Now each of your tests tests all three functions. This has drawbacks:</p>\n\n<ul>\n<li>When a test fails, the name of the failing test does not tell you in which function the bug is.</li>\n<li>It seems to me that you have chosen the test inputs with <code>makeRuns</code> in mind. If you would instead make tests separately, you have better opportunity to consider corner cases of each function.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T09:14:16.547",
"Id": "41147",
"Score": "0",
"body": "The problem with dividing into 3 tests each of those above, is that a single problem with makeRuns will result into three fails. (I copied only my three first instances out of 10 or so, which aim more specifically to meld and traverse.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T09:21:36.253",
"Id": "41148",
"Score": "1",
"body": "@Jeremy It is normal that a single bug causes many tests to fail."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-25T04:49:46.513",
"Id": "41214",
"Score": "1",
"body": "I humbly assert that \"if you would *instead* make tests separately...\" should say \"you should *also* make some tests separately\". Meaning, of course you should test \"high level\" behavior, but you must test the \"core\" methods as Janne says."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T05:38:23.007",
"Id": "26556",
"ParentId": "26532",
"Score": "1"
}
},
{
"body": "<blockquote>\n <p>The result can be described as an array of (say) 3*3 tests. Is the code below the correct implementation of such a test? (I find the result of the tests to be lacking in clarity.)</p>\n</blockquote>\n\n<p>Build data structures to generate more tests instead of writing more test code.</p>\n\n<p>It strikes me that the amount of test code explodes with the need to test more involved graph complexity. Test code must be as thoughtfully architected as the target code to avoid all the bad things about poor OO design.</p>\n\n<p>Looks like your tests are basically the same except for hard coded method parameters. Make the method parameters variables then you can have a single test method.</p>\n\n<ol>\n<li>Design a data object that holds the parameters for your method calls in your test. Imagine a property for each parameter for each call - including the <code>assert</code>s.</li>\n<li>You might want to design a data object factory such that you simply pass in <code>Node</code> construction arguments, probably in some kind of array arrangement. </li>\n<li>One object for each test; bundle them all in a single collection of some kind.</li>\n<li>A driver that iterates the collection and passes each data object to...</li>\n<li>A method that maps the data to the method parameter variables. Then call the test methods.</li>\n</ol>\n\n<p>Now the test code stays small yet your tests are as variably complex as your data object collection. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-25T05:39:41.140",
"Id": "26596",
"ParentId": "26532",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T14:40:01.187",
"Id": "26532",
"Score": "2",
"Tags": [
"python",
"unit-testing"
],
"Title": "Two dimensional unit testing"
}
|
26532
|
<pre><code>def stopWatchSeconds(secondCnt) :
""" counts second for secondCnt seconds """
# is there a better way to do this?
startTime = time.clock()
ellapsed = 0
for x in range(0, secondCnt, 1) :
print "loop cycle time: %f, seconds cnt: %02d" % (ellapsed , x)
ellapsed = 1 - (time.clock() - startTime)
time.sleep(ellapsed)
startTime = time.clock()
</code></pre>
<p>I'm reviewing some source code for a buddy of mine and came across this function. I am very new to Python so it is more of a learning experience for me. I see that he put in a comment about is there a better way to do this. I started thinking about it, and I know how I would do it in C#, but since python is so much more laxed it does seem like this function could be improved. </p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T06:54:17.250",
"Id": "41142",
"Score": "1",
"body": "Could you give a little bit more info about the goal of this function? Is it for benchmarking, a timer, etc? Different goals might make different methods more appropriate. Also, time.clock() behaves differently on *nix systems vs Windows systems. What is the target platform?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T13:55:34.210",
"Id": "41167",
"Score": "0",
"body": "Well the the program is to test a port by sending data for x amount of seconds on a Android device."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-26T00:04:42.677",
"Id": "41261",
"Score": "1",
"body": "This seems like a reasonable approach to me (as a nitpick, elapsed should only have one 'l'). You might also be able to use the Python timeit module which has a default_timer that tracks wall clock time."
}
] |
[
{
"body": "<p>I'm not sure this code does what you think it does, at least on a *nix OS. <a href=\"http://docs.python.org/2.7/library/time.html#time.clock\" rel=\"noreferrer\">According to the documentation</a>, <code>time.clock()</code> returns <em>processor time</em>, which basically means that any time spent in <code>time.sleep()</code> is not counted. However, on Windows, <code>time.clock()</code> returns the actual time since it was first called. </p>\n\n<p>A better way to determine the time since the function was first called is to use <code>time.time()</code>, which returns the number of seconds since the <em>epoch</em>. We can still use <code>time.clock()</code> to determine the process time if we are using a *nix OS. (If you are using Windows, you may want to upgrade to Python 3.3 which introduces the platform independent function <code>time.process_time()</code>. (There may be another way to do it if you are using 2.x, but I don't know what it is.)</p>\n\n<pre><code>#!/usr/bin/python\nimport time\n\ndef stopwatch(seconds):\n start = time.time()\n # time.time() returns the number of seconds since the unix epoch.\n # To find the time since the start of the function, we get the start\n # value, then subtract the start from all following values.\n time.clock() \n # When you first call time.clock(), it just starts measuring\n # process time. There is no point assigning it to a variable, or\n # subtracting the first value of time.clock() from anything.\n # Read the documentation for more details.\n elapsed = 0\n while elapsed < seconds:\n elapsed = time.time() - start\n print \"loop cycle time: %f, seconds count: %02d\" % (time.clock() , elapsed) \n time.sleep(1) \n # You were sleeping in your original code, so I've stuck this in here...\n # You'll notice that the process time is almost nothing.\n # This is because we are spending most of the time sleeping,\n # which doesn't count as process time.\n # For funsies, try removing \"time.sleep()\", and see what happens.\n # It should still run for the correct number of seconds,\n # but it will run a lot more times, and the process time will\n # ultimately be a lot more. \n # On my machine, it ran the loop 2605326 times in 20 seconds.\n # Obviously it won't run it more than 20 times if you use time.sleep(1)\n\nstopwatch(20)\n</code></pre>\n\n<p>If you find the comments more confusing than helpful, here's a non-commented version...</p>\n\n<pre><code>#!/usr/bin/python\nimport time\n\ndef stopwatch(seconds):\n start = time.time()\n time.clock() \n elapsed = 0\n while elapsed < seconds:\n elapsed = time.time() - start\n print \"loop cycle time: %f, seconds count: %02d\" % (time.clock() , elapsed) \n time.sleep(1) \n\nstopwatch(20)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-03-14T22:47:58.410",
"Id": "298670",
"Score": "0",
"body": "Thanks for pointing out the \"processor time\" distinction! I was wondering why time.clock() was reporting sub-second times around a 15-second HTTP request."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-27T13:15:08.913",
"Id": "26669",
"ParentId": "26534",
"Score": "9"
}
}
] |
{
"AcceptedAnswerId": "26669",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T14:42:04.043",
"Id": "26534",
"Score": "6",
"Tags": [
"python"
],
"Title": "Is there a better way to count seconds in python"
}
|
26534
|
<p>I have this API to control some hardware. The API is not very well documented, but I've been able to make do with what I have. It is a API for a RFID device, but also has LED's on it that are controlled from the API.</p>
<p>So the idea is that this is a OPOS program. The RFID device opens/claims/and enables. When it is enabled I start a thread that polls the reader to see if there is a RFID card in the field. The user has the ability to turn on and off the LED's when ever they want by using a DirectIO call.</p>
<p>Here is the hard part. I've found that if i make concurrent calls to the API that the commands will give me back some gibberish (might be wrong word) answer. Valid messages returned are 0 to -7. We wrote a simple parser to run commands for us so we don't have to change the program it self to test for bugs. </p>
<pre><code>Open
Claim
AllEnable
LightOn(White,45)
</code></pre>
<p>that is the bit of code I use to test this bug. I can't seem to fix it, and I've concluded that my multithreaded skills are.. lacking.</p>
<p>In my second thread that is checking for the cards it works something like this.</p>
<pre><code>while (pSO->reader.m_bDeviceEnabled && !closeForAutoDisable)
{
if(pSO->reader.m_nState == OPOS_S_IDLE)
{
Sleep(10);
if (CheckCardTimeout(pSO->reader.readerID, pSO->reader.m_nCardDelay))
{
pSO->reader.SetState(OPOS_S_BUSY);
int state = CheckForCard(pSO);
pSO->reader.SetState(OPOS_S_IDLE);
</code></pre>
<p>I use the state to tell if the reader is potentially sending commands to the API.</p>
<p>I tried putting in a CCtricialSection in my reader class but when I compile it says cannot access private memdeclared in class 'CObject'. I find that stupid because in my main class it has a CCriticalSection declared with no problem. so I had to comment out the CCriticalSection and the 2 methods I tried to use in reader.SetState</p>
<pre><code>void SetState(LONG state)
{
//locker.Lock();
m_nState = state;
//locker.Unlock();
}
</code></pre>
<p>Now for the section is bothers me. The "LED" on the device is actually a RGB LED. So to get White i have to make 3 api calls to turn on Red Green and Blue. Same goes with any other color I want. Below is the code. I took out the boring non-relevant code.</p>
<pre><code>LONG ReaderHelper::SetLED(LONG duration, CString color)
{
m_nResultCode = OPOS_E_BUSY;
for(int i=0; i<300; i++)
{
if(m_nState==OPOS_S_IDLE)
{
SetState(OPOS_S_BUSY);
m_nResultCode = OPOS_SUCCESS;
break;
}
Sleep(1); //wait at most 300ms
}
if(m_nResultCode == OPOS_E_BUSY)
{
WRITE_ERROR("Reader busy");
return WRITE_ENDO(m_nResultCode);
}
LONG err = SetLED(color[0], LEDtimes, duration);
SetState(OPOS_S_IDLE);
return err;
}
LONG ReaderHelper::SetLED(char color, BYTE times, BYTE duration)
{
WRITE_START;
if (IsNotOpen())
return WRITE_ENDO(m_nResultCode);
//if(IsBusy())
// return WRITE_ENDO(m_nResultCode);
SetState(OPOS_S_BUSY);
switch(color)
{
case 'r':
case 'R':
SetAllLights(true, true, true, 0, LedOff);
m_nResultCode = SetAllLights(true, false, false, times, duration);
break;
case 'g':
case 'G':
SetAllLights(true, true, true, 0, LedOff);
m_nResultCode = SetAllLights(false, true, false, times, duration);
break;
case 'b':
case 'B':
SetAllLights(true, true, true, 0, LedOff);
m_nResultCode = SetAllLights(false, false, true, times, duration);
break;
case 'y':
case 'Y':
SetAllLights(true, true, true, 0, LedOff);
m_nResultCode = SetAllLights(true, true, false, times, duration);
break;
case 'o':
case 'O':
SetAllLights(true, true, true, 0, LedOff);
m_nResultCode = SetAllLights(true, true, false, times, duration);
break;
case 'c':
case 'C':
SetAllLights(true, true, true, 0, LedOff);
m_nResultCode = SetAllLights(false, true, true, times, duration);
break;
case 'p':
case 'P':
SetAllLights(true, true, true, 0, LedOff);
m_nResultCode = SetAllLights(true, false, true, times, duration);
break;
case 'w':
case 'W':
SetAllLights(true, true, true, 0, LedOff);
m_nResultCode = SetAllLights(true, true, true, times, duration);
break;
}
return m_nResultCode;
}
LONG ReaderHelper::SetAllLights(bool red, bool green, bool blue, BYTE times, BYTE duration)
{
//there is not State checking or setting with this method because of concurrency
TurnOffAntenna();
LONG rc = OPOS_SUCCESS;
if(red)
{
rc |= GetError(TrySetLight(RedLed, times,duration));
}
if(blue)
{
rc |= GetError(TrySetLight(BlueLed, times, duration));
}
if (green)
{
rc |= GetError(TrySetLight(GreenLed, times, duration));
}
return rc;
}
int ReaderHelper::TrySetLight(BYTE led, BYTE blinks, BYTE duration)
{
int rc = LIB_SUCCESS;
//tried different time to try.. sticking with one for now
for(int i=0; i<1; i++)
{
rc = rf_Reader_SetLed(readerID, led, blinks,duration);
if(rc==LIB_SUCCESS)
break;
}
return rc;
}
</code></pre>
<p>The code at top that should turn the light white for 450ms. If I run that code in a completly non-OPOS environment all by itself it will flash white a billion times with no problems. In the multi-threaded OPOS program..it does strange things. most frequently red turns on first for a moment then green and blue turn on and then turn off at different intervals. (results vary, but this is most typical) I do know that the calls to the LED's are asynchronous (they have to be to allow for different color combo's) but I am completly lost as to how to block other API calls from my other threads until the coast is clear. Any suggestions?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-10-01T10:02:25.210",
"Id": "194635",
"Score": "0",
"body": "There's too little to really understand what this is about. You claim multithreading; I do not see anything threading. And by-the-way what is OPOS?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-10-01T12:03:02.927",
"Id": "194667",
"Score": "0",
"body": "@BogdanWilli I mention threading a few times in the question, but I don't show any of the code that does the actual spinning up of any threads... Which after reading this question again I think it doesn't fit the bill of a proper question for this site I believe. I have since thrown all that C++ code away and re-wrote it in C#. The problem also ended up resolving itself because the user changed their mind. As for OPOS, it's now called UPOS and stands for Point Of Service (you've probably heard of it as Point Of Sale): Essentially it's a set of interfaces you use/implement for the retail world."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-10-02T16:02:41.230",
"Id": "194877",
"Score": "0",
"body": "There exists a world beyond Windows. I never came across OPOS despite programming for Windows for years. You know that you can include links in your questions (and also edit your questions) You could turn it into a C# question if the problem still exists. The idea here on [CodeReview](https://codereview.stackexchange.com/) is to provide more complete code examples. If you have more specific question it is probably better to ask them on [stackoverflow](https://stackoverflow.com/). Unfortunately I'm not a C# guy."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T15:24:37.580",
"Id": "26538",
"Score": "1",
"Tags": [
"c++",
"multithreading"
],
"Title": "Multi threaded API calls problem"
}
|
26538
|
<p>The <a href="http://community.topcoder.com/stat?c=problem_statement&pm=1835&rd=4655" rel="nofollow">TopCoder question</a> specifies (in summary):</p>
<blockquote>
<p>Two words are considered rhyming if they have the same ending pattern (defined below). This comparison is case-insensitive (see Example 1.)</p>
<p>An ending pattern is a substring of a word such that:</p>
<ol>
<li>The word ends with that substring,</li>
<li>The substring contains exactly one contiguous string of vowels,</li>
<li>The first letter of the substring is a vowel, and</li>
<li>The substring must either be the whole string, or the letter immediately preceding the start of the substring must be a nonvowel.</li>
</ol>
<p>For example, the ending pattern of "bought" is "ought", the ending pattern of "spying" would be "ying", and the ending pattern of "all" would be "all". (Note that "spy" has no vowels, and thus is not a legal word.)</p>
<p>Example 1:</p>
<pre><code>{" ",
"Measure your height",
"AND WEIGHT ",
"said the doctor",
"",
"And make sure to take your pills",
" to cure your ills",
"Every",
"DAY"}
</code></pre>
<p>Returns: <code>" aab ccde"</code><br>
Even though "height" and "weight" don't actually rhyme in English, they do by the rules laid out above.</p>
</blockquote>
<p>I want to get general feedback and feedback about if I can make this more Ruby-like, if there are any obvious inefficiencies, and if I need to organize my class differently.</p>
<pre><code>#!/usr/bin/env ruby -w
require 'set'
class Poetry
def find_ending(str)
vowels = Set.new(['a', 'e', 'i', 'o', 'u'])
vowel_seen = false
ending = ""
str.reverse.each_char.with_index do |c, i|
if vowels.include?(c) or
(c == 'y' and i != 0 and i != str.length-1)
vowel_seen = true
ending = c + ending
elsif !vowel_seen
ending = c + ending
else
break
end
end
ending
end
def rhyme_scheme(poem_array)
scheme = ""
next_label = 'a'
ending_labels = {}
poem_array.each do |line|
if line.strip.empty?
scheme += ' '
else
word = line.split(' ')[-1]
ending = self.find_ending(word.downcase)
label = ending_labels[ending]
if label.nil?
scheme += next_label
puts ending_labels
ending_labels[ending] = next_label
puts ending_labels
if next_label == 'z'
next_label = 'A'
else
next_label = next_label.next
end
else
scheme += label
end
end
end
scheme
end
end
poetry = Poetry.new
poem_array = ["I hope this problem",
"is a whole lot better than",
"this stupid haiku"]
puts "'#{poetry.rhyme_scheme(poem_array)}'"
</code></pre>
|
[] |
[
{
"body": "<p>Instead of commenting on your code, I felt I had to make a rewrite. Your code is very hard to understand because of characteristics like:</p>\n\n<ul>\n<li>Your methods contain a lot of functionality</li>\n<li>Using a class without reason (e.g. no use of internal state, a lot of things being done in one class)</li>\n<li>Your loops are very confusing, a lot is being done in each of them</li>\n</ul>\n\n<p>I'm aware Topcoder is a competition platform to compete in fast code, not good code, but it seems from your question you want to learn to write better Ruby code and have simply chosen a challenging situation of doing so.</p>\n\n<p>This is not what I would write in a competitive environment, but may start to approach how I'd design it in a commercial application where good code is preferred is often to fast code. I've tried to break down things, so each method does as little as possible and is fairly easy to understand. Iterations upon my code would include a better way to handle the <code>'a-z' => 'A-Z'</code> transition as well as figuring out a better way to do <code>Line#ending</code>.</p>\n\n<pre><code>require 'set'\n\nclass Poem\n attr_accessor :lines\n\n def initialize\n @rhymes = {\"\" => \" \"}\n @lines = []\n end\n\n def rhymes\n @lines.map { |line| @rhymes[line.ending] ||= next_id }\n end\n\n def lines=(lines)\n @lines = lines.map { |line| Line.new(line) }\n end\n\n private\n\n def next_id\n fix_last_id(@rhymes.values.last)\n end\n\n def fix_last_id(last)\n return 'a' if last == ' '\n return \"A\" if last == 'z'\n last.next\n end\n\n public\n\n class Line\n VOWELS = Set.new(['a', 'e', 'i', 'o', 'u'])\n\n def initialize(line)\n @line = line.downcase\n @last_word = @line.split.last || \"\"\n end\n\n def ending\n last_vowel = nil\n\n reverse_last_word.chars.select.each_with_index do |character, index|\n if !last_vowel || vowel_after_vowel?(last_vowel, index)\n last_vowel = index if vowel?(index)\n character\n end\n end.reverse.join\n end\n\n private\n def reverse_last_word\n @reverse_last_word ||= @last_word.reverse\n end\n\n def vowel_after_vowel?(last_vowel, index)\n (index - last_vowel == 1 && vowel?(index))\n end\n\n def vowel?(index)\n VOWELS.include?(reverse_last_word[index]) || y_vowel?(index)\n end\n\n def y_vowel?(index)\n reverse_last_word[index] == 'y' && (1...@last_word.size).include?(index)\n end\n end\nend\n\npoem = Poem.new\n\npoem.lines = [\n \"One bright day in the middle of the night\",\n \"Two dead boys got up to fight\",\n \"Back to back they faced each other\",\n \"Drew their swords and shot each other\",\n \"\",\n \"A deaf policeman heard the noise\",\n \"And came to arrest the two dead boys\",\n \"And if you dont believe this lie is true\",\n \"Ask the blind man he saw it too\"\n]\n\nputs poem.rhymes.join\n</code></pre>\n\n<p>I haven't tried to upload it anywhere to check whether it is correct, however, it passes the public test cases.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T18:05:32.673",
"Id": "41186",
"Score": "0",
"body": "Need moar defs!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T19:08:14.760",
"Id": "41191",
"Score": "0",
"body": "@Nakilon :-) :-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-03T18:30:32.397",
"Id": "68765",
"Score": "2",
"body": "The constructor creates an object in a not-very-useful state. It would be better if the constructor accepted lines of text."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T20:12:02.830",
"Id": "26544",
"ParentId": "26541",
"Score": "7"
}
},
{
"body": "<p>I am a bit late, I hope the answer is still useful. Some notes:</p>\n\n<ul>\n<li>First, my <a href=\"https://codereview.stackexchange.com/users/2607/tokland?tab=answers\">tradicional advice</a>: don't use imperative programming! I mean, it's ok if you are writing assembler or C, but in a language like Ruby you're squandering its potential. Try to learn to program in <a href=\"https://github.com/tokland/tokland/wiki/RubyFunctionalProgramming\" rel=\"nofollow noreferrer\">functional style</a>, favouring the good old math expressions (with its abstractions, immutability, higher-order functions, modulatization and many other cool things).</li>\n<li>I'd use regular expressions to get the rhyming substring of each verse, no custom code can beat their compactness and expression power.</li>\n<li>There are two ways of solving the problem, one is traversing the verses only once, folding the verses into an output. The second one is more modular, traverse the verses to build the intermediate data structures needed to calculate the solution. This second approach is, in this case, less verbose.</li>\n</ul>\n\n<p>I'd write (second approach):</p>\n\n<pre><code>def rhyme_scheme(verses)\n ending_regexp = /((?:[aeiou]|\\By\\B)+[^aeiou]*)$/\n endings = verses.map { |verse| verse.strip.downcase[ending_regexp, 1] }\n ending_scheme_pairs = endings.uniq.compact.zip([*\"a\"..\"z\", *\"A\"..\"Z\"])\n schemes = ending_scheme_pairs.to_h.merge(nil => \" \")\n schemes.values_at(*endings).join\nend\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-29T19:13:23.700",
"Id": "26764",
"ParentId": "26541",
"Score": "9"
}
}
] |
{
"AcceptedAnswerId": "26544",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T16:16:03.723",
"Id": "26541",
"Score": "8",
"Tags": [
"strings",
"ruby"
],
"Title": "Determine a poem's rhyme scheme"
}
|
26541
|
<p>I've been writing this data structure for a few days, and now I'm really curious about what it actually is, and to get some critique on my logic. </p>
<p>A branch, based on this usage, exists when a <code>HEAD</code> node contains at least one node of the same type referenced. </p>
<p>The purpose of the structure is to have branches that are arranged by type. Each node on the branch has a reference to the next node on the branch (always of the same type) and an entry point to a <code>Subdata</code> branch. <code>Subdata</code> in this case being an instance of a class that inherits from the <code>AchievementNode</code>. When <code>subdata</code> is added and it is the first of it's kind on that branch it has the <code>HEAD</code> tag applied to it, additionally, it also has a tag that contains the metadata of the type of data contained (to bypass the <code>typeof</code> calls). </p>
<p>Implementation:</p>
<pre><code>public abstract class AchievementNode : ScriptableObject
{
public enum NodeTypes
{
NONE = 0x0,
HEAD = 0x1,
TAIL = 0x2,
TYPE = 0x4,
DATA = 0x8,
LEVEL = 0x16,
GLOBAL = 0x32
}
public NodeTypes nodeType;
public AchievementNode nextOfType;
public AchievementNode headOfSubnode;
public void OnEnable ()
{
hideFlags = HideFlags.HideAndDontSave;
}
public virtual void Init(NodeTypes type, int enumData)
{
nodeType = type;
}
protected void AddNode(NodeTypes type, AchievementNode originNode, AchievementNode newNode)
{
//Create SubNode branch notch when types mismatch.
if((originNode.nodeType & type) != type)
{
//If Has subNode Data Run to the end and assign new node
if(originNode.headOfSubnode!=null)
{
newNode.nodeType = type | NodeTypes.TAIL;
AppendToTail(type,GetEndOfBranch(originNode.headOfSubnode),newNode);
}//Search for proper SubNodeTypes then add. Wicked Recursion warning here...
else if((originNode.headOfSubnode.nodeType & type) != type)
{
Debug.LogError("Do Gnarly Search To Find!");
return;
}//Doesn't have subnode... add new Subnode.
else
{
newNode.nodeType = type | NodeTypes.HEAD | NodeTypes.TAIL;
originNode.headOfSubnode = newNode;
}
}
else
{
//Add to the current branch
newNode.nodeType = type | NodeTypes.TAIL;
AppendToTail(type,GetEndOfBranch(originNode),newNode);
}
}
private void AppendToTail(NodeTypes type,AchievementNode tailNode, AchievementNode newNode)
{
if((tailNode.nodeType & NodeTypes.HEAD) == NodeTypes.HEAD)
{
tailNode.nodeType = tailNode.nodeType | type;
}
else
{
tailNode.nodeType = type;
}
tailNode.nextOfType = newNode;
}
protected AchievementNode GetEndOfBranch(AchievementNode currentNode)
{
//Special Case where Node is HEAD and TAIL.
if((currentNode.nextOfType.nodeType & NodeTypes.TAIL) != NodeTypes.TAIL)
{
return GetEndOfBranch(currentNode.nextOfType);
}
else
{
return currentNode;
}
}
protected void SetType(NodeTypes type)
{
nodeType = type;
}
protected virtual AchievementNode FindInHierarchy(NodeTypes nodeCheck, AchievementNode currentNode)
{
if(currentNode == null)
{
return null;
}
else if((currentNode.nodeType & nodeCheck) == nodeCheck)
{
return currentNode;
}
else
{
return FindInHierarchy(nodeCheck,currentNode.nextOfType);
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T20:11:47.563",
"Id": "41120",
"Score": "0",
"body": "Looks like a type of Priority Queue to me."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T05:26:47.213",
"Id": "41139",
"Score": "0",
"body": "Just a side note: why do you `else` after a `return`? It is useless, `return` exits the code path."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T22:57:30.103",
"Id": "41206",
"Score": "0",
"body": "Sounds a bit like a LinkedList meets Tree Structure. LinkedTree ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T23:15:10.587",
"Id": "41209",
"Score": "0",
"body": "I guess you could say that! @_@ I finished the implementation today and I'm really pleased with the tag based lookups. I'll end up posting the source soon. @fge What if that return is never hit?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-25T12:16:52.850",
"Id": "41229",
"Score": "0",
"body": "@TylerDavidKirk well, the return is hit only if the condition is true; if it is not hit, the branch is not taken?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-25T23:27:42.000",
"Id": "41260",
"Score": "0",
"body": "Oh man! I see exactly what you're saying now... That is a goof on my part."
}
] |
[
{
"body": "<ol>\n<li>Why do you have HEAD and TAIL NodeTypes? Doesn't their position on the branch tell you that?</li>\n<li>I'm concerned that you have structure traversal code infused into <code>AchievementNode</code> class. Classically the structure - tree, queue, List, etc. - is independent of the objects it holds. I would think greatly upon using something like <code>Dictionary<T></code>, <code>List<T></code>, etc. <em>Use that structure's inherent reference/traversal features in the context of <code>NodeType</code></em>. - wrapping (inheriting?) that structure along with your concept of <code>NodeType</code> into a class that is essentially a <code>MyNodes<AcheivementNode></code> class. I wonder, is <code>MyNodes<NodeType></code> what you are really building? In any case I suspect the separation of concerns will make the <code>NodeType</code> idea standout better conceptually and architecturally.</li>\n<li>How many palaces do you have <code>NodeType</code> defined I wonder. Why is <code>NodeType</code> enum defined inside <code>AchievementNode</code>? That's unusual. You want it hidden from client code? I don't think so since you have method parameters of <code>NodeType</code>. </li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-08T22:43:15.823",
"Id": "42195",
"Score": "0",
"body": "1. The HEAD and TAIL NodeTypes are intended usage in the custom GUI that comes with it. I thought it would be quicker than searching the branch every time I wanted to see where it was on the branch. Aren't bitwise operations supposed to be super fast?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-08T22:44:59.987",
"Id": "42196",
"Score": "0",
"body": "2. You definitely made something click in my brain with this comment. I would really love to go back and refactor. It makes a lot more sense to isolate traversal methods in a generic class. That sounds incredibly reusable and flexible."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-08T22:46:36.837",
"Id": "42197",
"Score": "0",
"body": "3. NodeType is only defined within this class, as it only pertains to data that this class wants. It's referenced often but only internally for sorting and searching."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-08T18:39:13.393",
"Id": "27178",
"ParentId": "26543",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "27178",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T19:45:08.433",
"Id": "26543",
"Score": "2",
"Tags": [
"c#",
"recursion",
"linked-list",
"queue"
],
"Title": "What is this structure called?"
}
|
26543
|
<p>I have this class that pulls people out of a database. I want it to be a little prettier and function better.</p>
<pre><code><?php
class comps extends db_config {
public $output = array();
private $arr = array();
public $area;
public $me;
public $options = array();
public function __construct() {
$this->pdo = new PDO('mysql:host='.$this->_host.';dbname='.$this->_db.';charset='.$this->_charset, $this->_user, $this->_pass);
}
public function __toString() {
return var_dump($this->result());
}
public function result() {
return $this->output;
}
public function setoption($option, $value) {
array_push($this->options, array($option=>$value));
}
public function run() {
$where = array();
$limit = '';
$showMe = '';
if (isset($this->options['admin'])) {
$where[] = "admin = '".$this->options['admin']."'";
}
if (isset($this->options['area'])) {
$where[] = "area = '".$this->area."'";
}
if (isset($this->options['showMe']) && $this->options['showMe'] = true) {
$showMe = "AND missionary <> '".$this->me."'";
}
if (isset($this->options['limit'])) {
$limit = " LIMIT ".$this->options['admin'];
}
if (count($where) > 0) {
$where = implode(' AND ', $where);
} else {
$where = '';
}
$area = isset($this->area) ? $this->area : '';
if ($area != '') {
$sth = $this->pdo->prepare("SELECT missionary FROM missionary_areas WHERE area_uid = :area AND missionary_released = '0' ".$showMe);
$sth->bindParam(':area', $area);
$sth->execute();
$sth->setFetchMode(PDO::FETCH_OBJ);
while ($mis = $sth->fetch()) {
$sth2 = $this->pdo->prepare("SELECT * FROM missionarios WHERE ".$where." mid = :mid LIMIT 1");
$sth2->bindParam(':mid', $mis->missionary);
$sth2->execute();
$this->arr[] = $sth2->fetch(PDO::FETCH_ASSOC);
}
foreach($this->arr as $a) {
array_push($this->output, $a);
}
} else {
$sth = $this->pdo->prepare("SELECT * FROM missionarios ".$where.$limit);
$sth->execute();
$res = $sth->fetchAll(PDO::FETCH_ASSOC);
foreach($res as $a) {
array_push($this->output, $a);
}
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T20:34:58.237",
"Id": "41121",
"Score": "3",
"body": "This is a bug: `... && $this->options['showMe'] = true`, I believe you meant to use `==`."
}
] |
[
{
"body": "<p>Here's the code smells:</p>\n\n<ol>\n<li>The <code>new</code> keyword in a class definition</li>\n<li>A <code>result()</code> method and <code>$output</code> attribute for data created by single method</li>\n<li>A very long, ambiguous method: <code>run</code></li>\n<li>Two mostly-different SQL statements separated by an <code>if-else</code></li>\n</ol>\n\n<p>And here's what I'd do to eliminate them:</p>\n\n<ol>\n<li>Move the PDO object to a constructor argument (see below) so you're not violating the Law of Demeter (see <a href=\"http://misko.hevery.com/2008/07/30/top-10-things-which-make-your-code-hard-to-test/\" rel=\"nofollow\">#1 and 2 here</a>)</li>\n<li>Remove <code>result()</code> altogether and simply return the result from the method in which it's built.</li>\n<li>Break this into smaller, more meaningful methods based on responsibility (see #4 below)</li>\n<li>Create <code>getMissionaryByArea()</code> and <code>getAllMissionaries()</code> methods with optional parameters</li>\n</ol>\n\n<p>Here's what my code might look like:</p>\n\n<pre><code><?php\n\n/**\n * This class name is ambiguous.\n * I'm not sure what it means, so I cannot suggest a better name.\n */\nclass comps { \n\n public function __construct(PDO $pdo) {\n $this->pdo = $pdo;\n }\n\n public function getMissionariesByArea($area, $admin_id=false, $omit_missionary_id=false, $limit=100) {\n $sql = <<<'ENDSQL'\n SELECT m.*\n FROM missionarios m\n JOIN missionary_areas ma ON ma.missionary = m.mid\n WHERE ma.area_uid = :area \n AND ma.missionary_released = '0'\n LIMIT :limit\nENDSQL;\n $params = [\n 'area' => $area,\n 'limit' => $limit\n ];\n\n if ($omit_missionary_id) { \n $sql .= ' AND ma.missionary <> :omit_missionary_id';\n $params['omit_missionary_id'] = $omit_missionary_id;\n }\n\n if ($admin_id) {\n $sql .= ' AND m.admin = :admin_id';\n $params['admin_id'] = $admin_id;\n }\n\n $sth = $this->pdo->prepare($sql);\n $sth->execute($params);\n return $sth->fetchAll();\n }\n\n public function getAllMissionaries($admin_id=false, $limit=100) {\n $sql = 'SELECT * FROM missionarios';\n $params = ['limit' => $limit];\n\n if ($admin_id) {\n $sql .= ' AND admin = :admin_id';\n $params['admin_id'] = $admin_id;\n }\n\n $sth = $this->pdo->prepare($sql);\n $sth->execute($params);\n return $sth->fetchAll();\n }\n}\n</code></pre>\n\n<p>I can revise if I've missed something in my refactoring.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T18:29:30.790",
"Id": "41188",
"Score": "0",
"body": "I'm getting `Parse error: syntax error, unexpected '<<' (T_SL)`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T22:33:27.913",
"Id": "41205",
"Score": "0",
"body": "`<<<EOL;` is incorrect. besides using something more meaningful than \"EOL\", you dont put a semicolon there. @sun-tzu try removing the semicolon."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T23:07:01.887",
"Id": "41207",
"Score": "1",
"body": "Thanks Hiroto! I've corrected this and also changed it from heredoc to nowdoc to be positively sure SQL injection won't happen."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T18:11:06.257",
"Id": "26582",
"ParentId": "26545",
"Score": "4"
}
},
{
"body": "<p>I completely agree with the answer from <strong>John Syrinek</strong>, but there is one more thing I would like to point out.</p>\n\n<p><strong>The issue</strong></p>\n\n<p>I think your implementation of <code>__toString()</code> is somewhat buggy. The function <code>var_dump</code> does not return anything and since the magic method <code>__toString</code> <em>must</em> return a string, I consider this an error. </p>\n\n<p>The consider a scenario where you cast this class into a string and concatenate the returned value onto another string. You would not be appending anything, but the output would be populated with HTML from the <code>var_dump()</code> call.</p>\n\n<p><strong>A possible solution</strong></p>\n\n<p>You could fetch an array of the different names of each person and use the <code>implode()</code> native PHP method to make a pretty string you could return.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-04-26T19:22:49.397",
"Id": "159356",
"Score": "1",
"body": "[`print_r(…, TRUE)` and `var_export(…, TRUE)`](http://stackoverflow.com/q/5039431/1157100) serve a similar purpose to `var_dump(…)`, but they can return a string."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-04-26T18:29:02.323",
"Id": "88057",
"ParentId": "26545",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "26582",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T20:31:57.757",
"Id": "26545",
"Score": "2",
"Tags": [
"php",
"pdo"
],
"Title": "Pulling people out of a database"
}
|
26545
|
<p>I am diving into Scala (using 2.10) headfirst and am trying out a simple task of taking bulk data and then doing something with that stream. The first part is generating that stream. I have seem to be able to cobble together what seems to work, but I think I am missing shortcuts in scala. Any pointers or code cleanup recommendations are welcome! I feel like <code>getInnerPolygons</code> could be simplified using a <code>match</code> statement, but I haven't gotten my head around those yet.</p>
<p>So, the process: With gdal, you retrieve a dataset, then retrieve the layer. From the layer, you can iterate over the features. From those features, you can get the geometries from each feature. Now, most features are just one polygon. If it is, take the outer ring of that polygon and pass it up the line. If the polygon is multi-part (think the hawaii islands as one "feature" where each island is a polygon), retrieve the polygons, then split that into their individual outer rings (this is that recursive call into <code>getInnerPolygons</code>).</p>
<p>Again: any Scala best practices or shortcuts that I missed. I would love to hear about.</p>
<pre><code>def getInnerPolygons(geometry: Geometry) : Iterator[Geometry] = {
Iterator
.range(0,geometry.GetGeometryCount())
.flatMap(i=>{
val innerGeometry = geometry.GetGeometryRef(i)
if(innerGeometry.GetGeometryName().equals("LINEARRING"))
Iterator.single(innerGeometry)
else
getInnerPolygons(innerGeometry)
})
}
def getPolygons(layer : Layer) : Iterator[Geometry] = {
Iterator.continually[Feature](layer.GetNextFeature())
.takeWhile(_!=null)
.flatMap(feature=>getInnerPolygons(feature.GetGeometryRef()))
}
def main(args: Array[String]){
ogr.RegisterAll()
val dataSet = ogr.Open("myshapefile.shp")
val layer = dataSet.GetLayer(0)
for(i <- getPolygons(layer)) println(i.GetGeometryName())
println("Done")
}
</code></pre>
|
[] |
[
{
"body": "<p>Two thoughts:</p>\n\n<ol>\n<li><p>I doubt that <code>getInnerPolygons</code> is tail recursive, because the\nrecursive call to <code>getInnerPolygons</code> within <code>flatMap</code> is not the\nlast statement to be executed. This is <code>flatMap</code> itself (but I may\nbe wrong). Recursive calls to functions which are not tail recursive\ncan lead to a stack overflow, when recursion is going deeper. In\nthis case recursion can't be eliminated by the compiler.</p></li>\n<li><p>You could write</p>\n\n<pre><code>(0 to geometry.GetGeometryCount())\n</code></pre>\n\n<p>instead of</p>\n\n<pre><code>Iterator.range(0, geometry.GetGeometryCount())\n</code></pre>\n\n<p>to create a range. This is slightly shorter.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-03T11:52:54.013",
"Id": "26917",
"ParentId": "26547",
"Score": "1"
}
},
{
"body": "<p>micro changes:\nuse == instead of equals because \"==\" means \"equals\".</p>\n\n<p>Scala does not follow the Java convention of prepending set/get to mutator and accessor methods.</p>\n\n<p>Try to split different parts of work (abstraction)</p>\n\n<pre><code>def innerPolygons(geometry: Geometry) : Iterator[Geometry] =\n innerGeometry(geometry).flatMap(inner)\n\ndef innerGeometry(geometry: Geometry): Iterator[Geometry]=\n (0 to geometry.GetGeometryCount()).map(geometry.GetGeometryRef(_))\n\ndef inner:Geometry => Iterator = g => if (\"LINEARRING\"== g.GetGeometryName()) \n Iterator.single(g) \n else \n innerPolygons(g)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-13T21:20:19.397",
"Id": "29706",
"ParentId": "26547",
"Score": "3"
}
},
{
"body": "<p>I agree with the answer from @Adi Stadelmann. Here is my take on it. </p>\n\n<p>I used <code>List</code> instead of <code>Iterator</code> since I believe it is a lot more common in Scala. I created \"monkey patching\" methods to create a <code>List</code> for the sub-elements of both <code>Layer</code> and <code>Geometry</code>.</p>\n\n<p>In the original implementation of <code>getInnerPolygons</code>, the <code>Geometry</code> which is passed as the argument can never be itself included in the returned <code>List</code>. I kept that behavior, but I am not sure if that is really what the OP wanted.</p>\n\n<pre><code>object Gdal {\n\n /**\n * \"Monkey patching\" methods.\n */ \n object CustomSubElementsFetchers {\n\n implicit class GeometryWithSubList(val geom: Geometry) extends AnyVal {\n def subGeometries: List[Geometry] = {\n for (i <- List.range(0, geom.GetGeometryCount)) \n yield geom.GetGeometryRef(i) \n }\n }\n\n implicit class LayerWithSubList(val layer: Layer) extends AnyVal {\n def features: List[Feature] = {\n var list: List[Feature] = Nil\n var feature = layer.GetNextFeature\n while (feature != null) {\n list = feature :: feature :: list\n feature = layer.GetNextFeature\n }\n list.reverse\n }\n }\n }\n import CustomSubElementsFetchers._\n\n\n // @tailrec // Not tail recursive: stack overflow might occur.\n def getInnerPolygons(geometry: Geometry): List[Geometry] = {\n geometry.subGeometries.flatMap(subGeom => subGeom.GetGeometryName match {\n case \"LINEARRING\" => List(subGeom)\n case _ => getInnerPolygons(subGeom) \n })\n }\n\n def main(args: Array[String]) {\n val linearGeometry = new Geometry(\"LINEARRING\", Nil)\n val compoundGeometry = new Geometry(\"NONLINEARRING\", List(linearGeometry, linearGeometry))\n val layer = new Layer(List(new Feature(linearGeometry), new Feature(compoundGeometry)))\n\n val baseGeometries = layer.features.map(feature => feature.GetGeometryRef)\n val polygons: List[Geometry] = baseGeometries.flatMap(getInnerPolygons) \n polygons.map(polygon => polygon.GetGeometryName).foreach(println)\n }\n}\n</code></pre>\n\n<p>Note: if the GDAL data structures are huge and all the data cannot fit in <code>List</code>s, then it might be preferable to use <code>Stream</code>s instead.</p>\n\n<p>And here are the dummy GDAL classes I used to test it:</p>\n\n<pre><code> /**\n * Emulation of Gdal's Geometry.\n */\n class Geometry(val name: String, val subGeometries: List[Geometry]) {\n def GetGeometryName: String = name\n def GetGeometryCount: Int = subGeometries.size\n def GetGeometryRef(index: Int): Geometry = subGeometries(index)\n }\n\n /**\n * Emulation of Gdal's Feature.\n */\n class Feature(val geometry: Geometry) {\n def GetGeometryRef: Geometry = geometry\n }\n\n /**\n * Emulation of Gdal's Layer.\n * (This would be a horrible Scala class.)\n */\n class Layer(val features: List[Feature]) {\n var currentIndex = -1\n def GetNextFeature: Feature = {\n currentIndex = currentIndex + 1\n if (currentIndex >= features.size)\n null\n else\n features(currentIndex)\n }\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-25T22:59:45.527",
"Id": "45357",
"ParentId": "26547",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "29706",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T20:48:02.187",
"Id": "26547",
"Score": "2",
"Tags": [
"optimization",
"recursion",
"scala",
"iterator"
],
"Title": "Is this a correct recursive Scala iterator creation?"
}
|
26547
|
<p>I'm trying to read some SNMP packets on my own. So far so good, I was able to put up some functions to write some SNMP TRAP packets as I need them. However, now I need to be able to read them and while my code works, I'm not happy with it.</p>
<p>I'd like to see if any of you could please tell me if there's a better way to do and/or optimize my current code. My binary-fu isn't as good so I'd love if I could get some proposals without bit shifting as that confuses me and could confuse other people I program with.</p>
<p>I've heard and seen SNMP libraries for .NET but it's overkill for what I need to do. Also, I'm not allowed to use external libraries, and so far the code works, I just want to simplify it more and optimize it too, as it'll be used very extensively under high network traffic.</p>
<p>This is my (sample) code:</p>
<pre><code>private void ReadSNMP(byte[] buf, int size)
{
if (size > 0)
{
// IS UNIVERSAL SEQUENCE?
if (buf[0] == 0x30)
{
int iPos = 0;
int pckSize = ReadSNMPInt(buf, ref iPos);
int version = ReadSNMPInt(buf, ref iPos);
String comm = ReadSNMPString(buf, ref iPos);
}
}
}
</code></pre>
<p>And this is a sample ReadSNMPInt function:</p>
<pre><code>private int ReadSNMPInt(byte[] buf, ref int iPos)
{
MemoryStream ms = new MemoryStream();
iPos++;
if (buf[iPos] > 0x80) // > 80 = BER :(
{
if (buf[iPos] == 0x81)
ms.Write(new byte[] { buf[iPos + 1], 0x00, 0x00, 0x00 }, 0, 4);
if (buf[iPos] == 0x82)
ms.Write(new byte[] { buf[iPos + 2], buf[iPos + 1], 0x00, 0x00 }, 0, 4);
if (buf[iPos] == 0x83)
ms.Write(new byte[] { buf[iPos + 3], buf[iPos + 2], buf[iPos + 1], 0x00 }, 0, 4);
if (buf[iPos] == 0x84)
ms.Write(new byte[] { buf[iPos + 4], buf[iPos + 3], buf[iPos + 2], buf[iPos + 1] }, 0, 4);
iPos += buf[iPos] - 0x80;
}
else
{
iPos++;
ms.Write(new byte[] { buf[iPos], 0x00, 0x00, 0x00 }, 0, 4);
}
iPos++;
return BitConverter.ToInt32(ms.ToArray(), 0);
}
</code></pre>
<p>It works, but I noticed that when I needed to make the <code>ReadSNMPString</code> function, it needed kinda the same logic but different. I'm using <a href="http://www.vijaymukhi.com/vmis/snmp.htm" rel="nofollow">these docs</a> as reference (they're the best I've found, and so far their documentation helped to make the production code work). Also, replace snmp.htm with ber.htm to find out other links.</p>
<p>I'm trying to find out how to make a generic function to read at least one function for each datatype I need (simple though, only <code>int</code>s and strings) without using such ugly code.</p>
<p>I managed to make a new function now but I feel it can be a bit slower and/or not as optimized as I'd like.</p>
<pre><code>public static class ASN1Int
{
public static int Read(Stream s)
{
int preByte = s.ReadByte();
if (preByte <= 0x79)
return s.ReadByte();
int bSize = preByte - 0x80;
MemoryStream ms = new MemoryStream();
using (BinaryWriter b = new BinaryWriter(ms))
{
for (int i = 0; i < 4 - bSize; i++)
b.Write((byte)0x0);
for (int i = 0; i < bSize; i++)
b.Write((byte)s.ReadByte());
}
byte[] rv = ms.ToArray();
Array.Reverse(rv, 0, rv.Length);
return BitConverter.ToInt32(rv, 0);
}
}
</code></pre>
<p>Any ideas are really welcome, and if someone's gonna close this on here please do a bit more research before going trigger-happy on me.</p>
|
[] |
[
{
"body": "<p>So, based on your update it looks like you've switched to reading from <code>Stream</code> - good decision.</p>\n\n<p>A bit simplified/cleaner approach for reading int is:</p>\n\n<pre><code>public static class ASN1Int\n{\n public static int Read(Stream inputStream)\n {\n const int sizeMarker = 0x80; //TODO: name appropriately\n\n int size = inputStream.ReadByte();\n\n if (size < sizeMarker)\n return inputStream.ReadByte();\n\n size -= sizeMarker;\n //TODO: add assertion to make sure size<=4 if needed\n\n var result = inputStream.ReadByte();\n\n while (--size > 0)\n result = (result << 8) + inputStream.ReadByte();\n\n return result;\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T13:16:00.097",
"Id": "27348",
"ParentId": "26549",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "27348",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T21:55:34.767",
"Id": "26549",
"Score": "1",
"Tags": [
"c#",
"serialization"
],
"Title": "Reading BER-encoded data"
}
|
26549
|
<p>I'm trying to implement a PID without floating point operations on a micro controller. I appreciate all feedback I can get.</p>
<p>Header file:</p>
<pre><code>#ifndef BRUSHPID_H
#define BRUSHPID_H
#if defined(ARDUINO) && (ARDUINO >= 100) // Arduino Library
#include "Arduino.h"
#else
#include "WProgram.h"
#endif
#define KU_CONSTANT 2
#define DT 100 // in milliseconds, descrete time step size chose to be 0.1[s]=100[ms]
#define PERIOD 6000 // in milliseconds, measured as 6[s]=6000[ms]
// Ziegler Algorithem Constants
#define ZIEGLER_P 0
#define ZIEGLER_PI 1
#define ZIEGLER_CLASSIC_PID 2
#define ZIEGLER_PESSEN_INTEGAL_RULE 3
#define ZIEGLER_SOME_OVERSHOOT 4
#define ZIEGLER_NO_OVERSHOOT 5
// Tuning Type
#define TUNING_TYPE ZIEGLER_P
// bit extension to avoid float operations
#define LONG_SHIFT 10
class BrushPID{
private:
unsigned long p;
unsigned long i;
unsigned long d;
signed long lCurrentError;
signed long lLastError;
signed long lTotalError;
signed long lMaxError;
signed long lMaxTotalError;
signed long caclulateNextOutput(void);
unsigned long ulLastTimeStamp;
void zieglerNicholasTuning(signed int iTuningMethod);
void resetTotalError(void);
public:
BrushPID(void);
~BrushPID(void);
signed long getNextOutput(signed long *newError);
};
#endif BRUSHPID_H
</code></pre>
<p>Source File:</p>
<pre><code>#include "BrushPID.h"
#include "../BrushCommon/BrushCommon.h"
BrushPID::BrushPID(void) {
// init local object data
this->lCurrentError=0;
this->lLastError=0;
this->lTotalError=0;
this->ulLastTimeStamp=millis(); // timestamp since arduino boot in milliseconds
this->p=KU_CONSTANT;
this->i=0;
this->d=0;
//init PID paramaters according to chosen tuning type
this->zieglerNicholasTuning(TUNING_TYPE);
// calculate overflow boundry
this->lMaxTotalError=MAX_SIGNED_LONG-MAX_SIGNED_LONG/(max(this->i*DT,1)); // max to prevent division by 0
this->lMaxError=MAX_SIGNED_LONG-MAX_SIGNED_LONG/(max(max(this->p,this->d),1));
}
// destructor
BrushPID::~BrushPID(void) {
//nothing to do
}
// next step of discrete PID
long BrushPID::getNextOutput(long *newError){
//prevent overflows
if(lMaxTotalError<abs(this->lTotalError)) this->resetTotalError();
if(lMaxError<abs(*newError)) *newError=this->lLastError;
//check if DT has passed, by comparing current to last registered time stamp
while((millis()-this->ulLastTimeStamp)<DT);
//set new timestamp
this->ulLastTimeStamp=millis();
this->lLastError=this->lCurrentError;
this->lCurrentError=*newError;
this->lTotalError+=*newError*DT;
return caclulateNextOutput();
}
long BrushPID::caclulateNextOutput(void){
return (this->p*this->lCurrentError+this->i*this->lTotalError+this->d*(this->lCurrentError-this->lLastError)/DT)>>LONG_SHIFT;
}
/* ****
* Setting PID Parameter according to Ziegler-Nicholas tuning Method
* Source: http://en.wikipedia.org/wiki/Ziegler%E2%80%93Nichols_method
****/
void BrushPID::zieglerNicholasTuning(int iTuningMethod=ZIEGLER_P){
unsigned long shifted_constant=KU_CONSTANT<<LONG_SHIFT;
switch(iTuningMethod){
case(ZIEGLER_P):
this->p=shifted_constant>>1;
this->i=0;
this->d=0;
break;
case(ZIEGLER_PI):
this->p=(shifted_constant*22)/10;
this->i=(this->p*10)/12/max(PERIOD,1);
this->d=0;
break;
case(ZIEGLER_CLASSIC_PID):
this->p=(shifted_constant*6)/10;
this->i=2*this->p/max(PERIOD,1);
this->d=(this->p*PERIOD)>>3;
break;
case(ZIEGLER_PESSEN_INTEGAL_RULE):
this->p=(shifted_constant*7)/10;
this->i=(shifted_constant<<1);
this->d=(shifted_constant*15)/100;
default:
this->p=shifted_constant;
this->i=0;
this->d=0;
}
}
void BrushPID::resetTotalError(){
this->lTotalError=0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T03:15:55.550",
"Id": "41130",
"Score": "0",
"body": "I personally find all this `this->` business visually distracting. If you're coding in an IDE that can't highlight class members in a different color, I find that a simple leading underscore (naming convention) is enough to call out member data. I know this is a somewhat religious point, though."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T04:31:15.010",
"Id": "41133",
"Score": "0",
"body": "@Nate Agreed, except prefer trailing underscores, not leading underscores. *Each name that contains a double underscore __ or begins with an underscore followed by an uppercase\nletter is reserved to the implementation for any use.* - It's easy to forget this and get it wrong (I have a number of times in recent memory). Basically, use a simple rule: no `__` anywhere, and don't start anything with `_`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T05:09:04.270",
"Id": "41136",
"Score": "0",
"body": "@Yuushi, I find it extremely difficult to get that wrong. Typing an underscore is already relatively difficult. Typing two in a row is a mistake I've never made in about 17 years of coding. You shouldn't be referencing \"the implementation's\" variables anyway (the ones that start with `__`), so there should be no confusion. If your code had a mixture of variables starting with `__`, and `_`, then there would be a source of confusion. But, you should **only** have ones starting with `_` (single) in **application layer** code. Systems programmers would have different coding standards."
}
] |
[
{
"body": "<p>I know nothing of PID controllers, so I'll restrict comments to the code itself.</p>\n\n<h2>Comments on the header:</h2>\n\n<ul>\n<li><p>A <code>#endif</code> doesn't take a tag (BRUSHPID_H)</p></li>\n<li><p>Use of the 'signed' keyword is unusual. Do you have a good reason for its use?</p></li>\n<li><p>Hungarian notation (your variable type-prefixes) is a really bad idea</p></li>\n<li><p>Tuning methods would be better defined as an <code>enum</code> rather than as <code>#defines</code> and a <code>signed int</code> parameter (to <code>zieglerNicholasTuning</code>).</p></li>\n<li><p>OVERSHOOT defines are not used.</p></li>\n<li><p>pass <code>newError</code> into <code>getNextOutput</code> by reference ?</p></li>\n</ul>\n\n<h2>Comments of the source file:</h2>\n\n<ul>\n<li><p>It is better to define the include path in the Makefile instead of the\nsource file. So the Makefile would have something like </p>\n\n<pre><code>-I $(PROJECT)/BrushCommon/ \n</code></pre>\n\n<p>as a part of the compilation rule.</p></li>\n<li><p>Some of the code is hard to read because of a lack of spacing around\noperators (=, <, << etc) and after keywords (if, while, etc), and because of\nsingle-line expressions (better to use braces and multi-line). The function\n<code>caclulateNextOutput</code> is unreadable without adding spaces.</p></li>\n<li><p>The default tuning type should perhaps be a parameter (with default) to the\nconstructor.</p></li>\n<li><p><code>lMaxError</code>, <code>lMaxTotalError</code> seem to be constants. And why use\nMAX_SIGNED_LONG when LONG_MAX is available from limits.h</p></li>\n<li><p>According to the Wiki reference, ZEIGLER_PI 'p' value should be (* 10 / 22),\nthe ZIEGLER_PESSEN_INTEGAL_RULE 'i' value looks wrong and the\nZIEGLER_PESSEN_INTEGAL_RULE 'd' value has a hard-coded time constant (100)</p></li>\n<li><p>In <code>zieglerNicholasTuning</code>, I'd call <code>shifted_constant</code> just <code>ku</code> and make\nit <code>const</code>. But then again,... in the <code>BrushPID</code> constructor, 'p' is\ninitialised to KU_CONSTANT whereas in <code>zieglerNicholasTuning</code>, KU_CONSTANT\nis shifted by <code>LONG_SHIFT</code>. This seems wrong. The initial, wrong, value is\nunused, but to avoid this sort of error, I would probably define KU_CONSTANT\nas <code>(2 << (LONG_SHIFT))</code> in the header</p></li>\n<li><p><code>LONG_SHIFT</code> is, to me, an unhelpful name.</p></li>\n<li><p><code>DT</code> better as <code>DELTA_T</code> ?</p></li>\n<li><p>The while loop in <code>getNextOutput</code> would be better with explicit braces :</p>\n\n<pre><code>while ((millis() - this->ulLastTimeStamp) < DT) {\n // busy-wait\n}\n</code></pre>\n\n<p>I guess you have no other way of waiting and nothing else going on that\nneeds CPU time, so this is probably ok. But <strong>don't do it at interrupt\nlevel</strong>. In general, when there is an alternative, this sort of loop is\nbest avoided.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-25T13:09:33.247",
"Id": "41231",
"Score": "0",
"body": "we were taught Hungarian at uni as a uni convention, I guess you shouldn't believe everything you're taught. Thanks for the feedback, I've taken note and adjusted the library"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T03:02:20.823",
"Id": "26552",
"ParentId": "26551",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "26552",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T22:37:57.000",
"Id": "26551",
"Score": "3",
"Tags": [
"c++",
"library",
"arduino"
],
"Title": "PID Controller library"
}
|
26551
|
<p>This is working code for a URI template (RFC 6570) implementation; when the character to render is not within a specific character set, it is needed to grab the UTF-8 representation of that character and encode each byte as a percent-encoded sequence.</p>
<p>The question is whether something more efficient than this exists?</p>
<pre><code>private static String encodeChar(final char c)
{
final String tmp = new String(new char[] { c });
final byte[] bytes = tmp.getBytes(Charset.forName("UTF-8"));
final StringBuilder sb = new StringBuilder();
for (final byte b: bytes)
sb.append('%').append(UnsignedBytes.toString(b, 16));
return sb.toString();
}
</code></pre>
<p>Note: <code>UnsignedBytes.toString()</code> is from Guava.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T12:32:03.823",
"Id": "41157",
"Score": "0",
"body": "What kind of performance do you need? Is this just a general question? Did you try essentially the same thing on the whole string and see if it was faster?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T21:09:46.753",
"Id": "41198",
"Score": "0",
"body": "Doing it on a whole string is a no-no. Only the characters out of a specified character set need to be percent-encoded this way. What I am asking is whether a better way to achieve such an encoding of a single character exists. For reference, see RFC 6570, section 1.5."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-26T11:33:21.747",
"Id": "41267",
"Score": "0",
"body": "Of course, on a whole string it would skip most characters - I don't know how easy it would be with getBytes. (You didn't answer my first two questions.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-26T11:38:02.947",
"Id": "41268",
"Score": "0",
"body": "It is not a question of performance; the problem is that I think the code is a little clumsy as it stands. In this sense it is more of a general question. The main encoding function uses a `CharMatcher` to determine whether the current character in a string should be percent encoded or not."
}
] |
[
{
"body": "<p><a href=\"http://docs.oracle.com/javase/1.5.0/docs/api/java/net/URLEncoder.html\" rel=\"nofollow\">Documentation here</a></p>\n\n<pre><code>public static void main(final String[] args) {\n try {\n System.out.println(URLEncoder.encode(\"a?>éàùA-Z\",\n System.getProperty(\"sun.jnu.encoding\")));\n } catch (final UnsupportedEncodingException e) {\n System.out.println(\"BIG PB\");\n return; \n }\n }\n</code></pre>\n\n<p>Output :</p>\n\n<blockquote>\n <p>a%3F%3E%E9%E0%F9A-Z</p>\n</blockquote>\n\n<p>You have the same for <a href=\"http://docs.oracle.com/javase/1.4.2/docs/api/java/net/URLDecoder.html\" rel=\"nofollow\">URLEDecoder</a></p>\n\n<p><strong>EDIT</strong></p>\n\n<p><em>For URI</em><br>\nFound in src of <a href=\"http://sourceforge.net/projects/imemex/?source=dlp\" rel=\"nofollow\">iMeMex Dataspace ManagementSystem</a></p>\n\n<pre><code>public static URI encode(String uriStr) throws URISyntaxException {\n if (uriStr != null) {\n // poor man's encoding\n uriStr = uriStr.replaceAll(\" \", \"%20\");\n }\n return new URI(uriStr);\n}\n</code></pre>\n\n<p><a href=\"http://docs.oracle.com/javase/1.4.2/docs/api/java/net/URI.html\" rel=\"nofollow\">JavaDoc here</a></p>\n\n<p>But URI from Java does not change other %VALUES.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T07:24:33.087",
"Id": "41144",
"Score": "1",
"body": "This does not fit the bill. For instance, it replaces spaces with '+', and the encoded character list differs from what URI Template requires."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T06:57:22.260",
"Id": "26558",
"ParentId": "26553",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T04:51:20.127",
"Id": "26553",
"Score": "5",
"Tags": [
"java",
"guava",
"utf-8"
],
"Title": "Better code for converting a char to its UTF-8 percent encoding representation?"
}
|
26553
|
<p>I'm trying to figure out whether I should do the following:</p>
<p>This class (over-simplified version) retrieves information about an order by having 1 main query function that select a specific column from the table and throws out the value for that column and that specific order ID. </p>
<pre><code>class jobinfo
{
protected $id;
function __construct($job_id)
{
$this->id-$job_id;
}
protected function query_s($table, $col = '*', $where_col , $where, $return_col)
{
$SQL = mysql_query("SELECT $col FROM ".$table." WHERE $where_col='$where' LIMIT 1") or die(mysql_error());
$data = mysql_fetch_array($SQL);
return $data[$return_col];
}
public function qtyOrdered()
{
return $this->query_s('job_sheet','qty', 'job_id',$this->id, 1, 'qty');
}
public function dueDate()
{
return $this->query_s('job_sheet','due', 'job_id',$this->id, 1, 'due');
}
}
</code></pre>
<hr>
<p>The way I have it set up now is that I have this running in a <code>while</code> loop over 10,000 different orders like so:</p>
<pre><code>$sql = mysql_query("SELECT job_id FROM job_sheet");
while($data = mysql_fetch_array($sql))
{
$job_data = new jobinfo($data['job_id']);
//table goes here to output values
echo $job_data->dueDate();
echo $job_data->qtyOrdered();
///
}
</code></pre>
<hr>
<p>The one issue with this is that for every row that comes up, there are 2 queries that are happening in the back: one for the quantity and one for the due date. This ultimately causes to slow things down, especially when I'm outputting almost 11 columns for 11 different things. It adds up to a lot of queries per row. </p>
<p>My question is, should I go with something like this:</p>
<pre><code>class jobinfo
{
protected $id;
protected $due;
protected $qty;
function __construct($job_id)
{
$this->id-$job_id;
$this->retrieve();
}
protected function retrieve()
{
$sql = mysql_query("SELECT qty, due FROM job_sheet WHERE job_id=".$this->id." LIMIT 1");
$data = mysql_fetch_array($sql);
$this->due = $data['due'];
$this->qty = $data['qty'];
/// etc etc etc
}
public function qtyOrdered()
{
return $this->qty;
}
public function dueDate()
{
return $this->due;
}
}
</code></pre>
<p>Which would do only one query per row in this case.</p>
<p>My dilemma is that the only time I find the second class more efficient is when some of this information is called via Ajax on a refresh rate of 5 seconds to be displayed somewhere. There are 15 users and most of the stay on one page that refreshes data every 5 seconds for statistical purposes.The other time is when the user searches for something in a custom search engine. The rest of the site is primarily showing only a few things and don't need to search the entire database to retrieve one specific value like the second class would have been doing. And so, this is the reason why I've set up my class as the first one: 'retrieve as you go' basically:</p>
<p><code>$job = new jobinfo(123); echo $job->qty()</code>; </p>
<p>I'm not sure what to do at this point and need some advice/suggestions.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T05:19:47.427",
"Id": "41138",
"Score": "0",
"body": "What you should do first and foremost is using prepared statements instead of string concatenations!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T08:22:15.850",
"Id": "41145",
"Score": "0",
"body": "Please do not use mysql in new code, it is [deprecated](http://www.php.net/manual/en/intro.mysql.php). Use mysqli or PDO instead. Use prepared statements. I'd also use a general function to retrieve data from the database and call it from other functions, it reduces the amount of queries throughout the code, making it better to read an maintain."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T12:48:36.690",
"Id": "41158",
"Score": "0",
"body": "I completely agree with all this. It's just a matter of re-writing most of the code which would seem impossible. As for the new code, I've implemented PDO. Not sure what to do about old code..."
}
] |
[
{
"body": "<p>Doing this in a loop will be slow, and doubling the calls by retrieving each column with a different query will make things worse.</p>\n\n<p>Why not use a JOIN between your original query, something like this:-</p>\n\n<p>SELECT database.job_id, job_sheet.qty, job_sheet.row\nFROM database\nINNER JOIN job_sheet\nON database.job_id = job_sheet.job_id</p>\n\n<p>In your loop this would mean a single query rather than ~20000 queries.</p>\n\n<p>If you do need to do a separate query for each time through the loop then a prepared statement would help but peformance will likely still be poor.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T17:51:16.670",
"Id": "41185",
"Score": "0",
"body": "I changed the while loop: it's not `SELECT job_id FROM database` it should read `SELECT job_id FROM job_sheet`. Doing a query for every column multiplied by every row is insanity. I think perhaps what I'll do is doing an `INNER JOIN` but within my class; retrieving all the information first... I wonder if that would improve much. But that would be I would have to join almost 3 tables now for each row in my while loop."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-28T08:10:54.343",
"Id": "41374",
"Score": "0",
"body": "If it is a join on index int columns then it should be fast. I wouldn't worry about the performance of a JOIN as it will almost certainly be massively faster than a separate query to the 2nd table."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-28T19:20:37.080",
"Id": "41411",
"Score": "0",
"body": "You're right, I think by doing the JOIN withing the class an assigning each of my variable a piece of data would be a lot better than separate queries. I was just worried about 3 JOINS for every row displayed but 3 JOINS > 11 separate queries..."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T08:20:48.397",
"Id": "26560",
"ParentId": "26554",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "26560",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T04:37:33.030",
"Id": "26554",
"Score": "2",
"Tags": [
"php",
"performance",
"mysql"
],
"Title": "SQL Query efficiency within class"
}
|
26554
|
<p>If you were interviewing me, and saw this code written in a little under an hour, would you consider me as a candidate for a position at your company if you knew I had 2 years of C++ experience?</p>
<pre><code>#include <stdlib.h>
#include <cassert>
/*! \class Node to be used in likned list like constructors
*/
template <typename T>
class node
{
private:
T data;
node * next;
public:
/*! \brief Default constructor
* Initialize next pointer to NULL and let data's default constructor
* be called
*/
node() :
next(NULL)
{}
/*! \brief Parametered constructor
* Initialize next pointer to NULL and set data to t
*/
node(T t) :
data(t),
next(NULL)
{}
/*! \brief Copy constructor
*/
node(const node & other) :
data(other.data),
next(other.next)
{}
/*! \brief Destructor
*/
~node()
{}
/*! \brief Assignment operator
*/
node & operator=(const node &other)
{
data = other.data;
next = other.next;
return (*this);
}
/*! \brief Set the next pointer
*/
void set_next(node *next_node)
{
next = next_node;
}
/*! \brief Set the nodes data
*/
void set_data(T t)
{
data = t;
}
/*! \brief Get the nodes data
*/
T get_data() {
return data;
}
/*! \brief Get the nodes next pointer
*/
node * get_next()
{
return next;
}
/*! \brief Equivalence operator
*/
bool operator==(const node &other)
{
return (data == other.data && next == other.next);
}
/*! \brief Not equivalence operator
*/
bool operator!=(const node &other)
{
return (data != other.data || next != other.next);
}
};
/*! \class Linked List
*/
template <typename T>
class linked_list
{
private:
node<T> * head;
public:
/*! \brief Default constructor
* Initialize head pointer to NULL
*/
linked_list() :
head(NULL)
{}
/*! \brief Parametered constructor
* Initialize head to a node
*/
linked_list(node<T> &n) :
head(&n)
{}
/*! \brief Copy constructor
*/
linked_list(const linked_list & other) :
head(other.head)
{}
/*! \brief Destructor
*/
~linked_list()
{}
/*! \brief Assignment operator
*/
linked_list & operator=(const linked_list &other)
{
head = other.head;
return (*this);
}
/*! \brief Get the head node pointer
*/
node<int> * get_head()
{
return head;
}
/*! \brief Equivalence operator
*/
bool operator==(const linked_list &other)
{
return (head == other.head);
}
/*! \brief Not equivalence operator
*/
bool operator!=(const linked_list &other)
{
return (head != other.head);
}
};
void unit_test_linked_list()
{
// Default constructor
linked_list<int> l0;
assert(!l0.get_head());
// Parametered constructor
node<int> n(5);
linked_list<int> l1(n);
assert(l1.get_head()->get_data() == 5);
// Copy construtor
linked_list<int> l2(l1);
assert(l2 == l1);
// Assignment and equivalence
l0 = l2;
assert(l2 == l1);
assert(l2 == l0);
assert(l1 == l0);
}
void unit_test_node()
{
// Default constructor
node<int> n;
assert(!n.get_next());
// Parameterd constructor and assignment operator
n = node<int>(5);
assert(!n.get_next() && n.get_data() == 5);
// Copy constructor equivalence operator and not equivalent operator
node<int> m(n);
assert(n.get_data() == m.get_data() && n.get_next() == m.get_next());
assert(!(m != n) && m == n);
// Setters and getters
m.set_data(6);
m.set_next(&n);
assert(m.get_data() == 6 && m.get_next()->get_data() == 5);
assert(m.get_next()->get_next() == NULL);
}
int main()
{
unit_test_node();
unit_test_linked_list();
}
</code></pre>
|
[] |
[
{
"body": "<p>I can't speak for others, but I'd personally have some reservations. To be fair, perhaps I'm not being lenient enough for doing this under pressure in an hour, but there are multiple issues that I'd want to address with this code.</p>\n\n<h2>Questions and Small Problems</h2>\n\n<p>Why is <code>node</code> not an internal class of <code>linked_list</code>? Generally, the user should neither know nor care about exactly how a <code>node</code> is represented. I'd let this slide pretty easily though, because it's a small oversight and can be fairly easily corrected.</p>\n\n<p>You're not passing to your <code>node</code> constructor by <code>const T&</code> which I would have expected. If this is constructing from a type that is expensive to copy construct, this adds quite a bit of overhead. </p>\n\n<p>Usage of <code>NULL</code> vs <code>nullptr</code>. Not a big deal, but it'd make me push you a little bit on knowledge of <code>C++11</code> constructs.</p>\n\n<h2>Pain Points</h2>\n\n<p>The interface for your list is (somewhat) setup, but the implementation is very, very incomplete. As it currently stands, it doesn't really represent a list at all, but something that holds the address of a single element that exists outside the list, and is therefore tied to the lifetime of that object (which is a big, big problem).</p>\n\n<p>Your <code>linked_list</code> constructor takes a <code>node<T></code> as a parameter. This goes back to the first point about <code>node</code> being internal, but here it is more serious in my mind. This shows that you <strong>do</strong> expect the user to know/care about the <code>node</code> type. It also takes it by reference, and then simply makes the <code>head</code> node point to that address. This is all a bit worrying. It should be taking an element of type <code>T</code>, which it then wraps up in a <code>node</code>, and that is stored as the head element:</p>\n\n<pre><code>linked_list(const T& initial)\n : head(new node(initial))\n{ }\n</code></pre>\n\n<p>You never <code>new</code> or <code>delete</code> anything - a <code>linked_list</code> that uses absolutely no dynamic storage is very strange indeed. It'd certainly make me want to press you on things like object lifetimes, stack and heap allocation, dangling references and the like. </p>\n\n<p>There is no way to modify a list once it is created; something as basic as adding an element isn't possible. Even if these functions weren't finished in time, I'd expect just the declarations to be there, something like:</p>\n\n<pre><code>void push_front(const T& data)\n{ }\n</code></pre>\n\n<p>Because of the lack of dynamic allocation, your copy constructor and assignment operator don't really do anything, and you don't have a destructor. Implementations of these would be something I'd heavily scrutinize. For a start, do they do what they are supposed to do? A copy constructor should be doing a <strong>deep copy</strong> of the list it is passed - many people get this wrong and end up simply doing a shallow copy, which generally means pointers pointing to deleted memory, and undefined behaviour. </p>\n\n<p><code>operator=</code> should either be using the <em>copy-swap</em> idiom or at least doing basic checks like <code>(this != &rhs)</code>, clearing the current data in the list, and copying the data from what is passed in as the argument to <code>operator=</code>. With your current implementation, none of this can be demonstrated properly. </p>\n\n<p>Why is <code>get_head</code> declared as <code>node<int> *</code>? Why are you returning a <code>node</code> instead of simply returning the data? This should have two overloads, one for <code>const T&</code> and one for <code>T&</code>.</p>\n\n<p>Operators shouldn't be member functions, but that's pretty minor, and I wouldn't really care too much. However, if you do make them member functions, they should definitely be <code>const</code>:</p>\n\n<pre><code>bool operator!=(const linked_list &other) const\n //^^^^^\n</code></pre>\n\n<p>All in all, there is a lot lacking for an implementation, even given the short time span. The lack of any kind of dynamic memory allocation would probably be a deal-breaker for me personally. Without being able to hear your reasoning about this, I'd make the assumption that you didn't understand allocations or object lifetimes, which is of critical importance when programming in C++.</p>\n\n<p><strong>Edit</strong>: If given a limited time (such as one hour) to write something like a <code>list</code>, I'd probably approach it in the following way: firstly, sketch out the minimal interface I want to develop from. Given the pretty strict time requirements, I'd keep it as simple as possible:</p>\n\n<ol>\n<li>A private internal <code>node</code> struct with all public members (this cuts down on boilerplate code that needs to be written, and since it's private, it's not user facing, so I'd argue it's fine anyway).</li>\n<li>Private members for <code>list</code>, which I'd keep to a <code>node *head</code> and <code>std::size_t size</code>. </li>\n<li>Basic constructors, copy assignment, copy constructor, destructor.</li>\n<li>Insert, update and delete. Since this is a singly linked list, insert would be limited to adding something to the front (<code>push_front</code> if we're following standard lib naming), something to update a given value, and something to delete a given value. Usually these would use iterators, but that's too complex given the tight time restrictions.</li>\n<li>Something to get the size, if the list is empty, and maybe some basic comparison operators.</li>\n</ol>\n\n<p>Sketching out this API, I'd have something like:</p>\n\n<pre><code>template <typename T>\nclass linked_list\n{\nprivate:\n\n struct node\n {\n T data_;\n node* next_;\n\n node(const T& data)\n : data_(data),\n next(nullptr)\n { }\n };\n\n std::size_t size_;\n node* head_;\n\npublic:\n\n linked_list()\n : head_(nullptr),\n size_(0)\n { }\n\n linked_list(const T& data)\n : head(new node(data)),\n size_(1)\n { }\n\n ~linked_list() { }\n linked_list(const linked_list& rhs) { }\n linked_list& operator=(linked_list rhs) { } //Use copy-swap idiom\n\n bool is_empty() const { }\n std::size_t size() const { }\n\n void push_front(const T& value) { }\n bool remove(const T& value) { }\n bool update(const T& value) { } \n\n void swap(linked_list& rhs) { }\n};\n\ntemplate <typename T>\nvoid swap(linked_list<T>& lhs, linked_list<T>& rhs) { }\n\ntemplate <typename T>\nbool operator<(const linked_list<T>& lhs, const linked_list<T>& rhs) { }\n\ntemplate <typename T>\nbool operator>(const linked_list<T>& lhs, const linked_list<T>& rhs) { }\n\ntemplate <typename T>\nbool operator==(const linked_list<T>& lhs, const linked_list<T>& rhs) { }\n\ntemplate <typename T>\nbool operator!=(const linked_list<T>& lhs, const linked_list<T>& rhs) { } \n</code></pre>\n\n<p>I'd then start to fill in functions as I went - some of them are one-liners (<code>is_empty</code> and <code>size</code>), some of them take a bit more work. I'd pay the most attention to getting the destructor and copy constructor right, since these are probably the functions that would be scrutinized the most. Even if this API is slightly ambitious, and if some of the functions don't end up being implemented, at least it shows <em>intent</em>.</p>\n\n<p>Finally, after the hour was up, I'd want to be ready to discuss what this implementation is lacking compared to say, the standard library <code>list</code>: from memory, <code>Allocator</code> template parameter, <code>iterator</code> + <code>const_iterator</code>, <code>typedef</code>s such as <code>value_type</code>, <code>reference_type</code>, functions such as <code>remove_if</code>, <code>sort</code>, <code>unique</code> and so on (although this is probably getting to in-depth - unless you've been working with the standard library a lot and know it very well, this is probably too much detail - but it might be worth it to know at least a little bit about <code>std::list</code>).</p>\n\n<p>Given the incredibly limited time, I'd likely eschew unit testing. In fact, unless I had a compiler, I'd be almost positive there would be at least a few errors lurking around - syntax or otherwise. This wouldn't bother me - few people can sit down and bang out even a simplified container class without making a single mistake. To me, it is the high level overview that is important, along with those few key functions (destructor, copy constructor).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T18:06:15.610",
"Id": "41187",
"Score": "0",
"body": "Thanks for the feed back. This was a timed practice run of mine, and your comments make me happy that this was not the actual interview. But apparently I have a lot of work to do. If you were to be asked this question where would you start? Would you list out all the functionality, then implement it? Or would you do one thing at a time and demonstrate that you can unit test things one step at a time?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-25T05:09:44.647",
"Id": "41215",
"Score": "0",
"body": "@MatthewHoggan I've updated my post re your question, since it's a bit too much for a comment."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-25T05:42:13.230",
"Id": "41216",
"Score": "0",
"body": "I greatly appreciate you taking your time in answering my question. It is this kind of help that hopefully will bring more skilled c++ developers into this world."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T07:04:22.310",
"Id": "26559",
"ParentId": "26557",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "26559",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T05:40:48.077",
"Id": "26557",
"Score": "4",
"Tags": [
"c++",
"linked-list"
],
"Title": "Would this linked list be considered clean if written in an hour-long interview?"
}
|
26557
|
<p>Firstly, here's a link to the <a href="http://jsfiddle.net/RobH/zgJRb/1/" rel="nofollow">fiddle</a>.</p>
<p>Basically my situation is that there is a requirement to show tooltips on textboxes on some forms being created for a website to allow employees to update their personal information (among other things). </p>
<p>The customer likes the idea of the tooltip being displayed to the right of the textbox when the user clicks into it rather than jQuery UI's default of when hovering over it. To that end, I created the following code that shows and hides the tooltip when the user clicks into/out of the textbox:</p>
<pre><code>$(function () {
$('.tooltip').each(function () {
var $this,
id,
t;
$this = $(this);
id = this.id;
t = $('<span />', {
title: $this.attr('title')
}).appendTo($this.parent()).tooltip({
position: {
of: '#' + id,
my: "left+190 center",
at: "left center",
collision: "fit"
}
});
// remove the title from the real element.
$this.attr('title', '');
$('#' + id).focusin(function () {
t.tooltip('open');
}).focusout(function () {
t.tooltip('close');
});
});
});
</code></pre>
<p>My question is simple, is there a better way of doing this?</p>
<p>Note that I can rely on the inputs always having a unique Id as this is an ASP.Net application.</p>
|
[] |
[
{
"body": "<p><a href=\"http://jsfiddle.net/zgJRb/5/\" rel=\"nofollow\">The demo is seen here</a></p>\n\n<pre><code>$('.tooltip').each(function () {\n\n //title can be fetched directly from the element. I know no bugs for to\n //require the use of `attr()`. This removes several function calls.\n\n //No need to get the element by id since the current elements you are iterating\n //over each are the same DOM elements you are trying to attach events to. The\n //`this` in here is where you attach events.\n\n //You are appending the content to the parent, landing the span next to input.\n //Instead of doing that, you can use `insertAfter()` which inserts the object in\n //context after the specified element, which is the current object in the\n //`each()`. It also accepts a DOM element so no need to wrap it in jQuery.\n\n var t = $('<span />', {\n title: this.title\n }).insertAfter(this).tooltip({\n position: {\n of: '#' + this.id,\n my: \"left+190 center\",\n at: \"left center\",\n collision: \"fit\"\n }\n });\n\n this.title = '';\n\n //Now the only need to wrap the current object this is here, when we attach events. \n\n //Since the event methods are merely shorthands of `on(eventName,fn)`, we use \n //`on()` instead to lessen function calls. Also, it allows a map of events, which\n //results in calling `on()` only once.\n\n $(this).on({\n focusin: function () {\n t.tooltip('open');\n },\n focusout: function () {\n t.tooltip('close');\n }\n });\n});\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T09:36:55.500",
"Id": "26563",
"ParentId": "26561",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "26563",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T08:42:22.280",
"Id": "26561",
"Score": "1",
"Tags": [
"javascript"
],
"Title": "Showing jQuery UI tooltip on focus of text box"
}
|
26561
|
<p>I'd like a review of Haskell tree heap code in <a href="https://stackoverflow.com/questions/16639793/turning-a-tree-into-a-heap-in-haskell/16655447#comment24033886_16655447">Turning a tree into a heap in Haskell</a>.</p>
<pre><code>module Heapify where
data Tree a = Leaf a | Node (Tree a) a (Tree a)
deriving Show
ourTree = Node (Node (Leaf 8) 2 (Leaf 4)) 3 (Node (Leaf 1) 7 (Leaf 9))
atTop :: Tree a -> a
atTop (Leaf a) = a
atTop (Node _ a _) = a
replaceTop :: Ord a => Tree a -> a -> Tree a
replaceTop (Leaf _) a = Leaf a
replaceTop (Node l _ r) a = heapify (Node l a r)
adjustLeft :: Ord a => Tree a -> Tree a
adjustLeft (Leaf a) = Leaf a -- But we shouldn't ask to do this.
adjustLeft node@(Node l a r)
| topL <= a = node
| otherwise = Node (replaceTop l a) topL r
where topL = atTop l
adjustRight :: Ord a => Tree a -> Tree a
adjustRight (Leaf a) = Leaf a -- But we shouldn't ask to do this.
adjustRight node@(Node l a r)
| topR <= a = node
| otherwise = Node l topR (replaceTop r a)
where topR = atTop r
doTop :: Ord a => Tree a -> Tree a
doTop (Leaf a) = Leaf a
doTop node@(Node l a r)
| atTop l > atTop r = adjustLeft node
| otherwise = adjustRight node
heapify :: Ord a => Tree a -> Tree a
heapify (Leaf a) = Leaf a
heapify (Node l a r) = doTop (Node (heapify l) a (heapify r))
</code></pre>
|
[] |
[
{
"body": "<h2>Correctness? Unanticipated cases?</h2>\n\n<pre><code>module Heapify where\n\ndata Tree a = Leaf a | Node (Tree a) a (Tree a) \n deriving Show\n</code></pre>\n\n<p>I think this <strong>can't host an even number of elements</strong>. <code>fromList [1,2]</code> seems impossible.</p>\n\n<pre><code>ourTree = Node (Node (Leaf 8) 2 (Leaf 4)) 3 (Node (Leaf 1) 7 (Leaf 9))\n</code></pre>\n\n<p>an example data.</p>\n\n<pre><code>atTop :: Tree a -> a\natTop (Leaf a) = a\natTop (Node _ a _) = a\n</code></pre>\n\n<p>ok.</p>\n\n<pre><code>replaceTop :: Ord a => Tree a -> a -> Tree a\nreplaceTop (Leaf _) a = Leaf a\nreplaceTop (Node l _ r) a = heapify (Node l a r)\n</code></pre>\n\n<p><strong>produces a heap</strong>. doesn't know what data was put on top, must re-heapify. <em>Does not use the knowledge</em> whether <code>l</code>/<code>r</code> are in fact heaps already or not. If was called on a heap, both must have been heaps already. The usual flow would be for <code>heapify</code> to be called on arbitrary trees, but <code>replaceAtTop</code> to be called on heaps only. <em>This</em> might have an impact on performance.</p>\n\n<pre><code>adjustLeft :: Ord a => Tree a -> Tree a\nadjustLeft (Leaf a) = Leaf a -- But we shouldn't ask to do this. \nadjustLeft node@(Node l a r) \n | topL <= a = node\n | otherwise = Node (replaceTop l a) topL r\n where topL = atTop l\n</code></pre>\n\n<p><strong>assumes <code>l</code> was already a heap</strong>. If not, <code>l</code> might harbor some number yet bigger than <code>topL</code> and the <code>otherwise</code> clause could produce a non-heap (<code>replaceTop</code> fully heapifies its argument so its biggest number will get floated to its top).</p>\n\n<pre><code>adjustRight :: Ord a => Tree a -> Tree a\nadjustRight (Leaf a) = Leaf a -- But we shouldn't ask to do this. \nadjustRight node@(Node l a r) \n | topR <= a = node\n | otherwise = Node l topR (replaceTop r a) \n where topR = atTop r\n</code></pre>\n\n<p>similarly to the above, <strong>assumes <code>r</code> was a heap</strong>. Both functions assume both <code>l</code> and <code>r</code> were heaps actually, because <code>r</code> (corr., <code>l</code>) is kept unchanged. So <strong>both assume that only the top element can be out of place</strong> before the call, and produce a heap under that assumption. If the assumption does not hold, the produced value will not be a heap.</p>\n\n<pre><code>doTop :: Ord a => Tree a -> Tree a\ndoTop (Leaf a) = Leaf a\ndoTop node@(Node l a r) \n | atTop l > atTop r = adjustLeft node\n | otherwise = adjustRight node\n</code></pre>\n\n<p>assuming both <code>l</code> and <code>r</code> were heaps before call, produce a heap. </p>\n\n<pre><code>heapify :: Ord a => Tree a -> Tree a\nheapify (Leaf a) = Leaf a\nheapify (Node l a r) = doTop (Node (heapify l) a (heapify r))\n</code></pre>\n\n<p>assuming <code>heapify</code> fulfills its promise, OK. Base case (<code>Leaf a</code>): OK. </p>\n\n<p>So, <strong>OK</strong> (except for the data definition deficiency).</p>\n\n<h2>Call graph</h2>\n\n<pre><code> heapify (does not assume l/r were heaps)\n |\n |_____ heapify\n |\n |_____ doTop\n |\n |____ adjustLeft / adjustRight (assume l/r were heaps)\n |\n |____ replaceTop (does not assume l/r were heaps)\n |\n |_____ heapify\n</code></pre>\n\n<h2>Performance?</h2>\n\n<p>So, heapify essentially is</p>\n\n<pre><code>heapify (Leaf a) = Leaf a\nheapify (Node l a r) \n | a >= top = Node lh a rh\n | ltop > rtop = Node (replaceTop lh a) ltop rh -- lh is a heap!\n | otherwise = Node lh rtop (replaceTop rh a) -- rh is a heap!\n where\n lh = heapify l ----- superfluous, == id when called from (1) -- (2)\n rh = heapify r ----- superfluous, == id when called from (1) -- (2)\n ltop = atTop lh\n rtop = atTop rh\n top = max ltop rtop\n replaceTop (Leaf _) a = Leaf a\n replaceTop (Node l _ r) a = heapify (Node l a r) ------- (1)\n</code></pre>\n\n<p>Looks a very heavy recursion.</p>\n\n<hr>\n\n<p>One way to fix this is to assume that <code>heapify</code> will be called only on heaps, not on arbitrary trees. Then the fix is simply to eliminate the two (2) calls. Then it becomes logarithmic.</p>\n\n<ul>\n<li><p>Heaps would need to be created from lists. The usual way is <code>fold</code>/<code>insertElem</code>. </p></li>\n<li><p>The <code>data</code> type definition needs to be adjusted to allow insertion of <em>one</em> element into a heap tree. The definitions will have to be readjusted. Probably easier done with small snippets, like in OP code. <code>atTop</code> would have to produce a <code>Maybe</code> value, as now empty heaps become a possibility (say, one of the children of a <code>fromList [1,2]</code> heap tree - now both subtrees are <em>heaps</em>, and one is empty).</p></li>\n<li><p>The whole balance/depth issue is untouched here. </p></li>\n</ul>\n\n<p>It's probably simpler to re-write <code>replaceTop</code> to essentially duplicate the above code, without the calls to <code>heapify</code>. It will now assume it's operating on heaps only, not on arbitrary trees. This will make <code>replaceTop</code> logarithmic. Leaves all the other problems unaddressed. </p>\n\n<pre><code>replaceTop (Leaf _) a = Leaf a -- operates on heaps!\nreplaceTop (Node lh _ rh) a -- lh, rh are heaps!\n | a >= top = Node lh a rh\n | ltop > rtop = Node (replaceTop lh a) ltop rh \n | otherwise = Node lh rtop (replaceTop rh a)\n where\n ltop = atTop lh\n rtop = atTop rh\n top = max ltop rtop\n</code></pre>\n\n<p>According to <a href=\"http://en.wikipedia.org/wiki/Master_theorem#See_also\" rel=\"nofollow\">master theorem</a> for <code>2T(n/2) + O(log(n))</code> case, <code>heapify</code> will be <code>O(n)</code> then, assuming a balanced tree. A balanced tree can be built from a list in <code>O(n)</code> time.</p>\n\n<p><code>removeTop</code> will most probably be <code>O(log(n))</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T12:14:34.180",
"Id": "41153",
"Score": "0",
"body": "(I read that it was faster to heapify an unsorted balanced tree than to repeatedly insert.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T12:15:49.233",
"Id": "41154",
"Score": "0",
"body": "yes. your approach pays off. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-28T08:17:45.173",
"Id": "41375",
"Score": "0",
"body": "http://cs.brynmawr.edu/Courses/cs206/spring2012/slides/10_PriorityQueues.pdf has the algorithms in question and discusses the complexities; explains O(n) for heapification of unsorted array/tree."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-28T08:34:10.633",
"Id": "41376",
"Score": "0",
"body": "It does, using O(1) array lookup. Why not post an answer along those lines to the original question, using mutible arrays?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-28T08:57:13.790",
"Id": "41377",
"Score": "0",
"body": "@AndrewC too much work. :)"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T10:00:04.493",
"Id": "26565",
"ParentId": "26564",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "26565",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T10:00:04.493",
"Id": "26564",
"Score": "5",
"Tags": [
"haskell",
"tree",
"heap"
],
"Title": "Tree heap Haskell code"
}
|
26564
|
<p>I have Winform application and I want to separate the button click event from the main form.</p>
<p>My application has Add button which adds files into my <code>Listbox</code> and until now all my code was inside this button click event and caused my code to look complicated.<br>
So I created this class:</p>
<pre><code>public class ListboxFile
{
public delegate void OnFileAdd(string file);
public event OnFileAdd OnFileAddEvent;
private static List<string> _files;
public ListboxFile()
{
_files = new List<string>();
}
public void add(string file)
{
_files.Add(file);
OnFileAddEvent(file);
}
public void remove(string file)
{
if (_files.Contains(file))
{
_files.Remove(file);
}
}
public void clear()
{
_files.Clear();
}
public List<string> list
{
get { return _files; }
}
}
</code></pre>
<p>in the constructor I am initiate my <code>List</code> and each file that comes and add to my <code>List</code> raise an event and from the main form this file also add to my <code>Listbox</code></p>
<p>this is the event from the main form that responsible to add the file into the <code>Listbox</code>:</p>
<pre><code>private void lbf_OnFileAddEvent(string file)
{
if (InvokeRequired)
{
this.Invoke((MethodInvoker)delegate
{
listBoxFiles.Items.Add(file);
});
}
else
{
listBoxFiles.Items.Add(file);
}
}
</code></pre>
<p>and this is the Add button click that takes the files that the user chooses to add:</p>
<pre><code> private void btnAddfiles_Click(object sender, EventArgs e)
{
string fileToAdd = string.Empty;
System.IO.Stream stream;
OpenFileDialog thisDialog = new OpenFileDialog();
thisDialog.InitialDirectory = (lastPath.Length > 0 ? lastPath : "c:\\");
thisDialog.Filter = "(*.snoop, *.pcap, *.cap, *.net, *.pcapng, *.5vw, *.bfr, *.erf, *.tr1)" +
"|*.snoop; *.pcap; *.cap; *.net; *.pcapng; *.5vw; *.bfr; *.erf; *.tr1|" + "All files (*.*)|*.*";
thisDialog.FilterIndex = 1;
thisDialog.RestoreDirectory = false;
thisDialog.Multiselect = true;
thisDialog.Title = "Please Select Source File";
if (thisDialog.ShowDialog() == DialogResult.OK)
{
if (thisDialog.FileNames.Length > 0)
{
lastPath = Path.GetDirectoryName(thisDialog.FileNames[0]);
}
ListboxFile lbf = new ListboxFile();
lbf.OnFileAddEvent += lbf_OnFileAddEvent;
BackgroundWorker backgroundWorker = new BackgroundWorker();
backgroundWorker.WorkerReportsProgress = true;
backgroundWorker.DoWork +=
(s3, e3) =>
{
foreach (String file in thisDialog.FileNames)
{
try
{
if ((stream = thisDialog.OpenFile()) != null)
{
int numberOfFiles = thisDialog.SafeFileNames.Length;
using (stream)
{
lbf.add(file); //add the file
lastPath = Path.GetDirectoryName(thisDialog.FileNames[0]);
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
};
backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(
(s3, e3) =>
{
updateUi("bla bla"); //update the gui
});
backgroundWorker.RunWorkerAsync();
}
}
</code></pre>
<p>Would love to hear comments about this design since I am new developer.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T12:14:19.877",
"Id": "41152",
"Score": "1",
"body": "This looks a lot more complex than it needs to be, can you explain what you are trying to achieve with the code? Obviously the user is selecting some files to be added to a listbox but your background worker and related code is a bit odd and not really obvious why you're doing what you're doing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T13:02:37.547",
"Id": "41159",
"Score": "0",
"body": "As i mention before i am new developer so i don't have much experience and i would glad for some help, can you show me batter way ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T14:29:47.420",
"Id": "41170",
"Score": "2",
"body": "need to know what you are trying to achieve with your code before I can suggest a better way."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T15:01:09.417",
"Id": "41175",
"Score": "0",
"body": "I only use BackgroundWorker instead Thread in order to avoid my GUI stuck"
}
] |
[
{
"body": "<p>My first reaction is that your click handler is doing way too much work on its own. You should break up the code into smaller methods to make it easier to maintain.</p>\n\n<ol>\n<li>Move all the OpenFileDialog setup to the designer file. This will make it a field rather than local variable, preventing unnecessary object creation when a user clicks Add multiple times. Additionally, it will wire-up the proper Dispose call for you.</li>\n<li>Take the code for opening the files and put it into a separate method.</li>\n<li>Split off your worker event handlers into class methods rather than anonymous methods, better separating out method responsibilities.</li>\n</ol>\n\n<p>Other things I would do:</p>\n\n<ul>\n<li>Pass the filenames to the BackgroundWorker in its <code>RunWorkerAsync(Object)</code> overload. This prevents synchronization issues if a user clicks add while the worker is still running.</li>\n<li>Folowing the Single Responsibility Principle, you should move the file testing into the ListBoxFile class or some other helper class. UI views should not typically handle I/O.</li>\n<li>Make ListBoxFiles._files non-static. If you want singleton behavior for some reason, you can keep a static reference to a ListBoxFiles object. Providing instance-based methods but backing them with a static collection could be a bit jarring to callers, failing the Principle of Least Surprise.</li>\n<li>Instead of using <code>Stream</code>, it may be more clear to use <a href=\"http://msdn.microsoft.com/en-us/library/system.io.file.openread.aspx\" rel=\"nofollow\">File.OpenRead(string)</a>.</li>\n<li>With either <code>Stream</code> or <code>File.OpenRead</code>, you need to dispose the streams</li>\n<li>Instead of raising an add event on ListBoxFile, you should instead data bind your list control to a <a href=\"http://msdn.microsoft.com/en-us/library/ms132679.aspx\" rel=\"nofollow\">BindingList<T></a>. That will handle automatically updating your control as items are added/removed.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T20:24:50.353",
"Id": "41193",
"Score": "0",
"body": "What do u mean by saying move all the OpenFileDialog setup to the designer file ? can you show me the relevant code ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T20:31:35.927",
"Id": "41194",
"Score": "0",
"body": "Thanks for your reply Dan Lyons, it will be rude to ask code example for all this points ? i am quite new and don't know how to deal with all this"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T18:34:10.453",
"Id": "26583",
"ParentId": "26566",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T11:04:27.503",
"Id": "26566",
"Score": "1",
"Tags": [
"c#",
"winforms"
],
"Title": "Class design question"
}
|
26566
|
<p>The following program is supposed to return the length of a 'hidden' string within each of the sentences of another string, using pointers and avoiding as much as possible the use of <code>[]</code> as a means to access strings. We were instructed on how to declare the functions, hence their declarations are a given.</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
int getHiddenString(const char * str1 , const char * str2);
int divideStringIntoSentences(char * string, char * sentences[]);
char* readLine();
int main()
{
char *ptrarr[20];
int i = 0;
printf ("Please enter a string:\n");
char *str1 = readLine();
printf ("Please enter a hidden string:\n");
char *str2 = readLine();
if (str2 == NULL) return EXIT_FAILURE;
int j = divideStringIntoSentences(str1, ptrarr);
for (; i <= j; i++)
printf ("Sentence %d contains hidden string prefix length %d\n", i,
getHiddenString(*(ptrarr + i), str2));
free (str1);
free (str2);
return 0;
}
int getHiddenString(const char * str1 , const char * str2)
{
int hidlen = 0;
for (; *str1 != '\0' && *str2 != '\0'; str1++)
if (*str1 == *str2)
{
hidlen++;
str2++;
}
return (hidlen);
}
char* readLine()
{
int capacity = 1, index = 0;
char c;
char *str1 = (char*) malloc(capacity * sizeof(char));
if (str1 == NULL) return NULL;
for (c = getchar(); c != '\n' && capacity <= 100; c = getchar())
{
if (index == capacity - 1)
{
str1 = (char*) realloc(str1, (++capacity) * 2 * sizeof(char));
if (str1 == NULL) return NULL;
capacity*=2;
}
*(str1 + index++) = c;
}
*(str1 + index) = '\0';
return str1;
}
int divideStringIntoSentences(char * string, char * sentences[])
{
int sentnum = 0;
*sentences = string;
for (; *string != '\0'; string++)
if (*string == '.')
{
*string = '\0';
*(++sentences) = (string + 1);
sentnum++;
}
return (sentnum);
}
</code></pre>
|
[] |
[
{
"body": "<p>A couple of points:</p>\n\n<ul>\n<li>I don't know if it's just the way the question is formatted, but better indentation would improve readability</li>\n<li>In <code>divideStringIntoSentences</code>, it would be better to add <code>{ }</code> around the <code>if</code> as if you add something to the loop, you might forget to add the <code>{ }</code>s</li>\n<li>In <code>divideStringIntoSentences</code> there will be an extra sentence if the string ends with a full stop</li>\n<li>You've got a problem if there are more than 20 sentences.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T13:30:32.813",
"Id": "41162",
"Score": "0",
"body": "We were told that the number of sentences could not exceed. Pardon me, I forgot to mention that. What's wrong with a full stop? We were told that something like abc.. would be separated into \"abc\" and an empty string. Is the program not handling that case?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T13:45:32.940",
"Id": "41166",
"Score": "0",
"body": "The full stop at the end is no problem if you are expecting an extra empty string at the end. If the maximum is twenty sentences, the empty one will be 21 which is a problem."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T14:50:32.580",
"Id": "41173",
"Score": "0",
"body": "Solid point. That could be easily resolved, however, by simply allocating 21 pointers in ptrarr, right?"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T13:18:39.910",
"Id": "26568",
"ParentId": "26567",
"Score": "1"
}
},
{
"body": "<h2>Some generals comments:</h2>\n\n<p>Define functions in reverse order to avoid prototypes, make local functions static, add <code>void</code> to empty parameter lists, use braces even when unnecessary, use spaces consistently around operators, define a single variable per line, return statements don't need brackets (you are inconsistent in this).</p>\n\n<h2>In function <code>readLine</code></h2>\n\n<p>This function has many issues, some minor, such as casting <code>malloc</code>, using\n<code>sizeof(char)</code> (sizeof char is 1 by definition) and the arbitrary limit on a\nnew line of 100 chars. In your variable name, <code>str1</code>, the '1' is unnecessary,\nas you only use one string. And your default sentence allocation of 1 char is\nsilly - start with something reasonable, say 64 (arbitrary value).</p>\n\n<p>More seriously, <code>getchar</code> returns an <code>int</code> not <code>char</code>. This allows it to hold the value for EOF, the end-of-file marker. Your for-loop should test for EOF. If you fail to do this then if you input from a redirected file, the program will fail if EOF is reached without finding a \\n. A better loop would be, for example:</p>\n\n<pre><code>int ch;\nwhile((ch = getchar()) != EOF) {\n if (ch == '\\n') {\n break;\n }\n // do the necessary stuff\n}\n</code></pre>\n\n<p>Your reallocation should compute the new capacity then use that in the <code>realloc</code>\ncall rather than computing it twice. And your <code>realloc</code> call as it currently\nstands leaks memory on failure - the original string <code>str1</code> is not freed by\n<code>realloc</code> on failure.</p>\n\n<h2>In function <code>divideStringIntoSentences</code></h2>\n\n<p>You need to pass the size of <code>sentences[]</code> into the function to allow for overflow\ndetection.</p>\n\n<h2>In function <code>getHiddenString</code></h2>\n\n<p>Parameter names of <code>sentence</code> and <code>hidden</code> might be more understandable than\n<code>str1</code>, <code>str2</code>. More seriously, I don't know what it is supposed to\ndo. If it is supposed to find the hidden string in the sentence, then it\ndoesn't work. Library function <code>strstr</code> would do the job for you.</p>\n\n<h2>In <code>main</code></h2>\n\n<p>Although the functions handle malloc failures, <code>main</code> does not check for\n<code>str1</code> in the returned values. Again <code>str1</code> and <code>str2</code> are badly named, as is\n<code>ptrarr</code>. The for-loop should define the loop variable and should loop up to\nbut not including <code>j</code>: <code>for (int i = 0; i < j; ++i)</code>. And the printout\n\"Sentence # contains hidden string prefix length #\" is printed even if the\nsentence doesn't contain the hidden string. This make me think that the\n<code>getHiddenString</code> function is telling us the number of consecutive chars from\nthe hidden string contained in the sentence, or some such. In that case it\nstill doesn't work and is badly named (eg if I give it \"two twa twe\" and the\nhidden string \"twe\" it says, \"Sentence 0 contains hidden string prefix length 4\"</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-25T18:19:30.190",
"Id": "26609",
"ParentId": "26567",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T12:45:55.650",
"Id": "26567",
"Score": "4",
"Tags": [
"c",
"strings"
],
"Title": "Returning the length of a 'hidden' string within each of the sentences of another string"
}
|
26567
|
<p>While working on one of my projects I actively used Reflection. While working with class <code>Type</code> I expected methods: <code>TryGetMember</code>, <code>TryGetProperty</code>, <code>TryGetField</code>, <code>TryGetMethod</code>. I've implemented them as extension methods:</p>
<pre><code>public static class TypeExtensions
{
private const BindingFlags DEFAULT_LOOKUP = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public;
/// <summary>
/// Searches for the specified members, using the specified binding constraints.
/// </summary>
/// <param name="name">The string containing the name of the members to get.</param>
/// <param name="bindingAttr">
/// A bitmask comprised of one or more System.Reflection.BindingFlags that specify
/// how the search is conducted.-or- Zero, to return an empty array.
/// </param>
/// <param name="result">When this method returns, contains array of System.Reflection.MemberInfo with found members or empty (in a case of failure).</param>
/// <exception cref="ArgumentNullException"></exception>
/// <returns>returns true if method with the given data was found; otherwise false.</returns>
public static bool TryGetMember(this Type type, string name, BindingFlags bindingAttr, out MemberInfo[] result)
{
if (type == null)
throw new ArgumentNullException("type");
if (name == null)
throw new ArgumentNullException("name");
result = new MemberInfo[0];
try
{
result = type.GetMember(name, bindingAttr);
}
catch
{
}
return result.Count() != 0;
}
/// <summary>
/// Searches for the public members with the specified name.
/// </summary>
/// <param name="name">The string containing the name of the public members to get.</param>
/// <param name="result">When this method returns, contains array of System.Reflection.MemberInfo with found members or empty (in a case of failure).</param>
/// <exception cref="ArgumentNullException"></exception>
/// <returns>returns true if method with the given data was found; otherwise false.</returns>
public static bool TryGetMember(this Type type, string name, out MemberInfo[] result)
{
return type.TryGetMember(name, DEFAULT_LOOKUP, out result);
}
/// <summary>
/// Searches for the specified property, using the specified binding constraints.
/// </summary>
/// <param name="name">The string containing the name of the property to get.</param>
/// <param name="bindingAttr">
/// A bitmask comprised of one or more System.Reflection.BindingFlags that specify
/// how the search is conducted.-or- Zero, to return null.
/// </param>
/// <param name="result">When this method returns, contains System.Reflection.PropertyInfo of found property or null (in a case of failure).</param>
/// <exception cref="ArgumentNullException"></exception>
/// <returns>returns true if property with the given data was found; otherwise false.</returns>
public static bool TryGetProperty(this Type type, string name, BindingFlags bindingAttr, out PropertyInfo result)
{
if (type == null)
throw new ArgumentNullException("type");
if (name == null)
throw new ArgumentNullException("name");
result = default(PropertyInfo);
try
{
result = type.GetProperty(name, bindingAttr);
}
catch
{
}
return result != default(PropertyInfo);
}
/// <summary>
/// Searches for the public property with the specified name.
/// </summary>
/// <param name="name">The string containing the name of the property to get.</param>
/// <param name="result">When this method returns, contains System.Reflection.PropertyInfo of found property or null (in a case of failure).</param>
/// <exception cref="ArgumentNullException"></exception>
/// <returns>returns true if property with the given data was found; otherwise false.</returns>
public static bool TryGetProperty(this Type type, string name, out PropertyInfo result)
{
return type.TryGetProperty(name, DEFAULT_LOOKUP, out result);
}
/// <summary>
/// Searches for the specified public property whose parameters match the specified
/// argument types.
/// </summary>
/// <param name="name">The string containing the name of the property to get.</param>
/// <param name="returnType">The return type of the property.</param>
/// <param name="types">
/// An array of System.Type objects representing the number, order, and type
/// of the parameters for the indexed property to get.-or- An empty array of
/// the type System.Type (that is, Type[] types = new Type[0]) to get a property
/// that is not indexed.
/// </param>
/// <param name="result">When this method returns, contains System.Reflection.PropertyInfo of found property or null (in a case of failure).</param>
/// <exception cref="ArgumentNullException"></exception>
/// <returns>returns true if property with the given data was found; otherwise false.</returns>
public static bool TryGetProperty(this Type type, string name, Type returnType, Type[] types, out PropertyInfo result)
{
if (type == null)
throw new ArgumentNullException("type");
if (name == null)
throw new ArgumentNullException("name");
if (returnType == null)
throw new ArgumentNullException("returnType");
result = default(PropertyInfo);
try
{
result = type.GetProperty(name, returnType, types);
}
catch
{
}
return result != default(PropertyInfo);
}
/// <summary>
/// Searches for the public property with the specified name and return type.
/// </summary>
/// <param name="name">The string containing the name of the property to get.</param>
/// <param name="returnType">The return type of the property.</param>
/// <param name="result">When this method returns, contains System.Reflection.PropertyInfo of found property or null (in a case of failure).</param>
/// <exception cref="ArgumentNullException"></exception>
/// <returns>returns true if property with the given data was found; otherwise false.</returns>
public static bool TryGetProperty(this Type type, string name, Type returnType, out PropertyInfo result)
{
return type.TryGetProperty(name, returnType, null, out result);
}
/// <summary>
/// Searches for the specified field, using the specified binding constraints.
/// </summary>
/// <param name="name">The string containing the name of the data field to get.</param>
/// <param name="bindingAttr">
/// A bitmask comprised of one or more System.Reflection.BindingFlags that specify
/// how the search is conducted.-or- Zero, to return null.
/// </param>
/// <param name="result">When this method returns, contains System.Reflection.FieldInfo of found data field or null (in a case of failure).</param>
/// <exception cref="ArgumentNullException"></exception>
/// <returns>returns true if data field with the given data was found; otherwise false.</returns>
public static bool TryGetField(this Type type, string name, BindingFlags bindingAttr, out FieldInfo result)
{
if (type == null)
throw new ArgumentNullException("type");
if (name == null)
throw new ArgumentNullException("name");
result = default(FieldInfo);
try
{
result = type.GetField(name, bindingAttr);
}
catch
{
}
return result != default(FieldInfo);
}
/// <summary>
/// Searches for the public field with the specified name.
/// </summary>
/// <param name="name">The string containing the name of the data field to get.</param>
/// <param name="result">When this method returns, contains System.Reflection.FieldInfo of found data field or null (in a case of failure).</param>
/// <exception cref="ArgumentNullException"></exception>
/// <returns>returns true if data field with the given data was found; otherwise false.</returns>
public static bool TryGetField(this Type type, string name, out FieldInfo result)
{
return type.TryGetField(name, DEFAULT_LOOKUP, out result);
}
/// <summary>
/// When overridden in a derived class, returns the System.Reflection.EventInfo
/// object representing the specified event, using the specified binding constraints.
/// </summary>
/// <param name="name">
/// The string containing the name of an event which is declared or inherited
/// by the current System.Type.
/// </param>
/// <param name="bindingAttr">
/// A bitmask comprised of one or more System.Reflection.BindingFlags that specify
/// how the search is conducted.-or- Zero, to return null.
/// </param>
/// <param name="result">When this method returns, contains System.Reflection.EventInfo of found event or null (in a case of failure).</param>
/// <exception cref="ArgumentNullException"></exception>
/// <returns>returns true if event with the given data was found; otherwise false.</returns>
public static bool TryGetEvent(this Type type, string name, BindingFlags bindingAttr, out EventInfo result)
{
if (type == null)
throw new ArgumentNullException("type");
if (name == null)
throw new ArgumentNullException("name");
result = default(EventInfo);
try
{
result = type.GetEvent(name, bindingAttr);
}
catch
{
}
return result != default(EventInfo);
}
/// <summary>
/// Returns the System.Reflection.EventInfo object representing the specified
/// public event.
/// </summary>
/// <param name="name">
/// The string containing the name of an event that is declared or inherited
/// by the current System.Type.
/// </param>
/// <param name="result">When this method returns, contains System.Reflection.EventInfo of found event or null (in a case of failure).</param>
/// <exception cref="ArgumentNullException"></exception>
/// <returns>returns true if event with the given data was found; otherwise false.</returns>
public static bool TryGetEvent(this Type type, string name, out EventInfo result)
{
return type.TryGetEvent(name, DEFAULT_LOOKUP, out result);
}
/// <summary>
/// Searches for the specified method, using the specified binding constraints.
/// </summary>
/// <param name="name">The string containing the name of the method to get.</param>
/// <param name="bindingAttr">
/// A bitmask comprised of one or more System.Reflection.BindingFlags that specify
/// how the search is conducted.-or- Zero, to return null.
/// </param>
/// <param name="result">When this method returns, contains System.Reflection.MethodInfo of found method or null (in a case of failure).</param>
/// <exception cref="ArgumentNullException"></exception>
/// <returns>returns true if method with the given data was found and match is not ambiguous; otherwise false.</returns>
public static bool TryGetMethod(this Type type, string name, BindingFlags bindingAttr, out MethodInfo result)
{
if (type == null)
throw new ArgumentNullException("type");
if (name == null)
throw new ArgumentNullException("name");
result = default(MethodInfo);
try
{
result = type.GetMethod(name, bindingAttr);
}
catch
{
}
return result != default(MethodInfo);
}
/// <summary>
/// Searches for the public method with the specified name.
/// </summary>
/// <param name="name">The string containing the name of the public method to get.</param>
/// <param name="result">When this method returns, contains System.Reflection.MethodInfo of found method or null (in a case of failure).</param>
/// <exception cref="ArgumentNullException"></exception>
/// <returns>returns true if method with the given data was found and match is not ambiguous; otherwise false.</returns>
public static bool TryGetMethod(this Type type, string name, out MethodInfo result)
{
return type.TryGetMethod(name, DEFAULT_LOOKUP, out result);
}
/// <summary>
/// Searches for the specified public method whose parameters match the specified
/// argument types.
/// </summary>
/// <param name="name">The string containing the name of the public method to get.</param>
/// <param name="types">
/// An array of System.Type objects representing the number, order, and type
/// of the parameters for the method to get.-or- An empty array of System.Type
/// objects (as provided by the System.Type.EmptyTypes field) to get a method
/// that takes no parameters.
/// </param>
/// <param name="result">When this method returns, contains System.Reflection.MethodInfo of found method or null (in a case of failure).</param>
/// <exception cref="ArgumentNullException"></exception>
/// <returns>returns true if method with the given data was found; otherwise false.</returns>
public static bool TryGetMethod(this Type type, string name, Type[] types, out MethodInfo result)
{
if (type == null)
throw new ArgumentNullException("type");
if (name == null)
throw new ArgumentNullException("name");
result = default(MethodInfo);
try
{
result = type.GetMethod(name, types);
}
catch
{
}
return result != default(MethodInfo);
}
}
</code></pre>
<p>I know that there [almost] always is a reason why such simple and useful (at least, I think so) features are missing. Is there anything wrong (i.e.: some edge-cases that are not handled, leading to bad coding practices, etc.) with this or any other implementation of these methods? Also how can this code improved?</p>
|
[] |
[
{
"body": "<p>In the first <code>TryGetMember()</code>, I'd change the last line from <code>return result.Count() != 0;</code> to <code>return result.Length != 0;</code>. It's the only code that references LINQ and it's not really even needed there. If you feel compelled to use LINQ, that line would also be better written as <code>return result.Any();</code>.</p>\n\n<p><strong>(adding on)</strong></p>\n\n<p>So, in most of your methods, you're assigning to result twice for the happy path when you don't need to. Move the default assignment into your empty <code>catch</code> clauses and you'll have better performance overall and neater control code.</p>\n\n<p>Also, your XML documentation is missing the <code>type</code> parameter on every method plus any exception descriptions.</p>\n\n<p>So, I've gussied it up as described and here's the result:</p>\n\n<pre><code>public static class TypeExtensions\n{\n private const BindingFlags DefaultLookup = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public;\n\n /// <summary>\n /// Searches for the specified members, using the specified binding constraints.\n /// </summary>\n /// <param name=\"type\">The type whose members to get.</param>\n /// <param name=\"name\">The string containing the name of the members to get.</param>\n /// <param name=\"bindingAttr\">\n /// A bitmask comprised of one or more System.Reflection.BindingFlags that specify\n /// how the search is conducted.-or- Zero, to return an empty array.\n /// </param>\n /// <param name=\"result\">When this method returns, contains array of System.Reflection.MemberInfo with found members or empty (in a case of failure).</param>\n /// <exception cref=\"ArgumentNullException\"><paramref name=\"type\"/> may not be <c>null</c>.</exception>\n /// <exception cref=\"ArgumentNullException\"><paramref name=\"name\"/> may not be <c>null</c>.</exception>\n /// <returns>returns true if method with the given data was found; otherwise false.</returns>\n public static bool TryGetMember(this Type type, string name, BindingFlags bindingAttr, out MemberInfo[] result)\n {\n if (type == null)\n {\n throw new ArgumentNullException(\"type\");\n }\n\n if (name == null)\n {\n throw new ArgumentNullException(\"name\");\n }\n\n try\n {\n result = type.GetMember(name, bindingAttr);\n }\n catch\n {\n result = new MemberInfo[0];\n }\n\n return result.Length != 0;\n }\n\n /// <summary>\n /// Searches for the public members with the specified name.\n /// </summary>\n /// <param name=\"type\">The type whose members to get.</param>\n /// <param name=\"name\">The string containing the name of the public members to get.</param>\n /// <param name=\"result\">When this method returns, contains array of System.Reflection.MemberInfo with found members or empty (in a case of failure).</param>\n /// <exception cref=\"ArgumentNullException\"><paramref name=\"type\"/> may not be <c>null</c>.</exception>\n /// <exception cref=\"ArgumentNullException\"><paramref name=\"name\"/> may not be <c>null</c>.</exception>\n /// <returns>returns true if method with the given data was found; otherwise false.</returns>\n public static bool TryGetMember(this Type type, string name, out MemberInfo[] result)\n {\n return type.TryGetMember(name, DefaultLookup, out result);\n }\n\n /// <summary>\n /// Searches for the specified property, using the specified binding constraints.\n /// </summary>\n /// <param name=\"type\">The type whose properties to get.</param>\n /// <param name=\"name\">The string containing the name of the property to get.</param>\n /// <param name=\"bindingAttr\">\n /// A bitmask comprised of one or more System.Reflection.BindingFlags that specify\n /// how the search is conducted.-or- Zero, to return null.\n /// </param>\n /// <param name=\"result\">When this method returns, contains System.Reflection.PropertyInfo of found property or null (in a case of failure).</param>\n /// <exception cref=\"ArgumentNullException\"><paramref name=\"type\"/> may not be <c>null</c>.</exception>\n /// <exception cref=\"ArgumentNullException\"><paramref name=\"name\"/> may not be <c>null</c>.</exception>\n /// <returns>returns true if property with the given data was found; otherwise false.</returns>\n public static bool TryGetProperty(this Type type, string name, BindingFlags bindingAttr, out PropertyInfo result)\n {\n if (type == null)\n {\n throw new ArgumentNullException(\"type\");\n }\n\n if (name == null)\n {\n throw new ArgumentNullException(\"name\");\n }\n\n try\n {\n result = type.GetProperty(name, bindingAttr);\n }\n catch\n {\n result = default(PropertyInfo);\n }\n\n return result != default(PropertyInfo);\n }\n\n /// <summary>\n /// Searches for the public property with the specified name.\n /// </summary>\n /// <param name=\"type\">The type whose properties to get.</param>\n /// <param name=\"name\">The string containing the name of the property to get.</param>\n /// <param name=\"result\">When this method returns, contains System.Reflection.PropertyInfo of found property or null (in a case of failure).</param>\n /// <exception cref=\"ArgumentNullException\"><paramref name=\"type\"/> may not be <c>null</c>.</exception>\n /// <exception cref=\"ArgumentNullException\"><paramref name=\"name\"/> may not be <c>null</c>.</exception>\n /// <returns>returns true if property with the given data was found; otherwise false.</returns>\n public static bool TryGetProperty(this Type type, string name, out PropertyInfo result)\n {\n return type.TryGetProperty(name, DefaultLookup, out result);\n }\n\n /// <summary>\n /// Searches for the specified public property whose parameters match the specified\n /// argument types.\n /// </summary>\n /// <param name=\"type\">The type whose properties to get.</param>\n /// <param name=\"name\">The string containing the name of the property to get.</param>\n /// <param name=\"returnType\">The return type of the property.</param>\n /// <param name=\"types\">\n /// An array of System.Type objects representing the number, order, and type\n /// of the parameters for the indexed property to get.-or- An empty array of\n /// the type System.Type (that is, Type[] types = new Type[0]) to get a property\n /// that is not indexed.\n /// </param>\n /// <param name=\"result\">When this method returns, contains System.Reflection.PropertyInfo of found property or null (in a case of failure).</param>\n /// <exception cref=\"ArgumentNullException\"><paramref name=\"type\"/> may not be <c>null</c>.</exception>\n /// <exception cref=\"ArgumentNullException\"><paramref name=\"name\"/> may not be <c>null</c>.</exception>\n /// <exception cref=\"ArgumentNullException\"><paramref name=\"returnType\"/> may not be <c>null</c>.</exception>\n /// <returns>returns true if property with the given data was found; otherwise false.</returns>\n public static bool TryGetProperty(this Type type, string name, Type returnType, Type[] types, out PropertyInfo result)\n {\n if (type == null)\n {\n throw new ArgumentNullException(\"type\");\n }\n\n if (name == null)\n {\n throw new ArgumentNullException(\"name\");\n }\n\n if (returnType == null)\n {\n throw new ArgumentNullException(\"returnType\");\n }\n\n try\n {\n result = type.GetProperty(name, returnType, types);\n }\n catch\n {\n result = default(PropertyInfo);\n }\n\n return result != default(PropertyInfo);\n }\n\n /// <summary>\n /// Searches for the public property with the specified name and return type.\n /// </summary>\n /// <param name=\"type\">The type whose properties to get.</param>\n /// <param name=\"name\">The string containing the name of the property to get.</param>\n /// <param name=\"returnType\">The return type of the property.</param>\n /// <param name=\"result\">When this method returns, contains System.Reflection.PropertyInfo of found property or null (in a case of failure).</param>\n /// <exception cref=\"ArgumentNullException\"><paramref name=\"type\"/> may not be <c>null</c>.</exception>\n /// <exception cref=\"ArgumentNullException\"><paramref name=\"name\"/> may not be <c>null</c>.</exception>\n /// <exception cref=\"ArgumentNullException\"><paramref name=\"returnType\"/> may not be <c>null</c>.</exception>\n /// <returns>returns true if property with the given data was found; otherwise false.</returns>\n public static bool TryGetProperty(this Type type, string name, Type returnType, out PropertyInfo result)\n {\n return type.TryGetProperty(name, returnType, null, out result);\n }\n\n /// <summary>\n /// Searches for the specified field, using the specified binding constraints.\n /// </summary>\n /// <param name=\"type\">The type whose fields to get.</param>\n /// <param name=\"name\">The string containing the name of the data field to get.</param>\n /// <param name=\"bindingAttr\">\n /// A bitmask comprised of one or more System.Reflection.BindingFlags that specify\n /// how the search is conducted.-or- Zero, to return null.\n /// </param>\n /// <param name=\"result\">When this method returns, contains System.Reflection.FieldInfo of found data field or null (in a case of failure).</param>\n /// <exception cref=\"ArgumentNullException\"><paramref name=\"type\"/> may not be <c>null</c>.</exception>\n /// <exception cref=\"ArgumentNullException\"><paramref name=\"name\"/> may not be <c>null</c>.</exception>\n /// <returns>returns true if data field with the given data was found; otherwise false.</returns>\n public static bool TryGetField(this Type type, string name, BindingFlags bindingAttr, out FieldInfo result)\n {\n if (type == null)\n {\n throw new ArgumentNullException(\"type\");\n }\n\n if (name == null)\n {\n throw new ArgumentNullException(\"name\");\n }\n\n try\n {\n result = type.GetField(name, bindingAttr);\n }\n catch\n {\n result = default(FieldInfo);\n }\n\n return result != default(FieldInfo);\n }\n\n /// <summary>\n /// Searches for the public field with the specified name.\n /// </summary>\n /// <param name=\"type\">The type whose fields to get.</param>\n /// <param name=\"name\">The string containing the name of the data field to get.</param>\n /// <param name=\"result\">When this method returns, contains System.Reflection.FieldInfo of found data field or null (in a case of failure).</param>\n /// <exception cref=\"ArgumentNullException\"><paramref name=\"type\"/> may not be <c>null</c>.</exception>\n /// <exception cref=\"ArgumentNullException\"><paramref name=\"name\"/> may not be <c>null</c>.</exception>\n /// <returns>returns true if data field with the given data was found; otherwise false.</returns>\n public static bool TryGetField(this Type type, string name, out FieldInfo result)\n {\n return type.TryGetField(name, DefaultLookup, out result);\n }\n\n /// <summary>\n /// When overridden in a derived class, returns the System.Reflection.EventInfo\n /// object representing the specified event, using the specified binding constraints.\n /// </summary>\n /// <param name=\"type\">The type whose events to get.</param>\n /// <param name=\"name\">\n /// The string containing the name of an event which is declared or inherited\n /// by the current System.Type.\n /// </param>\n /// <param name=\"bindingAttr\">\n /// A bitmask comprised of one or more System.Reflection.BindingFlags that specify\n /// how the search is conducted.-or- Zero, to return null. \n /// </param>\n /// <param name=\"result\">When this method returns, contains System.Reflection.EventInfo of found event or null (in a case of failure).</param>\n /// <exception cref=\"ArgumentNullException\"><paramref name=\"type\"/> may not be <c>null</c>.</exception>\n /// <exception cref=\"ArgumentNullException\"><paramref name=\"name\"/> may not be <c>null</c>.</exception>\n /// <returns>returns true if event with the given data was found; otherwise false.</returns>\n public static bool TryGetEvent(this Type type, string name, BindingFlags bindingAttr, out EventInfo result)\n {\n if (type == null)\n {\n throw new ArgumentNullException(\"type\");\n }\n\n if (name == null)\n {\n throw new ArgumentNullException(\"name\");\n }\n\n try\n {\n result = type.GetEvent(name, bindingAttr);\n }\n catch\n {\n result = default(EventInfo);\n }\n\n return result != default(EventInfo);\n }\n\n /// <summary>\n /// Returns the System.Reflection.EventInfo object representing the specified\n /// public event.\n /// </summary>\n /// <param name=\"type\">The type whose events to get.</param>\n /// <param name=\"name\">\n /// The string containing the name of an event that is declared or inherited\n /// by the current System.Type.\n /// </param>\n /// <param name=\"result\">When this method returns, contains System.Reflection.EventInfo of found event or null (in a case of failure).</param>\n /// <exception cref=\"ArgumentNullException\"><paramref name=\"type\"/> may not be <c>null</c>.</exception>\n /// <exception cref=\"ArgumentNullException\"><paramref name=\"name\"/> may not be <c>null</c>.</exception>\n /// <returns>returns true if event with the given data was found; otherwise false.</returns>\n public static bool TryGetEvent(this Type type, string name, out EventInfo result)\n {\n return type.TryGetEvent(name, DefaultLookup, out result);\n }\n\n /// <summary>\n /// Searches for the specified method, using the specified binding constraints.\n /// </summary>\n /// <param name=\"type\">The type whose events to get.</param>\n /// <param name=\"name\">The string containing the name of the method to get.</param>\n /// <param name=\"bindingAttr\">\n /// A bitmask comprised of one or more System.Reflection.BindingFlags that specify\n /// how the search is conducted.-or- Zero, to return null.\n /// </param>\n /// <param name=\"result\">When this method returns, contains System.Reflection.MethodInfo of found method or null (in a case of failure).</param>\n /// <exception cref=\"ArgumentNullException\"><paramref name=\"type\"/> may not be <c>null</c>.</exception>\n /// <exception cref=\"ArgumentNullException\"><paramref name=\"name\"/> may not be <c>null</c>.</exception>\n /// <returns>returns true if method with the given data was found and match is not ambiguous; otherwise false.</returns>\n public static bool TryGetMethod(this Type type, string name, BindingFlags bindingAttr, out MethodInfo result)\n {\n if (type == null)\n {\n throw new ArgumentNullException(\"type\");\n }\n\n if (name == null)\n {\n throw new ArgumentNullException(\"name\");\n }\n\n try\n {\n result = type.GetMethod(name, bindingAttr);\n }\n catch\n {\n result = default(MethodInfo);\n }\n\n return result != default(MethodInfo);\n }\n\n /// <summary>\n /// Searches for the public method with the specified name.\n /// </summary>\n /// <param name=\"type\">The type whose methods to get.</param>\n /// <param name=\"name\">The string containing the name of the public method to get.</param>\n /// <param name=\"result\">When this method returns, contains System.Reflection.MethodInfo of found method or null (in a case of failure).</param>\n /// <exception cref=\"ArgumentNullException\"><paramref name=\"type\"/> may not be <c>null</c>.</exception>\n /// <exception cref=\"ArgumentNullException\"><paramref name=\"name\"/> may not be <c>null</c>.</exception>\n /// <returns>returns true if method with the given data was found and match is not ambiguous; otherwise false.</returns>\n public static bool TryGetMethod(this Type type, string name, out MethodInfo result)\n {\n return type.TryGetMethod(name, DefaultLookup, out result);\n }\n\n /// <summary>\n /// Searches for the specified public method whose parameters match the specified\n /// argument types.\n /// </summary>\n /// <param name=\"type\">The type whose methods to get.</param>\n /// <param name=\"name\">The string containing the name of the public method to get.</param>\n /// <param name=\"types\">\n /// An array of System.Type objects representing the number, order, and type\n /// of the parameters for the method to get.-or- An empty array of System.Type\n /// objects (as provided by the System.Type.EmptyTypes field) to get a method\n /// that takes no parameters.\n /// </param>\n /// <param name=\"result\">When this method returns, contains System.Reflection.MethodInfo of found method or null (in a case of failure).</param>\n /// <exception cref=\"ArgumentNullException\"><paramref name=\"type\"/> may not be <c>null</c>.</exception>\n /// <exception cref=\"ArgumentNullException\"><paramref name=\"name\"/> may not be <c>null</c>.</exception>\n /// <returns>returns true if method with the given data was found; otherwise false.</returns>\n public static bool TryGetMethod(this Type type, string name, Type[] types, out MethodInfo result)\n {\n if (type == null)\n {\n throw new ArgumentNullException(\"type\");\n }\n\n if (name == null)\n {\n throw new ArgumentNullException(\"name\");\n }\n\n try\n {\n result = type.GetMethod(name, types);\n }\n catch\n {\n result = default(MethodInfo);\n }\n\n return result != default(MethodInfo);\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T15:01:17.173",
"Id": "41176",
"Score": "1",
"body": "Nice review. Reducing dependencies is definitely great idea. There's no need in using `Linq` here so this class will become compatible with old `.NET` versions. And big thanks for improving documentation (I really suck at writing docs). I'll wait for another reviews (if there are any). If nobody will post better review, I'll accept this soon."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T13:43:30.210",
"Id": "26571",
"ParentId": "26569",
"Score": "3"
}
},
{
"body": "<h2>Read the documentation</h2>\n\n<ul>\n<li>No need for the try-catch blocks</li>\n<li>Every method returns a fix type if something goes wrong</li>\n</ul>\n\n\n\n<pre><code>public static class TypeExtensions\n{\n private const BindingFlags DefaultLookup = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public;\n\n private static void CheckNameArgument(string name)\n {\n if (name == null)\n throw new ArgumentNullException(\"name\");\n }\n\n private static void CheckTypeArgument(Type type)\n {\n if (type == null)\n throw new ArgumentNullException(\"type\");\n }\n\n private static void CheckReturnTypeArgument(Type returnType)\n {\n if (returnType == null)\n throw new ArgumentNullException(\"returnType\");\n }\n\n public static bool TryGetMember(this Type type, string name, BindingFlags bindingAttr, out MemberInfo[] result)\n {\n CheckTypeArgument(type);\n CheckNameArgument(name);\n\n result = type.GetMembers(bindingAttr).Where(x => x.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase)).ToArray();\n\n return result.Any();\n }\n\n public static bool TryGetMember(this Type type, string name, out MemberInfo[] result)\n {\n return type.TryGetMember(name, DefaultLookup, out result);\n }\n\n public static bool TryGetProperty(this Type type, string name, BindingFlags bindingAttr, out PropertyInfo result)\n {\n CheckTypeArgument(type);\n CheckNameArgument(name);\n var props = type.GetProperties(bindingAttr).Where(x => x.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase)).ToArray();\n\n result = props.Length == 1 ? props[0] : null;\n\n return props.Length == 1;\n }\n\n public static bool TryGetProperty(this Type type, string name, out PropertyInfo result)\n {\n return type.TryGetProperty(name, DefaultLookup, out result);\n }\n\n public static bool TryGetProperty(this Type type, string name, Type returnType, Type[] types, out PropertyInfo result)\n {\n //TODO:types?\n\n CheckTypeArgument(type);\n CheckNameArgument(name);\n CheckReturnTypeArgument(returnType);\n var properties = type.GetProperties()\n .Where(x => x.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase)\n && x.PropertyType == returnType)\n .ToArray();\n\n result = properties.Length == 1 ? properties[0] : null;\n\n return properties.Length == 1;\n }\n\n public static bool TryGetProperty(this Type type, string name, Type returnType, out PropertyInfo result)\n {\n return type.TryGetProperty(name, returnType, null, out result);\n }\n\n public static bool TryGetField(this Type type, string name, BindingFlags bindingAttr, out FieldInfo result)\n {\n CheckTypeArgument(type);\n CheckNameArgument(name);\n var fields = type.GetFields(bindingAttr).Where(x => x.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase)).ToArray();\n result = fields.Length == 1 ? fields[0] : null;\n\n return fields.Length == 1;\n }\n\n public static bool TryGetField(this Type type, string name, out FieldInfo result)\n {\n return type.TryGetField(name, DefaultLookup, out result);\n }\n\n public static bool TryGetEvent(this Type type, string name, BindingFlags bindingAttr, out EventInfo result)\n {\n CheckTypeArgument(type);\n CheckNameArgument(name);\n var events = type.GetEvents(bindingAttr).Where(x => x.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase)).ToArray();\n result = events.Length == 1 ? events[0] : null;\n\n return events.Length == 1;\n }\n\n public static bool TryGetEvent(this Type type, string name, out EventInfo result)\n {\n return type.TryGetEvent(name, DefaultLookup, out result);\n }\n\n public static bool TryGetMethod(this Type type, string name, BindingFlags bindingAttr, out MethodInfo result)\n {\n CheckTypeArgument(type);\n CheckNameArgument(name);\n var methods = type.GetMethods(bindingAttr)\n .Where(x => x.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase))\n .ToArray();\n\n result = methods.Length == 1 ? methods[0] : null;\n\n return methods.Length == 1;\n }\n\n public static bool TryGetMethod(this Type type, string name, out MethodInfo result)\n {\n return type.TryGetMethod(name, DefaultLookup, out result);\n }\n\n public static bool TryGetMethod(this Type type, string name, Type[] types, out MethodInfo result)\n {\n CheckTypeArgument(type);\n CheckNameArgument(name);\n var methods = type.GetMethods()\n .Where(x => x.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase)\n && x.GetParameters().All(y => types.Contains(y.ParameterType)))\n .ToArray();\n result = methods.Length == 1 ? methods[0] : null;\n\n return methods.Length == 1;\n }\n}\n</code></pre>\n\n<h2>Documentation</h2>\n\n<p>The documentation is completely unnecessary i think everthing is speaks for it's self.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T18:38:06.427",
"Id": "41189",
"Score": "0",
"body": "I want to ignore ambiguous matches as well that's why it's in try catch."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T23:46:57.650",
"Id": "41210",
"Score": "0",
"body": "I've made an edit to my answer the try-catch blocks are still unnecessary and only one TODO is left becouse i don't know how to apply that Type[] in the search."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-25T06:41:00.500",
"Id": "41220",
"Score": "0",
"body": "But you create dependency on `linq` that makes code incompatible with old versions of `.NET framework`. Also your code will have more overhead than `try/catch` (Actually, you managed to make `O(1)` problem `O(n)`) . And finally, it's true that most of us hate writing docs, but they are necessary and should always be written. Otherwise, you, as a developer, will expect method doing something but won't know if your expectations are correct."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-25T07:54:23.583",
"Id": "41223",
"Score": "0",
"body": "Try-catch blocks doesn't have overload but exceptions do. The Linq can be replaced by for cycles everywhere and we don't have to worry about O(1) vs. O(n) problem when finding the correct methods/properties/fields becouse reflection is slow as hell."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-25T09:46:27.790",
"Id": "41224",
"Score": "0",
"body": "`we don't have to worry about O(1) vs. O(n) problem when finding the correct methods/properties/fields becouse reflection is slow as hell.` I completely disagree with this. We should be worried about performance because _reflection is slow as hell_ and we don't want to make it even slower, do we?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-25T09:58:43.973",
"Id": "41228",
"Score": "1",
"body": "When the CLR looking after matching properties/methods/fileds it will also iterate through at least 2 times over the found values if you are looking after one property (GetProerty method for example). So if we first collect all possible values manually we are not creating any overhead. But if we expecting one value (GetProperty) and the CLR found multiple value it has to throw an Exception which has a huge overhead check out with profiling."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T15:56:52.517",
"Id": "26575",
"ParentId": "26569",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "26571",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T13:24:11.970",
"Id": "26569",
"Score": "2",
"Tags": [
"c#",
"reflection",
"extension-methods"
],
"Title": "Extension methods for class Type"
}
|
26569
|
<p>I have implemented the first coding challenge on <a href="http://projecteuler.net/" rel="nofollow">http://projecteuler.net/</a>. I would love to get it reviewed by some expert rubyists!</p>
<pre><code># Multiples of 3 and 5
#
# If we list all of the natural numbers below 10 that are multiples of
# 3 and 5, we get 3,5,6 and 9. THe sum of these multiples is 23.
#
# Find the sum of all the multiples of 3 or 5 below 1000.
class Multiples
def multiples
numbers = Array(1..999)
multiples = Array.new
for i in numbers
if i%3 == 0 or i%5 == 0
multiples.push(i)
end
end
multiples
end
def sumMultiples(multiples)
total = 0
multiples.each { |i| total+= i }
puts(total)
end
end
multiples = Multiples.new
multiples.sumMultiples(multiples.multiples)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T14:20:58.180",
"Id": "41169",
"Score": "12",
"body": "`(1...1000).select { |x| x % 3 == 0 || x % 5 == 0 }.reduce(:+)`. Food for thought: http://en.wikipedia.org/wiki/Side_effect_(computer_science) and http://en.wikipedia.org/wiki/Functional_programming"
}
] |
[
{
"body": "<ul>\n<li><p>Don't use <code>or</code>. It's for flow control. Use <code>||</code> for boolean logic.</p></li>\n<li><p>Don't use <code>Array.new</code>, use <code>[]</code></p></li>\n<li><p>Don't use <code>(1..999).to_a</code> or <code>Array(1..999)</code> when all you really want to do is iterate. It's expensive to instantiate a 1000 item array when really you just want to iterate from 1 to 999</p></li>\n<li><p>Any time you find yourself declaring an empty array and pushing items onto it in a loop, you are probably missing a <code>map</code> or <code>select</code>:</p>\n\n<pre><code>def multiples\n numbers = Array(1..999)\n multiples = Array.new\n for i in numbers\n if i%3 == 0 or i%5 == 0\n multiples.push(i)\n end\n end\n multiples\nend\n</code></pre>\n\n<p>Could be better written this way:</p>\n\n<pre><code>def multiples\n (1..999).select do |i|\n i % 3 == 0 || i % 5 == 0\n end\nend\n</code></pre></li>\n</ul>\n\n<p>Your summation loop follows a similar pattern:</p>\n\n<pre><code>def sumMultiples(multiples)\n total = 0\n multiples.each { |i| total+= i }\n puts(total)\nend\n</code></pre>\n\n<p>Again, there is a more idiomatic way of doing this via <code>inject</code>:</p>\n\n<pre><code>def sumMultiples(multiples)\n total = multiples.inject(&:+)\nend\n</code></pre>\n\n<p>A breakdown of how this works can be found in <a href=\"https://stackoverflow.com/questions/1538789/how-to-sum-array-of-numbers-in-ruby\">How to sum array of numbers in Ruby?</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-25T07:53:14.207",
"Id": "41222",
"Score": "0",
"body": "thanks @meagar. That looks a lot more elegant. Also, thanks for the advice on not using Array(1..999)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T16:35:54.663",
"Id": "26578",
"ParentId": "26573",
"Score": "11"
}
},
{
"body": "<p>A fun question! A little mathematical analysis can go a long way in reducing the amount of computation:</p>\n\n<p>First of all, you don't actually need to iterate anything. To get the sum of all the numbers from <code>1 to n</code>, just get the midpoint between the first and last numbers, which is simply the arithmetic average <code>(1+n)/2</code>. Then multiply this average by <code>n</code>. So the sum of all the numbers from <code>1</code> to <code>n</code> is:</p>\n\n<pre><code>((1+n)/2) * n\n</code></pre>\n\n<p>Similarly, the sum of all the multiples of <code>a</code> from <code>a</code> to <code>z</code> (assuming <code>z</code> is a multiple of <code>a</code>) is the midpoint between <code>a</code> and <code>z</code> times the number of multiples of <code>a</code> in the sequence <code>a .. z</code>.</p>\n\n<p>So, since there are 333 numbers in the sequence <code>3,6,9,12 ... 999</code>, the sum of all the multiples of 3 that are less than 1000 is:</p>\n\n<pre><code>((3+999)/2) * 333\n</code></pre>\n\n<p>or, in other words <code>333 x 501</code>.</p>\n\n<p>And the sum of all the multiples of 5 that are less than 1000 would be:</p>\n\n<pre><code>((5+995)/2) * 199\n</code></pre>\n\n<p>which is <code>199 x 500</code>.</p>\n\n<p>If we added these two sums together, we would be almost done, except for one little detail: each number that is a multiple of 15 was added twice. So we have to subtract those.</p>\n\n<p>The sum of all the multiples of 15 that are less than 1000 is <code>((15+990)/2) * 66</code>, or <code>66 x 502.5</code>.</p>\n\n<p>So our answer would be:</p>\n\n<pre><code>((3+999)/2) * 333 + ((5+995)/2) * 199 - ((15+990)/2) * 66\n</code></pre>\n\n<p>which is</p>\n\n<pre><code>166,833 + 99,500 - 33,165\n</code></pre>\n\n<p>or <code>233,168</code>.</p>\n\n<p>A \"technically correct, but totally useless\" answer to the code challenge would be</p>\n\n<pre><code>def get_the_sum\n 233168\nend\n</code></pre>\n\n<p>or without the syntactic shortcuts</p>\n\n<pre><code>def get_the_sum\n sum = 233168\n return sum\nend\n</code></pre>\n\n<p>We can, however, write a more useful general purpose method</p>\n\n<pre><code>sum_all_multiples_ab(a,b,max)\n</code></pre>\n\n<p>that finds the sum of all multiples of <code>a</code> or <code>b</code> that are less than <code>max</code>. Then the answer to your example problem would be given by:</p>\n\n<pre><code>sum_all_multiples_ab(3, 5, 1000)\n</code></pre>\n\n<p>We could define such a method like this:</p>\n\n<pre><code>def sum_all_multiples_ab(a, b, max)\n sum = sum_all_multiples(a, max)\n sum += sum_all_multiples(b, max)\n sum -= sum_all_multiples(a*b, max)\n sum\nend\n</code></pre>\n\n<p>where <code>sum_all_multiples()</code> is defined by</p>\n\n<pre><code>def sum_all_multiples(n,max)\n count = (max-1)/n\n last = count * n\n sum = ((n + last) / 2.0) * count\n sum\nend\n</code></pre>\n\n<p>We need to specify <code>2.0</code> in the last computation because we want a real number result, whereas for <code>count</code> (the number of values) and <code>last</code> (the last multiple less than 1000 or <code>max</code>) we want the truncated integer result.</p>\n\n<p>(We will only get an odd number for the average when we have an even number of values, so the ultimate result will always be an integer.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-25T13:46:47.007",
"Id": "41233",
"Score": "0",
"body": "I made an edit to change the divisor in the last computation to `2.0` because we need a real, not integer (truncated) result. The other division statement, `(max -1)/n`, still needs a truncated result, however."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-25T03:34:58.330",
"Id": "26594",
"ParentId": "26573",
"Score": "9"
}
},
{
"body": "<pre><code> def sumMultiples(multiples)\n # (...)\n end\n</code></pre>\n\n<p>I wouldn't use camelCase here. </p>\n\n<p>In Ruby there is a very solid convention:</p>\n\n<ul>\n<li>CamelCase for classes and modules</li>\n<li>CAPITALIZED_UNDERSCORED for constants</li>\n<li>snake_case for everything else (methods, variables)</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-05T19:36:01.657",
"Id": "27055",
"ParentId": "26573",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T14:06:56.543",
"Id": "26573",
"Score": "5",
"Tags": [
"ruby",
"programming-challenge"
],
"Title": "Multiples of 3 and 5 from Euler code challenge"
}
|
26573
|
<p>I have the following code:</p>
<pre><code><?php
include '../../inc/config.php';
$size = isset($_REQUEST['size']) ? $_REQUEST['size'] : 'full';
$image = isset($_REQUEST['image']) ? $_REQUEST['image'] : FALSE;
if(!$image) {
print 'Nenhuma imagem definida!';
exit;
}
$img_hash = $PDO->prepare("SELECT url FROM missionary_photos WHERE hash = :hash");
$img_hash->bindValue(':hash', $image);
$img_hash->execute();
$img_hash = $img_hash->fetchAll(PDO::FETCH_ASSOC);
$img_url = SITE_URL.$img_hash[0]['url'];
// Get the image mime type
function get_mime_type($url)
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_NOBODY, 1);
curl_exec($ch);
return curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
}
$mime_type = get_mime_type($img_url);
header('Content-type: '.$mime_type);
readfile($img_url);
</code></pre>
<p>I want to clean up the code a little bit and add the ability to resize the image using a GET or POST. Any ideas?</p>
|
[] |
[
{
"body": "<p>You can use <a href=\"http://php.net/manual/en/function.getimagesize.php\" rel=\"nofollow\">PHP's getimagesize() function</a> to get the MIME type.</p>\n\n<pre><code><?php\ninclude '../../inc/config.php';\n\nif(!isset($_REQUEST['image'])) die('Nenhuma imagem definida!');\n\n$size = isset($_REQUEST['size']) ? $_REQUEST['size'] : 'full';\n$image = $_REQUEST['image'];\n\n$img_hash = $PDO->prepare(\"SELECT url FROM missionary_photos WHERE hash = :hash\");\n$img_hash->bindValue(':hash', $image);\n$img_hash->execute();\n$img_hash = $img_hash->fetchAll(PDO::FETCH_ASSOC);\n$img_url = SITE_URL.$img_hash[0]['url'];\n\n$info = getimagesize($img_url);\nheader('Content-type: '.$info['mime']);\n\nreadfile($img_url);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T17:34:34.960",
"Id": "41184",
"Score": "0",
"body": "Thanks, that's awesome. Any ideas on the thumbnail thing?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T23:12:55.177",
"Id": "41208",
"Score": "1",
"body": "Glad I could help. Resizing images has been done so many times, and this is really out of the scope of Code Review. I'm sure you could try Stack Overflow or Google for guidance. Here's an example I found on nettuts: http://net.tutsplus.com/tutorials/php/image-resizing-made-easy-with-php/ Give it a shot and post your revised code for feedback!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T17:25:08.077",
"Id": "26579",
"ParentId": "26577",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T16:04:03.547",
"Id": "26577",
"Score": "1",
"Tags": [
"php"
],
"Title": "Need to clean up my code and add the ability to resize the image"
}
|
26577
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.