body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>I have just started playing around with L4 and would like to get some feedback on how I implemented a multi-page form</p>
<p>Here are my routes:</p>
<pre><code>Route::model('appointment', 'Appointment');
Route::get('appointment/book_new/{appointment}', array('as' => 'booking-form', 'uses' => 'AppointmentBookingController@index') );
Route::post('appointment/book_new/verify/{appointment}', 'AppointmentBookingController@verify');
Route::post('appointment/book_new/success/{appointment}', 'AppointmentBookingController@success');
</code></pre>
<p>Here is my controller:</p>
<pre><code>class AppointmentBookingController extends BaseController {
public function index(Appointment $appt)
{
return View::make('appointment/bookings/book', array('appt' => $appt));
}
public function verify(Appointment $appt){
$fields = array('name', 'email', 'description');
// Declare the rules for the form validation
$rules = array(
'name' => 'required',
'email' => 'required|email',
'description' => 'required',
);
// Create a new validator instance from our validation rules
$validator = Validator::make(Input::all(), $rules);
// If validation fails, we'll exit the operation now.
if ($validator->fails())
{
foreach($fields as $v)
{
Session::flash($v, Input::get($v));
}
return View::make('appointment/bookings/book', array('appt' => $appt, 'errors' => $validator->messages()));
} else {
Session::put('booking-form-index', Input::all());
return View::make('/appointment/bookings/verify', array('appt' => $appt));
}
}
public function success(Appointment $appt){
// validate, if valid save the booking.
// don't do anything for now
var_dump ( Session::get('booking-form-index') );
exit();
// display the success page
// return View::make('/appointment/bookings/success', array('appt' => $appt));
}
</code></pre>
<p>Here are my views ( book.blade.php )</p>
<pre><code>{{ Form::open(array('url' => '/appointment/book_new/verify/'. $appt->id )) }}
<!-- CSRF Token -->
{{ Form::token() }}
<!-- Name -->
<div>
{{ Form::text('name', Session::get('name'), array('placeholder' => 'Name')) }}
{{ $errors->first('name') }}
</div>
<!-- Email -->
<div >
{{ Form::text('email', Session::get('email'), array('placeholder' => 'email@email.com')) }}
{{ $errors->first('email') }}
</div>
<!-- Description -->
<div >
{{ Form::textarea ('description') }}
{{ $errors->first('description') }}
</div>
<!-- Form actions -->
{{ Form::submit('Click Me!') }}
{{ Form::close() }}
</code></pre>
<p>verify.blade.php</p>
<pre><code>{{ Form::open(array('url' => 'appointment/book_new/success/' . $appt->id )) }}
{{ Form::text('validate') }}
{{ Form::submit('Click Me!') }}
{{ Form::close() }}
</code></pre>
<p>success.blade.php</p>
<pre><code>Success
</code></pre>
|
[] |
[
{
"body": "<p>Looks pretty standard to me! The only minor tweak I would make just for readability is to eliminate the <code>else</code> in <code>AppointmentBookingController::verify()</code>; since you <code>return</code> in the <code>if</code>, the <code>else</code> block is not necessary, and using guard clauses like this will (arguably) make your code more readable. See <a href=\"https://stackoverflow.com/questions/268132/invert-if-statement-to-reduce-nesting?rq=1\">Invert \"if\" statement to reduce nesting</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-03T15:17:33.793",
"Id": "26939",
"ParentId": "26918",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-31T03:02:36.043",
"Id": "26918",
"Score": "1",
"Tags": [
"php",
"mvc",
"laravel"
],
"Title": "Multi-page form attempt"
}
|
26918
|
<p>I have a WCF service, which has a method for updating a EF entity. The update method works just fine but looks ugly. I think due to some EF design I have to manually set the change tracker state to <code>Modified</code> or <code>Deleted</code> or <code>Added</code>. The update method in the server side looks like this:</p>
<pre><code>public Event UpdateEvent(Guid sessionID, Event _event)
{
Session session = IFSHelperClass.CheckSession(sessionID);
try
{
using (IFSDB ifsdb = new IFSDB())
{
ifsdb.Events.Attach(_event);
ifsdb.ObjectStateManager.ChangeObjectState(_event, System.Data.EntityState.Modified);
// mark the modified and added items
// for the navigation property 'EventPersons'
foreach (var p in _event.EventPersons)
{
if (p.ChangeTracker.State == IFSEntities.ObjectState.Added)
ifsdb.ObjectStateManager.ChangeObjectState(p, System.Data.EntityState.Added);
if (p.ChangeTracker.State == IFSEntities.ObjectState.Modified)
ifsdb.ObjectStateManager.ChangeObjectState(p, System.Data.EntityState.Modified);
}
// since the deleted items will not be available in the
// navigation property, delete them manually from the
// ChangeTracker object.
if (_event.ChangeTracker.ObjectsRemovedFromCollectionProperties.Count > 0)
{
var personsToDelete = _event.ChangeTracker.ObjectsRemovedFromCollectionProperties.Where(t => t.Key == "EventPersons").Select(t => t.Value)
.FirstOrDefault()
.ToList();
foreach (EventPerson p in personsToDelete)
{
ifsdb.EventPersons.Attach(p);
ifsdb.EventPersons.DeleteObject(p);
}
}
// save all changes and accept them
ifsdb.SaveChanges();
_event.AcceptChanges();
foreach (var p in _event.EventPersons)
p.AcceptChanges();
return _event;
}
}
catch (Exception ex)
{
Logger.LogError("UpdateEvent()", ex.Message, ex.ToString(), session.User.UserID);
throw ex;
}
}
</code></pre>
<p>As you can see, II iterate through the navigation property items to check for updates or deletes and mark them manually. </p>
<p>Is this the way? or am I doing something ugly here?</p>
|
[] |
[
{
"body": "<p>You shouldn't expose entities in WCF service. Every change in entity will cause WCF webservice change and incompatibility for existing consumers. I would create decicated data transfer objects for WCF webservice and use library like Automapper to handle property mapping. </p>\n\n<p>EF entities often contain various properties (example: creation date, creator info), that shouldn't be modified, but when you expose whole entities, you allow this, which in future may cause security issues.</p>\n\n<p>Small example (without Automapper):</p>\n\n<pre><code>public class EventDTO \n{\n public int Id { get; set; }\n public DateTime EventDate { get; set; }\n public string Title { get; set; }\n}\n</code></pre>\n\n<p>In webservice class:</p>\n\n<pre><code>public Event UpdateEvent(Guid sessionID, EventDTO eventDTO)\n{\n using (IFSDB ifsdb = new IFSDB())\n {\n var event = ifsdb.Events.First(item => item.Id == eventDTO.Id);\n event.EventDate = eventDTO.EventDate;\n event.Title = eventDTO.Title;\n ifsdb.SaveChanges();\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-01T21:01:59.743",
"Id": "26920",
"ParentId": "26919",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-01T14:14:11.560",
"Id": "26919",
"Score": "2",
"Tags": [
"c#",
"entity-framework"
],
"Title": "Updating entities with EF (Delete, Add, Update) with one method"
}
|
26919
|
<p>is there a better why how can I refactor this code, making sure that values in a <code>Hash</code> are typecasted to <code>true/false</code> if their value is <code>'1'</code> or <code>'0'</code> while leaving unaltered the rest?</p>
<p>I'm using Ruby 2.0.0 if that matters, and I'd like to improve this code.</p>
<pre><code> def transform
hsh = {}
preferences.each do |k, v|
v = case v
when '1'
true
when '0'
false
else
v
end
hsh[k.to_sym] = v
end
hsh
end
</code></pre>
<p><em>updated with benchmarks</em></p>
<p>All right, here's the performance test based on the replies so far:</p>
<pre><code>class Test
HSH = {"xxx"=>"xxx-rrr", "yyy"=>"0", "rrr"=>"1", "nnn"=>"0", "kkk"=>"1", "iii"=>"1", "lll"=>"default", "mmm"=>"76", "www"=>"1"}
def self.transform_case
hsh = {}
HSH.each do |k, v|
v = case v
when '1'
true
when '0'
false
else
v
end
hsh[k.to_sym] = v
end
hsh
end
def self.transform_ternary
Hash[ HSH.map { |k, v| [k.to_sym, v == '1' ? true : v == '2' ? false : v ] } ]
end
def self.transform_fetch
special_values = {"1" => true, "0" => false}
Hash[HSH.map { |k, v| [k.to_sym, special_values.fetch(v, v)] }]
end
def self.transform_negation
Hash[ preferences.map {|k,v| [k.to_sym, !!v]} ]
end
end
Benchmark.bm(20) do|b|
b.report('case') do
1500.times { Test.transform_case }
end
b.report('ternary') do
1500.times { Test.transform_ternary }
end
b.report('fetch') do
1500.times { Test.transform_fetch }
end
b.report('negation') do
1500.times { Test.transform_negation }
end
end
user system total real
case 0.010000 0.000000 0.010000 ( 0.009282)
ternary 0.010000 0.000000 0.010000 ( 0.013794)
fetch 0.010000 0.000000 0.010000 ( 0.012804)
negation 0.010000 0.000000 0.010000 ( 0.010760)
</code></pre>
<p>It appears that my original implementation is faster. Or is the BM test wrong?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-03T14:27:58.090",
"Id": "41739",
"Score": "0",
"body": "don't select an answer so soon! leave time for others to answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-03T14:38:25.950",
"Id": "41740",
"Score": "0",
"body": "Oh ok, thanks :) I'm going to do some benchmarks between the replies before selecting then. Thanks!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-04T07:25:41.770",
"Id": "41795",
"Score": "1",
"body": "I agree with @tokland that this kind of benchmark is not quite relevant : as your current code works, the question you asked was implicitly about expressiveness. And then : 1) your `HSH` should be a lot longer for your benchmark to be representative (possible differences in big'O) 2) in `transform_fetch` you create a `special_values` hash every time the method is called, which is not necessary and hurts performance"
}
] |
[
{
"body": "<p>Code should be as declarative as possible (usually by using <a href=\"https://code.google.com/p/tokland/wiki/RubyFunctionalProgramming\" rel=\"nofollow\">functional style</a>):</p>\n\n<pre><code>def transform\n special_values = {\"1\" => true, \"0\" => false}\n Hash[preferences.map { |k, v| [k.to_sym, special_values.fetch(v, v)] }]\nend\n</code></pre>\n\n<p>However, <code>Hash[...]</code> is very ugly and I prefer a more OOP approach with <a href=\"http://rdoc.info/github/rubyworks/facets/master/Enumerable#graph-instance_method\" rel=\"nofollow\">Enumerable#mash</a>, so I'd really write <code>preferences.mash { |k, v| [k.to_sym, special_values.fetch(v, v)] }</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-03T14:45:32.107",
"Id": "41743",
"Score": "0",
"body": "Added benchmarks to the original post"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-03T15:17:15.930",
"Id": "41747",
"Score": "3",
"body": "@John: A benchmark of this kind of code is not relevant. Go for the most declarative code."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-03T14:29:45.347",
"Id": "26933",
"ParentId": "26923",
"Score": "4"
}
},
{
"body": "<p>You can do this:</p>\n\n<pre><code>Hash[ preferences.map {|k,v| [k.to_sym, v.nonzero? or false]} ]\n</code></pre>\n\n<p>This preserves the value if it is nonzero, otherwise makes it false. It does not change a 1 to true though. I like @tokland's answer best, because it not only does the exact transformation you want, but makes it easy to extend and use as a general purpose transformer (if you ever need to change other values as well), which one might assume is your purpose for this method, based on the name.</p>\n\n<p><strong>Code review</strong></p>\n\n<p>Note that when you initialize a return variable and then loop over another variable, e.g.</p>\n\n<pre><code>hsh = {}\npreferences.each do\n #something that updates hsh\nend\n</code></pre>\n\n<p>A more idiomatic Ruby way to do this is with a <code>map</code>, as the answers show. This will in general result in more concise, expressive code.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-03T14:42:21.153",
"Id": "26936",
"ParentId": "26923",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "26933",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-03T13:55:09.390",
"Id": "26923",
"Score": "1",
"Tags": [
"ruby"
],
"Title": "Manipulate Hash to typecast true/false for certain values"
}
|
26923
|
<p>I have a small WPF application which I'm not exactly localizing, but not hard-coding resources either. I know WPF doesn't use .resx files for that purpose, but I exposed the resource strings as public ViewModel properties which the view's controls bind to:</p>
<pre><code>using resx = MyApp.Properties.Resources;
...
public string InterferingProcessesText { get { return resx.InterferingProcessesText; } }
public string SettingsText { get { return resx.SettingsText; } }
public string ExecuteInstallerCommandText { get { return resx.ExecuteInstallerCommandText; } }
public string SaveSettingsCommandText { get { return resx.SaveSettingsCommandText; } }
public string RefreshProcessesCommandText { get { return resx.RefreshProcessesCommandText; } }
public string KillInterferingProcessesCommandText { get { return resx.KillInterferingProcessesCommandText; } }
</code></pre>
<p>And then if I ever decide to translate the strings I can copy my .resx file and rename it with a culture suffix just like I would have done in WinForms or in any other Web app.</p>
<p>I know I'm supposed to put <code>x:Uid</code> all over my XAML and localize my app the way WPF has it, but just how bad is that, and why?</p>
<p>Yes, it clutters up my ViewModels with public string properties (<code>#region</code> to the rescue!). But does it violate some MVVM principle that will come and bite me in the *** later?</p>
|
[] |
[
{
"body": "<p>I have had the same thought when implementing localisation in WPF, and came to the conclusion that .resx files are fine. I came to that conclusion because alternatives quickly became more complicated than I could be bothered with, and a RESX-based solution works for me.</p>\n\n<p>So, in my various View.xaml files, I use bindings like this;</p>\n\n<pre><code><MenuItem Name=\"Exit\" Header=\"{x:Static Resources:Strings.MENU_HEADER_EXIT}\" />\n</code></pre>\n\n<p>Changing languages is simply a matter of creating language-specific versions of the RESX entries. (<a href=\"http://msdn.microsoft.com/en-us/library/vstudio/aa992030%28v=vs.100%29.aspx\">http://msdn.microsoft.com/en-us/library/vstudio/aa992030%28v=vs.100%29.aspx</a>).</p>\n\n<p>Now in regards to your actual question; I do not think this sort of data belongs in a ViewModel. There is no 'modelling' going on with these strings; they are just label text, and as such are view-only data. If we follow your above suggestion to an overzealous conclusion, we might as well add ViewModel properties (and Bindings) like;</p>\n\n<pre><code>Font InterferingProcessesFont { get { return FontFamily.Arial; }\nColor InterferingProcessesFontColor { get { return Color.Black; }\nFontStyle InterferingProcessesFontStyle { get { return FontStyle.Normal; }\n. \netc.\n. \n</code></pre>\n\n<p>For my mind, localised labels like this are fixed display settings that will not change for the life of an application, and in most cases, will never change for a particular user. Why clutter a ViewModel with static text?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-04T11:44:19.637",
"Id": "41806",
"Score": "0",
"body": "Wow I didn't realize I could bind with resx directly in the xaml! I totally agree they don't quite belong there at all!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-04T04:31:13.400",
"Id": "26965",
"ParentId": "26928",
"Score": "7"
}
},
{
"body": "<p>RESX files are very ok! And if you have Microsoft MAT (Multilingual App Toolkit) installed (free extension) for visual studio it simplifies the management of your translations ;-)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-12T07:01:43.217",
"Id": "198340",
"ParentId": "26928",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "26965",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-03T14:13:19.360",
"Id": "26928",
"Score": "5",
"Tags": [
"c#",
"wpf",
"localization"
],
"Title": "WPF Localisation - using resx"
}
|
26928
|
<p>I have a deep equality comparison method that returns <code>true</code> when two objects are equal (<a href="http://www.boilerjs.com/#api_isEqual" rel="nofollow">see method Doc</a>):</p>
<pre><code>_.isEqual = function (obj1, obj2) {
// Quick compare objects that don't have nested objects
if (_.type(obj1) === _.type(obj2) && !_.isPlainObject(obj1) && !_.isArray(obj1)) {
switch (_.type(obj1)) {
case "function" :
if (obj1.toString() !== obj2.toString()) return false;
break;
case "nan" :
if (obj1 === obj2) return false;
break;
default:
if (obj1 !== obj2) return false;
}
} else {
// When target or comparison is falsy we compare them directly
if (_.isFalsy(obj1) || _.isFalsy(obj2)) {
if (obj1 !== obj2) return false;
}
for (var o in obj1) {
switch (true) {
// Catch comparison of element first to prevent infinite loop when caught as objects
case ( _.isElement(obj1[o]) ) :
if (obj1[o] !== obj2[o]) return false;
break;
case ( _.isNaN(obj1[o]) ) :
if (!_.isNaN(obj2[o])) return false;
break;
case ( typeof obj1[o] === "object" ) :
if (!_.isEqual(obj1[o], obj2[o])) return false;
break;
case ( typeof obj1[o] === "function" ) :
if (!_.isFunction(obj2[o])) return false;
if (obj1[o].toString() !== obj2[o].toString()) return false;
break;
default :
if (obj1[o] !== obj2[o]) return false;
}
}
// Reverse comparison of `obj2`
for (var o in obj2) {
if (typeof obj1 === "undefined") return false;
if (obj1 === null || obj1 === undefined) return false;
if (_.isFalsy(obj1[o])) {
if (_.isNaN(obj1[o])) {
if (!_.isNaN(obj2[o])) return false;
} else if (obj1[o] !== obj2[o]) return false;
}
}
}
return true;
};
</code></pre>
<p>I'm looking for advice on strategies I can use to improve its performance. My initial thoughts are get rid of my calls to internal library methods? Should I implement a different type of loop. Would a <code>while</code> lead to any performance gains?</p>
<hr>
<p>After taking much of what @Joseph the Dreamer said into account I refactored <code>_.isEqual</code> in a seemingly much more efficient manner, which now compares the properties and values that might be attached to functions as well. As you can see I did away with a great many of my previous comparisons because they're rendered redundant in this iteration (I believe).</p>
<p>Here are the unit tests to back this method up: <a href="http://www.boilerjs.com/tests/?testNumber=91" rel="nofollow">_.isEqual Unit Tests</a></p>
<p>The code:</p>
<pre><code>_.isEqual = function (obj1, obj2) {
var type = _.type(obj1), result, o;
switch (true) {
// Not the same TYPE
case type != _.type(obj2) :
return false;
// NaNs
case type == 'nan' :
return _.isNaN(obj1) && _.isNaN(obj2);
// Primitives (types that will compare correctly with ===)
case ((typeof obj1 != 'object' && type != 'function') || type == 'null') :
return obj1 === obj2;
// Functions or Elements
case type == 'function' || type == 'element' :
return obj1.constructor === obj2.constructor;
// JavaScript Objects
default :
if (_.len(obj1) == 0) {
result = _.len(obj2) == 0;
} else {
for (o in obj1) {
if (!(result = _.isEqual(obj1[o], obj2[o]))) break;
}
}
}
return result;
};
</code></pre>
|
[] |
[
{
"body": "<p>After going through the code and the library itself, here are some thoughts:</p>\n\n<ul>\n<li><p>Functions are still objects. You can even attach properties to it. You might want to look into this unless you only want to compare the function, excluding the things attached to it.</p>\n\n<pre><code>function foo(){};\nfoo.bar = 'baz';\nconsole.log(foo.bar); //baz\n</code></pre></li>\n<li><p>Early on, you can weed out values that are equal or actually the same to avoid going through everything. Equal strings, numbers, booleans and even objects in general (Since they are compared by identity) return <code>true</code>.</p>\n\n<pre><code>obj1 === obj2\n</code></pre>\n\n<p>If this returns <code>false</code>, it could be that the values are non-equal primitives, or non-identical objects. You can return <code>false</code> for the primitives. For objects in general, only then will you do the \"structure equality check\".</p></li>\n<li><p>Comparisons return a boolean value. So if you return a boolean after a comparison without doing anything else after, you can shorten the statement.</p>\n\n<pre><code>/*from*/ if(a !== b) return false;\n/* to */ return a === b;\n</code></pre></li>\n<li><p>While <code>for(var o in obj1)</code> is perfectly valid JS, it's something you'd look out for. You actually did this twice in the code. If you pass your code through a linter, you'd get a <code>o already defined</code> error. Do this instead</p>\n\n<pre><code>var o;\n\nfor(o in obj1){...}\n...\nfor(o in obj2){...}\n</code></pre>\n\n<p>Or better, just use another variable name instead of <code>o</code> on the second loop.</p></li>\n<li><p>You seem to already have a lot of abstractions in your library, which is good. However, your code seems to use a mix of abstracted and vanilla code. I suggest using your abstracted code so that in case the approach for a certain operation is wrong, you only need to modify the abstracted version. </p>\n\n<p>jQuery actually does this. It keeps a \"Core API\" which is used by the other parts of the source. If you look at their source, <code>each</code> and <code>extend</code> are used quite a lot.</p></li>\n<li><p><code>null</code> and <code>undefined</code> are already falsy values. Assuming you already weeded out other values for <code>obj1</code>, you could already simplify.</p>\n\n<pre><code>if(typeof obj1 === \"undefined\") return false;\nif(obj1 === null || obj1 === undefined) return false;\n\n//to\n\nif(!obj1) return false;\n//or\nif(_.isFalsy(obj1)) return false;\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-04T15:21:30.450",
"Id": "41824",
"Score": "1",
"body": "I took much of what you said under advisement and posted a revised iteration of the method above. Thank you! ... I'll post the results of the performance tests soon."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-05T15:14:49.320",
"Id": "41912",
"Score": "0",
"body": "Initial performance tests are looking quite good: http://jsperf.com/boiler-isequal-vs-underscore-isequal"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-05T15:21:15.100",
"Id": "41913",
"Score": "0",
"body": "@Xaxis You might want to run the unit tests from other libraries to your own implementation, just to be sure. Maybe your code took shortcuts for optimization which other libraries didn't take for compatibility, crash-proofing or some other reason. But the tests look good."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-04T02:54:19.110",
"Id": "26960",
"ParentId": "26929",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-03T14:16:20.057",
"Id": "26929",
"Score": "2",
"Tags": [
"javascript",
"performance",
"library-design"
],
"Title": "Boiler.js Deep Object Comparison Code/Performance Optimizations?"
}
|
26929
|
<p>The purpose is just to create a dictionary with a path name, along with the file's SHA-256 hash.</p>
<p>I'm very new to Python, and have a feeling that there's a much better way to implement the following code. It works, I'd just like to clean it up a bit.
fnamelst = [r'C:\file1.txt',
r'C:\file2.txt']</p>
<pre><code>[fname.replace('\\', '\\\\') for fname in fnamelst]
diction = [{fname: hashlib.sha256(open(fname, 'rb').read()).digest()} for fname in fnamelst]
for iter in range(0,len(fnamelst)):
dic2 = {fnamelst[iter]: hashlib.sha256(open(fnamelst[iter], 'rb').read()).digest()}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-03T14:20:10.763",
"Id": "41735",
"Score": "1",
"body": "Why are you replacing slashes??"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-03T14:20:58.690",
"Id": "41736",
"Score": "1",
"body": "Well, you've created the dictionary twice. What's the question?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-03T14:24:24.227",
"Id": "41737",
"Score": "2",
"body": "Note that the `for` loop will overwrite `dic2` each time, instead of extending it."
}
] |
[
{
"body": "<p>In python, <code>for iter in range(0,len(container)):</code> is pretty much always a bad pattern.</p>\n\n<p>Here, you can rewrite :</p>\n\n<pre><code>for f in fnamelst:\n dic2 = {f: hashlib.sha256(open(f, 'rb').read()).digest()}\n</code></pre>\n\n<p>As @tobias_k pointed out, this doesn't do much at the moment as <code>dict2</code> gets overriden.\nIn Python 2.7+ or 3, you can just use the <a href=\"http://www.python.org/dev/peps/pep-0274/\" rel=\"nofollow\">dict comprehension</a> directly.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-03T14:30:47.510",
"Id": "26934",
"ParentId": "26931",
"Score": "2"
}
},
{
"body": "<p>In your code, you show two ways to create your dictionary, but both are somewhat flawed:</p>\n\n<ul>\n<li><code>diction</code> will be a list of dictionaries, each holding just one entry</li>\n<li><code>dic2</code> will get overwritten in each iteration of the loop, and will finally hold only one dictionary, again with only one element.</li>\n</ul>\n\n<p>Instead, try this:</p>\n\n<pre><code>diction = dict([ (fname, hashlib.sha256(open(fname, 'rb').read()).digest())\n for fname in fnamelst ])\n</code></pre>\n\n<p>Or shorter, for Python 2.7 or later:</p>\n\n<pre><code>diction = { fname: hashlib.sha256(open(fname, 'rb').read()).digest()\n for fname in fnamelst }\n</code></pre>\n\n<p>The first one uses a list comprehension to create a list of key-value tuples, and then uses the <code>dict</code> function to create a single dictionary from that list. The second one does the same, using a dict comprehension.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-03T14:38:12.107",
"Id": "26935",
"ParentId": "26931",
"Score": "4"
}
},
{
"body": "<p>You have some confusion about using backslahses in Python strings.</p>\n\n<p><code>r'C:\\file1.txt'</code> is a raw string and the backslash is a backslash. <code>r</code> in front denotes raw.</p>\n\n<p><code>'C:\\\\file1.txt'</code> is the same string written as a normal string literal. Now the backslash has to be written as <code>\\\\</code>, because otherwise <code>\\f</code> would be interpreted as a control character <code>\\x0c</code>.</p>\n\n<p>Doubling the backslash using <code>replace</code> serves no purpose here. Moreover, as tobias_k points out, the line with the replace has no effect at all because the resulting modified list is not assigned to a variable.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-04T07:43:42.323",
"Id": "41797",
"Score": "1",
"body": "Moreover, the line with the `replace` has no effect at all, as the strings in the list are immutable, and the new list is not assigned to a variable."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-04T06:01:51.437",
"Id": "26967",
"ParentId": "26931",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-03T14:18:40.437",
"Id": "26931",
"Score": "1",
"Tags": [
"python",
"hash-map"
],
"Title": "Creating a dictionary with a path name and SHA-256 hash"
}
|
26931
|
<p>I was solving one of the problem in USACO 2007 Open Silver:</p>
<blockquote>
<p><strong>Description</strong></p>
<p>Farmer John has taken his cows on a trip to the city! As the sun sets, the cows gaze at the city horizon and observe the beautiful silhouettes formed by the rectangular buildings.</p>
<p>The entire horizon is represented by a number line with \$N (1 ≤ N ≤ 40,000\$) buildings. Building \$i\$'s silhouette has a base that spans locations \$Ai\$ through \$Bi\$ along the horizon \$1 ≤ Ai < Bi ≤ 1,000,000,000\$ and has height \$Hi\$ (\$1 ≤ Hi ≤ 1,000,000,000\$).</p>
<p>Determine the area, in square units, of the aggregate silhouette formed by all \$N\$ buildings.</p>
<p><strong>Input</strong></p>
<ul>
<li>Line 1: A single integer: N</li>
<li>Lines 2...N+1: Input line i+1 describes building \$i\$ with three space-separated integers: \$Ai\$, \$Bi\$, and \$Hi\$.</li>
</ul>
<p><strong>Output</strong></p>
<p>Line 1: The total area, in square units, of the silhouettes formed by all \$N\$ buildings</p>
<p><strong>Sample Input</strong></p>
<pre class="lang-none prettyprint-override"><code>4
2 5 1
9 10 4
6 8 2
4 6 3
</code></pre>
<p><strong>Sample Output</strong></p>
<pre class="lang-none prettyprint-override"><code>16
</code></pre>
</blockquote>
<p>I used a divide-and-conquer algorithm to solve this problem, but failed. The feedback of the online judgement system is Time Limit Exceeded. Could you help me to make my code more efficient, readable, and clear?</p>
<pre class="lang-c prettyprint-override"><code>#include <stdio.h>
#include <malloc.h>
#define INF 10000000000
enum {MAX = 2, DIM = 3};
typedef struct Outline Outline;
struct Outline {
int pos;
int height;
};
/* merge two outlines of buildings */
Outline *mergebuilding(Outline *a, Outline *b, int num)
{
int a_move = 0;
int b_move = 0;
int r_count = 0;
int r_move = 0;
int pre = -1;
int x = 0;
int y = 0;
Outline *r = (Outline *) malloc(MAX * num * (sizeof(Outline)) + sizeof(Outline));
while (a[a_move].pos < INF || b[b_move].pos < INF) {
r[r_move].pos = (a[a_move].pos <= b[b_move].pos) ? a[a_move].pos : b[b_move].pos;
if (r[r_move].pos == a[a_move].pos) {
x = a[a_move].height;
a_move++;
}
if (r[r_move].pos == b[b_move].pos) {
y = b[b_move].height;
b_move++;
}
r[r_move].height = (x >= y) ? x : y;
if (r[r_move].height != pre) {
pre = r[r_move].height;
r[r_move+1] = r[r_move];
r_move++;
}
}
r[r_move].pos = INF;
return r;
}
/* divide-and-conquer */
Outline *recursive(Outline **p, int low, int high)
{
/*
Recursively divide the set of buildings into two parts
until one block, then merge two blocks from the bottom to the top.
*/
Outline *part1, *part2, *merge;
int mid;
if (low == high)
return p[low];
mid = (low + high) / 2;
part1 = recursive(p, low, mid);
part2 = recursive(p, mid+1, high);
merge = mergebuilding(part1, part2, low+high+1);
free(part1);
free(part2);
return merge;
}
int main()
{
int **bul;
int num;
Outline **p, *cp;
scanf("%d", &num);
bul = (int **) malloc(num * sizeof(int));
p = (Outline **) malloc(num * sizeof(Outline));
for (int i = 0; i < num; i++) {
bul[i] = (int *) malloc(DIM * sizeof(int));
p[i] = (Outline *) malloc(DIM * sizeof(Outline));
scanf("%d %d %d", &bul[i][0], &bul[i][1], &bul[i][2]);
p[i][0].pos = bul[i][0];
p[i][0].height = bul[i][2];
p[i][1].pos = bul[i][1];
p[i][1].height = 0;
p[i][2].pos = INF;
free(bul[i]);
}
free(bul);
cp = recursive(p, 0, num-1);
free(p);
int temp, square;
square = 0;
for (int i = 0; cp[i].pos < INF; i++) {
temp = (cp[i+1].pos - cp[i].pos) * cp[i].height;
square += temp;
}
printf("%d\n", square);
free(cp);
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-03T21:43:02.093",
"Id": "41773",
"Score": "0",
"body": "Is this algorithm complexity O(n log n)? I'm thinking that using radix sort, it should be possible to get it down to O(n)."
}
] |
[
{
"body": "<p>I don't know for sure why your program is running out of time (since I know nothing about the target platform), but my guess is that it's either item (1) or (2) in the list below. These errors lead to <em>undefined behaviour</em>, and then, well, anything could happen (that's what <em>undefined</em> means), including an infinite loop.</p>\n\n<ol>\n<li><p>This line computes the wrong size for the allocation:</p>\n\n<pre><code>bul = (int **) malloc(num * sizeof(int));\n</code></pre>\n\n<p>You want an array of <code>num</code> <em>pointers to integers</em> but you are allocating space for <code>num</code> <em>integers</em>. So this will only work if an integer is the same size as a pointer. On my platform/compiler (x86-64/Clang) an integer is 4 bytes long but a pointer is 8 bytes long so this computes a size that is too small, and then the loop writes off the end of the array, which results in undefined behaviour. (On my platform this causes the program to crash with a segmentation fault.)</p>\n\n<p>You need to write:</p>\n\n<pre><code>bul = malloc(num * sizeof(int *));\n</code></pre>\n\n<p>or:</p>\n\n<pre><code>bul = malloc(num * sizeof *bul);\n</code></pre>\n\n<p>instead. Note that there's no need to cast the result of <code>malloc()</code> since the function returns <code>void *</code> and that type is convertible to any object pointer type without a cast.</p></li>\n<li><p>The total area might be close to 10<sup>18</sup> units. For example if the input was </p>\n\n<pre><code>1\n1 1000000000 1000000000\n</code></pre>\n\n<p>then your program would need to output</p>\n\n<pre><code>999999999000000000\n</code></pre>\n\n<p>and yet you are accumulating the area in the variable <code>square</code>, which is an <code>int</code>. Is <code>int</code> large enough on the target platform/compiler to store a number of this size? It certainly isn't on mine (x86-64/Clang) where <code>INT_MAX</code> is <code>2147483647</code>.</p>\n\n<p>This means that your program causes integer overflow, which yields undefined behaviour. (<a href=\"http://blog.regehr.org/archives/213\" rel=\"nofollow\">John Regehr has a good explanation here.</a>)</p>\n\n<p>On my platform (with item (1) above fixed) this bug causes <code>mergebuilding()</code> to run off the end of the array in an infinite loop (because the comparison with <code>INF</code> goes wrong) and this eventually hits unmapped memory and crashes with a segmentation fault.</p>\n\n<p>I'm surprised that you didn't spot this at compilation time. I get these warnings from Clang:</p>\n\n<pre><code>cr26938.c:46:21: warning: implicit conversion from 'long' to 'int' changes value\n from 10000000000 to 1410065408 [-Wconstant-conversion]\n r[r_move].pos = INF;\n ~ ^~~\ncr26938.c:4:13: note: expanded from macro 'INF'\n#define INF 10000000000\n ^~~~~~~~~~~\n</code></pre>\n\n<p>And these from gcc:</p>\n\n<pre><code>cr26938.c: In function ‘mergebuilding’:\ncr26938.c:26: warning: comparison is always true due to limited range of data type\ncr26938.c:26: warning: comparison is always true due to limited range of data type\ncr26938.c:46: warning: overflow in implicit constant conversion\n</code></pre>\n\n<p>Perhaps you can say what compiler you are using?</p>\n\n<p>You need to use a type that's large enough on the target platform to store numbers of the required size. If the target platform conforms to C99, then you can</p>\n\n<pre><code>#include <stdint.h>\n</code></pre>\n\n<p>and then use <code>int64_t</code>, which is guaranteed by the standard to be a signed integer type with exactly 64 bits. But if the target platform does not conform to C99, then, well, I guess you need to read the compiler manual to find out what type is big enough (but probably <code>long</code> or <code>long long</code> would work).</p></li>\n<li><p>You write</p>\n\n<pre><code>#include <malloc.h>\n</code></pre>\n\n<p>which is non-standard: in Standard C, <code>malloc()</code> is declared in <code>stdlib.h</code>. Unless your platform is really non-standard, I'd stick with <code>stdlib.h</code>.</p></li>\n<li><p>What is the role of the <code>bul</code> array? You only ever use one element at a time, and then only to read some numbers which you immediately copy out again. Why not read the input into variables on the stack instead? Perhaps like this:</p>\n\n<pre><code>for (int i = 0; i < num; i++) {\n int a, b, h;\n scanf(\"%d %d %d\", &a, &b, &h);\n</code></pre></li>\n<li><p>You don't check the return values of the functions you call. <code>malloc()</code> returns <code>NULL</code> if it can't allocate, and <code>scanf()</code> returns the number of input items assigned, which might be less than the number of format specifiers if there was an error. I know this is only a simple program that doesn't require much in the way of error handling, but it's still an opportunity for you to practice your skills. And it doesn't have to be burdensome: you can write</p>\n\n<pre><code>if (p[i] == NULL) error(\"out of memory\");\nif (scanf(\"%d %d %d\", &a, &b, &h) != 3) error(\"malformed input\");\n</code></pre>\n\n<p>with <code>error()</code> defined like this:</p>\n\n<pre><code>void error(const char *message) {\n fprintf(stderr, \"%s\\n\", message);\n abort();\n}\n</code></pre></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-08T07:39:30.913",
"Id": "42173",
"Score": "0",
"body": "Sorry for the late reply, the compiler I'm using is VS 2010. I have already corrected these mistakes but still running out of time. I guess this algorithm may not be suitable to the problem. BTW, here is the [link](http://poj.org/problem?id=3277) for the online judgement system."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-03T18:08:37.267",
"Id": "26945",
"ParentId": "26938",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-03T14:52:57.073",
"Id": "26938",
"Score": "3",
"Tags": [
"optimization",
"c",
"programming-challenge"
],
"Title": "Why is this divide and conquer algorithm inefficient?"
}
|
26938
|
<p>I've tried to write an "OOP" approach to printing a website using the DOMDocument class. I'm kind of stuck here because I feel like I am blundering in how I am passing and using the DOMDocument. I found that I can just return the object from the class and use it that way. </p>
<p>What are some safe practices here? Best approach? I know it's far from OOP, but I at least want to be considerate of the model while learning. I realize my approach is probably all backwards. How bad is this code and what are some ways to improve this?</p>
<p>All styling is done in CSS, any and all critique is welcome about any aspect of the code. </p>
<p>If this isn't considered to be a useful question let me know and I will remove it.</p>
<pre><code><?php
require 'viewer.php'
//new viewer class
$v= new viewer();
//read html document structure from a template
$page= $v->setPage('template.html');
//find body
$body= $v->returnBody();
//create new element and attach it to body
$v->newElement('div', $body, "id=container");
$cont = $v->getElement("container");
$v->newElement('div', $cont, "id=title", "My Website");
$v->newElement('ul', $cont, "id=menu;class=menu");
$v->newElement('li', $v->getElement("menu"), NULL, "Forums" );
$v->newElement('div', $cont, "id=content");
$v->newElement('div', $v->getElement("content"), "id=content_title", "Content Title Here!");
$v->newElement('div', $v->getElement("content"), "id=content_box");
$mb = $v->getElement("content_box");
$v->newElement('a',$mb,NULL,"Some Link");
$content = " And after the link, this is the content.";
$dd=$v->rDOM();
$c=$dd->createTextNode($content);
$mb->appendChild($c);
$v->printHTML();
?>
</code></pre>
<p>Where the <code>Viewer</code> class is:</p>
<pre><code><?php
class viewer {
protected $dom;
public function __construct(){
$this->dom = new DOMDocument();
}
//Creates an element of the type passed in string, appends parameters passed in string
//and finally inserts into the passed node
public function newElement($type, $insertInto = NULL, $params=NULL, $content=""){
$element = $this->dom->createElement($type, $content);
if(gettype($params) == "string" && strlen($params) > 0){
$attrCollec = preg_split("/;/", $params);
foreach($attrCollec as $attr){
$value = preg_split("/=/", $attr);
$element->setAttribute($value[0], $value[1]);
}
}
$insertInto->appendChild($element);
}
public function getElement($param){
//if($this->dom->validate()){
$elem = $this->dom->getElementById($param);
return $elem;
//}
}
public function setPage($fileName){
//does this even work? should validate before each getElement call?
$this->dom->validateOnParse = true;
$this->dom->loadHTMLFile($fileName);
}
public function printHTML(){
echo $this->dom->saveHTML();
}
public function returnBody(){
$nodeList = $this->dom->getElementsByTagName('body');
$body = $nodeList->item(0);
return $body;
}
public function rDOM(){
return $this->dom;
}
}
?>
</code></pre>
|
[] |
[
{
"body": "<h2>Some things I spot on the fly:</h2>\n\n<ul>\n<li>Lack of documentation. <strong><a href=\"http://www.phpdoc.org/\" rel=\"nofollow\">PHPDoc</a></strong> works well, every method, every class, every file should have a DocBlock.</li>\n<li>Naming conventions. It's considered good naming convention to have <code>methodNames()</code> and <code>$variableNames</code> in camelCase, but <code>ClassNames</code> and <code>ObjectNames</code> in <code>UppercaseCamelCase</code>.</li>\n<li>Code style. Conforming to a single code style is great. Conforming to an established standard is <strong>awesome!</strong>. Check out the <strong><a href=\"https://github.com/php-fig/fig-standards/tree/master/accepted\" rel=\"nofollow\">PSR Code style standards page</a></strong>.</li>\n<li>On the <code>newElement</code> method, <code>preg_split</code> is redundant. <code>explode</code> by <code>;</code> or <code>=</code> is enough, and is faster!</li>\n<li>Last but not least, if the entire file is PHP (without embedding HTML), it's considered safe (and even recommended!) to omit the closing <code>?></code> at the end of the file. This helps with line break and whitespace issues.</li>\n</ul>\n\n<p>I'll continue editing as I explore more.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-31T15:58:25.037",
"Id": "29233",
"ParentId": "26947",
"Score": "4"
}
},
{
"body": "<p>You should consider to use an array to pass the attributes to the <code>newElement</code> method.\nAlso you need a <code>DOMElement</code> as parameter, as you use call the method <code>appendChild</code>, but you made it optional.</p>\n\n<pre><code>public function newElement($type, DOMElement $insertInto, $params=array(), $content=\"\"){\n $element = $this->dom->createElement($type, $content);\n foreach($params as $attr => $value){\n $element->setAttribute($attr, $value);\n }\n $insertInto->appendChild($element);\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>$v->newElement('div', $body, array('id'=>\"container\"));\n</code></pre>\n\n<p>In my oppinion it will become very hard to read and handle if you want to create a complex pages with tables and forms with the DOM class. Personally I would prefer a plain PHP template with placeholders or a template engine like smarty or twig for example.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T01:37:37.670",
"Id": "42381",
"ParentId": "26947",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "29233",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-03T18:43:21.733",
"Id": "26947",
"Score": "5",
"Tags": [
"php",
"beginner",
"dom"
],
"Title": "OOP approach to using DOMDocument"
}
|
26947
|
<p>I always considered <code>switch</code> statement as somehow defective:</p>
<ul>
<li>works only on integral types and enumerations.</li>
<li>isn't an readability improvement over traditional if/else chain.</li>
<li>forget a <code>break</code> - you have a bug.</li>
<li>variable declaration spills over neighbouring cases.</li>
<li>is essentially a computed goto</li>
</ul>
<p>Because of said reasons, and also as an exercise on lambdas and variadic templates I created my own flow control function. </p>
<pre><code>#include <functional>
#include <tuple>
template<typename V>
bool switch_on(const V& value)
{
return false;
}
template<typename V, typename P, typename... Args>
bool switch_on(const V& value, const P& p, Args... args)
{
if(std::get<0>(p)(value, std::get<1>(p)))
{
std::get<2>(p)();
return true;
}
else
{
return switch_on(value, args...);
}
}
template<template <typename> class P, typename F, typename V >
auto case_of(const V& v, const F& p) -> decltype( std::make_tuple(P<V>(), v, p) )
{
return std::make_tuple(P<V>(), v, p);
}
template<typename P, typename F, typename V >
auto case_of(const V& v, const F& p) -> decltype( std::make_tuple(P(), v, p) )
{
return std::make_tuple(P(), v, p);
}
template<typename F, typename V >
auto case_of(const V& v, const F& p) -> decltype( std::make_tuple(std::equal_to<V>(), v, p) )
{
return std::make_tuple(std::equal_to<V>(), v, p);
}
</code></pre>
<p>so I can use:</p>
<pre><code>using std::less;
using std::greater;
int main()
{
int a = 42;
switch_on(a,
case_of<less>(0, [&]{
std::cout << "LESS THAN ZEROOOOOOOOOOOOOO.";
}),
case_of(42, [&]{
std::cout << "Yes";
}),
case_of<greater>(9000, [&]{
std::cout << "IT'S OVER NINE THOUSAAAAAAAAND!!!";
})
);
}
</code></pre>
<p>While in Lisp, it is encouraged to create new forms of flow control, what about C++? I would also like to see some opinions about template usage, some pointers on how to improve the code and possible corner cases when this code will break.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-05T00:58:36.253",
"Id": "41868",
"Score": "0",
"body": "Not sure I agree wiht: `isn't an readability improvement over traditional if/else chain.` or `forget a break - you have a bug` lot of functionality for fall through and when you do need it the compiler will warn you about it being missing so not a real problem. Don't believe this is true `variable declaration spills over neighboring cases` in C++. Anything with a constructor is bound into a case scope. Though true `is essentially a computed goto` you can use the same argument for `for(;;)`, `while()`, `if(){}else{}` etc. Any control flow basically boils down to a computed goto."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-05T01:41:50.403",
"Id": "41875",
"Score": "0",
"body": "@LokiAstari `when you do need it the compiler will warn you about it being missing so not a real problem`. Not sure what you mean here - can compiler distinguish when I need fall-through? `Anything with a constructor is bound into a case scope.` [Well, apparently only if you use braces to introduce one](http://stackoverflow.com/a/92730/1012936), that is, by `is essentially a computed goto` I meant `goto` not on assembler level, but on a high-level language level. And the rant against `break` is because `switch` favours less common case (I want to fall-throgh) over more common case."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-05T01:46:22.287",
"Id": "41876",
"Score": "0",
"body": "@LokiAstari I realise that my approach is flawed though - this function doesn't integrate so well with language, but I'm still looking for alternatives."
}
] |
[
{
"body": "<p>Lisp has an uniform syntax, so it’s possible to create user defined flow control constructs that look exactly like the built in constructs. In C++, that’s generally not possible.</p>\n\n<p>Your code is certainly clever, and it solves the problem of omitted breaks (I consider the other drawbacks you list less important). However:</p>\n\n<ul>\n<li>Despite naming this a “switch”, you’ve essentially recreated an if-else chain. Notably, a compiler may have a bit more difficulty optimizing this than a traditional switch.</li>\n<li>Your implementation does not seem to support range comparisons or a default case, although both of these seem to be doable in your conceptual framework.</li>\n<li>When used in a disciplined way, falling through from one switch case to the next is not always devoid of merit.</li>\n<li>I’m not sure that returning this boolean has a great benefit. It might be preferable to design a construct that ensures that one of the cases is always executed.</li>\n<li>Be honest: do you really find this more readable than a traditional switch statement?</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-04T14:03:30.903",
"Id": "41811",
"Score": "0",
"body": "Thank you for your opinion. Well, at first I tried to copy Pascal's `case of` statement, and halfway switched to VB's `Select Case`. So... yeah, maybe it's not that readable."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-04T06:04:27.920",
"Id": "26968",
"ParentId": "26952",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "26968",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-03T20:54:33.977",
"Id": "26952",
"Score": "4",
"Tags": [
"c++",
"c++11"
],
"Title": "Creating my own flow control statements in C++. Is that acceptable?"
}
|
26952
|
<p>There is repetition here and would appreciate help in improving this code. Suggestions? Here's the framework for it:</p>
<pre><code>Class Author {
private Integer id;
public static List<Book> sortBooksAlphabetically( Author a ) {
Integer id = a.id;
if (id == null) { return null; }
List<Book> list = getAllBooksForAuthor( id );
// do some sorting and return list
}
public static List<Book> sortBooksReverseAlphabetically( Integer id ) {
if (id == null ) { return null; }
List<Book> list = getAllBooksForMusician( id );
// do some sorting and return list
}
public static List<Book> sortBooksByPopularity( Integer id ) {
if (id == null ) { return null; }
List<Book> list = getAllBooksForAuthor( id );
// do some sorting and return list
}
public static List<Book> getAllBooksForAuthor( Integer id ) {
if (id == null ) throw new NullPointerException();
...
return listOfBooks;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-03T23:03:26.123",
"Id": "41777",
"Score": "0",
"body": "http://qconlondon.com/london-2009/presentation/Null+References:+The+Billion+Dollar+Mistake ;-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-04T00:09:12.397",
"Id": "41778",
"Score": "0",
"body": "Try not to use static classes. When is int going to be null? if id==null then java will already throw a NullPointerException no need to throw another one."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-04T00:59:29.537",
"Id": "41779",
"Score": "0",
"body": "@RobertSnyder \"sneaking\" `NullPointerException`s are never a good idea..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-04T01:09:40.493",
"Id": "41780",
"Score": "0",
"body": "Just one \"side remark\": you say you want to refactor and optimize the class, fine; but what is this class supposed to do to begin with?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-04T01:28:16.340",
"Id": "41781",
"Score": "0",
"body": "OK, this is very, very confusing. Why is `id` a parameter of the sorting functions of lists? Why do I have the sneaking suspiscion that the `id` passed as an argument here is always the id of the enclosing `Author` instance?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-04T02:56:22.457",
"Id": "41782",
"Score": "0",
"body": "@fge I would never tell anyone to be sneaky with any exception, but this is a clear violation of DRY. The compiler will throw a NullPointerException if there is no ID supplied, or if the Author does not return any results. So don't repeat it. I would rather use inheritance and polymorphism to solve this problem."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-04T03:03:44.843",
"Id": "41783",
"Score": "1",
"body": "@RobertSnyder while I agree with you, I suspect the problem here is much deeper than that. Dubious NPE handling is the least of the OP's concern here :/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-04T03:22:16.593",
"Id": "41784",
"Score": "0",
"body": "@fge I wish I could have given you 2+'s :) 1 for the use of dubious and 2 for hitting the nail on the head."
}
] |
[
{
"body": "<p>Tentative answer...</p>\n\n<p>First of all, it looks like you didn't include the source of the <em>full</em> <code>Author</code> class. Where is the list of <code>Book</code>s for that author, for instance?</p>\n\n<p>Second: you seem to want methods to sort this inner list of books for a given author; why, then, pass the id of the author as an argument? You should have a lookup method for an <code>Author</code> given its id -- but this lookup method should not be a method of one <code>Author</code> instance; at worst, it should be a static method in the <code>Author</code> class. What is your backend like? How do you look up an author by its id eventually?</p>\n\n<p>Third: the JDK has <code>Collections.sort()</code>; and given that you want to have a sorted list of books according to several criteria, you want to write several <code>Comparator</code>s for that book. See below for a solution to that.</p>\n\n<p>Fourth, and not the least: you should not operate on the list in the <code>Author</code> class itself, but on a copy of that list.</p>\n\n<p>Given these four points above, here are some code extracts...</p>\n\n<p>First: how to return a <code>List<Book></code> from an author -- don't return the list itself but at least an unmodifiable version of it:</p>\n\n<pre><code>// in class Author; it is supposed that the list has name \"bookList\" in the class\npublic List<Book> getBookList()\n{\n return new Collections.unmodifiableList(bookList); // not modifiable!\n}\n</code></pre>\n\n<p>Second: you want book lists sorted in various ways; one solution is to create an enum:</p>\n\n<pre><code>public enum BookSort\n{\n BY_NAME (new Comparator<Book>()\n {\n @Override\n public int compare(final Book a, final Book b)\n {\n return a.getName().compareTo(b.getName());\n }\n }),\n // other values\n\n private final Comparator<Book> comparator;\n\n BookSort(final Comparator<Book> comparator)\n {\n this.comparator = comparator;\n }\n\n // Return a sorted copy of books\n public List<Book> sort(final List<Book> list)\n {\n final List<Book> ret = new ArrayList<Book>(list);\n Collections.sort(ret, comparator);\n return ret;\n }\n}\n</code></pre>\n\n<p>Then, in your code:</p>\n\n<pre><code>final List<Book> sorted = BookSort.BY_NAME.sort(original);\n</code></pre>\n\n<p>But all this code is moot to begin with if you do not provide the <strong>full code</strong> of both the <code>Author</code> and <code>Book</code> class; along with the existing mechanism to grab instances of these two classes.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-04T07:00:34.700",
"Id": "41793",
"Score": "0",
"body": "+1 @viv you will find all explanations about 'fge' response in the *Joshua Bloch*'s book **Effective Java** http://www.amazon.com/Effective-Java-Edition-Joshua-Bloch/dp/0321356683 . If you want to write good and secure code, it is perhaps the only book you have to understand deeply"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-04T13:36:11.400",
"Id": "41808",
"Score": "0",
"body": "what elegant solution for the comparator. Last time I did those it wasn't near as nice looking as that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-04T13:59:54.180",
"Id": "41810",
"Score": "0",
"body": "Actually, it is even bettter to use an enum here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-04T14:32:40.510",
"Id": "41814",
"Score": "0",
"body": "@fge I'm trying my best to understand how a enum would be better. Unless you mean to have just one sort method with a switch in it. I think I would overload the sort method and have the second one pass in a comparator. This way you have a default sort (say by book id) and you can pass in a mock comparator if needed."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-04T14:35:56.553",
"Id": "41815",
"Score": "0",
"body": "@RobertSnyder that is a design choice, really... I kind of don't like \"data\" classes which do too much :p Now, if the OP included his full code..."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-04T03:50:45.510",
"Id": "26962",
"ParentId": "26956",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-03T22:13:33.233",
"Id": "26956",
"Score": "0",
"Tags": [
"java"
],
"Title": "refactoring and optimization the class"
}
|
26956
|
<p>I've tried to catch all exceptions and errors in PHP in a way so that I can deal with them consistently.</p>
<p>This is the code with the exception of the very last bit where I instead pass <code>$e</code> on to a method that outputs an error page as HTML.</p>
<pre><code>// Only let PHP report errors in dev
error_reporting(ENV === 'dev' ? E_ALL : 0);
// Register handler
set_error_handler("error_handler");
set_exception_handler("error_handler");
register_shutdown_function("error_handler");
function error_handler()
{
// Check for unhandled errors (fatal shutdown)
$e = error_get_last();
// If none, check function args (error handler)
if($e === null)
$e = func_get_args();
// Return if no error
if(empty($e))
return;
// "Normalize" exceptions (exception handler)
if($e[0] instanceof Exception)
{
call_user_func_array(__FUNCTION__, array(
$e[0]->getCode(),
$e[0]->getMessage(),
$e[0]->getFile(),
$e[0]->getLine(),
$e[0]));
return;
}
// Create with consistent array keys
$e = array_combine(array('number', 'message', 'file', 'line', 'context'),
array_pad($e, 5, null));
// Output error page
var_dump($e);
exit;
}
</code></pre>
<p>I'm wondering if this is a decent way of doing it or if I have missed anything crucial. Any comments?</p>
|
[] |
[
{
"body": "<ol>\n<li><p>I don't think that printing raw errors/data to the users is a good idea:</p>\n\n<blockquote>\n<pre><code>var_dump($e);\n</code></pre>\n</blockquote>\n\n<p>They (usually) can't fix it, so it doesn't help them. (<a href=\"https://codereview.stackexchange.com/a/45075/7076\">See #3 here</a>) It might also contain sensitive information which could help attackers.</p>\n\n<p>Instead of that you should <a href=\"https://stackoverflow.com/a/12835262/843804\">log the errors to a log file</a>, hide the details from the user (don't forget to print a friendly error message) and fix the errors. Your users might not call/mail you when they found a bug. They just simply use one of your competitor's service.</p></li>\n<li><p>Instead of using the same function for three more or less different purposes:</p>\n\n<blockquote>\n<pre><code>set_error_handler(\"error_handler\");\nset_exception_handler(\"error_handler\");\nregister_shutdown_function(\"error_handler\");\n</code></pre>\n</blockquote>\n\n<p>I'd use three different functions (with proper signatures) which might call a fourth one. It would be cleaner (easier to read, understand and maintain). It would make unnecessary the internal magic with <code>error_get_last()</code>, <code>func_get_args()</code> and <code>instanceof</code>.</p></li>\n<li><blockquote>\n<pre><code>// Only let PHP report errors in dev\nerror_reporting(ENV === 'dev' ? E_ALL : 0);\n</code></pre>\n</blockquote>\n\n<p>It seems to me as a <a href=\"https://en.wikipedia.org/wiki/Code_smell\" rel=\"nofollow noreferrer\">code smell</a>: <a href=\"http://xunitpatterns.com/Test%20Logic%20in%20Production.html\" rel=\"nofollow noreferrer\">Test Logic in Production</a>. I'd use php.ini to set this, I guess php.ini is a straightforward place for most of the PHP developers to set this instead of a PHP file.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-24T00:06:23.060",
"Id": "45170",
"ParentId": "26957",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-03T23:47:58.903",
"Id": "26957",
"Score": "6",
"Tags": [
"php",
"error-handling"
],
"Title": "Catching all exceptions and errors in PHP"
}
|
26957
|
<p>I'm taking a text file that looks like this:</p>
<blockquote>
<pre><code>77, 66, 80, 81
40, 5, 35, -1
51, 58, 62, 34
0, -1, 21, 18
61, 69, 58, 49
81, 82, 90, 76
44, 51, 60, -1
64, 63, 60, 66
-1, 38, 41, 50
69, 80, 72, 75
</code></pre>
</blockquote>
<p>and I'm counting which numbers fall in a certain bracket:</p>
<pre><code>f = open("//path to file", "r")
text = f.read()
split = text.split()
greater70=0
sixtys=0
fiftys=0
fortys=0
nomarks=0
for word in split:
temp = word.replace(',', '')
number = int(temp)
if number > 70:
greater70+=1
if number >= 60 and number <= 69:
sixtys+=1
if number >= 50 and number <= 59:
fiftys+=1
if number >= 40 and number <= 49:
fortys+=1
if number == -1:
nomarks+=1
print greater70
print sixtys
print fiftys
print fortys
print nomarks
</code></pre>
<p>Have I done it in an efficient way sensible way or do experienced Python users think it looks a little convoluted?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-07T09:32:47.040",
"Id": "42109",
"Score": "2",
"body": "Is 70 meant to be ignored or is that a mistake?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-11-24T06:18:46.120",
"Id": "278206",
"Score": "0",
"body": "I'd be tempted to divide by 10 and use counter."
}
] |
[
{
"body": "<p>Looks good, but there are a few things I've noticed that could be better:</p>\n\n<ul>\n<li>You should use the <code>with</code> statement when working with files. This ensures that the file will be closed properly in any case.</li>\n<li><p>I would split the input string on <code>','</code> instead of replacing the comma with a space. This way, something like <code>'-7,67,34,80'</code> will be handled correctly. (It's a bit tricky because you want to split on newlines too, though. I did it using a <a href=\"http://docs.python.org/2/tutorial/datastructures.html#list-comprehensions\" rel=\"nofollow\">list comprehension</a>.)</p>\n\n<p><code>int()</code> will ignore any whitespace before or after the number, so <code>int(' 50')</code> works just fine.</p></li>\n<li>You can write those conditions as <code>60 <= number <= 69</code>.</li>\n<li>Since the numbers can only fall into one of the five categories, it's clearer (and more efficient) to use <code>elif</code> instead of <code>if</code>.</li>\n<li>Assignments with <code>=</code> or <code>+=</code> should have spaces around them in Python. (See <a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">PEP 8</a> for a Python style guide.)</li>\n</ul>\n\n<p>This is how the changes would look:</p>\n\n<pre><code>with open(\"//path to file\", \"r\") as f:\n split = [word for line in f for word in line.split(',')]\n\ngreater70 = 0\nsixties = 0\nfifties = 0\nforties = 0\nnomarks = 0\n\nfor word in split:\n number = int(word)\n if number > 70:\n greater70 += 1\n elif 60 <= number <= 69:\n sixties += 1 \n elif 50 <= number <= 59:\n fifties += 1\n elif 40 <= number <= 49:\n forties += 1 \n elif number == -1:\n nomarks += 1 \n\nprint greater70 \nprint sixties\nprint fifties\nprint forties\nprint nomarks\n</code></pre>\n\n<p>You might also want to think about how to avoid the repetition of code when you're calculating and printing the 40s, 50s and 60s (which, by the way, are spelt <code>forties, fifties, sixties</code>).</p>\n\n<p>I also noticed that 70 falls into none of the categories, is that the way it's supposed to be?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-04T02:17:45.307",
"Id": "26959",
"ParentId": "26958",
"Score": "1"
}
},
{
"body": "<p>Few points i have noticed in your code, that i hope, will help you.</p>\n\n<p>1) Try changing your conditions like this: (no need to check two conditions)</p>\n\n<pre><code>if number > 69:\n greater70+=1\nelif number > 59:\n sixtys+=1 \nelif number > 49:\n fiftys+=1\nelif number > 40:\n fortys+=1 \nelif number == -1:\n nomarks+=1 \n</code></pre>\n\n<p>2) Always take care of closing file handler, or better to use <code>with</code> statements as other expert suggested.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-04T06:09:35.167",
"Id": "26969",
"ParentId": "26958",
"Score": "0"
}
},
{
"body": "<p>Notes:</p>\n\n<ul>\n<li><p>Creating so many variables is a warning sign that they should be grouped somehow (an object, a dictionary, ...). I'd use a dictionary here.</p></li>\n<li><p>Consider learning some <a href=\"http://docs.python.org/2/howto/functional.html\" rel=\"nofollow\">functional programming</a> (as opposed to imperative programming) to apply it when it improves the code (IMO: most of the time). Here it means basically using <a href=\"http://docs.python.org/2/library/collections.html#collections.Counter\" rel=\"nofollow\">collections.counter</a> and <a href=\"http://www.python.org/dev/peps/pep-0289/\" rel=\"nofollow\">generator expressions</a>.</p></li>\n<li><p>Don't read whole files, read them line by line: <code>for line in file_descriptor</code>.</p></li>\n<li><p>There are programmatic ways of detecting intervals of numbers (simple loop, binary search). However, since you have here only 5 intervals it's probably fine just to write a conditional as you did. If you had, let's say 20 intervals, a conditional branch would be a very sad thing to see.</p></li>\n<li><p>Conditional branches are more clear when you use non-overlapping conditions with <code>if</code>/<code>elif</code>/<code>else</code> (effectively working as expressions instead of statements).</p></li>\n</ul>\n\n<p>I'd write:</p>\n\n<pre><code>from collections import Counter\n\ndef get_interval(x):\n if x > 70:\n return \"greater70\"\n elif 60 <= x < 70:\n return \"sixtys\" \n elif x >= 50:\n return \"fiftys\"\n elif x >= 40:\n return \"fortys\" \n elif x == -1:\n return \"nomarks\" \n\nwith open(\"inputfile.txt\") as file:\n counter = Counter(get_interval(int(n)) for line in file for n in line.split(\",\"))\n# Counter({'sixtys': 10, 'greater70': 10, None: 7, ..., 'fortys': 4})\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-23T23:42:24.983",
"Id": "43169",
"Score": "0",
"body": "Aren't those `for` clauses the wrong way around? I.e. shouldn't it be `Counter(get_interval(int(n)) for n in line.split(\",\") for line in file)`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-24T08:17:37.003",
"Id": "43187",
"Score": "0",
"body": "@user9876: no, I am pretty sure it's correct (the output is real, I run that code). A list-comprehension is written in the same order you'd write a normal for-loop."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-04T22:04:22.630",
"Id": "27010",
"ParentId": "26958",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-04T01:04:11.230",
"Id": "26958",
"Score": "6",
"Tags": [
"python",
"interval"
],
"Title": "Counting which numbers fall in a certain bracket"
}
|
26958
|
<p>I'm learning BackboneJS and I just made an attempt at converting a pre-existing module to a Backbone.View. I was hoping to get some feedback on my attempt and learn. I've been using the <a href="http://backbonejs.org/docs/todos.html" rel="nofollow noreferrer">annotated ToDo source</a> as a guide.</p>
<p>Here's some HTML to give you a rough idea:</p>
<pre><code><div id="VolumeControl">
<div id="MuteButton" class="volumeControl" title="Toggle Volume">
<svg width="16" height="16">
<path d="M0,6 L3,6 L7,2 L7,14 L3,10 L0,10Z" fill="#fff" />
<rect class="MuteButtonBar" id="MuteButtonBar1" x="9" y="6.5" width="1" height="3" />
<rect class="MuteButtonBar"id="MuteButtonBar2" x="11" y="5" width="1" height="6" />
<rect class="MuteButtonBar" id="MuteButtonBar3" x="13" y="3.5" width="1" height="9" />
<rect class="MuteButtonBar" id="MuteButtonBar4" x="15" y="2" width="1" height="12" />
</svg>
</div>
<div id="VolumeSliderWrapper" class="volumeControl">
<input type="range" id="VolumeSlider" class="volumeControl" title="Click or drag to change the volume." min="0" max="100" step="1" value="0" />
</div>
</div>
</code></pre>
<p>It's essentially a two-part control consisting of a mute button and an HTML5 range slider which expands out.</p>
<p>Here's a quick screenshot to bring things together mentally:</p>
<p><img src="https://i.stack.imgur.com/lNq5F.png" alt="enter image description here"></p>
<p>Here's my Backbone.View:</p>
<pre><code>// Responsible for controlling the volume indicator of the UI.
define(['player'], function (player) {
'use strict';
var volumeControlView = Backbone.View.extend({
el: $('#VolumeControl'),
events: {
'change #VolumeSlider': 'setVolume',
'click #MuteButton': 'toggleMute',
'mousewheel .volumeControl': 'scrollVolume',
'mouseenter .volumeControl': 'expand',
'mouseleave': 'contract'
},
render: function () {
var volume = player.get('volume');
// Repaint the amount of white filled in the bar showing the distance the grabber has been dragged.
var backgroundImage = '-webkit-gradient(linear,left top, right top, from(#ccc), color-stop(' + volume / 100 + ',#ccc), color-stop(' + volume / 100 + ',rgba(0,0,0,0)), to(rgba(0,0,0,0)))';
this.volumeSlider.css('background-image', backgroundImage);
var activeBars = Math.ceil((volume / 25));
this.muteButton.find('.MuteButtonBar:lt(' + (activeBars + 1) + ')').css('fill', '#fff');
this.muteButton.find('.MuteButtonBar:gt(' + activeBars + ')').css('fill', '#666');
if (activeBars === 0) {
this.muteButton.find('.MuteButtonBar').css('fill', '#666');
}
var isMuted = player.get('muted');
if (isMuted) {
this.muteButton
.addClass('muted')
.attr('title', 'Click to unmute.');
} else {
this.muteButton
.removeClass('muted')
.attr('title', 'Click to mute.');
}
return this;
},
// Initialize player's volume and muted state to last known information or 100 / unmuted.
initialize: function () {
this.volumeSliderWrapper = this.$('#VolumeSliderWrapper');
this.volumeSlider = this.$('#VolumeSlider');
this.muteButton = this.$('#MuteButton');
// Set the initial volume of the control based on what the YouTube player says is the current volume.
var volume = player.get('volume');
this.volumeSlider.val(volume).trigger('change');
this.listenTo(player, 'change:muted', this.render);
this.render();
},
// Whenever the volume slider is interacted with by the user, change the volume to reflect.
setVolume: function () {
var newVolume = parseInt(this.volumeSlider.val(), 10);
player.set('volume', newVolume);
this.render();
},
// Adjust volume when user scrolls mousewheel while hovering over volumeControl.
scrollVolume: function (event, delta) {
// Convert current value from string to int, then go an arbitrary, feel-good amount of volume points in a given direction (thus *3 on delta).
var newVolume = parseInt(this.volumeSlider.val(), 10) + delta * 3;
this.volumeSlider.val(newVolume).trigger('change');
},
toggleMute: function () {
var isMuted = player.get('muted');
player.set('muted', !isMuted);
},
// Show the volume slider control by expanding its wrapper whenever any of the volume controls are hovered.
expand: function () {
this.volumeSliderWrapper.addClass('expanded');
},
contract: function () {
this.volumeSliderWrapper.removeClass('expanded');
}
});
var volumeControl = new volumeControlView;
})
</code></pre>
<p>Am I doing too much in render? Anything look weird?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-05T19:53:10.190",
"Id": "41938",
"Score": "0",
"body": "RequireJS, correct?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-05T21:44:54.687",
"Id": "41943",
"Score": "0",
"body": "Hmm? Yes, the example uses RequireJS as indicated in the tags, but that's a pretty simple wrapper. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T14:36:42.507",
"Id": "42022",
"Score": "0",
"body": "I just wanted to make sure. So why are you defining `player` as a dependency of the `volumeControlView` class rather than a parameter to the constructor? I'm not saying this is wrong, I've just never seen this. I've always seen the module define a class and export/return the class for other code to instantiate, passing in the appropriate parameters (e.g. `player`)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T14:38:17.657",
"Id": "42023",
"Score": "0",
"body": "I could be wrong, but this looks to be very similar to a singleton."
}
] |
[
{
"body": "<p>I think this is fine for something as simple as a volume control; however, there are some limitations to at least be aware of:</p>\n\n<ol>\n<li>Since RequireJS invokes the module, it would be problematic to\nconstruct <code>player</code> dynamically.</li>\n<li>There's no good way of creating more than one instance of your view – probably not a problem.</li>\n<li>The View is tightly bound to a specific DOM structure. This means it will require extra code to make your View responsive. e.g. a small volume control for mouses (desktop) and a big one for fingers (mobile).</li>\n</ol>\n\n<p>Here are some potential solutions:</p>\n\n<ol>\n<li>Likely, <code>player</code> just has a single default state, but if you ever\nwant to construct this object yourself, you should consider return-/exporting the <code>volumeControlView</code> definition from your module, rather than returning an instance of it. </li>\n<li>A simple solution here is to simply return the result of <code>Backbone.View.extend</code>.</li>\n<li>Use a template. In the future, you can use additional templates to support other platforms. e.g. start with a desktop template, later on create a mobile template, and choose the template dynamically at runtime based on the environment.</li>\n</ol>\n\n<p>I would define your module like so (uses <a href=\"https://github.com/requirejs/text\" rel=\"nofollow\">RequireJS text plugin</a>):</p>\n\n<pre><code>define(['Backbone', 'underscore', 'text!templates/volume-bar.html'], function (Backbone, _, volume_bar) {\n 'use strict';\n\n return Backbone.View.extend({\n template: _.template(volume_bar),\n\n // ...\n\n });\n});\n</code></pre>\n\n<p>This lets you instantiate the view like so:</p>\n\n<pre><code>require(['models/Player', 'views/VolumeBar', function(PlayerModel, VolumeBarView) {\n 'use strict';\n\n var player = new PlayerModel({...});\n var volume = new VolumeBarView({\n model: player\n });\n volume.render().$el.appendTo('#player');\n});\n</code></pre>\n\n<p>Doing so would change how you bind your events and render your HTML, so I'm leaving it at this just to give you the general idea.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-07T06:11:53.487",
"Id": "42093",
"Score": "0",
"body": "Heya. Could you elaborate on your first point a bit more, please? I don't understand what 'construct a player dynamically' means in this context. For my purposes, the player module is hosted in a background page and, as a business rule, must exist and be ready before this module is loaded. This volumeControl has no need to interact with other objects. Its only goal is to send \"i was interacted upon\" events to the player such that it can respond to the UI being interacted upon. I agree that a template would be nice -- this is a Google Chrome Extension, but porting is an option."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-11T01:54:27.413",
"Id": "42303",
"Score": "0",
"body": "If you define your view to require `player`, you're demanding that RequireJS load the module for you. This means you have to instantiate `player` in the same place you define it. This is fine so long as `player` doesn't require anything outside of it's scope to instantiate; however, should the player's construction ever rely on some external factor (e.g. current user, connection speed, browser features, etc.), you'll have to inject these dependencies into the player module rather than implementing them somewhere more appropriate like in a parent. Honestly, I don't think this will be a problem."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T18:19:47.270",
"Id": "27106",
"ParentId": "26963",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "27106",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-04T04:10:45.810",
"Id": "26963",
"Score": "2",
"Tags": [
"javascript",
"jquery",
"backbone.js",
"require.js"
],
"Title": "Control consisting of a mute button and an expanding range slider"
}
|
26963
|
<p>I have two arrays:</p>
<ul>
<li>first one is ip addresses from billing for blocking</li>
<li>second is ip addresses from firewall - already blocked</li>
</ul>
<p>My task is, compare it, and if ip address new in billing list - block it (run a command) if ip address not in billing list unblock it.</p>
<p>Current solutions is:</p>
<pre><code>#billing->router
foreach $ip (@ipfw_ip) {
if ( grep $_ eq $ip, @bill_ip ) {
} else {
`/sbin/ipfw table 11 add $ip`;
print "$ip blocked\n";
}
}
#router->billing
foreach $ip (@bill_ip) {
if ( grep $_ eq $ip, @ipfw_ip ) {
} else {
`/sbin/ipfw table 11 delete $ip`;
print "$ip unblocked\n";
}
}
</code></pre>
<p>I hate 'grep' in the loops, and looking for better solution. Any advice?</p>
<p>UPD:
difference function from Set::Functional helps me.</p>
<pre><code>for(difference (\@ipfw_ip, \@bill_ip)) {
..._;
}
sub difference(@) {
my $first = shift;
return unless $first && @$first;
my %set;
undef @set{@$first};
do { delete @set{@$_} if @$_ } for @_;
return keys %set;
}
</code></pre>
|
[] |
[
{
"body": "<p>The completely procedural way to write the same is:</p>\n\n<pre><code>foreach my $fw_ip (@ipfw_ip) {\n foreach my $bill_ip (@bill_ip) {\n if($fw_ip eq $bill_ip) {\n ...\n last;\n }\n }\n}\n</code></pre>\n\n<p>The main advantage is that it is easy to understand for anybody, and not using too much perl-fu.</p>\n\n<p>I find it odd that you write</p>\n\n<pre><code> if ( grep $_ eq $ip, @bill_ip ) {\n } else {\n `/sbin/ipfw table 11 add $ip`;\n print \"$ip blocked\\n\";\n }\n</code></pre>\n\n<p>In stead of</p>\n\n<pre><code> if ( not grep $_ eq $ip, @bill_ip ) {\n `/sbin/ipfw table 11 add $ip`;\n print \"$ip blocked\\n\";\n }\n</code></pre>\n\n<p>or even</p>\n\n<pre><code> unless ( grep $_ eq $ip, @bill_ip ) {\n `/sbin/ipfw table 11 add $ip`;\n print \"$ip blocked\\n\";\n }\n</code></pre>\n\n<p>P.s. <em>always</em> <code>use strict;</code> and <code>use warnings;</code>. It looks as if you aren't.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-05T04:12:12.400",
"Id": "41879",
"Score": "0",
"body": "2xforeach the same then grep in foreach. I hope it possible do that task without loop in loop. And thank you about \"if else\" no idea how I writed that. Probably there was deleted code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-05T06:20:45.803",
"Id": "41883",
"Score": "0",
"body": "Sure - you can do the same completely without a loop. Will be back with that."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-04T19:09:45.473",
"Id": "26994",
"ParentId": "26966",
"Score": "1"
}
},
{
"body": "<p>You can use <code>Set::Functional</code> to make the code very short:</p>\n\n<pre><code>use Set::Functional 'difference';\nfor(difference [@ipfw_ip], [@bill_ip]) {\n `/sbin/ipfw table 11 add $ip`;\n print \"$ip blocked\\n\";\n}\n</code></pre>\n\n<p>Another advantage of the approach above is that you don't have to worry about duplicate entries in the two arrays.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-07T03:22:34.043",
"Id": "42088",
"Score": "0",
"body": "Thank you alot! I dislike new dependencies but looks into Set::Functional and see the code. Its simple. I will update my question with solution."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T17:58:49.963",
"Id": "27104",
"ParentId": "26966",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "27104",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-04T05:21:02.627",
"Id": "26966",
"Score": "0",
"Tags": [
"array",
"perl"
],
"Title": "Comparing two arrrays"
}
|
26966
|
<p>I've tried to improve the speed of my query in MySQL, but when condition <code>IN</code> clause happens too often, the query runs very slowly. Can anyone help me optimize the query?</p>
<pre><code>EXPLAIN SELECT bi.syouhin_sys_code AS syouhin_sys_code
,dwh_syo.name AS syouhin_sys_name
,dwh_syo.code AS syouhin_code
,dwh_syo.brand_code AS brand_code
,brand.name AS brand_name
,bi.bunrui_code AS bunrui_code
,bunrui.bunrui_name AS bunrui_name
,SUM(bi.syouhin_count) AS syouhin_count
,CASE WHEN dwh_syo.teika = 0
THEN 0 ELSE IFNULL(TRUNCATE((sik.price / (dwh_syo.teika * 100 / 105)) * 100, 2), 0)
END AS siire_rate
,SUM(bi.jyutyuu_teika) AS jyutyuu_teika
,SUM(bi.jyutyuu_hanbai) AS jyutyuu_hanbai
,SUM(bi.jyutyuu_sikiri) AS jyutyuu_sikiri
,SUM(bi.jyutyuu_hanbai) - SUM(bi.jyutyuu_sikiri) AS jyutyuu_profit
,CASE WHEN SUM(bi.jyutyuu_hanbai) = 0
THEN 0 ELSE TRUNCATE(((SUM(bi.jyutyuu_hanbai) - SUM(bi.jyutyuu_sikiri)) / SUM(bi.jyutyuu_hanbai) * 100),2)
END AS jyutyuu_profit_rate
,SUM(bi.nouhin_teika) AS nouhin_teika
,SUM(bi.nouhin_hanbai) AS nouhin_hanbai
,SUM(bi.nouhin_sikiri) AS nouhin_sikiri
,SUM(bi.nouhin_hanbai) - SUM(bi.nouhin_sikiri) AS nouhin_profit
,CASE WHEN SUM(bi.nouhin_hanbai) = 0
THEN 0 ELSE TRUNCATE(((SUM(bi.nouhin_hanbai) - SUM(bi.nouhin_sikiri)) / SUM(bi.nouhin_hanbai) * 100),2)
END AS nouhin_profit_rate
,CONCAT(CASE WHEN sel.hyouji_name1 IS NULL OR sel.hyouji_name1 = ''
THEN '' ELSE sel.hyouji_name1
END
,CASE WHEN sel.hyouji_name2 IS NULL OR sel.hyouji_name2 = ''
THEN '' ELSE CONCAT('/',sel.hyouji_name2)
END
,CASE WHEN sel.hyouji_name3 IS NULL OR sel.hyouji_name3 = ''
THEN '' ELSE CONCAT('/',sel.hyouji_name3)
END
,CASE WHEN sel.hyouji_name4 IS NULL OR sel.hyouji_name4 = ''
THEN '' ELSE CONCAT('/',sel.hyouji_name4)
END
,CASE WHEN sel.hyouji_name5 IS NULL OR sel.hyouji_name5 = ''
THEN '' ELSE CONCAT('/',sel.hyouji_name5)
END
,CASE WHEN sel.hyouji_name6 IS NULL OR sel.hyouji_name6 = ''
THEN '' ELSE CONCAT('/',sel.hyouji_name6)
END) AS syouhin_spec
FROM bi_bunrui_syouhin_shop_day_jyutyuu AS bi
LEFT OUTER JOIN dwh_rc_syouhin AS dwh_syo
ON bi.syouhin_sys_code = dwh_syo.syouhin_sys_code
LEFT OUTER JOIN tbl_sikiri_now AS sik
ON bi.syouhin_sys_code = sik.syouhin_sys_code
LEFT OUTER JOIN mst_syouhin_all_select AS sel
ON bi.syouhin_sys_code = sel.syouhin_sys_code
LEFT OUTER JOIN mst_brand AS brand
ON dwh_syo.brand_code = brand.brand_code
LEFT OUTER JOIN mst_bunrui AS bunrui
ON bi.bunrui_code = bunrui.bunrui_code
WHERE bi.tyumon_date_unixtime BETWEEN UNIX_TIMESTAMP(20121001)
AND UNIX_TIMESTAMP(20130603)
AND( bi.syouhin_sys_code LIKE '%%' OR dwh_syo.name LIKE '%%' )
AND bi.shop_code IN ('0000','0001','0002','0009','0003','0006','9000','9001')
AND bi.bunrui_code IN ('0001','1000','1001','1005','1006','1007','1008','1009'
,'1010','1011','1012','1013','1014','1015','1016','1017',
'1018','1020','1021','1022','1023','1030','1031','1032'
,'1033','1034','1036','1037','1038','1039','1040','1041'
,'1043','1044','1045','1046','1050','1054','1055','1060'
,'1061','1070','1080','1081','1082','1083','1084','1085','1086'
,'1088','1090','1091','1092','1093','1094','1095','1096','1097'
,'1100','1101','1102','1103','1104','1105','1106','1107','1108'
,'1109','1110','1111','1112','1113','1114','1115','1116','1117'
,'1118','1119','1120','1121','1122','1123','1130','1131','1132'
,'1133','1134','1135','1136','1137','1140','1141','1142','1143'
,'1145','1148','1150','1151','1152','1153','1154','1155','1156'
,'1157','1160','1161','1162','1163','1164','1165','1166','1167'
,'1168','1169','1170','1171','1180','1181','1182','1183','1184'
,'1187','1189','1200','1201','1202','1203','1204','1205','1206'
,'1207','1210','1211','1212','1220','2003','2009','2022','2028'
,'2042','2048','2062','2068','2082','2088','2102','2108','2122'
,'2125','2128','2129','2134','2141','2144','2161','2182','2186'
,'2222','2228','2242','2253','2262','2268','2302','2511','2512'
,'2513','3180','3207','3208','4023','4024','4028','4029','4030'
,'4031','4032','4033','4034','4036','4040','4041','4042','4043'
,'4044','4062','4064','4066','4067','4068','4069','4070','4071'
,'4092','5013','5014','5015','5016','5017','5018','6200','6201'
,'6202','6203','6204','6205','6220','6221','6222','6223','6224'
,'6225','6226','6234','6235','6240','6241','6242','6243','6244'
,'6245','6246','6247','6249','6250','6251','6260','6261','6262'
,'6263','6264','6265','6280','6281','6282','6283','6284','6285'
,'6286','6287','6288','6289','6290','6291','6292','6293','6300'
,'6301','6302','6303','6304','6305','6320','6321','6322','6323'
,'6324','6325','6340','6342','6343','6344','6345','6346','6347'
,'6348','6349','6360','6361','6362','6363','6364','6365','6366'
,'6367','6368','6369','6371','6372','6373','6374','6375','6376'
,'6377','6378','6379','6380','6381','6382','6383','6384','6385'
,'6400','6401','6402','6403','6406','6407','6408','6420','6421'
,'6422','6423','6424','6425','6426','6427','6428','6429','6430'
,'6431','6432','6433','6434','6435','6436','6440','6441','6442'
,'6443','6444','6445','6446','6447','6448','6449','6450','6451'
,'6452','6453','6454','6455','6456','6457','6458','6459','6460'
,'6470','6471','6472','6473','6474','6475','6476','6477','6478'
,'6480','6481','6482','6483','6484','6485','6486','6487','6489'
,'6490','6500','6501','6502','6504','6505','6506','6507','6508'
,'6509','6510','6511','6512','6513','6514','6515','6520','6521'
,'6522','6523','6524','6525','6526','6527','6528','6529','6530'
,'6531','6550','6551','6552','6553','6554','6555','6556','6557'
,'6558','6559','6560','6561','6562','6563','6564','6565','6567'
,'6568','6569','6570','6572','6573','6574','7694','7993','9200'
,'9201','9202','9203','9204','9205','9206','9208','9310','9320')
GROUP BY bi.syouhin_sys_code
HAVING SUM(bi.syouhin_count) > 0
ORDER BY jyutyuu_hanbai DESC
</code></pre>
<p>This is the statement that makes the query run slowly:</p>
<pre><code>AND bi.bunrui_code IN ('0001','1000','1001',...)
</code></pre>
<p>Here is the <code>EXPLAIN</code> output:</p>
<pre><code>id select_type table type possible_keys key key_len ref rows Extra
1 SIMPLE bi range PRIMARY PRIMARY 12 NULL 256360 Using where; Using temporary; Using filesort
1 SIMPLE dwh_syo eq_ref PRIMARY PRIMARY 8 analyst.bi.syouhin_sys_code 1 Using where
1 SIMPLE sik eq_ref PRIMARY,syouhin_sys_code,idx_syouhin_sys_code PRIMARY 8 analyst.bi.syouhin_sys_code 1
1 SIMPLE sel eq_ref PRIMARY PRIMARY 8 analyst.bi.syouhin_sys_code 1
1 SIMPLE brand eq_ref PRIMARY PRIMARY 4 analyst.dwh_syo.brand_code 1
1 SIMPLE bunrui eq_ref PRIMARY PRIMARY 8 analyst.bi.bunrui_code 1
</code></pre>
<p>The run time is more than 16s.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-04T13:36:23.630",
"Id": "41809",
"Score": "1",
"body": "Welcome to Code Review. This is a very specific question with little information about your own research into the problem, and as such is likely to be [closed](http://codereview.stackexchange.com/faq#close). Could you please add more information, for example the actual `EXPLAIN` output, the alternatives you've tried, and their timings?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-05T01:55:48.450",
"Id": "41877",
"Score": "0",
"body": "@l0b0 I added more information"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-07T08:17:39.997",
"Id": "59534",
"Score": "2",
"body": "Difficult to comment without knowing the table layouts, as I can't really see what the indexes are that it has chosen to use. However with close to 500 items in the IN clause it might well be better to instead put those items into a temp table and then join that temp table against *bi_bunrui_syouhin_shop_day_jyutyuu* ."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-29T02:58:03.730",
"Id": "59536",
"Score": "2",
"body": "how do you know that it isn't this statement `AND( bi.syouhin_sys_code LIKE '%%' OR dwh_syo.name LIKE '%%' ) `"
}
] |
[
{
"body": "<p>Optimizing this query can only properly be done on a system where the data exists, and you can 'play' a little bit. There are four things I recommend that you improve:</p>\n\n<ol>\n<li>temporary table</li>\n<li>better case statements</li>\n<li>better joins</li>\n<li>LIKE</li>\n</ol>\n\n<h2>Temp table:</h2>\n\n<pre><code>create temporary table validbunrui (bunrui_code int not null, bunrui_name nvarchar(40) not null);\n\ninsert into validbunrui\nselect bunrui_code, bunrui_name\nfrom bunrui\nwhere bunrui_code IN ('0001','1000','1001','1005','1006','1007','1008','1009'\n ,'1010','1011','1012','1013','1014','1015','1016','1017',\n '1018','1020','1021','1022','1023','1030','1031','1032'\n ,'1033','1034','1036','1037','1038','1039','1040','1041'\n ,'1043','1044','1045','1046','1050','1054','1055','1060'\n ,'1061','1070','1080','1081','1082','1083','1084','1085','1086'\n ,'1088','1090','1091','1092','1093','1094','1095','1096','1097'\n ,'1100','1101','1102','1103','1104','1105','1106','1107','1108'\n ,'1109','1110','1111','1112','1113','1114','1115','1116','1117'\n ,'1118','1119','1120','1121','1122','1123','1130','1131','1132'\n ,'1133','1134','1135','1136','1137','1140','1141','1142','1143'\n ,'1145','1148','1150','1151','1152','1153','1154','1155','1156'\n ,'1157','1160','1161','1162','1163','1164','1165','1166','1167'\n ,'1168','1169','1170','1171','1180','1181','1182','1183','1184'\n ,'1187','1189','1200','1201','1202','1203','1204','1205','1206'\n ,'1207','1210','1211','1212','1220','2003','2009','2022','2028'\n ,'2042','2048','2062','2068','2082','2088','2102','2108','2122'\n ,'2125','2128','2129','2134','2141','2144','2161','2182','2186'\n ,'2222','2228','2242','2253','2262','2268','2302','2511','2512'\n ,'2513','3180','3207','3208','4023','4024','4028','4029','4030'\n ,'4031','4032','4033','4034','4036','4040','4041','4042','4043'\n ,'4044','4062','4064','4066','4067','4068','4069','4070','4071'\n ,'4092','5013','5014','5015','5016','5017','5018','6200','6201'\n ,'6202','6203','6204','6205','6220','6221','6222','6223','6224'\n ,'6225','6226','6234','6235','6240','6241','6242','6243','6244'\n ,'6245','6246','6247','6249','6250','6251','6260','6261','6262'\n ,'6263','6264','6265','6280','6281','6282','6283','6284','6285'\n ,'6286','6287','6288','6289','6290','6291','6292','6293','6300'\n ,'6301','6302','6303','6304','6305','6320','6321','6322','6323'\n ,'6324','6325','6340','6342','6343','6344','6345','6346','6347'\n ,'6348','6349','6360','6361','6362','6363','6364','6365','6366'\n ,'6367','6368','6369','6371','6372','6373','6374','6375','6376'\n ,'6377','6378','6379','6380','6381','6382','6383','6384','6385'\n ,'6400','6401','6402','6403','6406','6407','6408','6420','6421'\n ,'6422','6423','6424','6425','6426','6427','6428','6429','6430'\n ,'6431','6432','6433','6434','6435','6436','6440','6441','6442'\n ,'6443','6444','6445','6446','6447','6448','6449','6450','6451'\n ,'6452','6453','6454','6455','6456','6457','6458','6459','6460'\n ,'6470','6471','6472','6473','6474','6475','6476','6477','6478'\n ,'6480','6481','6482','6483','6484','6485','6486','6487','6489'\n ,'6490','6500','6501','6502','6504','6505','6506','6507','6508'\n ,'6509','6510','6511','6512','6513','6514','6515','6520','6521'\n ,'6522','6523','6524','6525','6526','6527','6528','6529','6530'\n ,'6531','6550','6551','6552','6553','6554','6555','6556','6557'\n ,'6558','6559','6560','6561','6562','6563','6564','6565','6567'\n ,'6568','6569','6570','6572','6573','6574','7694','7993','9200'\n ,'9201','9202','9203','9204','9205','9206','9208','9310','9320')\n</code></pre>\n\n<p>Then, use this table in the join with the main table instead of referencing <code>bunrui</code> directly.</p>\n\n<pre><code>select .....\n .....\n ,bunrui.bunrui_code AS bunrui_code \n ,bunrui.bunrui_name AS bunrui_name\n ,.....\n ,.....\nfrom ......\n ...... \nLEFT OUTER JOIN validbunrui AS bunrui \n ON bi.bunrui_code = bunrui.bunrui_code \n</code></pre>\n\n<h2>Better CASE statements.</h2>\n\n<p>Your code has a lot of case statements:</p>\n\n<blockquote>\n<pre><code>,CONCAT(CASE WHEN sel.hyouji_name1 IS NULL OR sel.hyouji_name1 = '' \n THEN '' ELSE sel.hyouji_name1 \n END \n ,CASE WHEN sel.hyouji_name2 IS NULL OR sel.hyouji_name2 = '' \n THEN '' ELSE CONCAT('/',sel.hyouji_name2) \n END \n ,CASE WHEN sel.hyouji_name3 IS NULL OR sel.hyouji_name3 = '' \n THEN '' ELSE CONCAT('/',sel.hyouji_name3) \n END \n ,CASE WHEN sel.hyouji_name4 IS NULL OR sel.hyouji_name4 = '' \n THEN '' ELSE CONCAT('/',sel.hyouji_name4) \n END \n ,CASE WHEN sel.hyouji_name5 IS NULL OR sel.hyouji_name5 = '' \n THEN '' ELSE CONCAT('/',sel.hyouji_name5) \n END \n ,CASE WHEN sel.hyouji_name6 IS NULL OR sel.hyouji_name6 = '' \n THEN '' ELSE CONCAT('/',sel.hyouji_name6) \n END) AS syouhin_spec\n</code></pre>\n</blockquote>\n\n<p>These case statements can be replaced with MySQL's <code>IFNULL(..., ...)</code> function:</p>\n\n<pre><code> ,CONCAT(IFNULL(sel.hyouji_name1, ''),\n IFNULL(sel.hyouji_name2 ....\n ....) AS syouhin_spec\n</code></pre>\n\n<h2>Better joins.</h2>\n\n<p>I really struggle to believe that you need all of those outer joins.</p>\n\n<p>Outer joins are a really, really poor performance choice. Are you really sure that those all need to be outer joins? Only you can answer that, but, you should investigate.</p>\n\n<h2>LIKE clauses.</h2>\n\n<p>LIKE clauses are also really slow. They require a scan of the data rather than an index search.... Further, your LIKE queries are <em>bogus</em> ....:</p>\n\n<blockquote>\n<pre><code>AND( bi.syouhin_sys_code LIKE '%%' OR dwh_syo.name LIKE '%%' )\n</code></pre>\n</blockquote>\n\n<p>What is that supposed to do? Whatever it is, you have a problem.... ;-)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T16:13:45.060",
"Id": "42164",
"ParentId": "26974",
"Score": "6"
}
},
{
"body": "<p>Make a temporary table with <code>bunrui_code</code> and <code>bunrui_name</code> as the other poster suggests, put an index on the code and then <strong><code>inner</code></strong> <code>left join</code> it (not <code>outer left join</code> it) with the main query, that way you can simply remove the <code>IN</code> statement in the where clause.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-24T11:12:43.757",
"Id": "45198",
"ParentId": "26974",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-04T09:55:59.680",
"Id": "26974",
"Score": "2",
"Tags": [
"optimization",
"mysql",
"sql"
],
"Title": "Speed up MySQL query with IN clause"
}
|
26974
|
<p>I come from the world of Python, so I'm used to every file representing their own enclosed module, never polluting the global environment. Up until now (I've worked with Ruby for a week) I've created one file per class in a nested structure such as this:</p>
<pre>lib
`- project_name
|- sub_module
| `- foo_bar.rb
`- some_class.rb</pre>
<p>Where <em>some_class.rb</em> contains:</p>
<pre><code>module ProjectName
class SomeClass
# ...
end
end
</code></pre>
<p>And <em>foo_bar.rb</em> contains:</p>
<pre><code>module ProjectName::SubModule
class FooBar
# ...
end
end
</code></pre>
<p>This has incidentally worked fine up until now, but I realized that if I require <em>foo_bar.rb</em> before I require <em>some_class.rb</em> I would get a <code>NameError: uninitialized constant ProjectName</code>. So now I'm exploring workarounds for <em>foo_bar.rb</em>, all pretty ugly in my opinion:</p>
<pre><code>module ProjectName
module SubModule
# Double indent for all the code in the file!?
end
end
module ProjectName end
module ProjectName::SubModule
# Fair enough, I suppose...
end
module ProjectName module SubModule
# Ugly
end end
</code></pre>
<p>I suppose any of these would work and the choice would be a matter of taste, but I'd rather use the option that <em>most</em> developers in this situation uses. The question is in the title, please comment.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-04T22:45:21.390",
"Id": "41858",
"Score": "0",
"body": "In ruby, it is standard practice to indent two spaces (not four). So a double indent is just four spaces, if that helps you cope with it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-05T05:48:23.057",
"Id": "41881",
"Score": "0",
"body": "@MarkThomas, this practice appeared just because some random noob from github adviced it, while others were more accurate and weren't thinking they should dictate any standart. So I will never see any sense of working under the *practice* born from some random githuber, until some huge comittee make oficially a deep research of how to indent code in Ruby."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-05T18:08:55.287",
"Id": "41931",
"Score": "0",
"body": "@Nakilon the practice is widespread in the Ruby community, and is the defacto standard. For example, the entire Rails codebase uses 2-space indents."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T08:02:11.820",
"Id": "41981",
"Score": "1",
"body": "@MarkThomas, Ruby != Rails"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T11:56:54.430",
"Id": "41991",
"Score": "0",
"body": "@Nakilon, ruby_community.include? rails_community #=> true"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T12:09:41.313",
"Id": "41993",
"Score": "0",
"body": "@MarkThomas, that totally doesn't mean, Ruby inherits Rails standarts."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T12:36:09.957",
"Id": "41998",
"Score": "2",
"body": "@Nakilon True, but I didn't claim it did. That was an example I'm familiar with. Want others? Let's peruse GitHub for popular Non-Rails Ruby projects. OpsCode Chef: 2 spaces; PuppetLabs Puppet: 2 spaces; Sinatra: 2 spaces; Cucumber: 2 spaces; Watir: 2 spaces."
}
] |
[
{
"body": "<p>I use the version with double indent and I think it is the common usage:</p>\n\n<pre><code>module ProjectName\n module SubModule\n # Double indent for all the code in the file!?\n end\nend\n</code></pre>\n\n<p>If you don't like the double indention, just don't do it. </p>\n\n<p>It is best practice to indent each code level (module, class, def, loops...), but no must.\nIn Python it is part of the syntax, but not in Ruby.</p>\n\n<p>See also <a href=\"https://stackoverflow.com/questions/3833641/is-there-an-acceptable-way-of-putting-multiple-module-declarations-on-the-same-l\">https://stackoverflow.com/questions/3833641/is-there-an-acceptable-way-of-putting-multiple-module-declarations-on-the-same-l</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-07T07:11:04.970",
"Id": "42096",
"Score": "0",
"body": "This seems to me to be the most \"correct\" method. I've also started using two spaces for indenting to reduce the impact of all the nesting."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-04T20:26:51.583",
"Id": "26998",
"ParentId": "26977",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "26998",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-04T10:33:44.357",
"Id": "26977",
"Score": "3",
"Tags": [
"ruby"
],
"Title": "What is the best practice for working with a project as nested modules?"
}
|
26977
|
<p>I think many people for some reason use a singleton class to handle the PDO connection (?) but I was thinking it would be nice to have a parent abstract class initializing the connection and the child DAO classes would just have to extend that class and use a $db variable. Code below (I didn't test it so sorry if there are some syntax mistakes) and more explanation below the code.</p>
<pre><code>abstract class AbstractDao {
protected static $_db = NULL;
public function __construct() {
if(is_null(self::$_db)) {
throw new MyDBException('No DB connection available');
}
}
public static function loadDB($config) {
static $lastConfig = NULL;
if($config == $lastConfig) return self::$_db;
self::$_db = self::connect($config);
$lastConfig = $config;
return self::$_db;
}
private static function connect($config) {
$dsn = sprintf('mysql:dbname=%s;host=%s;port=%d;', $config['database'], $config['hostname'], $config['port']);
$db = new PDO($dsn, $user, $pass);
$db->exec("SET NAMES utf8");
return $db;
}
}
</code></pre>
<p>The $_db variable is static because I want to avoid to open many connections if I initialize many DAO classes (and thus if the $_db variable is static, I'll have one open connection for all my DAO classes). On the other hand it confuses me a bit because I have seen no one doing something like self::$_db->prepare(...). Maybe I am doing something wrong ?</p>
<p>Note also that loadDB with a default config array needs to be called in the application bootstrap.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-04T13:10:21.997",
"Id": "41807",
"Score": "0",
"body": "First remove all static keyword you don't need them (static is evil untestable, unreadable and anyone can change a static instance state). If you wan't to use only one database bridge make your classes the way they can accept constructor arguments for example a PDO instance (and use a dependency injection container if needed)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-04T14:58:57.133",
"Id": "41820",
"Score": "0",
"body": "But if I remove the static keyword, every child class that I instantiate and that inherit from this parent class, will start a new connection. The static keyword was to avoid that and ensure that one request will create only one connection. What do you think about that?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-04T15:03:21.623",
"Id": "41821",
"Score": "0",
"body": "Hah I think you meant I need to create a class somehow containing the connection, and pass this class to my DAO objects?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-04T15:27:19.027",
"Id": "41825",
"Score": "0",
"body": "Correct, Peter is saying construct the connection in a dependency container, and have the container ensure that any object requesting a database connection gets the same connection. See my answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-04T15:35:27.463",
"Id": "41826",
"Score": "0",
"body": "Where is your answer?:)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-04T15:53:06.327",
"Id": "41828",
"Score": "0",
"body": "Just finished it... it was long ;)"
}
] |
[
{
"body": "<p>Continuing on Peter Kiss's answer, the <code>static</code> keyword is indeed hard to test, but you don't have to worry about it when it's in a dependency container. If you use <a href=\"http://en.wikipedia.org/wiki/Inversion_of_control\" rel=\"nofollow\">Inversion of Control</a> and have your objects <em>ask</em> for a DB connection, rather than <em>getting</em> one, you don't have to worry about using singletons or static class properties – you just let the dependency layer manage connections, and this can be done with a simple static variable inside a closure (see below). </p>\n\n<p>This answer is verbose, because I'm going to assume ignorance and try to explain <a href=\"http://en.wikipedia.org/wiki/Dependency_injection\" rel=\"nofollow\">Dependency Injection</a> in as simple terms as possible (I still haven't found a concise explanation of DI). Afterwards, I'll explain how you can use DI to ensure no more than one DB connection is created.</p>\n\n<p>You need to create a very generic container object to contain dependencies. At runtime, you insert these dependencies into this container (typically before you do anything else). Then, you pass this container to the constructor of any object with a dependency. The object then retrieves the dependency it needs from the container. </p>\n\n<p>This allows the dependent object to be completely ignorant of how the dependency was constructed: e.g. a database object could have been constructed from PDO rather than MySQLi (though you'd want them to share the same API). This aids in making your code much easier to test by <a href=\"http://misko.hevery.com/2008/07/30/top-10-things-which-make-your-code-hard-to-test/\" rel=\"nofollow\">keeping object graph construction and application logic separate</a>.</p>\n\n<p>If you're using PHP 5.3+, I'd recommend looking into <a href=\"http://pimple.sensiolabs.org/\" rel=\"nofollow\">PIMPLE</a>. Here's how you'd set things up.</p>\n\n<pre><code>// Construct the container and all dependencies\n// This is usually done in a separate file\n\n$container = new Pimple();\n$container['db'] = function() {\n $db = ...; // Construct the DB connection\n return $db;\n}\n\n// Define a class that depends on the DB\nclass SomeObjectThatUsesDB {\n function __construct($container) {\n $this->container = $container;\n\n // No `new` keyword – this is a good thing!\n }\n\n function doSomething() {\n $db = $this->container['db'];\n // Do something with the DB\n }\n}\n\n// Use the class to do some work with the DB\n$obj = new SomeObjectThatUsesDB($container);\n$obj->doSomething();\n</code></pre>\n\n<p>The advantage here is <code>$container['db']</code> can be anything as long as it shares the same API.</p>\n\n<p>OK, so now let's talk about ensuring only one DB connection exists at any given time. Since the DI dependencies are just anonymous functions, you can just use the static keyword inside of the dependency definition; however, Pimple makes this even easier by providing a <code>share()</code> method that does this for you. As per the documentation:</p>\n\n<blockquote>\n <p>By default, each time you get an object, Pimple returns a new instance\n of it. If you want the same instance to be returned for all calls,\n wrap your anonymous function with the share() method</p>\n</blockquote>\n\n<p>Here's what it looks like:</p>\n\n<pre><code>$container['db'] = $container->share(function($container) {\n $db = ...; // Construct the DB connection\n return $db;\n});\n</code></pre>\n\n<p>This will make sure that sure only one $db is ever created. Here's the source code from Pimple's <code>share()</code> method for demonstration purposes:</p>\n\n<pre><code>/**\n * Returns a closure that stores the result of the given closure for\n * uniqueness in the scope of this instance of Pimple.\n *\n * @param Closure $callable A closure to wrap for uniqueness\n *\n * @return Closure The wrapped closure\n */\npublic static function share(Closure $callable)\n{\n return function ($c) use ($callable) {\n static $object;\n\n if (null === $object) {\n $object = $callable($c);\n }\n\n return $object;\n };\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-04T15:52:13.557",
"Id": "26989",
"ParentId": "26978",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "26989",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-04T10:55:51.763",
"Id": "26978",
"Score": "1",
"Tags": [
"php",
"pdo"
],
"Title": "Creating a PDO abstract parent class"
}
|
26978
|
<p>I have this code:</p>
<pre><code>JPanel controlPanel = new JPanel();
controlPanel.setLayout(new BoxLayout(controlPanel, BoxLayout.PAGE_AXIS));
TitledBorder tb2 = BorderFactory.createTitledBorder(null, "Control Panel",
TitledBorder.CENTER, TitledBorder.DEFAULT_POSITION, myFont, new Color(0, 153, 0));
controlPanel.setBorder(tb2);
JPanel fromDate = new JPanel();
fromDate.setLayout(new BoxLayout(fromDate, BoxLayout.X_AXIS));
fromDate.add(new JLabel("From date: "));
JButton fromDateButton = new JButton("...");
fromDateButton.setMaximumSize(new Dimension(100,15));
fromDate.add(fromDateButton);
JPanel toDate = new JPanel();
toDate.setLayout(new BoxLayout(toDate, BoxLayout.X_AXIS));
toDate.add(new JLabel("Until date: "));
JButton toDateButton = new JButton("...");
toDateButton.setMaximumSize(new Dimension(100,15));
toDate.add(toDateButton);
controlPanel.add(Box.createRigidArea(new Dimension(0,10)));
controlPanel.add(fromDate);
controlPanel.add(Box.createRigidArea(new Dimension(0,10)));
controlPanel.add(toDate);
toDate.setAlignmentX(Component.LEFT_ALIGNMENT);
fromDate.setAlignmentX(Component.LEFT_ALIGNMENT);
gui.add(controlPanel, BorderLayout.WEST);
</code></pre>
<p>Which produce this GUI (The relevant part is shown):</p>
<p><img src="https://i.stack.imgur.com/75Wri.png" alt="enter image description here"></p>
<p>I want to have a label and a button right next to it. There should be a better way to achieve this. Any suggestions?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-10T12:44:48.503",
"Id": "42274",
"Score": "1",
"body": "BoxLayout accepting min, max and preferred size, override these coordinates, but GBC is easier"
}
] |
[
{
"body": "<p>When you create a form, a <code>GridBagLayout</code> is usually needed.</p>\n\n<p>Here's one way to create the form in your question.</p>\n\n<pre><code>import java.awt.GridBagConstraints;\nimport java.awt.GridBagLayout;\nimport java.awt.Insets;\n\nimport javax.swing.JButton;\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\nimport javax.swing.JPanel;\nimport javax.swing.SwingUtilities;\n\npublic class SimpleGridBagLayout implements Runnable {\n\n @Override\n public void run() {\n JFrame frame = new JFrame(\"GridBagLayout Test\");\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n\n JPanel panel = new JPanel();\n panel.setLayout(new GridBagLayout());\n\n GridBagConstraints gbc = new GridBagConstraints();\n gbc.insets = new Insets(10, 10, 10, 10);\n gbc.gridwidth = 2;\n gbc.gridx = 0;\n gbc.gridy = 0;\n\n JLabel titleLabel = new JLabel(\"Control Panel\");\n panel.add(titleLabel, gbc);\n\n gbc.anchor = GridBagConstraints.LINE_START;\n gbc.fill = GridBagConstraints.HORIZONTAL;\n gbc.gridwidth = 1;\n gbc.gridy++;\n\n JLabel fromDateLabel = new JLabel(\"From date:\");\n panel.add(fromDateLabel, gbc);\n\n gbc.gridx++;\n\n JButton fromDateButton = new JButton(\"...\");\n panel.add(fromDateButton, gbc);\n\n gbc.gridx = 0;\n gbc.gridy++;\n\n JLabel toDateLabel = new JLabel(\"To date:\");\n panel.add(toDateLabel, gbc);\n\n gbc.gridx++;\n\n JButton toDateButton = new JButton(\"...\");\n panel.add(toDateButton, gbc);\n\n frame.add(panel);\n frame.setSize(250, 200);\n frame.setVisible(true);\n }\n\n public static void main(String[] args) {\n SwingUtilities.invokeLater(new SimpleGridBagLayout());\n }\n\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T06:56:58.307",
"Id": "41974",
"Score": "0",
"body": "Thanks. Is there a way to resize the buttons? (Using `setpreferredsize` or `setMaximumSize` doesn't work for this Layout)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T06:59:05.680",
"Id": "41976",
"Score": "0",
"body": "@Maroun Maroun: The horizontal fill should ensure that the buttons are the same size."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T07:06:46.700",
"Id": "41978",
"Score": "0",
"body": "Indeed. But I want then to be smaller than the size the horizontal fill makes. (Look at the image in my question)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-04T14:03:02.203",
"Id": "26982",
"ParentId": "26980",
"Score": "4"
}
},
{
"body": "<p>Add a glue in x 3 to get the extra space and then buttons won't get bigger.</p>\n\n<pre><code>panel.add(Box.createGlue(), gbc);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-13T16:52:09.327",
"Id": "31246",
"ParentId": "26980",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "26982",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-04T12:22:26.113",
"Id": "26980",
"Score": "1",
"Tags": [
"java",
"swing",
"gui",
"layout"
],
"Title": "Nested layouts - BoxLayout inside BorderLayout"
}
|
26980
|
<p>I'm relatively new to JavaScript and jQuery so go easy on me. I'm creating a website where upon jQuery <code>document.ready</code> a set of basic animations are performed on different <code>div</code>s on the HTML markup. All <code>div</code>s have separate IDs and I am storing all <code>div</code>s with same CSS property change in the same variable. Using these variables I run the function after. This code works fine but what would be a more effective manner of writing it?</p>
<pre><code><script src="jquery-1.8.3.js" type="text/javascript" ></script>
<script type="text/javascript">
$(document).ready(function() {
function fader(){
var logofade = $('#portlogo, #toolslogo, #contactlogo, #portfoliolblw, #toolslblw, #contactlblw'),
homefade = $('#homelogo'),
homeline = $('#hline'),
uline = $('#upline'),
acrossline = $('#acrossline'),
glow = $('#logoglow');
logofade.fadeOut(0)
homefade.fadeOut(0).delay(300).fadeIn(100)
homeline.delay(100).animate({'width': '150px'}, 100)
uline.delay(200).animate({'height': '41px', 'top':'-30px'}, 100)
acrossline.delay(300).animate({'width': '825px'}, 100)
glow.fadeOut(0).delay(600).fadeIn(600);
}
fader()
});
function logochange() { $('#homelogo').delay(300).fadeIn(100);}
function logochange1() { $('#portlogo, #toolslogo, #contactlogo').fadeOut(100);}
function logochange2() { $('#portlogo').delay(300).fadeIn(100);}
function logochange3() { $('#toolslogo, #homelogo, #contactlogo').fadeOut(100);}
function logochange4() { $('#toolslogo').delay(300).fadeIn(100);}
function logochange5() { $('#portlogo, #homelogo, #contactlogo').fadeOut(100);}
function logochange6() { $('#contactlogo').delay(300).fadeIn(100);}
function logochange7() { $('#portlogo, #homelogo, #toolslogo').fadeOut(100);}
function homebtn() { $('#homelblw').fadeIn(0);}
function homebtn1() { $('#homelblw').fadeOut(0);}
function portbtn() { $('#portfoliolblw').fadeIn(0);}
function portbtn1() { $('#portfoliolblw').fadeOut(0);}
function toolsbtn() { $('#toolslblw').fadeIn(0);}
function toolsbtn1() { $('#toolslblw').fadeOut(0);}
function contactbtn() { $('#contactlblw').fadeIn(0);}
function contactbtn1() { $('#contactlblw').fadeOut(0);}
function hline1() {$('#hline').animate({'width': '150px'}, 100);}
function hline2() {$('#hline').animate({'width': '0px'}, 100);}
function pline1() {$('#pline').animate({'width': '150px'}, 100);}
function pline2() {$('#pline').animate({'width': '0px'}, 100);}
function tline1() {$('#tline').animate({'width': '150px'}, 100);}
function tline2() {$('#tline').animate({'width': '0px'}, 100);}
function cline1() {$('#cline').animate({'width': '150px'}, 100);}
function cline2() {$('#cline').animate({'width': '0px'}, 100);}
function upline1() {
$('#upline').animate({
'height': '-41px', 'top':'0px'
}, 0).delay(100).animate({
'height': '41px', 'top':'-30px'
}, 100);
}
function acrossline1() {
$('#acrossline').animate({
'width': '0px'
}, 0).delay(200).animate({
'width': '825px'
}, 100);
}
</script>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-04T14:41:33.253",
"Id": "41816",
"Score": "0",
"body": "not the best example of coding best practises, but a nudge in the right direction would be grateful :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-04T14:48:18.477",
"Id": "41817",
"Score": "0",
"body": "Maybe use `each()`?"
}
] |
[
{
"body": "<p>I would say two things could improve this considerably:</p>\n\n<ol>\n<li>Use CSS classes elements that share the same animations. This way you can just fetch <em>all</em> the elements that need to be animated with a single <code>$()</code>. e.g. <code>$('.animate')</code></li>\n<li>Instead of using jQuery's animation methods, use CSS transitions. This will make your code simpler, and you know you're using the browser's native animation rendering.</li>\n</ol>\n\n<p>Here's an example:</p>\n\n<pre><code><div id=\"logo1\" class=\"fade-out\">Logo 1</div>\n<div id=\"logo2\" class=\"fade-out\">Logo 2</div>\n<div id=\"upline\" class=\"expand-x\">Some text</div>\n<style>\n .fade-out {\n opacity: 1.0;\n transition: opacity 0 .2s;\n }\n .fade-out.animate { opacity: 0; }\n\n .expand-x { \n width: 100px;\n transition: width .1s .2s;\n }\n .expand-x.animate { width: 200px; }\n</style>\n\n<script>\n $('.fade-out').addClass('animate');\n $('.expand-x').addClass('animate');\n</script>\n</code></pre>\n\n<p>You could simplify this even further by using a single CSS class for all elements that need animating. e.g. <code>$('.needs-animation').addClass('animate');</code> </p>\n\n<p>Also, if there are any animations that are triggered by mousehover, you could do all the animation in CSS with the <code>:hover</code> pseudo-selector.</p>\n\n<p>Finally, make sure the CSS transitions you use are compatible with all the browsers you're supporting.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-04T15:12:08.903",
"Id": "26986",
"ParentId": "26984",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "26986",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-04T14:39:22.180",
"Id": "26984",
"Score": "3",
"Tags": [
"javascript",
"jquery",
"css"
],
"Title": "More efficient jQuery scripting when manipulating multiple elements with multiple CSS attributes"
}
|
26984
|
<p>I'm a PHP newbie and I have a question. Is there a better way to do this? A nice solution?</p>
<pre><code>$list = isset($_GET['list']) ? htmlspecialchars($_GET['list']) : "experience";
<select name="type" id="type">
<option value="experience">Experience</option>
<option value="magic"<?=$list == "magic" ? 'selected' : '';?>>Magic Points</option>
<option value="shielding"<?=$list == "shielding" ? 'selected' : '';?>>Shielding</option>
<option value="distance"<?=$list == "distance" ? 'selected' : '';?>>Distance</option>
<option value="melee"<?=$list == "sword" ? 'selected' : '';?>>Melee</option>
<option value="fishing"<?=$list == "fishing" ? 'selected' : '';?>>Fishing</option>
</select>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-04T16:01:46.970",
"Id": "41829",
"Score": "0",
"body": "See also: http://codereview.stackexchange.com/a/26810/20611"
}
] |
[
{
"body": "<p>You can use a <a href=\"http://php.net/manual/en/language.types.array.php\" rel=\"nofollow\">lookup table</a> for your values like this:</p>\n\n<pre><code>$values = array(\"magic\" => \"Magic points\", ...);\n</code></pre>\n\n<p>and then <a href=\"http://ch2.php.net/manual/en/control-structures.foreach.php\" rel=\"nofollow\">loop</a> over that to <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow\">reduce the duplication</a>:</p>\n\n<pre><code>foreach ($values as $key => $value) {\n ...\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-04T15:58:29.177",
"Id": "26990",
"ParentId": "26987",
"Score": "3"
}
},
{
"body": "<p>You might want to build a wrapper for this.</p>\n\n<pre><code>$output->add_select(array $fields, $id, $name, $multichoice = false) {\n\n $html = \"<select name='$type' id='type'>\";\n\n foreach ($fields AS $field){\n $html.=...\n }\n\n ... \n return $html;\n\n}\n</code></pre>\n\n<p>You get the idea. There is nothing more convenient hat having all those form-gruntworks in methods.</p>\n\n<p><code>$output->add_select($this->get_powers(), 'power', 'power'));</code> or alike and you are good to go.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T16:25:00.027",
"Id": "42032",
"Score": "0",
"body": "This might be a bit overkill, but definitely a good way to introduce OP to OOP and compartmentalization."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-04T22:03:23.037",
"Id": "27009",
"ParentId": "26987",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-04T15:38:07.523",
"Id": "26987",
"Score": "1",
"Tags": [
"beginner",
"php",
"form"
],
"Title": "Making a preselected drop-down selection box in HTML"
}
|
26987
|
<p>I am using a long array of over 300 var & 7,000 lines of code written like this:</p>
<pre><code>var a = [];
var b = [];
var c = [];
var d = [];
var e = [];
a[0] = "a";
b[0] = "b";
c[0] = "c";
d[0] = "d";
e[0] = "e";
a[1] = "1";
b[1] = "2";
c[1] = "3";
d[1] = "4";
e[1] = "5";
a[2] = "one";
b[2] = "two";
c[2] = "three";
d[2] = "four";
e[2] = "five";
</code></pre>
<p>Im guessing it is the same as a much cleaner and shorter - </p>
<pre><code>var a = [a,1,one];
var b = [b,2,two];
var c = [c,3,three];
var d = [d,4,four];
var e = [e,5,five];
</code></pre>
<p>Is there an easy or automatic way to rewrite the original array like the 2nd method?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-04T16:48:12.680",
"Id": "41832",
"Score": "0",
"body": "If you have a finite number of elements that you need to add to an array which follow a pattern, use a for loop. If you don't know how many you're going to need, a while loop will do the trick. Loop through them and use the index to assign the numbers accordingly."
}
] |
[
{
"body": "<p>If you have a finite number of elements that you need to add to an array which follow a pattern, use a for loop. If you don't know how many you're going to need, a while loop will do the trick. Loop through them and use the index to assign the numbers accordingly.</p>\n\n<pre><code>for (var i = 0; i < 36; i++) {\n var a = [String.fromCharCode(65 + i).toLowerCase(), i+1, toWords(i) ];\n};\n\nconsole.log(a); \n\nvar th = ['','thousand','million', 'billion','trillion'];\nvar dg = ['zero','one','two','three','four', 'five','six','seven','eight','nine'];\nvar tn = ['ten','eleven','twelve','thirteen', 'fourteen','fifteen','sixteen', 'seventeen','eighteen','nineteen'];\nvar tw = ['twenty','thirty','forty','fifty', 'sixty','seventy','eighty','ninety'];\n\nfunction toWords(s){\n s = s.toString();\n s = s.replace(/[\\, ]/g,'');\n if (s != parseFloat(s))\n return 'not a number';\n var x = s.indexOf('.'); \n if (x == -1) \n x = s.length; \n if (x > 15) \n return 'too big'; \n var n = s.split(''); \n var str = ''; \n var sk = 0; \n for (var i=0; i < x; i++) {\n if ((x-i)%3==2) {\n if (n[i] == '1') {\n str += tn[Number(n[i+1])] + ' ';\n i++;\n sk=1;\n } else if (n[i]!=0) {\n str += tw[n[i]-2] + ' ';\n sk=1;\n }\n } else if (n[i]!=0) {\n str += dg[n[i]] +' ';\n if ((x-i)%3==0)\n str += 'hundred ';\n sk=1;\n } \n if ((x-i)%3==1) {\n if (sk)\n str += th[(x-i-1)/3] + ' ';\n sk=0;\n }\n }\n if (x != s.length) {\n var y = s.length;\n str += 'point ';\n for (var i=x+1; i<y; i++)\n str += dg[n[i]] +' ';\n } \n return str.replace(/\\s+/g,' ');\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-04T17:07:20.770",
"Id": "26991",
"ParentId": "26988",
"Score": "1"
}
},
{
"body": "<p>First of all:</p>\n\n<pre><code>var a = [a,1,one];\nvar b = [b,2,two];\nvar c = [c,3,three];\nvar d = [d,4,four];\nvar e = [e,5,five];\n</code></pre>\n\n<p>is not the same as:</p>\n\n<pre><code>var a = [\"a\",1,one];\nvar b = [\"b\",2,two];\nvar c = [\"c\",3,three];\nvar d = [\"d\",4,four];\nvar e = [\"e\",5,five];\n</code></pre>\n\n<p>Second: Technically, it would have the same effect, to declare an array step by step or in a row.</p>\n\n<p>And no: there is no real way to convert your code automatically from the former to the latter. But perhaps, your question goes in another direction. Perhaps you want a solution to easily build combined arrays. For that task I suggest to take a look at <a href=\"http://underscorejs.org/#zip\" rel=\"nofollow\">underscore's zip</a> function:</p>\n\n<pre><code>_.zip(['moe', 'larry', 'curly'], [30, 40, 50], [true, false, false]);\n</code></pre>\n\n<p>outcome: </p>\n\n<pre><code>[[\"moe\", 30, true], [\"larry\", 40, false], [\"curly\", 50, false]]\n</code></pre>\n\n<p>So in your case:</p>\n\n<pre><code>_.zip([\"a\", \"b\", \"c\", ...], [\"1\", \"2\", \"3\", ...], [\"one\", \"two\", \"three\", ...]);\n</code></pre>\n\n<p>would be, what you are looking for.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-05T17:30:30.137",
"Id": "41924",
"Score": "0",
"body": "I thought if I had my arrays like the 2nd method my array js file would be a lot smaller, and easier to read etc. The filesize reduction would be my biggest goal - thanks"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-04T19:56:34.507",
"Id": "26996",
"ParentId": "26988",
"Score": "1"
}
},
{
"body": "<p>First of all I think you meant:</p>\n\n<pre><code>a = [\"a\",\"1\",\"one\"]; // instead of [a, 1, one]\n</code></pre>\n\n<p>I handle these rare kind of issues as follow:</p>\n\n<ul>\n<li>Open your browser (the following code is tested against Chrome)</li>\n<li>Open the JavaScript console [Control -Shift -J (Chrome:Windows/Linux)]</li>\n<li>Copy/paste your own code into the console</li>\n</ul>\n\n<p>and then paste the following code</p>\n\n<pre><code>copy('abcde'.split('').map(function(varName){\nreturn 'var ' + varName + ' = ' + JSON.stringify(window[varName])+';';\n}).join('\\n'));\n</code></pre>\n\n<p>If your variable names are more than 1 character use this code instead: (<strong>of course the following code won't work with the file example you specified, I changed the variable names for demonstration purpose</strong>)</p>\n\n<pre><code>copy(['var1', 'myVar2', 'blablabla'].map(function(varName){\nreturn varName + ' = ' + JSON.stringify(window[varName])+';';\n}).join('\\n'));\n</code></pre>\n\n<ul>\n<li>Hit enter</li>\n</ul>\n\n<p>the above code will copy the following JavaScript code into your clipboard:</p>\n\n<pre><code>a = [\"a\",\"1\",\"one\"];\nb = [\"b\",\"2\",\"two\"];\nc = [\"c\",\"3\",\"three\"];\nd = [\"d\",\"4\",\"four\"];\ne = [\"e\",\"5\",\"five\"];\n</code></pre>\n\n<p>Paste it into your file, save it and that's all!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-05T17:35:39.297",
"Id": "41925",
"Score": "0",
"body": "wow. Looks good, but it looks like I need to make an array of my vars 1st before I run this. Ill test it out - Thanks"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T07:58:34.393",
"Id": "41980",
"Score": "0",
"body": "If your variables follow a specified pattern just tell me what it is and I'll see what I can do about it :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T11:33:58.530",
"Id": "41989",
"Score": "0",
"body": "They are product codes so dont really have a pattern. I have them in csv format so it should be easy enough. Thanks"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T14:59:41.313",
"Id": "42025",
"Score": "0",
"body": "excellent - thanks so much. I went from 180kb file to 80kb, and I think easier to manage file. I dont have var before the variables though. It works but not best practice?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T15:04:51.893",
"Id": "42026",
"Score": "0",
"body": "I added 2 things to the explanation so idiots can follow - the shortkey to the JS console, and hit enter at the end!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-07T09:28:53.157",
"Id": "42108",
"Score": "0",
"body": "Thanks, edit accepted. \"var before the variables though. It works but not best practice?\" indeed, just change varName + by \"var \" + varName + to fix this in the script"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-05T09:30:45.443",
"Id": "27028",
"ParentId": "26988",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "27028",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-04T15:48:25.190",
"Id": "26988",
"Score": "3",
"Tags": [
"javascript",
"array"
],
"Title": "re-write javascript array"
}
|
26988
|
<p>I wrote this code to solve a problem from a John Vuttag book:</p>
<blockquote>
<p>Ask the user to input 10 integers, and then print the largest odd number that was entered. If no odd number was entered, it should print a message to that effect.</p>
</blockquote>
<p>Can my code be optimized or made more concise? Any tips or errors found?</p>
<pre><code>{
a = int (raw_input("enter num: "))
b = int (raw_input("enter num: "))
c = int (raw_input("enter num: "))
d = int (raw_input("enter num: "))
e = int (raw_input("enter num: "))
f = int (raw_input("enter num: "))
g = int (raw_input("enter num: "))
h = int (raw_input("enter num: "))
i = int (raw_input("enter num: "))
j = int (raw_input("enter num: "))
num_List = {a,b,c,d,e,f,g,h,i,j }
mylist=[]
## Use for loop to search for odd numbers
for i in num_List:
if i&1 :
mylist.insert(0,i)
pass
elif i&1 is not True:
continue
if not mylist:
print 'no odd integers were entered'
else:
print max (mylist)
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-04T19:04:50.700",
"Id": "41836",
"Score": "0",
"body": "Here's my response to a suspiciously similar question: http://codereview.stackexchange.com/questions/26187/i-need-my-code-to-be-more-consise-and-i-dont-know-what-is-wrong-with-it-its/26191#26191"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-04T19:12:33.970",
"Id": "41838",
"Score": "0",
"body": "this question is a \"finger exercise\" in John Vuttag book, introduction to programming. Sorry if it was posted before"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-04T20:09:49.907",
"Id": "41842",
"Score": "0",
"body": "Oh no problem, I was just trying to help :)"
}
] |
[
{
"body": "<p>Your main loop can just be:</p>\n\n<pre><code>for i in num_list:\n if i & 1:\n mylist.append(i)\n</code></pre>\n\n<p>There is no need for the else at all since you don't do anything if <code>i</code> is not odd.</p>\n\n<p>Also, there is no need at all for two lists. Just one is enough:</p>\n\n<pre><code>NUM_ENTRIES = 10\n\nfor dummy in range(NUM_ENTRIES):\n i = int(raw_input(\"enter num: \"))\n if i & 1:\n mylist.append(i)\n</code></pre>\n\n<p>Then the rest of the program is as you wrote it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-04T18:56:23.207",
"Id": "41833",
"Score": "0",
"body": "Thanks! it looks cleaner. I am working on using one raw_input instead of 10"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-04T19:04:09.980",
"Id": "41835",
"Score": "0",
"body": "No problem! I am no Python specialist though"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-04T20:03:10.350",
"Id": "41839",
"Score": "0",
"body": "@fge one small thing, wouldn't a `for j in range(10)` be better than incrementing in a `while` loop?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-04T21:08:00.250",
"Id": "41853",
"Score": "0",
"body": "tijko: yup... I didn't know of `range` :p"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-04T18:48:14.310",
"Id": "26993",
"ParentId": "26992",
"Score": "4"
}
},
{
"body": "<p>One other minor change you could make, would be to just loop over a range how many times you want to prompt the user for data:</p>\n\n<pre><code>mylist = list()\nfor _ in range(10):\n while True:\n try:\n i = int(raw_input(\"enter num: \"))\n if i & 1:\n mylist.append(i)\n break\n except ValueError:\n print \"Enter only numbers!\"\n</code></pre>\n\n<p>No need to create an extra variable and increment it here.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-18T00:56:32.527",
"Id": "66257",
"Score": "1",
"body": "Since you don't care about the value of `j`, it's customary to write `for _ in range(10)` instead."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-04T20:09:18.560",
"Id": "26997",
"ParentId": "26992",
"Score": "4"
}
},
{
"body": "<p>I'd write:</p>\n\n<pre><code>numbers = [int(raw_input(\"enter num: \")) for _ in range(10)]\nodd_numbers = [n for n in numbers if n % 2 == 1]\nmessage = (str(max(odd_numbers)) if odd_numbers else \"no odd integers were entered\")\nprint(message)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-05T14:00:43.563",
"Id": "27035",
"ParentId": "26992",
"Score": "1"
}
},
{
"body": "<p>My 2c: though I don't know Python syntax that well, here's an optimization idea that would be more important given a (much) bigger dataset.</p>\n\n<p>You don't need any lists at all. On the outside of the loop, declare a \"maximum odd\" variable, initially equal to -1. On the inside of the loop, whenever a number is input, if it's odd and greater than <code>maximumOdd</code>, then set <code>maximumOdd</code> equal to that number. This requires nearly no memory, whereas building up a list and then operating on it scales linearly in memory (not good).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T13:45:07.303",
"Id": "42010",
"Score": "0",
"body": "I was trying to get the loop concept down, this is taking it to the next level, Thanks. Can you please tell me why you set the variable to -1"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T18:58:58.060",
"Id": "42049",
"Score": "0",
"body": "The variable is set to -1, or some other value making it obvious that it's \"unset\". That way, if the loop runs through without finding any odd numbers, you can tell afterwards."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-05T20:27:46.970",
"Id": "27058",
"ParentId": "26992",
"Score": "3"
}
},
{
"body": "<p>This is a solution that doesn't use lists, and only goes through the input once.</p>\n\n<pre><code>maxOdd = None\n\nfor _ in range(10):\n num = int (raw_input(\"enter num: \"))\n if num & 1:\n if maxOdd is None or maxOdd < num:\n maxOdd = num\n\nif maxOdd:\n print \"The max odd number is\", maxOdd \nelse:\n print \"There were no odd numbers entered\"\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-17T23:55:39.783",
"Id": "44628",
"ParentId": "26992",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "26993",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-04T18:35:39.707",
"Id": "26992",
"Score": "4",
"Tags": [
"python",
"beginner"
],
"Title": "Print the largest odd number entered"
}
|
26992
|
<p>I wrote an example program about UNIX semaphores, where a process and its child lock/unlock the same semaphore. I would appreciate your feedback about what I could improve in my C style. Generally I feel that the program flow is hard to read because of all those error checks, but I didn't find a better way to write it. It's also breaking the rule of "one vertical screen maximum per function" but I don't see a logical way to split it into functions.</p>
<pre><code>#include <semaphore.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
int main(void)
{
/* place semaphore in shared memory */
sem_t *sema = mmap(NULL, sizeof(sema),
PROT_READ |PROT_WRITE,MAP_SHARED|MAP_ANONYMOUS, -1, 0);
if (!sema) {
perror("Out of memory");
exit(EXIT_FAILURE);
}
/* create, initialize semaphore */
if (sem_init(sema, 1, 0) < 0) {
perror("semaphore initilization");
exit(EXIT_FAILURE);
}
int i, nloop=10;
int ret = fork();
if (ret < 0) {
perror("fork failed");
exit(EXIT_FAILURE);
}
if (ret == 0) {
/* child process*/
for (i = 0; i < nloop; i++) {
printf("child unlocks semaphore: %d\n", i);
sem_post(sema);
sleep(1);
}
if (munmap(sema, sizeof(sema)) < 0) {
perror("munmap failed");
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}
if (ret > 0) {
/* back to parent process */
for (i = 0; i < nloop; i++) {
printf("parent starts waiting: %d\n", i);
sem_wait(sema);
printf("parent finished waiting: %d\n", i);
}
if (sem_destroy(sema) < 0) {
perror("sem_destroy failed");
exit(EXIT_FAILURE);
}
if (munmap(sema, sizeof(sema)) < 0) {
perror("munmap failed");
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}
}
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li><code>main()</code> must always return an <code>int</code>. <code>return 0</code> at the end of your function.</li>\n<li>The <a href=\"https://stackoverflow.com/questions/461449/return-statement-vs-exit-in-main\">consensus</a> is that, when possible, <code>return</code> instead of <code>exit</code>.</li>\n<li>You could make a helper function that accepts a <code>bool</code> (from <code>stdbool.h</code>) and a <code>const char *</code>, and if the bool is false then <code>perror</code> and <code>exit(EXIT_FAILURE)</code> are called.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-04T21:00:45.383",
"Id": "41850",
"Score": "2",
"body": "No. It is right, that the main function always returns an int. But you have not explicitly write a return statement for that. According to the C99 standard, the compiler does that for you: »5.1.2.2.3 Program termination [...]\nreaching the } that terminates the\nmain function returns a value of 0.«"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-04T21:04:24.470",
"Id": "41851",
"Score": "0",
"body": "Frankly, I don't care what the standard says. It may be doing the right thing, but this is a matter of style - if there's a return value specified, supply it, for the purposes of clarity."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-05T06:24:56.550",
"Id": "41885",
"Score": "0",
"body": "Thank you for your feedback! I also read the thread you linked to but I wasn't sure because most of the answers applied to C++ destructors, I'll use return then."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-04T20:46:51.223",
"Id": "27001",
"ParentId": "27000",
"Score": "3"
}
},
{
"body": "<p>Your code is good, especially the error checks. Error checking always takes\nup space and can be distracting, but good error checking is a mark of good\ncode (and of a good programmer).</p>\n\n<p>As you say, <code>main</code> is a bit long, but it can be shortened quite nicely by\nextracting the two for-loops into functions. You can also remove the duplicate\n<code>munmap</code> call. Here's what you get after the semaphore initialisation:</p>\n\n<pre><code>int pid = fork();\nif (pid < 0) {\n perror(\"fork\");\n exit(EXIT_FAILURE);\n}\nelse if (pid == 0) {\n child(sema, nloops);\n}\nelse {\n parent(sema, nloops);\n int stat;\n wait(&stat);\n if (sem_destroy(sema) < 0) {\n perror(\"sem_destroy\");\n exit(EXIT_FAILURE);\n }\n}\nif (munmap(sema, sizeof *sema) < 0) {\n perror(\"munmap\");\n exit(EXIT_FAILURE);\n}\nexit(EXIT_SUCCESS);\n</code></pre>\n\n<p>Note that I renamed <code>ret</code> as <code>pid</code>, as it holds a process ID. And I added a\n<code>wait</code> call after the parent loop completes so that the parent waits for the\nchild to exit (<code>stat</code> holds the child exit status). I also removed the word\n\"failed\" from the <code>perror</code> calls, as the message <code>perror</code> prints will make\nit clear that the call failed.</p>\n\n<p>Some other points: my Mac's <code>mmap</code> takes <code>MAP_ANON</code> not <code>MAP_ANONYMOUS</code> -\nwhich system are you using? And also there is a <code>MAP_HASSEMAPHORE</code> flag that\nwould be appropriate here, although your system may not have it (no idea\nexactly what it does though).</p>\n\n<p>Finally, the <code>mmap</code>/<code>munmap</code> calls use <code>sizeof(sema)</code> which is the size of the\npointer. If it works, I would guess that <code>mmap</code> is actually mapping a whole\npage and ignoring the size. However, it should be <code>sizeof *sema</code> or <code>sizeof(sema_t)</code></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-05T06:23:12.087",
"Id": "41884",
"Score": "0",
"body": "Thank you for the feedback! `MAP_ANONYMOUS` seems to be better, according to `mmap` man page: \"`MAP_ANON`\n Synonym for `MAP_ANONYMOUS`. Deprecated.\" I'm running the program on Linux (Ubuntu)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-05T01:58:01.490",
"Id": "27019",
"ParentId": "27000",
"Score": "4"
}
},
{
"body": "<p>One thing to note:</p>\n\n<pre><code>sem_t *sema = mmap(NULL, sizeof(sema), \n PROT_READ |PROT_WRITE,MAP_SHARED|MAP_ANONYMOUS, -1, 0);\nif (!sema) {\n</code></pre>\n\n<p>Failure in <code>mmap</code> will return <code>MAP_FAILED</code>, not <code>NULL</code> (usually I think <code>MAP_FAILED</code> expands to <code>-1</code> cast to a pointer, meaning your failure check won't work).</p>\n\n<p>As for style: This is just an opinion, but I think your style could benefit from the concept of a \"cleanup block\".</p>\n\n<p>For example, instead of this kind of style [paraphrasing your code, not doing literal quotes]:</p>\n\n<pre><code>sema = mmap(/* ... */);\n\nif (sema == MAP_FAILED)\n{\n exit(EXIT_FAILURE);\n}\n\nfoo = malloc(sizeof(*foo));\nif (!foo)\n{\n exit(EXIT_FAILURE);\n}\n</code></pre>\n\n<p>You could do something like:</p>\n\n<pre><code> int status = EXIT_FAILURE;\n sem_t *sema = NULL;\n struct foo *foo = NULL;\n\n sema = mmap(/* ... */);\n\n if (sema == MAP_FAILED)\n {\n goto cleanup;\n }\n\n foo = malloc(sizeof(*foo));\n if (!foo)\n {\n goto cleanup;\n }\n\n // TODO: do stuff with sema and foo\n\n // mark success\n status = EXIT_SUCCESS;\n\ncleanup:\n if (sema && sema != MAP_FAILED)\n munmap(sema, /* ... */);\n if (foo)\n free(foo);\n\n return status;\n</code></pre>\n\n<p>The benefit to this kind of style is that you can add any type of allocation you want (in between the other stuff, before it, after it, whatever), and you just need to add a quick line or two in the cleanup block, and suddenly, all success and failure paths get the resources freed. If any of the intermediate steps fail and you wind up in the cleanup block, you can be assured that you're not leaking anything, and it won't feel repetitive to make that happen.</p>\n\n<p>There are other variants of this, for example if you or someone you're working with has some religious objection to <code>goto</code> (even though it's the cleanest way to do error handling in plain C), on the slightly more repetitive side you could repeatedly check <code>status</code> to see that you're still succeeding:</p>\n\n<pre><code>int status = EXIT_SUCCESS;\nsem_t *sema = NULL;\nstruct foo *foo = NULL;\n\nif (status == EXIT_SUCCESS)\n{\n sema = mmap(/* ... */);\n\n if (sema == MAP_FAILED)\n {\n status = EXIT_FAILURE;\n }\n}\n\nif (status == EXIT_SUCCESS)\n{\n foo = malloc(sizeof(*foo));\n if (!foo)\n {\n status = EXIT_FAILURE;\n }\n}\n\nif (status == EXIT_SUCCESS)\n{\n // TODO: do stuff with sema and foo\n}\n\nif (sema && sema != MAP_FAILED)\n munmap(sema, /* ... */);\nif (foo)\n free(foo);\n\nreturn status;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-05T12:18:45.043",
"Id": "41900",
"Score": "0",
"body": "Add the individual `perror` calls back (which are necessary) and these approaches still have 2 lines per error..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T01:33:33.217",
"Id": "41957",
"Score": "0",
"body": "@WilliamMorris - Yes, but as the number of things going on in the function grow, it will just have 2 lines per error (not, say, 1 to 6 if there are 6 allocations, as a random example)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-05T07:23:04.510",
"Id": "27023",
"ParentId": "27000",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "27019",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-04T20:38:33.683",
"Id": "27000",
"Score": "3",
"Tags": [
"c",
"linux"
],
"Title": "UNIX semaphores"
}
|
27000
|
<p>I am starting to write some functions while studying how to program in C. In this small function I take a string as an argument and print it out in reverse order.</p>
<pre><code>#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[]) {
int aLen = argc;
char *sWord = argv[aLen - 1];
char *reversed;
int sLen = strlen(sWord);
int i = 0;
reversed = reversed + sLen; // offset pointer to the length of string
while (i <= sLen) {
if (sWord[i] != '\0') { // check if character is null-terminator
*reversed = sWord[i]; // if not, let reversed correct address
} // equal letter.
i++;
reversed--;
}
printf("%s reversed is:%s\n", sWord, reversed);
return 0;
}
</code></pre>
<p>I was hoping to get some tips on best practice or corrections on any errors.</p>
|
[] |
[
{
"body": "<p>You need to allocate storage for the reversed string using <code>malloc</code> unless that's changed in the last twenty years and place a <code>'\\0'</code> string terminator at the end.</p>\n\n<pre><code>char *reversed = malloc(sLen + 1);\nreversed[sLen] = '\\0';\n</code></pre>\n\n<p>Also, you're writing to cells 1 .. <code>sLen</code> when you should be writing to 0 .. <code>sLen - 1</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-04T21:27:31.833",
"Id": "41854",
"Score": "0",
"body": "I will check on the these points you brought up, I appreciate the help."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-05T07:31:15.880",
"Id": "41888",
"Score": "0",
"body": "You don't need to allocate any memory to do an *in-place* reversal of a string - and it looks kind of like that's what's being attempted."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-05T07:50:52.703",
"Id": "41891",
"Score": "0",
"body": "@asveikau - I thought so as well until I saw this: `reversed = reversed + sLen;`."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-04T21:02:59.713",
"Id": "27004",
"ParentId": "27003",
"Score": "3"
}
},
{
"body": "<p>For simply reversing the string, you could do it without allocating additional memory:</p>\n\n<pre><code>int main(int argc, char* argv[])\n{\n if(argc==2){\n char *message=argv[argc-1];\n size_t offsetLength=strlen(message);\n char *last=message+(offsetLength);\n while(last-- > message){\n putc(*(last), stdout);\n }\n }\n return 0;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-05T02:44:42.697",
"Id": "41878",
"Score": "0",
"body": "Is allocating memory `malloc` only for resource heavy situations?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-05T07:53:49.110",
"Id": "41892",
"Score": "0",
"body": "You can allocate memory in the heap using `malloc` or on the stack by declaring a sized array. It doesn't need to involve \"resource heavy situations.\" You can allocate a single byte on the stack using `byte b` (if the compiler doesn't inline it into a register)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-05T11:34:28.320",
"Id": "41898",
"Score": "0",
"body": "There is one clear answer: it depends ;) No, it is not only for ressource-heavy-situations. Yes, in some use-cases as the one above, there is no need for allocating extra memory. To make it a bit clearer: if you want to preserve the original and work with a copy, it makes sense to dynamically allocate memory needed."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-04T21:53:54.143",
"Id": "27008",
"ParentId": "27003",
"Score": "2"
}
},
{
"body": "<p>Your code has a number of issues, the main one being that it doesn't work.</p>\n\n<p>If you want to reverse a string in place then I suggest you write a function just\nfor that, separate from <code>main</code>. The function will need a temporary variable\nand will, for example:</p>\n\n<pre><code>swap first and last characters\nswap 2nd and 2nd-from-last characters\nswap 3rd and 3rd-from-last characters\netc\n</code></pre>\n\n<p>To swap the characters pointed to by <code>a</code> and <code>b</code>, you would do</p>\n\n<pre><code>char temp = *a;\n*a = *b;\n*b = *temp;\n</code></pre>\n\n<p>or if you have a pointer and a length:</p>\n\n<pre><code>char temp = a[0];\na[0] = b[len];\nb[len] = temp;\n</code></pre>\n\n<p>So your reversal function needs to contain one of these sequences in a loop\nand the loop must arrange <code>a</code> and <code>b</code> to point to the correct places. For\nexample, here is a reverse function:</p>\n\n<pre><code>static char* reverse(char *str)\n{\n char *s = str;\n char *end = s + strlen(s) - 1;\n for (; s < end; ++s, --end) {\n char ch = *end;\n *end = *s;\n *s = ch;\n }\n return str;\n}\n</code></pre>\n\n<p><hr>\nThen in <code>main</code> all you do is call the reverse function with the desired\nstring:</p>\n\n<pre><code>printf(\"'%s'\\n\", reverse(argv[1]));\n</code></pre>\n\n<p>Of course it is best to check that <code>argv[1]</code> exists first (remember that argv[0] is the program name and argc is always greater than or equal to 1):</p>\n\n<pre><code>if (argc == 2) {\n printf(\"'%s' reversed is \", argv[1]);\n printf(\"'%s'\\n\", reverse(argv[1]));\n} \n</code></pre>\n\n<p><hr>\nNotes: </p>\n\n<p>In your code, <code>aLen</code> and <code>sWord</code> are unnecessary. And <code>reversed</code> is\nnot initilaised but is then used in </p>\n\n<pre><code>reversed = reversed + sLen; // See the EDIT below\n</code></pre>\n\n<p>In the line</p>\n\n<pre><code>int sLen = strlen(sWord);\n</code></pre>\n\n<p><code>strlen</code> returns the length as a <code>size_t</code>, not <code>int</code></p>\n\n<p><strong>EDIT</strong></p>\n\n<p>When you declare a variable local to a function, the compiler sets aside a\nspace on the stack. It does <strong>not</strong> write anything there unless you declare\nthe initial value for the variable. So in your code, <code>reserved</code> contains\nwhatever happens to be at that location on the stack and, as <code>reserved</code> is a\npointer, it therefore points to some unknown (unplanned) location in memory.\nIf you are <strong>unlucky</strong> that location will be writeable, your accesses 'work'\nand you won't see the problem (or not immediately - in a larger program you\nwill probably encounter strange behaviour later on while the code is executing\nbecause your accesses have overwritten something important); if you are\n<strong>lucky</strong> and the location is unwritable you will see the problem the first\ntime you run the program.</p>\n\n<p>The moral is always to initialise variables, just to be safe. Zero (NULL) is\na good value for pointers. With C99 you are not restricted to defining them at\nthe start of a function, so it is often best to define a variable only at the\npoint where you need it and have a useful value with which to initialise it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-05T18:10:43.120",
"Id": "41933",
"Score": "0",
"body": "This code compiles without errors and prints out the argument to the screen in reverse order. In what way do you mean it doesn't work?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T00:52:59.507",
"Id": "41955",
"Score": "0",
"body": "It compiles without errors but not without warnings - the inconsequential type conversion of `strlen()` and the **fatal** use of the uninitialised variable `reversed`. It cannot possibly 'work' reliably with that uninitialised access. When I run it, it seg-faults, which is not at all surprising."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T02:13:35.430",
"Id": "41958",
"Score": "0",
"body": "Thanks for getting back to me on this. I didn't want to come off as disrespectful or ungrateful, considering you took the time to write a lengthy and extensive response. I haven't had this segfault on me or spit out warnings when compiling. This is why I was wanting to know exactly where and why this would fail. I have more than alot to learn with C and will be studying up on the issues you brought up here. Maybe when I make some more well informed edits I'll post again :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T02:39:41.053",
"Id": "41960",
"Score": "0",
"body": "Well, I went back to testing this code and sure enough it just to fail with any string over 9 characters in length. I still don't receive any compilation warnings/errors had I, I wouldn't have even bothered with posting this. Embarassing but, I should learn plenty from your post and the others."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T13:42:11.763",
"Id": "42009",
"Score": "0",
"body": "It depends upon the compiler. I tried `gcc` and it doesn't give me a warning; `clang` with -Wall does. `clang` is often better than `gcc` in this respect. I will update my answer to give a little more detail on the error..."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-05T12:46:09.527",
"Id": "27033",
"ParentId": "27003",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "27033",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-04T20:51:33.837",
"Id": "27003",
"Score": "3",
"Tags": [
"c"
],
"Title": "Learning C, basic string reversal function"
}
|
27003
|
<p>I wanted an excuse to do some OO JavaScript and I decided to do a JSON editor. It will basically allow you to input JSON and either collapse objects to see other objects better, delete objects (can currently only delete KV pairs), or edit objects. If you give it valid JSON it will output valid JSON. </p>
<p>The editor can be seen here. </p>
<p><a href="http://spencergaddyisamazing.com/jsonDemin.html" rel="nofollow">This</a> is for testing purposes; just hit load then stock JSON. The JavaScript is <a href="http://spencergaddyisamazing.com/scripts/demin.js" rel="nofollow">here</a>. </p>
<p>One thing I am weary about is the fields in my base object. they are basically global. So I can always do something like</p>
<pre><code>toPretty.json; //
</code></pre>
<p>I am thinking I should create some methods in my base object to return a new JSON instead of reading the file directly from the object. </p>
<p>Anyways, tear through this and please reply if you have any suggestions or critiques. It is still a work in progress and just a little fun side project. </p>
<pre><code>var obj = {"widget": { "debug": "on", "window": { "title": "Sample Konfabulator Widget", "name": "main_window", "width": 500, "height": 500 }, "image": { "src": "Images/Sun.png", "name": "sun1", "hOffset": 250, "vOffset": 250, "alignment": "center" }, "text": { "data": "Click Here", "size": 36, "style": "bold", "name": "text1", "hOffset": 250, "vOffset": 100, "alignment": "center", "onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;" } }};
function CodeArray(obj) {
this.items = [];
this.json = obj;
}
CodeArray.prototype = {
createHtml: function (json) {
var tierNum = 0, id = 0, self = this, str = "";
this.items.length = 0;
// id corresponds the markup element id
function addElement(html, id) {
var element = {}
element.html = html;
element.id = id;
self.items.push(element);
}
// TODO: use J templates to add the html into addElement???
// TODO: fix bug related to variable font width, and bug where if you send it a number it set input size the size is undefined
function traverse(o) {
id++;
tierNum != 0 ? addElement("<li><div class='del'>x</div><ul class=t" + tierNum + " id=" + id + ">", id) : addElement("<ul class=t" + tierNum + " id=" + id + "><div class='del'>x</div>", id);
for (var key in o) {
if (typeof o[key] === "object") {
if (isNaN(key)) { addElement("<li class='item'><input type='text' class='key' value=" + key + " size=" + key.toString().length + ">: </li>", id); }
tierNum++;
traverse(o[key]);
tierNum--;
} else {
addElement("<li class='item'><input type='text' class='key' value='" + key + "' size=" + key.toString().length + "> : <input type='text' class='val' value='" + o[key] + "' size=" + o[key].length + "><div class='del'>x</div><div class='save'> &#10003; </div></li>", id);
}
}
tierNum != 0 ? addElement("</ul></li>", id) : addElement("</ul>", id);
}
traverse(json);
updateResultsContainer(this.items);
$("#textJson textarea").text(JSON.stringify(toPretty.json));
},
print: function () {
for (var i = 0; i < this.items.length; i++) {
console.log(this.items[i].id + " " + this.items[i].html);
}
},
// TODO: delete Lists using list key.
deleteItems: function (toDelete) {
var keys = toDelete.find(".key");
var vals = toDelete.find(".val");
function remove(delKey, delVal, o) {
for (var key in o) {
if (typeof o[key] === "object") {
if (remove(delKey, delVal, o[key])) { return true; }
} else {
if (delKey == key && delVal == o[key]) {
delete o[key];
return true;
}
}
}
}
for (var i = 0; i < keys.length; i++) {
remove(keys[i].value, vals[i].value, this.json);
}
this.createHtml(this.json);
},
convertToJson: function () {
console.log(JSON.stringify(this.json));
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-05T00:04:17.703",
"Id": "41863",
"Score": "0",
"body": "See \"Make sure you include your code in your question\" http://codereview.stackexchange.com/helpcenter/on-topic"
}
] |
[
{
"body": "<p>Not bad. Regarding your concerns that toPretty.json is visible from outside object-scope, people typically get around this by using the <a href=\"http://addyosmani.com/resources/essentialjsdesignpatterns/book/#modulepatternjavascript\" rel=\"nofollow\">Module Pattern</a>.</p>\n\n<blockquote>\n <p>I am thinking I should create some methods in my base object to return\n a new json instead of reading the file directly from the object.</p>\n</blockquote>\n\n<p>I'm not following. Which file/object? You appear to pass the JSON object from <code>$.ajax</code> to your constructor, and this is just a plain JavaScript object.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-05T00:53:58.457",
"Id": "41867",
"Score": "0",
"body": "Thanks for the reply. When I say 'base Object' I was refering to my CodeArray 'class'. So I would do something like this instead.\n\n`function CodeArray(obj) {\n this.items = [];\n this.json = function() {\n return new json;\n }\n}`"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-05T00:36:05.067",
"Id": "27016",
"ParentId": "27005",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-04T21:43:48.727",
"Id": "27005",
"Score": "5",
"Tags": [
"javascript",
"jquery",
"object-oriented",
"html"
],
"Title": "Should I encapsulate my fields differently?"
}
|
27005
|
<p>I've been thinking about implementing events and wrote some abstract code:</p>
<pre><code>#include <memory>
#include <vector>
#include <iostream>
template<typename Event>
class Dispatcher
{
public:
class Listener
{
public:
virtual void OnEvent(Event& event, Dispatcher& sender) {};
};
private:
typedef std::shared_ptr<Listener> ListenerPtr;
typedef std::vector<ListenerPtr> Listeners;
Listeners _listeners;
public:
void Reg(ListenerPtr listener)
{
if( _listeners.end() != std::find(_listeners.begin(), _listeners.end(), listener) )
return;
_listeners.push_back(listener);
}
void Unreg(ListenerPtr listener)
{
Listeners::iterator iter = std::find(_listeners.begin(), _listeners.end(), listener);
if( _listeners.end() == iter )
return;
_listeners.erase(iter);
}
void Dispatch(Event& event)
{
for( Listeners::iterator iter = _listeners.begin(); iter != _listeners.end(); ++iter )
(*iter)->OnEvent(event, *this);
}
};
struct SomeEvent
{
int someParam;
SomeEvent(int someParam) : someParam(someParam) {}
};
class SomeDispatcher : public Dispatcher<SomeEvent>
{
};
struct OtherEvent
{
int otherParam;
OtherEvent(int otherParam) : otherParam(otherParam) {}
};
class OtherDispatcher :
public SomeDispatcher, public Dispatcher<OtherEvent>
{
};
class Consumer :
public Dispatcher<SomeEvent>::Listener,
public Dispatcher<OtherEvent>::Listener
{
virtual void OnEvent(SomeEvent& event, Dispatcher<SomeEvent>& sender)
{
std::cout << "OnEvent SomeEvent " << event.someParam << std::endl;
}
virtual void OnEvent(OtherEvent& event, Dispatcher<OtherEvent>& sender)
{
std::cout << "OnEvent OtherEvent " << event.otherParam << std::endl;
}
};
int main(int argc, char **argv)
{
OtherDispatcher dispatcher;
std::shared_ptr<Consumer> consumer(new Consumer());
dispatcher.Dispatcher<SomeEvent>::Reg( consumer );
dispatcher.Dispatcher<OtherEvent>::Reg( consumer );
dispatcher.Dispatcher<SomeEvent>::Dispatch(SomeEvent(1));
dispatcher.Dispatcher<OtherEvent>::Dispatch(OtherEvent(2));
dispatcher.Dispatcher<SomeEvent>::Unreg( consumer );
dispatcher.Dispatcher<SomeEvent>::Dispatch(SomeEvent(3));
dispatcher.Dispatcher<OtherEvent>::Dispatch(OtherEvent(4));
return 0;
}
</code></pre>
<p>It compiles and works as expected, but... I have to write more code to inherit from <code>Dispatcher</code> and <code>Listener</code>, to register listener and to define more exactly which dispatcher I'm registering to. And this method does not allow registering of custom class method, but only <code>OnEvent()</code>.</p>
<p>Apart from this, are there any issues with this code? Is it compatible with different compilers and platforms? Any suggestions?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-04T21:54:01.277",
"Id": "41855",
"Score": "0",
"body": "Could you make Listener::OnEvent(...) into a pure virtual destructor, turning Listener into an interface? That would clear up most of your inheritance issues."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-04T21:55:50.417",
"Id": "41856",
"Score": "0",
"body": "@ShotgunNinja What do you mean by \"inheritance issues\"?"
}
] |
[
{
"body": "<p>Listner needs a virtual destructor<br>\nand the <code>OnEvent()</code> method should probably be pure virtual:</p>\n\n<pre><code>class Listener\n{\npublic:\n virtual void OnEvent(Event& event, Dispatcher& sender) {};\n};\n\n// Try\n\nclass Listener\n{\n public:\n virtual ~Listener() {}\n virtual void OnEvent(Event& event, Dispatcher& sender) = 0;\n};\n</code></pre>\n\n<p>You need the virtual destructor because delete will more than likely be called via a pointer to the base class (Listener) at some point.</p>\n\n<p>No point in implementing <code>OnEvent()</code> to do nothing if you need sombody to over-ride it.</p>\n\n<p>Personally I would prefer to use <code>boost::ptr_vector<></code> rather than a <code>std::vector<std::shared_ptr<>></code>. The boost vector has a couple of advantages (less lcoks required). Also its members are provided via references rather than pointers so it makes it more natural to use with the standard algorithms (not such a big deal in C++11 (with lambdas) but it makes C++03 much easier to use).</p>\n\n<pre><code>typedef std::shared_ptr<Listener> ListenerPtr;\ntypedef std::vector<ListenerPtr> Listeners;\nListeners _listeners;\n\n// Replace with:\n\nboost::ptr_vector<Listener> listeners;\n</code></pre>\n\n<p>Be careful of using '_` on the front of identifiers. The rules are not obvious so best avoided to make sure you don't actually break them. <a href=\"https://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier/228797#228797\">Underscore Rules</a></p>\n\n<p>Personally not a fan of the following:</p>\n\n<pre><code> if( _listeners.end() != std::find(_listeners.begin(), _listeners.end(), listener) )\n</code></pre>\n\n<p>Nothing wrong with it. But reversing the order of the test just makes you pause a second. See <a href=\"https://softwareengineering.stackexchange.com/q/162256/12917\">Yoda Conditionals</a>.</p>\n\n<p>Prefer to use standard algorithms rather than hand coded loops.</p>\n\n<pre><code> for( Listeners::iterator iter = _listeners.begin(); iter != _listeners.end(); ++iter )\n (*iter)->OnEvent(event, *this);\n\n // Try\n std::for_each(listeners.begin(), listeners.end(),\n std::bind2nd(Listner::OnEvent, event)\n ); // Assume boost::ptr_vector<>\n\n // Or go all C++11 on us\n std::for_each(std::begin(listeners), std::end(listeners),\n [&event](std::shared_ptr<Listener>& lis) {lis->OnEvent(event);}\n );\n</code></pre>\n\n<p>If you want to have listeners that only deal with a specific type of event. You can write your Listner to be a filtering lsitener.</p>\n\n<pre><code>class Listener\n{\npublic:\n virtual void OnEvent(Event& event, Dispatcher& sender) {};\n};\n</code></pre>\n\n<p>Change to:</p>\n\n<pre><code>template<class ForEvent>\nclass Listener\n{\n public:\n ~Listener() {}\n\n // This is the method called by the dispatcher.\n void eventFilter(OnEvent& event, Dispatcher& sender)\n {\n // dynamic_cast to a pointer type.\n // Result is NULL if not the correct type.\n // If you used a value type then it would throw an exception.\n ForEvent* specialEvent = dynamic_cast<ForEvent*>(&event);\n if (specialEvent != NULL)\n {\n // Only call the OnEvent for the types we want.\n // put back to a references (so OnEvent does not need to\n // check for NULL).\n this->OnEvent(*specialEvent, sender);\n }\n }\n\n virtual void OnEvent(ForEvent& event, Dispatcher& sender) = 0;\n};\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-05T00:39:15.757",
"Id": "27017",
"ParentId": "27007",
"Score": "6"
}
},
{
"body": "<p>So, I think the following scenario will break the otherwise elegant Dispatcher class:</p>\n\n<p>The consumer removes itself from the Dispatcher within the OnEvent() notification.</p>\n\n<p>Suppose the example were a single shot timer expiration and the consumer wants to remove itself from notifications once the timer it is interested in expires.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-03-18T23:42:20.297",
"Id": "189897",
"ParentId": "27007",
"Score": "-1"
}
},
{
"body": "<p><code>std::find</code> is in header <code><algorithm></code>, which is missing.</p>\n\n<p>For me it did not compile without it.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-04-21T07:48:31.683",
"Id": "192612",
"ParentId": "27007",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-04T21:52:08.327",
"Id": "27007",
"Score": "4",
"Tags": [
"c++",
"c++11",
"inheritance",
"event-handling",
"polymorphism"
],
"Title": "Very simple events implementation"
}
|
27007
|
<p>How can I improve the access time to this unordered map? If I instead allocate a 8 x 10 x 30 x 30 x 24000:</p>
<pre><code>std::vector<std::vector<std::vector<std::vector<std::vector<float> > > > >
</code></pre>
<p>each access is about 0.0001 ms. Using an <code>unordered_map</code> implementation, each access is about 0.001 ms, 10x slower. What can I do to reduce the access time for this <code>unordered_map</code>? I'm doing a lot of insertions and modifications of existing entries.</p>
<pre><code>#include <cstdio>
#include <random>
#include <unordered_map>
#include "boost/functional/hash.hpp"
#include "boost/date_time/posix_time/posix_time.hpp"
struct Key {
Key(int a, int b, int x, int y, int z) :
a_(a), b_(b), x_(x), y_(y), z_(z) {
}
bool operator==(const Key& other) const {
return (a_ == other.a_ &&
b_ == other.b_ &&
x_ == other.x_ &&
y_ == other.y_ &&
z_ == other.z_);
}
int a_, b_, x_, y_, z_;
};
namespace std {
template <>
struct hash<Key> {
typedef Key argument_type;
typedef std::size_t result_type;
result_type operator()(const Key& key) const {
std::size_t val = 0;
boost::hash_combine(val, key.a_);
boost::hash_combine(val, key.b_);
boost::hash_combine(val, key.x_);
boost::hash_combine(val, key.y_);
boost::hash_combine(val, key.z_);
return val;
}
};
} // namespace std.
int main(int argc, char** argv) {
std::default_random_engine generator;
std::uniform_int_distribution<int> random_z(1,24000);
std::uniform_real_distribution<float> random_vote(0.0, 1.0);
std::unordered_map<Key, float> votes;
int total_accesses = 0;
boost::posix_time::ptime start =
boost::posix_time::microsec_clock::local_time();
for (int i = 0; i < 200000; ++i) {
int z = random_z(generator); // z in [1,24000]
for (int a = 0; a < 8; ++a) {
for (int b = 0; b < 10; ++b) {
for (int x = 0; x < 30; ++x) {
for (int y = 0; y < 30; ++y) {
float this_vote = random_vote(generator);
Key key(a, b, x, y, z);
if (this_vote > 0.8) {
votes[key] += this_vote; // This is what is slow.
++total_accesses;
}
}
}
}
}
if ((i + 1) % 1000 == 0) {
boost::posix_time::ptime now =
boost::posix_time::microsec_clock::local_time();
boost::posix_time::time_duration diff = now - start;
printf("%d / %d : Milliseconds per access: %f\n",
i + 1, 200000,
static_cast<float>(diff.total_milliseconds()) / total_accesses);
}
}
}
</code></pre>
<p>I find it's amortized access time to be slow, and it takes a growing amount of memory (3.1GB after 4000 iterations of the main loop, 6.3GB after 8000 iterations, and 8.6GB after 12000 iterations):</p>
<pre class="lang-none prettyprint-override"><code>1000 / 200000 : Milliseconds per access: 0.000548
2000 / 200000 : Milliseconds per access: 0.000653
3000 / 200000 : Milliseconds per access: 0.000682
4000 / 200000 : Milliseconds per access: 0.000834
5000 / 200000 : Milliseconds per access: 0.000874
6000 / 200000 : Milliseconds per access: 0.000926
7000 / 200000 : Milliseconds per access: 0.001107
8000 / 200000 : Milliseconds per access: 0.001143
9000 / 200000 : Milliseconds per access: 0.001187
10000 / 200000 : Milliseconds per access: 0.001234
11000 / 200000 : Milliseconds per access: 0.001285
12000 / 200000 : Milliseconds per access: 0.001338
</code></pre>
<p>Here is the version using the vector of vectors instead:</p>
<pre class="lang-c prettyprint-override"><code>#include <cstdio>
#include <random>
#include <vector>
#include "boost/functional/hash.hpp"
#include "boost/date_time/posix_time/posix_time.hpp"
struct Key {
Key(int a, int b, int x, int y, int z) :
a_(a), b_(b), x_(x), y_(y), z_(z) {
}
bool operator==(const Key& other) const {
return (a_ == other.a_ &&
b_ == other.b_ &&
x_ == other.x_ &&
y_ == other.y_ &&
z_ == other.z_);
}
int a_, b_, x_, y_, z_;
};
namespace std {
template <>
struct hash<Key> {
typedef Key argument_type;
typedef std::size_t result_type;
result_type operator()(const Key& key) const {
std::size_t val = 0;
boost::hash_combine(val, key.a_);
boost::hash_combine(val, key.b_);
boost::hash_combine(val, key.x_);
boost::hash_combine(val, key.y_);
boost::hash_combine(val, key.z_);
return val;
}
};
} // namespace std.
int main(int argc, char** argv) {
std::default_random_engine generator;
std::uniform_int_distribution<int> random_z(1,24000);
std::uniform_real_distribution<float> random_vote(0.0, 1.0);
// This makes an 8 x 10 x 30 x 30 x 24000 vector of vectors... of vectors.
std::vector<std::vector<std::vector<std::vector<std::vector<float> > > > > votes;
for (size_t a = 0; a < 8; ++a) {
std::vector<std::vector<std::vector<std::vector<float> > > > a_grid;
for (size_t b = 0; b < 10; ++b) {
std::vector<std::vector<std::vector<float> > > b_grid;
for (size_t y = 0; y < 30; ++y) {
std::vector<std::vector<float> > y_grid;
for (size_t x = 0; x < 30; ++x) {
y_grid.push_back(std::vector<float>(24000, 0));
}
b_grid.push_back(y_grid);
}
a_grid.push_back(b_grid);
}
votes.push_back(a_grid);
}
int total_accesses = 0;
boost::posix_time::ptime start =
boost::posix_time::microsec_clock::local_time();
for (int i = 0; i < 200000; ++i) {
int z = random_z(generator); // z in [1,24000]
for (int a = 0; a < 8; ++a) {
for (int b = 0; b < 10; ++b) {
for (int x = 0; x < 30; ++x) {
for (int y = 0; y < 30; ++y) {
float this_vote = random_vote(generator);
if (this_vote > 0.8) {
votes[a][b][y][x][z] += this_vote;
++total_accesses;
}
}
}
}
}
if ((i + 1) % 1000 == 0) {
boost::posix_time::ptime now =
boost::posix_time::microsec_clock::local_time();
boost::posix_time::time_duration diff = now - start;
printf("%d / %d : Milliseconds per access: %f\n",
i + 1, 200000,
static_cast<float>(diff.total_milliseconds()) / total_accesses);
}
}
}
</code></pre>
<p>It takes 7.2GB of memory and reports constant, low (relative to <code>unordered_map</code>) access time:</p>
<pre class="lang-none prettyprint-override"><code>1000 / 200000 : Milliseconds per access: 0.000179
2000 / 200000 : Milliseconds per access: 0.000179
3000 / 200000 : Milliseconds per access: 0.000179
4000 / 200000 : Milliseconds per access: 0.000179
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-08-01T14:41:45.663",
"Id": "255921",
"Score": "0",
"body": "If your access pattern is the same as in provided example it's better to use single vector or even static array to store all data, and calculate index like this: `[z*8*10*30*30 + a*10*30*30 + b*30*30 + x*30 + y]`. It looks ugly, but it's fastest and straightest way in C++."
}
] |
[
{
"body": "<p>Firstly, it's somewhat hard to say, because you haven't given the code you are using with <code>vector</code>. Are you keeping it sorted and doing some kind of binary search to find the element, or is this just raw vector access times where you don't care about adding <code>this_vote</code> to a specific key? If so, of course raw <code>vector</code> access with something like <code>push_back</code> will be much faster, due to locality of reference, not requiring the computation of a hash function for each <code>Key</code>, and so on.</p>\n\n<hr>\n\n<p>Secondly, this is where we grab our trusty profiler to see what exactly is taking up so much time. Compiling with <code>-O3</code> and running gives this:</p>\n\n<blockquote>\n<pre><code>% cumulative self self total \ntime seconds seconds calls ms/call ms/call name \n79.19 26.15 26.15 165 158.48 158.48 std::_Hashtable<Key, std::pair<Key const, float>, std::allocator<std::pair<Key const, float> >, std::_Select1st<std::pair<Key const, float> >, std::equal_to<Key>, std::hash<Key>, std::__detail::_Mod_range_hashing, std::__detail::_Default_ranged_hash, std::__detail::_Prime_rehash_policy, true, false, true>::_M_rehash(unsigned int, std::pair<unsigned int, unsigned int> const&)\n</code></pre>\n</blockquote>\n\n<p>Which, if you squint hard enough at, becomes clear that <code>_M_rehash</code> is the culprit, taking almost 80% of the time. Unfortunately, I'm running this on GCC 4.7, which has a known bug that slows down <code>unordered_map</code> quite a lot: it's on the <a href=\"http://www.mail-archive.com/gcc-bugs@gcc.gnu.org/msg368041.html\" rel=\"nofollow noreferrer\">mailing list</a> if you're interested. Further, <code>reserve</code> doesn't fix this problem. If you're using GCC 4.7, <code>unordered_map</code> will be slow.</p>\n\n<p>The actual <code>insert</code> call is called 14311307 times, and accounts for only 0.64% of the time at 0.21s:</p>\n\n<blockquote>\n<pre><code>0.64 32.88 0.21 14311307 0.00 0.00 std::__detail::_Node_iterator<std::pair<Key const, float>, false, true> std::_Hashtable<Key, std::pair<Key const, float>, std::allocator<std::pair<Key const, float> >, std::_Select1st<std::pair<Key const, float> >, std::equal_to<Key>, std::hash<Key>, std::__detail::_Mod_range_hashing, std::__detail::_Default_ranged_hash, std::__detail::_Prime_rehash_policy, true, false, true>::_M_insert_bucket<std::pair<Key, float> >(std::pair<Key, float>&&, unsigned int, unsigned int)\n</code></pre>\n</blockquote>\n\n<p>Let's switch over to a regular <code>std::map</code>:</p>\n\n<blockquote>\n<pre><code>4.26 10.10 0.46 14311307 0.00 0.00 std::_Rb_tree_iterator<std::pair<Key const, float> > std::_Rb_tree<Key, std::pair<Key const, float>, std::_Select1st<std::pair<Key const, float> >, std::less<Key>, std::allocator<std::pair<Key const, float> > >::_M_insert_unique_<std::pair<Key const, float> >(std::_Rb_tree_const_iterator<std::pair<Key const, float> >, std::pair<Key const, float>&&)\n</code></pre>\n</blockquote>\n\n<p>Now we have the same 14311307 calls to insert, which take up 4.26% of the time at 0.46s. However, there is not the huge overhead of having to rehash the map, hence this is actually quite a bit quicker.</p>\n\n<p>The <code>std::map</code> code is exactly the same, except with a specialization of <code>std::less</code>:</p>\n\n<pre><code>#include <map>\n#include <tuple>\n#include <functional>\n\nnamespace std\n{\ntemplate <>\nstruct less<Key>\n{\n bool operator()(const Key& k1, const Key& k2) const\n {\n return std::tie(k1.a_, k1.b_, k1.x_, k1.y_, k1.z_) <\n std::tie(k2.a_, k2.b_, k2.x_, k2.y_, k2.z_);\n }\n};\n}\n</code></pre>\n\n<p>and with <code>votes</code> being declared as:</p>\n\n<pre><code>std::map<Key, float> votes;\n</code></pre>\n\n<hr>\n\n<p>Since you're already using <code>boost</code>, why not try <code>boost::unordered_map</code> instead?</p>\n\n<pre><code>#include \"boost/unordered_map.hpp\"\n\nstd::size_t hash_value(const Key& key) \n{\n typedef Key argument_type;\n typedef std::size_t result_type;\n std::size_t val = 0;\n boost::hash_combine(val, key.a_);\n boost::hash_combine(val, key.b_);\n boost::hash_combine(val, key.x_);\n boost::hash_combine(val, key.y_);\n boost::hash_combine(val, key.z_);\n return val;\n}\n\nboost::unordered_map<Key, float, boost::hash<Key>> votes;\n</code></pre>\n\n<p>You can also save a bit of time by not constructing the <code>Key</code> if it isn't needed, and passing an <code>rvalue</code> instead of an <code>lvalue</code> reference:</p>\n\n<pre><code>float this_vote = random_vote(generator);\nif (this_vote > 0.8) {\n votes[Key(a, b, x, y, z)] += this_vote; \n ++total_accesses;\n}\n</code></pre>\n\n<p>If you have an up to date version of <code>boost</code>, you might also try using <code>emplace</code>:</p>\n\n<pre><code>if (this_vote > 0.8) {\n auto val = votes.emplace(a, b, x, y, z);\n if(!val.second)\n *(val.first) += this_vote;\n</code></pre>\n\n<p>This may or may not be slower. I can't test it, but my gut feeling is it will be slower because <code>Key</code> is a thin object. If it contained more than a few integers, this would possibly be faster.</p>\n\n<hr>\n\n<p>Basically, the final advice is to profile. Further, you're unlikely to get access times equivalent to a <code>vector</code> for anything else, as <code>vector</code> is guaranteed to be contiguous, hence will have good locality of reference and likely won't require as many dereferences as any other container.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T00:43:44.400",
"Id": "41954",
"Score": "0",
"body": "@Sancho I modified it to perform less loops. I'm running on a machine with significantly less memory."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2013-06-05T02:54:21.067",
"Id": "27020",
"ParentId": "27013",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2013-06-04T23:47:00.310",
"Id": "27013",
"Score": "7",
"Tags": [
"c++",
"performance",
"c++11"
],
"Title": "Accessing an unordered_map"
}
|
27013
|
<p>I have two classes <code>DigBackground</code> and <code>DigParallaxBackgroundLayer</code> (a parallax background is a image consisting of several images that move at different scroll speeds, for games etc.). My idea was to have the <code>DigBackground</code> class which is basically just a image with some added properties that can be set were it will draw itself on the screen. It just has one method currently and that is the <code>initWithImageNamed</code> that sets all of it properties. Some of its properties are public, but read-only. So they can be accessed by the <code>DigParallaxBackground</code> class.</p>
<p>The <code>DigParallaxBackground</code> class currently also have one method at present - the initializer which takes an array of <code>DigBackground</code>´s as argument. And will display them on screen.</p>
<p>I want to know if this is decent design and how I can improve it if need be.</p>
<p>This is how it's used:</p>
<pre><code> DigBackground *bg1 = [[DigBackground alloc]initWithImageNamed:@"Default.png"
withScrollSpeed:1.0f
InitialOffsetOf:ccp(0, 0)
position:ccp(100, 100)
setFlipX:NO];
DigParallaxBackgroundLayer *parallaxBg = [[DigParallaxBackgroundLayer alloc]
initParallaxBackgroundWithImages:@[bg1] inOrder:kAscending];
[self addChild: parallaxBg];
</code></pre>
<p>Header for <code>DigBackground</code>:</p>
<pre><code>@property (nonatomic, readonly) float bgScrollSpeed;
@property (nonatomic, readonly) CGPoint initialOffset;
// Designated initializer
- (id) initWithImageNamed: (NSString *)image
withScrollSpeed: (float)scrollspeed
InitialOffsetOf: (CGPoint)offset
position: (CGPoint)position
setFlipX: (BOOL)flipX;
</code></pre>
<p>Header for <code>DigParallaxBackground</code>:</p>
<pre><code>typedef enum {
kAscending,
kDescending
} ImagesOrder;
@interface DigParallaxBackgroundLayer : CCLayer
{
NSArray *backgrounds;
}
// Designated initializer
- (id) initParallaxBackgroundWithImages: (NSArray *) images inOrder: (ImagesOrder) order;
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-05T12:54:53.897",
"Id": "41902",
"Score": "1",
"body": "Looks pretty straightforward. `InitialOffsetOf:` is not idiomatic, I would have expected lowercase, and why not just `initialOffset:`? Also, are there technical reasons why the properties should be immutable once set? I would think that especially in games, being able to vary the scroll speed is an advantage if implementing that is straightforward."
}
] |
[
{
"body": "<p>Just a couple nit-picky things...</p>\n\n<p><code>InitialOffsetOf:</code> should instead be <code>initialOffset:</code></p>\n\n<p><code>withScrollSpeed:</code> should just be <code>scrollSpeed:</code></p>\n\n<p>I'd probably also add factory methods. When I'm writing code, no class is complete until it has its factory methods.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T05:02:36.773",
"Id": "42104",
"ParentId": "27018",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-25T20:08:40.927",
"Id": "27018",
"Score": "3",
"Tags": [
"object-oriented",
"objective-c",
"ios",
"graphics"
],
"Title": "Classes for background layer and parallax effect"
}
|
27018
|
<p>I need to do a long running task. I've done this by executing a Task while there's a loading box on the UI. When an exception is thrown, I want to stop the task and show a msgbox to the user. If everything goes right, I stop the loading box.</p>
<p>The code below works as expected, but I was wondering if I'm doing it correct here since this is the first time I'm doing something like this.</p>
<p><strong><em>MyClassLibrary</em></strong></p>
<p><strong>Baseclass:</strong></p>
<pre><code> private readonly CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
public MyEnum Stage {get; protected set;}
public event EventHandler<EventArgs> ProgrammingStarted;
public event EventHandler<ProgrammingExecutedEventArgs> ProgrammingExecuted;
protected void ProgramImage()
{
this.OnProgrammingStarted(new EventArgs());
var task =
Task.Factory.StartNew(this.ProgramImageAsync)
.ContinueWith(
this.TaskExceptionHandler,
cancellationTokenSource.Token,
TaskContinuationOptions.OnlyOnFaulted,
TaskScheduler.FromCurrentSynchronizationContext()) //Catch exceptions here
.ContinueWith(
o => this.ProgramImageAsyncDone(),
cancellationTokenSource.Token,
TaskContinuationOptions.NotOnFaulted,
TaskScheduler.FromCurrentSynchronizationContext()); //Run this when no exception occurred
}
private void ProgramImageAsync()
{
Thread.Sleep(5000); // Actual programming is done here
throw new Exception("test");
}
private void TaskExceptionHandler(Task task)
{
var exception = task.Exception;
if (exception != null && exception.InnerExceptions.Count > 0)
{
this.OnProgrammingExecuted(
new ProgrammingExecutedEventArgs { Success = false, Error = exception.InnerExceptions[0] });
this.Explanation = "An error occurrred during the programming.";
}
// Stop execution of further taks
this.cancellationTokenSource.Cancel();
}
private void ProgramImageAsyncDone()
{
this.OnProgrammingExecuted(new ProgrammingExecutedEventArgs { Success = true });
this.Explanation = ResourceGeneral.PressNextBtn_Explanation;
this.IsStepComplete = true;
}
</code></pre>
<p><strong>Derived class:</strong></p>
<pre><code>public override AdvanceStage()
{
switch (this.Stage)
{
case MyEnum.Stage1:
this.DoSomething();
this.Stage = MyEnum.Stage2;
break;
case MyEnum.Stage2:
this.ProgramImage();
this.Stage = MyEnum.Stage6;
break;
case MyEnum.Stage3:
this.DoSomethingElse();
this.Stage = MyEnum.Stage4;
break;
case MyEnum.Stage4:
this.ProgramImage();
this.Stage = MyEnum.Stage7;
break;
//And so one...
//The setting of the next stage depends of other factors too, but this is not important now.
}
}
</code></pre>
<p><strong><em>UI</em></strong> </p>
<p><strong>MyUserControl</strong></p>
<pre><code>private MyClassLibrary.MyDerivedClass myDerivedObject;
public MyUserControl() //ctor
{
...
this.myDerivedObject = new MyClassLibrary.MyDerivedClass();
this.myDerivedObject.ProgrammingStarted += this.OnProgrammingStarted;
this.myDerivedObject.ProgrammingExecuted += this.OnProgrammingExecuted;
}
private void BtnNextStageClick(object sender, RoutedEventArgs e)
{
try
{
//Do some stuff
this.myDerivedObject.AdvanceStage();
}
catch (Exception ex)
{
MessageBox.Show("Error blabla...");
}
}
private void OnProgrammingStarted(object sender, EventArgs e)
{
this.ShowLoadingBox();
}
private void OnProgrammingExecuted(object sender, EventArgs e)
{
this.RemoveLoadingBox();
if (!e.Success)
{
MessageBox.Show("Error blabla " + e.Error.Message);
}
}
</code></pre>
<p>As you can see, the UI doesn't know what's going to be executed in <code>AdvanceStage()</code>.
Only the <code>ProgramImage()</code> is a long running task. All others should be executed sequentially.
Therefore I've implemented the events so the object can inform the UI that the programming is started or finished. </p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-05T05:56:44.503",
"Id": "41882",
"Score": "0",
"body": "I had asked [this question on SO](http://stackoverflow.com/questions/16914891/tasks-exceptions-and-cancelation), but maybe that wasn't the right place."
}
] |
[
{
"body": "<p>Since you're using Task-based async processing it's better to declare long-running method as returning <code>Task</code> or <code>Task<T></code> object:</p>\n\n<pre><code>public async Task ProgramImageAsync()\n{\n await Task.Delay(TimeSpan.FromSeconds(5)); // Actual programming is done here\n throw new DivideByZeroException(\"test\");\n}\n</code></pre>\n\n<p>Then all you need on UI side is to have an asynchronous method like this:</p>\n\n<pre><code>private async void RunLongUIPreparation()\n{\n //TODO: Show loading box here \n\n var processor = new YourClassContainingProgramImageAsync();\n try\n {\n await processor.ProgramImageAsync();\n //TODO: Hide loading box here\n }\n catch (DivideByZeroException exception)\n {\n //TODO: Show messagebox with warning here\n }\n}\n</code></pre>\n\n<p><strong>UPDATE</strong> (based on updated question):\nYour solution doesn't have proper separation of concerns. The class containing <code>ProgramImage</code> method (<code>MyDerivedClass</code>) knows about UI as it handles strings shown on UI (e.g. <code>Explanation</code> property), events (even though they are named as a business flow events) are designed specifically for UI interaction.</p>\n\n<p>In order to properly separate concerns you should move all the logic related to UI to your user control, and leave only business logic in the <code>MyDerivedClass</code>. </p>\n\n<p>In order to do that you need to decide what is the actual trigger for showing a loading box. I'll stick to assumption that the actual reason to show a loading box is not a \"programming\" stage, but a long-running process, i.e. if you would add a new stage that may also take a long time to complete you may also want to show the loading box there. </p>\n\n<p>The next question to answer is how do you want to detect a long-running stage? I can suggest 2 options:</p>\n\n<ul>\n<li>show a loading box if stage hasn't completed within a certain timeout (set a timeout inside UI control);</li>\n<li>add a progress notification support to <code>MyDerivedClass</code> so that it can notify clients about its progress (using an <a href=\"http://msdn.microsoft.com/en-us/library/hh193692.aspx\" rel=\"nofollow\"><code>IProgress</code></a> interface specifically designed for asynchronous progress notification).</li>\n</ul>\n\n<p>I'll use the first option in my example as it requires less changes to my previous code:</p>\n\n<p><strong>Business logic</strong>:</p>\n\n<pre><code>public async Task ProgramImageAsync()\n{\n await Task.Delay(TimeSpan.FromSeconds(5)); // Actual programming is done here\n throw new DivideByZeroException(\"test\");\n}\n</code></pre>\n\n<p><strong>UI</strong>:</p>\n\n<pre><code>private async void RunLongUIPreparation()\n{\n var processor = new YourClassContainingProgramImageAsync();\n try\n {\n Task stageTask = processor.ProgramImageAsync();\n ShowLoadingBoxIfRunningTooLong(stageTask);\n await processor.ProgramImageAsync();\n }\n catch (DivideByZeroException exception)\n {\n //TODO: Show messagebox with warning here\n }\n}\n\nprivate async void ShowLoadingBoxIfRunningTooLong(Task stageTask)\n{\n await Task.Delay(TimeSpan.FromMilliseconds(100));\n if (stageTask.IsCompleted)\n return;\n\n try\n {\n this.ShowLoadingBox();\n await stageTask;\n }\n finally\n {\n this.RemoveLoadingBox();\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T05:04:29.613",
"Id": "41961",
"Score": "0",
"body": "Thanks for the feedback. Never used async before, so I have 1 more question regarding this: when using Tasks as I did, the exception doesn't \"bubble up\" to the UI. Here it seems it does. Am I right about this?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T07:25:19.720",
"Id": "41979",
"Score": "0",
"body": "yes, `await` translates the exception from asynchronous execution/thread to the place where the task is being awaited"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T12:35:12.987",
"Id": "41997",
"Score": "0",
"body": "I've tried to do it your way, but the structure is a bit more complex then stated in my question. The method `ProgramImage`is called from inside a method in the class (that method is called by the UI), depending on the state of a property. Otherwise something else is executed which doesn't need the loading box. The UI is not aware of that property, hence it's not possible for it to know whether or not it must call it async or not. Therefore I had used the 2 events to notify the UI."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T12:42:09.427",
"Id": "42000",
"Score": "0",
"body": "Please edit your question to show the specifics, it is hard to answer the question properly until you describe your specifics"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T17:26:10.013",
"Id": "42037",
"Score": "0",
"body": "I know, but I didn't think the changes would have such impact. I'll do it as soon as I arrive at work tomorrow."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-07T05:36:29.300",
"Id": "42092",
"Score": "0",
"body": "More code + some explanation added. Already a big thanks for your help."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-07T10:59:17.753",
"Id": "42115",
"Score": "0",
"body": "Thanks Almaz. Not sure I can implement it the way you sugest (it's an existing app and I don't want to break too much), but I will definitely keep this in mind for later use."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-05T08:45:02.417",
"Id": "27027",
"ParentId": "27021",
"Score": "2"
}
},
{
"body": "<p>I find the structure of your continuation confusing. The <code>ProgramImageAsyncDone()</code> continuation will execute <em>when the previous continuation doesn't fault</em>. That doesn't sound like what you wanted. Though your code will actually work, because when the original task faults, you also cancel the remaining continuation.</p>\n\n<p>I think a clearer way to write this would be to have both continuations on the original <code>Task</code>:</p>\n\n<pre><code>var task = Task.Factory.StartNew(this.ProgramImageAsync);\nvar scheduler = TaskScheduler.FromCurrentSynchronizationContext();\ntask.ContinueWith(\n this.TaskExceptionHandler,\n CancellationToken.None,\n TaskContinuationOptions.OnlyOnFaulted,\n scheduler); //Catch exceptions here\ntask.ContinueWith(\n o => this.ProgramImageAsyncDone(),\n CancellationToken.None,\n TaskContinuationOptions.NotOnFaulted,\n scheduler); //Run this when no exception occurred\n</code></pre>\n\n<p>Or even better, using a single continuation:</p>\n\n<pre><code>Task.Factory.StartNew(this.ProgramImageAsync)\n .ContinueWith(\n t =>\n {\n if (t.IsFaulted)\n this.TaskExceptionHandler(t);\n else\n this.ProgramImageAsyncDone();\n }, TaskScheduler.FromCurrentSynchronizationContext());\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T05:05:23.397",
"Id": "41962",
"Score": "0",
"body": "Thanks for your feedback. The last one is indeed a lot clearer to read."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-05T11:51:12.420",
"Id": "27032",
"ParentId": "27021",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "27027",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-05T05:50:41.753",
"Id": "27021",
"Score": "5",
"Tags": [
"c#",
"error-handling",
"task-parallel-library"
],
"Title": "Tasks: exceptions and cancelation"
}
|
27021
|
<p>Is there a tighter (less characters) way to use perl on the command line to search and replace text from STDIN than I've got here? The code below works.</p>
<pre><code>echo hi | perl -e '$a = <STDIN>; $a =~ s/i/o/g; print $a;'
</code></pre>
|
[] |
[
{
"body": "<p>You can use <code>-p</code> option (see <code>perl --help</code>):</p>\n\n<blockquote>\n <p>assume loop like -n but print line also, like sed</p>\n</blockquote>\n\n<p>So the script becomes:</p>\n\n<pre><code>echo hi | perl -pe 's/i/o/g'\n</code></pre>\n\n<p>which is really compiled to:</p>\n\n<pre><code>$ perl -MO=Deparse -pe 's/i/o/g'\nLINE: while (defined($_ = <ARGV>)) {\n s/i/o/g;\n}\ncontinue {\n die \"-p destination: $!\\n\" unless print $_;\n}\n-e syntax OK\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-05T07:48:08.117",
"Id": "27024",
"ParentId": "27022",
"Score": "9"
}
}
] |
{
"AcceptedAnswerId": "27024",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-05T07:21:41.897",
"Id": "27022",
"Score": "4",
"Tags": [
"perl"
],
"Title": "Search and replace on command line"
}
|
27022
|
<p>A Base10 Pandigital Number is a number which uses all the digits 0-9 once:</p>
<ul>
<li>1234567890</li>
<li>2468013579</li>
<li>etc...</li>
</ul>
<p>My naive solution was just to use a bunch of nested loops to do this but it's quite slow. And I'm blanking on a more efficient way to do it? The following takes ~6 seconds.</p>
<pre><code>IEnumerable<long> GeneratePandigital()
{
var other=Enumerable.Range(0,10);
foreach(var a in other)
foreach(var b in other.Except(new int [] {a}))
foreach(var c in other.Except(new int [] {a,b}))
foreach(var d in other.Except(new int [] {a,b,c}))
foreach(var e in other.Except(new int [] {a,b,c,d}))
foreach(var f in other.Except(new int [] {a,b,c,d,e}))
foreach(var g in other.Except(new int [] {a,b,c,d,e,f}))
foreach(var h in other.Except(new int [] {a,b,c,d,e,f,g}))
foreach(var i in other.Except(new int [] {a,b,c,d,e,f,g,h}))
foreach(var j in other.Except(new int [] {a,b,c,d,e,f,g,h,i}))
{
yield return a * 1000000000L +
b * 100000000L+
c * 10000000L+
d * 1000000+
e * 100000+
f * 10000+
g * 1000+
h * 100+
i * 10+
j;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-05T16:54:29.590",
"Id": "41922",
"Score": "0",
"body": "http://users.telenet.be/vdmoortel/dirk/Maths/permutations.html"
}
] |
[
{
"body": "<p>The easiest way to do this is to note that each value that is generated will be a permutation of the values <code>0 - 9</code>. This will generate <code>10! = 3628800</code> possibilities. There are a number of algorithms to generate permutations, the easiest in this case would simply be to generate them in lexicographic order.</p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Permutation#Software_implementations\" rel=\"nofollow\">Wiki</a> has a rundown of some algorithms you can use to generate permutations.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-05T08:55:25.680",
"Id": "41893",
"Score": "0",
"body": "*sigh* how did I not spot this... and I actually curate a combinatorics library on Nuget that's perfect for this. http://nuget.org/packages/Combinatorics/ - I blame the early hour. Thanks"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-05T08:27:43.283",
"Id": "27026",
"ParentId": "27025",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "27026",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-05T08:13:30.563",
"Id": "27025",
"Score": "2",
"Tags": [
"c#",
"performance",
"mathematics"
],
"Title": "Generating Pandigital Numbers"
}
|
27025
|
<p>This reads in data from a .csv file and generates an .xml file with respect to the .csv data. Can you spot any parts where re-factoring can make this code more efficient?</p>
<pre><code>import csv
from xml.etree.ElementTree import Element, SubElement, Comment, tostring
from xml.etree.ElementTree import ElementTree
import xml.etree.ElementTree as etree
def main():
reader = read_csv()
generate_xml(reader)
def read_csv():
with open ('1250_12.csv', 'r') as data:
return list(csv.reader(data))
def generate_xml(reader):
root = Element('Solution')
root.set('version','1.0')
tree = ElementTree(root)
head = SubElement(root, 'DrillHoles')
head.set('total_holes', '238')
description = SubElement(head,'description')
current_group = None
i = 0
for row in reader:
if i > 0:
x1,y1,z1,x2,y2,z2,cost = row
if current_group is None or i != current_group.text:
current_group = SubElement(description, 'hole',{'hole_id':"%s"%i})
collar = SubElement (current_group, 'collar',{'':', '.join((x1,y1,z1))}),
toe = SubElement (current_group, 'toe',{'':', '.join((x2,y2,z2))})
cost = SubElement(current_group, 'cost',{'':cost})
i+=1
def indent(elem, level=0):
i = "\n" + level*" "
if len(elem):
if not elem.text or not elem.text.strip():
elem.text = i + " "
if not elem.tail or not elem.tail.strip():
elem.tail = i
for elem in elem:
indent(elem, level+1)
if not elem.tail or not elem.tail.strip():
elem.tail = i
else:
if level and (not elem.tail or not elem.tail.strip()):
elem.tail = i
indent(root)
tree.write(open('holes1.xml','w'))
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T13:29:56.623",
"Id": "42008",
"Score": "1",
"body": "one note : you have a `for elem in elem` that reassigns elem to the last element of elem, and then you access elem again. Not sure if that's what you want to do or not, but anyway that's confusing."
}
] |
[
{
"body": "<p>Minor stuff:</p>\n\n<ul>\n<li>Remove the last <code>import</code> - <code>etree</code> is not used anywhere.</li>\n<li>Merge the two first <code>import</code>s</li>\n</ul>\n\n<p>Possibly speed-improving stuff:</p>\n\n<ul>\n<li>Avoid converting the <code>csv.reader</code> output before <code>return</code>ing unless absolutely necessary.</li>\n<li>Skip <code>indent</code> unless the output must be readable by a human with a non-formatting editor.</li>\n<li>If you need to indent the output, <a href=\"https://stackoverflow.com/questions/749796/pretty-printing-xml-in-python\">existing solutions</a> are probably very efficient.</li>\n<li>Use <code>reader.next()</code> to skip the header line in <code>generate_xml</code>, then you don't need to keep checking the value of <code>i</code>.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-05T14:59:18.540",
"Id": "27043",
"ParentId": "27037",
"Score": "1"
}
},
{
"body": "<p>Don't use something like <code>for elem in elem</code> at some point with larger for loops you will miss that elem is different variable before and in/after the for loop:</p>\n\n<pre><code>for subelem in elem:\n indent(subelem, level+1)\n\nif not subelem.tail or not elem.tail.strip():\n subelem.tail = i\n</code></pre>\n\n<p>Since indent(subelem...) already sets the tail, you probably do not need to do that again.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-12T04:30:52.473",
"Id": "27290",
"ParentId": "27037",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-05T14:35:37.980",
"Id": "27037",
"Score": "3",
"Tags": [
"python",
"xml",
"csv"
],
"Title": "Generating .xml files based on .csv files"
}
|
27037
|
<p>I have a very simple Pong game that I've built in Java. The code is quite long so I've decided to focus this question on the collision that occurs with the ball and the bat and also the effects in the game. I'm using ACM Graphics package to learn Java so most of the methods are from that package. I want to know how I can improve this checking process and if the way I revert the speed and direction is efficient. I'm also open to any suggestions for the game.</p>
<pre><code>//Setting up variables
static final int WAIT = 50;
static final int MV_AMT = 20;
static final int BATWIDTH = 120;
static final int BATHEIGHT = 20;
static final int WINDOWX = 400;
static final int WINDOWY = 400;
static final int BALLRADIUS = 10;
private int batX = 150, batY = 400; //Starting positions
private int ballX = 160, ballY = 370;
private int ballSpeedX = 2; //the ball speed on the X axis
private int ballSpeedY = -9; //the ball speed on the Y axis
public void run(){
//... Stuff that runs before the game, ie. draw the sceen etc.
int currentTime = 0;
//Do all our stuff here
while(continueGame){
//Pause dat loop
pause(WAIT);
currentTime = currentTime + WAIT;
//Up the speed every 5 seconds
if (currentTime % 5000 == 0) {
if(ballSpeedY>0)
ballSpeedY += 2;
else
ballSpeedY -= 2;
if(ballSpeedX>0)
ballSpeedX += 2;
else
ballSpeedX -= 2;
}
//Move the ball
ballX=ballX+ballSpeedX;
ballY=ballY+ballSpeedY;
ball.setLocation(ballX, ballY);
//Check
checkCollisions();
}
//... Stuff that gets done after game over
}
public void checkCollisions(){
//This method is quite long so I won't be posting it all
//Just the part the calls the collision method
//Get the bounds
GRectangle batBounds = bat.getBounds();
GRectangle ballBounds = ball.getBounds();
//Where is the ball?
ballX = (int)ball.getX();
ballY = (int)ball.getY();
//Where is the bat?
batX = (int)bat.getX();
batY = (int)bat.getY();
//Did the bat touch the ball?
if(batBounds.intersects(ballBounds)){
batCollision();
}
}
public void batCollision(){
if( ballX+BALLRADIUS > batX+(BATWIDTH/2) ){ //Which side of the bat?
//Which direction is the ball traveling when it hits?
if(ballSpeedX >> 31 !=0){
ballSpeedX = ballSpeedX * -1;
} else {
ballSpeedX = ballSpeedX;
}
} else {
if(ballSpeedX >> 31 !=0){
ballSpeedX = ballSpeedX;
} else {
ballSpeedX = -ballSpeedX;
}
}
ballSpeedY = -ballSpeedY; //Adjust Y speed
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-05T15:25:45.913",
"Id": "41914",
"Score": "0",
"body": "Is it on purpose that none of what seems to be instance variables are `private`? Also, why aren't `WAIT` and `MV_AMT` `static`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-05T15:34:47.367",
"Id": "41915",
"Score": "0",
"body": "They are private, I just didn't want to have to have it written out every time here. I'll just edit those in anyways."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-05T16:00:34.743",
"Id": "41917",
"Score": "1",
"body": "There are potential race conditions everywhere throughout this code. See: http://codereview.stackexchange.com/a/26948/20611"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T16:04:38.283",
"Id": "42031",
"Score": "0",
"body": "How are there race conditions? Everything I can see is done within one single-threaded loop."
}
] |
[
{
"body": "<p>In the original Pong® brand video game, there were two bats which were confined to move vertically. A collision would be detected if ball circuit was triggered at the same time as one of the bat circuits, and if the ball was not already moving in the proper direction for that bat. The ball's vertical speed would be set to an odd number in the range -15 to +15 based upon the number of scan lines of bat that were displayed before the collision was detected (basically the difference between the ball's Y position and the bat's position). What exact bounce behavior are you looking for in your game?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-07T00:29:48.687",
"Id": "42076",
"Score": "0",
"body": "So I've made sort of a hybrid between Pong and Breakout. What I'm looking for is to determine the side of the bat that was hit and in which direction the incoming ball was moving to set the return speed accordingly."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T21:39:50.750",
"Id": "27117",
"ParentId": "27038",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-05T14:36:23.093",
"Id": "27038",
"Score": "2",
"Tags": [
"java",
"game",
"collision"
],
"Title": "Java Pong Game Collision between bat and ball"
}
|
27038
|
<p>Something that has bugged me for a while, is what way is best to perform a conditional where a string is compared to other strings. </p>
<p>Here is some sample code. This code is just for illustration purposes.</p>
<p>The 3 methods I use are</p>
<ol>
<li>Do a word for word comparison. This is probably the most optimal, but ugliest code</li>
<li>Create an array on the fly and do a comparison</li>
<li>Have a predefined array. This is probably better placed in an external file for easier maintainability.</li>
</ol>
<p>I just wanted to see what your takes are on this, and if there is an even better way to do it. I know Enums would probably work well here as well.</p>
<pre><code> private bool IsWordBad(string word)
{
//First Method
if (word == "Foo" || word == "Bar" || word == "FooBar")
{
return true;
}
//Second Method
if ((new[] { "Foo", "Bar", "FooBar" }).Contains(word))
{
return true;
}
//Third Method
var badWords = new[] { "Foo", "Bar", "FooBar" };
if (badWords.Contains(word))
{
return true;
}
return false;
}
</code></pre>
|
[] |
[
{
"body": "<p>I'd use the third version, albeit with a small modification:</p>\n\n<pre><code>return badWords.Contains(word);\n</code></pre>\n\n<p>After all, the <code>Contains()</code> method returns a boolean!</p>\n\n<p>Also, I'd put <code>badWords</code> out of the method, so that it needn't be recreated on each method call...</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-05T20:05:32.547",
"Id": "41939",
"Score": "0",
"body": "Are you able to clarify what you mean by \"put badWords out of the method\", as just because it's out of the method doesn't mean it might not be created on each method call."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-05T15:33:44.423",
"Id": "27045",
"ParentId": "27044",
"Score": "1"
}
},
{
"body": "<p>If you really have just three words, then the performance most likely won't matter. In other words, unless profiling shows that this method is performance-critical, use the method that you find most readable.</p>\n\n<p>Some other options you could consider:</p>\n\n<ol>\n<li><p>Using a <code>switch</code>:</p>\n\n<pre><code>switch (word)\n{\n case \"Foo\":\n case \"Bar\":\n case \"FooBar\":\n return true;\n default:\n return false;\n}\n</code></pre>\n\n<p>This has the advantage that it can use compiler optimizations. (Under certain circumstances, the compiler will turn such <code>switch</code> into a <code>Dictionary</code> lookup.)</p></li>\n<li><p>Use a <code>HashSet<string></code> instead of an array. Looking up in a hash set is O(1), but O(n) for an array. This could make sense if you had large number of strings to search for.</p></li>\n<li><p>Use a <a href=\"http://en.wikipedia.org/wiki/Trie\" rel=\"nofollow\">trie</a>. This has the advantage of comparing only relevant parts of the input string. This could make sense if you had long input strings or if you huge number of strings to search for.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-05T17:51:46.763",
"Id": "41927",
"Score": "0",
"body": "Not sure a `HashSet` has an O(1) lookup time; it would mean the hash used is actually a bijection..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-05T17:57:59.220",
"Id": "41929",
"Score": "0",
"body": "@fge That's not true. O(1) lookup doesn't require *no* collisions, all it requires is that collisions are rare enough and don't slow you down too much. So, yes, in the worst case where all strings are in the same bucket, you'll get O(n) lookup, but that case is *extremely* unlikely. Under normal circumstances, `HashSet` really is O(1)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T14:15:42.687",
"Id": "42015",
"Score": "0",
"body": "@fge just to confirm that `HashSet` lookup is really a O(1) operation: see remark in [HashSet<T>.Contains](http://msdn.microsoft.com/en-us/library/bb356440.aspx) documentation"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-05T16:18:08.183",
"Id": "27047",
"ParentId": "27044",
"Score": "4"
}
},
{
"body": "<p>also you can try:</p>\n\n<pre><code>if(Array.IndexOf(badWords,word)==-1)\n{\n //Your logic here \n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T05:40:00.533",
"Id": "27072",
"ParentId": "27044",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-05T15:19:21.210",
"Id": "27044",
"Score": "2",
"Tags": [
"c#",
".net"
],
"Title": "What's the most optimal way to see if a string is included in a list of strings?"
}
|
27044
|
<p>Is it? And maybe theres a better way to do this?</p>
<pre><code>$allowed = array("name_desc", "name_asc", "level_desc", "level_asc", "vocation_desc", "vocation_asc");
$order = isset($_GET['order']) ? $_GET['order'] : "name";
$order = in_array($order, $allowed) ? str_replace("_", " ", $order) : "name";
$query = "SELECT * FROM players
WHERE status = 0 AND group_id < 3 ORDER BY $order";
</code></pre>
|
[] |
[
{
"body": "<p>It is safe. You have a white list of allowed values and ensure that the user provided input is on the list.</p>\n\n<p>But I'd still do the white list checking as the very first thing, and then do the other processing later, so it would be:</p>\n\n<pre><code>$field = 'name';\n$direction = 'asc';\nif(preg_match('^([a-z]+)_(asc|desc)$', $_GET['order'], $matches)) {\n if(in_array($matches[0], array(\"name\", \"level\", \"vocation\"))) {\n $field = $matches[0];\n $direction = $matches[1];\n }\n}\n</code></pre>\n\n<p>What happens here is that the block splits up and validates the input. You can be sure that once you're past this block, <code>$field</code> and <code>$direction</code> can be trusted. An important point is to use <code>$_GET['order']</code> exactly <em>once</em>, since accessing it multiple times may lead to errors that will leak non-validated data.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-05T17:47:39.907",
"Id": "41926",
"Score": "0",
"body": "So I dont have to escape the string before using it in a query?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-05T17:56:07.510",
"Id": "41928",
"Score": "0",
"body": "No. You have just made sure it contains nothing dangerous. Escaping wouldn't change the contents of the string anyway."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-05T17:45:23.800",
"Id": "27049",
"ParentId": "27048",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "27049",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-05T17:19:13.290",
"Id": "27048",
"Score": "1",
"Tags": [
"php",
"sql",
"security"
],
"Title": "Is this a safe way of using HTTP query parameters to build a SQL query?"
}
|
27048
|
<p>I've written a function for converting strings to upper case. It currently works by replacing each character using a Regex pattern with a hash:</p>
<pre><code># Special upcase function that handles several Norwegian symbols.
def norwegian_upcase(string)
string.upcase.gsub(/[æøåäâãàáëêèéïîìíöôõòóüûùúý]/, {
'æ' => 'Æ',
'ø' => 'Ø',
'å' => 'Å',
'ä' => 'Ä',
'â' => 'Â',
'ã' => 'Ã',
'à' => 'À',
'á' => 'Á',
'ë' => 'Ë',
'ê' => 'Ê',
'è' => 'È',
'é' => 'É',
'ï' => 'Ï',
'î' => 'Î',
'ì' => 'Ì',
'í' => 'Í',
'ö' => 'Ö',
'ô' => 'Ô',
'õ' => 'Õ',
'ò' => 'Ò',
'ó' => 'Ó',
'ü' => 'Ü',
'û' => 'Û',
'ù' => 'Ù',
'ú' => 'Ú',
'ý' => 'Ý'
})
end
</code></pre>
<p>I have the feeling that it's horribly inefficient to be using Regex like this, and that I should probably be using another method. Can anyone suggest a better way to replace single characters, or is Regex fit for the task?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-05T18:25:57.860",
"Id": "41934",
"Score": "1",
"body": "I'd suggest looking over http://stackoverflow.com/questions/1020568/how-does-one-convert-a-string-to-lowercase-in-ruby which covers .downcase .upcase .capitalize and the gem unicode_utils for i8n"
}
] |
[
{
"body": "<p>After a cursory glance at the character codes for these, it looks like the lowercase is 32 (decimal) higher than uppercase. e.g. 'é'.ord - 32 == 'É'.ord</p>\n\n<p>You could try something like this:</p>\n\n<pre><code>string.upcase.gsub(/[æøåäâãàáëêèéïîìíöôõòóüûùúý]/){|s| (s.ord-32).chr(Encoding::UTF_8)}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-05T19:13:09.870",
"Id": "27054",
"ParentId": "27050",
"Score": "0"
}
},
{
"body": "<p>One-to-one substitution is precisely what <code>tr</code> is for.</p>\n\n<pre><code>def norwegian_upcase(string)\n string.upcase.tr('æ-ý','Æ-Ý')\nend\n</code></pre>\n\n<p>That being said, the <a href=\"http://unicode-utils.rubyforge.org/UnicodeUtils.html\" rel=\"nofollow\">unicode_utils</a> gem provides a method for this:</p>\n\n<pre><code>def norwegian_upcase(string)\n UnicodeUtils.upcase(string, :no)\nend\n</code></pre>\n\n<p>I don't know Norwegian, but you can supply language subtags <code>:nb</code> (Norwegian Bokmal) or <code>:nn</code> (Norwegian Nynorsk) if they would behave differently than general <code>:no</code> (Norwegian).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T13:58:03.130",
"Id": "42013",
"Score": "0",
"body": "I tried UnicodeUtils without success, it simply doesn't upcase `æøå` to `ÆØÅ` no matter what language i pass to it. I tried `:en`, `:no`, `:nb` and `:nn`. I haven't tried tr, but I'll check that out."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T12:05:05.037",
"Id": "27081",
"ParentId": "27050",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-05T17:51:39.340",
"Id": "27050",
"Score": "2",
"Tags": [
"ruby",
"regex"
],
"Title": "Should I be using Regex to uppercase uncommon characters?"
}
|
27050
|
<p>I'm reviewing my code and trying to figure out how I can do some simplifying to flatten my code. Whether it be making simpler function out of the segment of code or by removing parts of it and wanted some opinions.</p>
<pre><code>if ($regenerated_post_password !== $user_data->password)
{
/* Password from login from does not match user stored password */
if ($failed_logins == 0)
{
/* First time user has not entered username and password successfully */
$this->session->set_userdata('failed_logins', 1);
$this->users_model->increase_login_attempt($this->input->ip_address(), $post_username, gmdate('Y-m-d H:i:s', time()));
$this->output('Incorrect username and password credentials!', 'Incorrect Login Credentials', 'Error');
return;
}
/* User has atleast one failed login attempt for the current session */
if ($failed_logins !== 4)
{
/* User has a few more chances to get password right */
$failed_logins++;
$this->session->set_userdata('failed_logins', $failed_logins);
$this->users_model->increase_login_attempt($this->input->ip_address(), $post_username, gmdate('Y-m-d H:i:s', time()));
$this->output('Incorrect username and password credentials!', 'Incorrect Login Credentials', 'Error');
return;
}
$this->users_model->lock_out_user($user_data->user_id, gmdate('Y-m-d H:i:s', time()+(60*15)));
//$this->functions_model->send_email('maximum_failed_login_attempts_exceeded', $user_data->email_address, $user_data)
$this->output('Your account is currently locked, we apologize for the inconvienence. You must wait 15 minutes before you can log in again! An email was sent to the owner of this account! Forgotten your username or password? <a href="forgotusername">Forgot Username</a> or <a href="forgotpassword">Forgot Password</a>', 'Account Locked', 'Error');
return;
}
</code></pre>
<p>The entire controller:</p>
<pre><code><?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Login extends Backend_Controller
{
public function __construct()
{
parent::__construct();
}
public function index()
{
Asset::js('theme::login.js');
$this->template
->title('Login')
->set_layout('usermanagement')
->build('login');
}
public function form_is_valid()
{
/* Set validation rules for post data */
$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean|min_length[6]|max_length[12]|regex_match[/[a-z0-9]/]');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|min_length[6]|max_length[12]|regex_match[/[a-z0-9]/]');
//$this->form_validation->set_rules('remember', 'Remember Me', 'trim|xss_clean|integer');
/* Form validation passed */
return $this->form_validation->run();
}
public function is_user_locked($user_lock_date, $user_id)
{
if (strtotime($user_lock_date) > 0)
{
/* User is locked out */
if (strtotime(gmdate('Y-m-d H:i:s', time())) < strtotime($user_lock_date))
{
/* User is still locked out */
return TRUE;
}
else
{
/* User can be unlocked and form be resubmitted */
$this->users_model->unlock_user($user_id);
/* User is no longer locked out */
return FALSE;
}
}
}
public function check_user_status($user_status_id)
{
/* Match user status */
switch ($user_status_id)
{
case 1:
$this->output('Sorry you must verify your account before logging in!', 'Account Unverified', 'Error');
break;
case 3:
$this->output('Your account has been suspended!', 'Account Suspended', 'Error');
break;
case 4:
$this->output('Your account has been suspended!', 'Account Banned', 'Error');
break;
case 5:
$this->output('Your account has been deleted!', 'Account Deleted', 'Error');
break;
default:
return;
}
}
public function output($message, $title, $status)
{
switch (strtoupper($status))
{
default:
case 'ERROR':
$status = 'Error';
break;
case 'NOTICE':
$status = 'Notice';
break;
case 'SUCCESS':
$status = 'Success';
break;
}
$this->output
->set_content_type('application/json')
->set_output(json_encode(array('output_status' => $status, 'output_title' => $title, 'output_message' => $message)));
}
public function start_user_session($user_id)
{
/* Start session with user id and clear previous failed login attempts */
$this->session->set_userdata('uid', $user_id);
$this->session->unset_userdata('failed_logins');
$this->users_model->insert_session($user_id, gmdate('Y-m-d H:i:s', time()));
return;
}
public function submit()
{
if (!$this->form_is_valid())
{
$this->output('The form did not validate successfully!', 'Form Not Validated', 'Error');
return;
}
/* Post values from login form */
$post_username = $this->input->post('username');
$post_password = $this->input->post('password');
/* Test to see value of posted login form */
//echo '<pre>';
//var_dump($post_username);
//var_dump($post_password);
//echo '</pre>';
//die();
/* Get user data from post username value */
$user_data = $this->users_model->get_by('username', $post_username);
/* Test to see value of $user_data */
//echo '<pre>';
//var_dump($user_data);
//echo '</pre>';
//die();
if (count($user_data) == 0)
{
/* User was not found in database */
$this->output('The user was not found in the database!', 'User Not Found', 'Error');
return;
}
/* User was found in database */
if ($this->is_user_locked($user_data->lock_date, $user_data->user_id))
{
/* User is locked from logging in from too many failed attempts */
$this->output('This user account is currently locked!', 'Account Locked', 'Error');
return;
}
if ($user_data->user_status_id != 2)
{
/* User has a status that is not allowed to proceed */
$this->user_status_message($user_data->user_status_id);
}
/* User is registered and validated */
$regenerated_post_password = $this->genfunc->reGenPassHash($post_password, $user_data->password_hash);
$failed_logins = $this->session->userdata('failed_logins');
if ($regenerated_post_password !== $user_data->password)
{
/* Password from login from does not match user stored password */
if ($failed_logins == 0)
{
/* First time user has not entered username and password successfully */
$this->session->set_userdata('failed_logins', 1);
$this->users_model->increase_login_attempt($this->input->ip_address(), $post_username, gmdate('Y-m-d H:i:s', time()));
$this->output('Incorrect username and password credentials!', 'Incorrect Login Credentials', 'Error');
return;
}
/* User has atleast one failed login attempt for the current session */
if ($failed_logins !== 4)
{
/* User has a few more chances to get password right */
$failed_logins++;
$this->session->set_userdata('failed_logins', $failed_logins);
$this->users_model->increase_login_attempt($this->input->ip_address(), $post_username, gmdate('Y-m-d H:i:s', time()));
$this->output('Incorrect username and password credentials!', 'Incorrect Login Credentials', 'Error');
return;
}
$this->users_model->lock_out_user($user_data->user_id, gmdate('Y-m-d H:i:s', time()+(60*15)));
//$this->functions_model->send_email('maximum_failed_login_attempts_exceeded', $user_data->email_address, $user_data)
$this->output('Your account is currently locked, we apologize for the inconvienence. You must wait 15 minutes before you can log in again! An email was sent to the owner of this account! Forgotten your username or password? <a href="forgotusername">Forgot Username</a> or <a href="forgotpassword">Forgot Password</a>', 'Account Locked', 'Error');
return;
}
/* Password from login form matches user stored password and user may login */
$this->start_user_session($user_data->user_id);
$this->output('Successful login! Sending you to the dashboard!', 'Login Sucessful', 'Success');
return;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>First thing to do is to notice the code repeted in the different branches. Then your code becomes :</p>\n\n<pre><code>if ($regenerated_post_password !== $user_data->password)\n{ \n /* User has atleast one failed login attempt for the current session */\n\n if ($failed_logins < 4)\n {\n /* User has a few more chances to get password right */\n $failed_logins++;\n $this->session->set_userdata('failed_logins', $failed_logins);\n $this->users_model->increase_login_attempt($this->input->ip_address(), $post_username, gmdate('Y-m-d H:i:s', time()));\n $this->output('Incorrect username and password credentials!', 'Incorrect Login Credentials', 'Error');\n }\n else\n {\n $this->users_model->lock_out_user($user_data->user_id, gmdate('Y-m-d H:i:s', time()+(60*15)));\n //$this->functions_model->send_email('maximum_failed_login_attempts_exceeded', $user_data->email_address, $user_data)\n $this->output('Your account is currently locked, we apologize for the inconvienence. You must wait 15 minutes before you can log in again! An email was sent to the owner of this account! Forgotten your username or password? <a href=\"forgotusername\">Forgot Username</a> or <a href=\"forgotpassword\">Forgot Password</a>', 'Account Locked', 'Error');\n }\n}\n</code></pre>\n\n<p>(I took this chance to replace <code>!=4</code> with <code><4</code> just in case we ever reach something after 4 for whatever reason)</p>\n\n<p>Then you could put the content of the else-block and the content of the if-block in functions on their own but this doesn't seem really required to me.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T20:45:38.567",
"Id": "42054",
"Score": "0",
"body": "Shouldn't you be returning inside the if and else areas."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-07T08:54:13.723",
"Id": "42101",
"Score": "1",
"body": "Well, I'm missing some context here but if needed you can add one after the else block. If you could show us the whole piece of code this is part of, then I could try to advice."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-07T17:25:58.783",
"Id": "42130",
"Score": "0",
"body": "I'll edit the post with the entire controller."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-05T20:20:41.837",
"Id": "27057",
"ParentId": "27052",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-05T18:28:59.483",
"Id": "27052",
"Score": "-1",
"Tags": [
"php",
"authentication",
"controller",
"codeigniter"
],
"Title": "Counting failed login attempts to enforce temporary lockout"
}
|
27052
|
<p>You can check the problem here:
<a href="http://projecteuler.net/problem=14" rel="nofollow">http://projecteuler.net/problem=14</a></p>
<p>My first approach in Haskell was this:</p>
<pre><code>import Data.Ord
import Data.List
computeCollatzSequenceLength n = let
compute l n
| n == 1 = l+1
| even n = compute (l+1) (n `div` 2)
| otherwise = compute (l+1) (3*n+1)
in generate 0 n
main = print $ fst $ maximumBy (comparing snd) $ zip [1..1000000] $ map computeCollatzSequenceLength [1..1000000]
</code></pre>
<p>Too slow it was, so I tried to use a sort of memoization by using an unboxed array:</p>
<pre><code>import Data.Ord
import Data.List
import Data.Int
import Data.Array.Unboxed
computeCollatzSequenceLength :: (UArray Int64 Int64) -> Int64 -> (Int64, [Int64])
computeCollatzSequenceLength a n = let
compute :: Int64 -> [Int64] -> Int64 -> (Int64, [Int64])
compute l s n'
| n' == 1 = (l+1, reverse s)
| v > 0 = (l+v, reverse s)
| even n' = compute (l+1) (n':s) (n' `div` 2)
| otherwise = compute (l+1) (n':s) (3*n'+1)
where v = if n' > (snd $ bounds a) then 0 else a!n'
in compute 0 [] n
computeMax m = let
compute :: (Int64,Int64) -> Int64 -> (UArray Int64 Int64) -> (Int64,Int64)
compute candidate n a
| n == (m+1) = candidate
| otherwise = let
(l, u) = computeCollatzSequenceLength a n
a' = a//(filter (\(n',_) -> n' <= m) (zip u [l,l-1..]))
in if (snd candidate) < l then compute (n,l) (n+1) a' else compute candidate (n+1) a'
in compute (0,0) 1 (array (1,m) [ (i,0) | i <- [1..m] ])
main = print $ fst $ computeMax 1000000
</code></pre>
<p>But, this was also very slow...(Both took more than a few minutes on my machine. Actually, the latter seems to take much longer...) I don't know what I've done wrong(I'm still a novice in Haskell.) In theory, the memoized version should be faster. I want to avoid using one of existing memoization packages out there.</p>
<p>What are issues with the current approach and how can I optimize this while still keeping its overall structure/approach?</p>
<p>EDIT: I found an elegant solution here: <a href="http://www.haskell.org/haskellwiki/Euler_problems/11_to_20#Problem_14" rel="nofollow">http://www.haskell.org/haskellwiki/Euler_problems/11_to_20#Problem_14</a> (The last one there, I mean.) Imperativeness and assignment are so hardwired in me as an inveterate C++ programmer, I cannot think of such a solution on my own at the moment. Still, I'd like to know what were issues with my approach above.</p>
<p>EDIT2: My not-working try based on @Hammar's advice:</p>
<pre><code>import Data.Int(Int64)
import Data.List(maximumBy)
import Data.Ord(comparing)
import Control.Monad
import Control.Monad.ST
import Data.Array.ST
import Data.Array.Unboxed
getCollatzSequenceLengthUpto :: Int64 -> (UArray Int64 Int64)
getCollatzSequenceLengthUpto n = runSTUArray $ do
seqLengths <- newArray (1,n) 0
forM_ [1..n] $ \i -> do
let compute l s n' = do
v <- if n' > n then 0 else (readArray seqLengths n')
if n' == 1
then
return (l+1, reverse s)
else
if v > 0
then
return (l+v, reverse s)
else
if even n'
then do
out <- compute (l+1) (n':s) (n' `div` 2)
return out
else do
out <- compute (l+1) (n':s) (3*n'+1)
return out
(l, u) <- compute 0 [] i
forM_ (filter (\(n',_) -> n' <= n) $ zip u [l,l-1..]) $ \(ix, e) -> do
writeArray seqLengths ix e
return seqLengths
main = print $ fst $ maximumBy $ (comparing snd) $ assocs $ getCollatzSequenceLengthUpto 1000000
</code></pre>
|
[] |
[
{
"body": "<p>The main reason why this is slow is that every update to your array is making a new copy of it. The version you linked to on the wiki avoids this problem by using a boxed array instead, which allows you to define the array in one go and let lazy evaluation take care of evaluating the elements in an appropriate order and modifying the array behind the scenes.</p>\n\n<p>A boxed array is less memory efficient since it's basically an array of pointers to individually-allocated integers, but for the size of this problem it's not too bad. If you want to use an unboxed array for improved space efficiency, you would probably want to use a mutable one in the ST monad instead. There's an example of how how to do that in <a href=\"https://stackoverflow.com/questions/8197032/starray-documentation-for-newbies-and-state-st-related-questions/8197275#8197275\">an old answer of mine on Stack Overflow</a>.</p>\n\n<hr>\n\n<p>Regarding your second attempt:</p>\n\n<p>First off, let's get this code to compile.</p>\n\n<ul>\n<li><p>Since the <code>else</code> branch of this <code>if</code> is returning a statement in the ST monad, so must the <code>then</code> branch. A quick fix is to add <code>return</code>:</p>\n\n<pre><code>v <- if n' > n then return 0 else (readArray seqLengths n')\n ^^^^^^\n</code></pre></li>\n<li><p>And there shouldn't be a <code>$</code> when passing the comparison function\nto <code>maximumBy</code> here:</p>\n\n<pre><code>main = print $ fst $ maximumBy (comparing snd) $ assocs $ getCollatzSequenceLengthUpto 1000000\n ^\n</code></pre></li>\n</ul>\n\n<p>With those small changes, it compiles and it runs in about 4 seconds on my netbook. Not too bad! </p>\n\n<p>However, it's a bit messy, let's see if we can fix that. First of all, let's reduce that ball of nested if's.</p>\n\n<ul>\n<li><p>We can get rid of the outermost <code>if</code> by using a separate equation for when <code>n'</code> is <code>1</code>:</p>\n\n<pre><code>compute l s 1 = return (l+1, reverse s)\n</code></pre></li>\n<li><p>The two branches of the innermost <code>if</code> are almost the same. We can move the <code>if</code> inside to the only place they differ. Also <code>do out <- compute ...; return out</code> is the same as just <code>compute ...</code>:</p>\n\n<pre><code>compute l s n' = do\n v <- if n' > n then return 0 else readArray seqLengths n'\n if v > 0\n then return (l+v, reverse s)\n else compute (l+1) (n':s) (if even n' then n' `div` 2 else (3*n'+1))\n</code></pre></li>\n</ul>\n\n<p>Here is the full working code after these adjustments. I still think the way\nyou're using a list to deal with the updates is somewhat complicated, but I think fixing that in a satisfactory way would require more substantial changes to your algorithm, so I've left it the way it is.</p>\n\n<pre><code>import Control.Monad (forM_)\nimport Control.Monad.ST\nimport Data.Array.ST\nimport Data.Array.Unboxed\nimport Data.Int (Int64)\nimport Data.List (maximumBy)\nimport Data.Ord (comparing)\n\ngetCollatzSequenceLengthUpto :: Int64 -> (UArray Int64 Int64)\ngetCollatzSequenceLengthUpto n = runSTUArray $ do\n seqLengths <- newArray (1,n) 0\n forM_ [1..n] $ \\i -> do\n let compute l s 1 = return (l+1, reverse s)\n compute l s n' = do\n v <- if n' > n then return 0 else readArray seqLengths n'\n if v > 0\n then return (l+v, reverse s)\n else compute (l+1) (n':s) (if even n' then n' `div` 2 else (3*n'+1))\n (l, u) <- compute 0 [] i\n forM_ (filter (\\(n',_) -> n' <= n) $ zip u [l,l-1..]) $ \\(ix, e) -> do\n writeArray seqLengths ix e \n return seqLengths\n\nmain = print $ fst $ maximumBy (comparing snd) $ assocs $ getCollatzSequenceLengthUpto 1000000\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-07T22:31:45.900",
"Id": "42159",
"Score": "0",
"body": "First of all, thank you for an answer, hammar. I tried to implement this as you suggested, but couldn't quite get my head around how monadic functions work in Haskell. I updated the post with my failed code. Any more help about it, please? :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-07T06:04:51.587",
"Id": "27130",
"ParentId": "27059",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "27130",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-05T20:27:53.717",
"Id": "27059",
"Score": "4",
"Tags": [
"optimization",
"haskell",
"project-euler"
],
"Title": "Project Euler #14 (Longest Collatz Sequence) in Haskell"
}
|
27059
|
<p>I would like some feedback on the code below. And how would I Implement pattern match on find users in role so that exact match not required? </p>
<pre><code>// MembershipProvider.FindUsersByName
public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)
{
MembershipUserCollection users = new MembershipUserCollection();
try
{
Profile.MembershipMapper memberMapper = new MembershipMapper();
List<Profile.Membership> recs = (List<Profile.Membership>)memberMapper.GetMembershipsByUsername(_memberUtil.GetApplicationId(), usernameToMatch, pageIndex, pageSize, out totalRecords);
foreach (Profile.Membership rec in recs)
{
users.Add(GetUserFromModel(rec, usernameToMatch));
}
}
catch (Exception ex)
{
Exception e = CheckEventLog(ex, "FindUsersByName");
throw e;
}
return users;
}
</code></pre>
|
[] |
[
{
"body": "<pre><code>List<Profile.Membership> recs = (List<Profile.Membership>)memberMapper.GetMembershipsByUsername(_memberUtil.GetApplicationId(), usernameToMatch, pageIndex, pageSize, out totalRecords);\n</code></pre>\n\n<p>I don't understand why is the cast needed here, <code>GetMembershipsByUsername()</code> doesn't sound like a method for which a cast would be necessary.</p>\n\n<p>Also, I think you should consider using <code>var</code> here, especially if you're going to keep the cast, so the type of the variable is clear. (I would probably use <code>var</code> even without the cast, but that's more debatable.)</p>\n\n<pre><code>Exception e = CheckEventLog(ex, \"FindUsersByName\");\nthrow e;\n</code></pre>\n\n<p>I don't see any reason for the (not very well named) variable <code>e</code> here, just <code>throw</code> the exception directly:</p>\n\n<pre><code>throw CheckEventLog(ex, \"FindUsersByName\");\n</code></pre>\n\n<p>Also, I think the method name <code>CheckEventLog()</code> could be improved. It's not clear at all that it returns an <code>Exception</code>, or what that exception means.</p>\n\n<pre><code>return users;\n</code></pre>\n\n<p>I would move this before the end of the <code>try</code>. That way, it's clearer that the method either returns a meaningful result or throws an exception. (And if you changed that later by removing or limiting the <code>throw</code>, you would get a compile error, which I think is a plus.)</p>\n\n<p>Also, doing this means you can move the declaration of the <code>users</code> variable into the <code>try</code> too.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-05T21:27:36.357",
"Id": "27063",
"ParentId": "27061",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-05T20:45:14.613",
"Id": "27061",
"Score": "2",
"Tags": [
"c#"
],
"Title": "Implement pattern match on FindUsersByName"
}
|
27061
|
<p>I have this very simple problem : my code is too repetitive. It works, but it could be much cleaner. I don't know exactly where to start. </p>
<p>I'd like to learn to work better, and I'd really like someone to help me with it.</p>
<p>Here's the 2 bits of my code that are very repetitive (everything I've done myself) :</p>
<pre><code>$(document).ready(function () {
// Setup your Lazy Line element.
// see README file for more settings
$('#drawing1').lazylinepainter({
'svgData': dr1,
'strokeWidth': 1.2,
'strokeColor': '#65615a',
'onComplete': function () {
}
})
$('#drawing2').lazylinepainter({
'svgData': dr2,
'strokeWidth': 1.2,
'strokeColor': '#65615a',
'onComplete': function () {
}
})
$('#drawing3').lazylinepainter({
'svgData': dr3,
'strokeWidth': 1.2,
'strokeColor': '#65615a',
'onComplete': function () {
}
})
$('#drawing4').lazylinepainter({
'svgData': dr4,
'strokeWidth': 1.2,
'strokeColor': '#65615a',
'onComplete': function () {
}
})
$('#drawing5').lazylinepainter({
'svgData': dr5,
'strokeWidth': 1.2,
'strokeColor': '#65615a',
'onComplete': function () {
}
})
// Paint your Lazy Line, that easy!
})
})(jQuery);
</code></pre>
<p>Second part of the code:</p>
<pre><code>var eventsFiredDr1 = 0;
var drawing1 = function () {
if(eventsFiredDr1 == 0) {
$('#drawing1').lazylinepainter('paint');
eventsFiredDr1++; // <-- now equals 1, won't fire again until reload
}
}
var eventsFiredDr2 = 0;
var drawing2 = function () {
if(eventsFiredDr2 == 0) {
$('#drawing2').lazylinepainter('paint');
eventsFiredDr2++; // <-- now equals 1, won't fire again until reload
}
}
var eventsFiredDr3 = 0;
var drawing3 = function () {
if(eventsFiredDr3 == 0) {
$('#drawing3').lazylinepainter('paint');
eventsFiredDr3++; // <-- now equals 1, won't fire again until reload
}
}
var eventsFiredDr4 = 0;
var drawing4 = function () {
if(eventsFiredDr4 == 0) {
$('#drawing4').lazylinepainter('paint');
eventsFiredDr4++; // <-- now equals 1, won't fire again until reload
}
}
var drawing5 = function () {
if(eventsFiredDr5 == 0) {
$('#drawing5').lazylinepainter('paint');
eventsFiredDr5++; // <-- now equals 1, won't fire again until reload
}
}
$(window).resize(function () {
if($(window).width() < 820) {
$("svg").hide()
$(".fallback").show()
$("#drawing2").css("height", "auto")
}
});
if($(window).width() > 820) {
$(".fallback").hide()
$(window).scrollStopped(function () {
if($("#drawing1").is(":within-viewport")) {
drawing1()
}
if($("#drawing2").is(":within-viewport")) {
drawing2()
}
if($("#drawing3").is(":within-viewport")) {
drawing3()
}
if($("#drawing4").is(":within-viewport")) {
drawing4()
}
if($("#drawing5").is(":within-viewport")) {
drawing5()
}
});
</code></pre>
<p>( I know I should put DOM elements in variables, but I planned on doing it when I would refactor the code. )</p>
<p>My first guess would be creating an array but.. No idea how to use it in my code. (I'm a big beginner)</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-10-05T13:34:27.280",
"Id": "195377",
"Score": "0",
"body": "As we all want to make our code more efficient or improve it in one way or another, try to write a title that summarizes what your code does, not what you want to get out of a review. For examples of good titles, check out [Best of Code Review 2014 - Best Question Title Category](http://meta.codereview.stackexchange.com/q/3883/23788) You may also want to read [How to get the best value out of Code Review - Asking Questions](http://meta.codereview.stackexchange.com/a/2438/41243)."
}
] |
[
{
"body": "<p>Before removing the code repetition, let's have a look at :</p>\n\n<pre><code>var eventsFiredDr1 = 0;\nvar drawing1 = function() {\n if (eventsFiredDr1 == 0) {\n $('#drawing1').lazylinepainter('paint');\n eventsFiredDr1++; // <-- now equals 1, won't fire again until reload\n }\n}\n</code></pre>\n\n<p>Things would probably be clearer if you were using booleans instead of integers :</p>\n\n<pre><code>var eventsFiredDr1 = false;\nvar drawing1 = function() {\n if (!eventsFiredDr1) {\n $('#drawing1').lazylinepainter('paint');\n eventsFiredDr1 = true; //won't fire again until reload\n }\n}\n</code></pre>\n\n<p>Now, to remove the duplicated code, you could create an array associating the name of the elements to their \"eventsFiredDr\" value :</p>\n\n<pre><code>drawings = { '#drawing1':false, '#drawing2':false};\n</code></pre>\n\n<p>Then you could rewrite :</p>\n\n<pre><code>$(window).scrollStopped(function(){\n if ($(\"#drawing1\").is(\":within-viewport\")) { \n drawing1()\n } \n\n if ($(\"#drawing2\").is(\":within-viewport\")) { \n drawing2()\n }\n\n if ($(\"#drawing3\").is(\":within-viewport\")) { \n drawing3()\n }\n\n if ($(\"#drawing4\").is(\":within-viewport\")) { \n drawing4()\n }\n\n if ($(\"#drawing5\").is(\":within-viewport\")) { \n drawing5()\n }\n\n});\n</code></pre>\n\n<p>as</p>\n\n<pre><code>$(window).scrollStopped(function(){\n for (drawing in drawings)\n {\n if ($(drawing).is(\":within-viewport\") && !drawings[drawing])\n { \n $(drawing).lazylinepainter('paint');\n drawings[drawing] = true; // <-- now equals 1, won't fire again until reload\n } \n }\n});\n</code></pre>\n\n<p>(This is a minimalist solution, also it's not tested at all)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-05T21:41:18.930",
"Id": "27065",
"ParentId": "27062",
"Score": "0"
}
},
{
"body": "<p>For the code repetition you can use</p>\n\n<pre><code>$(function () { // shorter form of document-ready\n $.each([dr1, dr2, dr3], function (index, data) {\n $('#drawing' + (index + 1)).lazylinepainter({\n svgData: data,\n strokeWidth: 1.2,\n strokeColor: '#65615a',\n onComplete: function () {}\n });\n });\n});\n</code></pre>\n\n<p>For the second part, use <code>boolean</code> values as Josay suggested but place the <code>fired</code> flag inside a function that returns a closure. Each call to <code>createPaintGuard</code> establishes its own <code>fired</code> flag without having to package them all into an array or object.</p>\n\n<pre><code>function createPaintGuard(index) {\n var fired = false;\n return function () {\n if (!fired) {\n $('#drawing' + index).lazylinepainter('paint');\n fired = true;\n }\n };\n}\n\nvar drawing1 = createPaintGuard(1);\nvar drawing2 = createPaintGuard(2);\nvar drawing3 = createPaintGuard(3);\n</code></pre>\n\n<p>Note that I would probably store the three <code>drawingX</code> variables into an array instead of individually-named variables, but I have no idea how they're being used in the wider context. The code here should be a drop-in replacement for yours.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T06:09:06.890",
"Id": "27073",
"ParentId": "27062",
"Score": "4"
}
},
{
"body": "<p>Here's a slightly different approach (warning : untested, but i believe the concept is right). </p>\n\n<p>Instead of creating a lot of different functions, we'll use a more object-oriented approach (see below for more explanation):</p>\n\n<pre><code>MyLazyLinePainter = function( jqElement ){\n\n // first, create the lazy line painter, using svg data \n // stored on MyLazyLinePainter's prototype\n jqElement.lazylinepainter({\n 'svgData': this.svgData[ jqElement.attr('id') ],\n 'strokeWidth': 1.2,\n 'strokeColor': '#65615a',\n 'onComplete': function () {}\n });\n\n // then create a painting handler, specific to this element\n var jqScope = $(window); \n var paintHandler = function(){\n if (jqElement.is(\":within-viewport\")){ \n jqElement.lazylinepainter( 'paint' );\n // here comes the magic: the handler will remove \n // the event listener itself when successfully executed !\n jqScope.off( 'scrollStopped', paintHandler );\n } \n }; \n\n // attach the paint handler to a window event\n jqScope.on( 'scrollStopped', paintHandler ); \n};\n\n// extend jQuery for ease of use\n$.fn.myLazyLinePainter = function(){\n return $(this).each( function(){ new MyLazyLinePainter($(this)) } );\n}\n\n// store the svg data\nMyLazyLinePainter.prototype.svgData = {\n id1: // store your data here, one key for each element id\n};\n\n// here we go !\n$('.myLazyLinePainter').myLazyLinePainter();\n</code></pre>\n\n<p>So, to sum up :</p>\n\n<ul>\n<li>each element having the class <code>myLazyLinePainter</code> will be passed to the constructor function we defined, <code>MyLazyLinePainter</code></li>\n<li>the contructor attaches a <code>lazylinepainter</code> to the element. To do so, it fetches svg data from a data store, <strong>using the element id as a key</strong>. The data store could be anything, even something powered by AJAX queries ; you couls also (while ugly) store the data in an HTML data attribute on the element itself... </li>\n<li>the constructor then crafts a handler specific to the element :\n<ul>\n<li>the handler is attached to <code>$(window)</code>, and listens to the <code>scrollStopped</code> event</li>\n<li>the handler, when called, checks if the element is in viewport ; if so, it triggers painting, <strong>AND</strong> removes itself from the <code>scrollStopped</code> listeners attached to <code>$(window)</code>, so that it fires only once.</li>\n</ul></li>\n</ul>\n\n<p><strong>EDIT</strong></p>\n\n<p>I'll attempt to clarify. There are distinct concepts introduced by this approach :</p>\n\n<p><strong>1) use a \"fire-once\" event listener</strong></p>\n\n<p>The concept here is to create one function :</p>\n\n<pre><code>foo = function(){ console.log('ok') }\n</code></pre>\n\n<p>...and then attach it as a handler for one event : </p>\n\n<pre><code>$(window).on('scroll', foo )\n</code></pre>\n\n<p>But we want this handler to <strong>fire only once</strong>, so the handler will remove itself from listeners :</p>\n\n<pre><code>var foo = function(){\n console.log('ok')\n $(window).off('scroll', foo)\n}\n$(window).on('scroll', foo )\n</code></pre>\n\n<p>Ok, this part is weird : we reference <code>foo</code> from inside of <code>foo</code>. As the function is a closure, we can do this : the body of the function is not evaluated yet, and <em>when it will be</em>, <code>foo</code> in its body will reference the scope the closure <em>encloses</em>, in which <code>foo</code> is a var holding the function (headaches!)</p>\n\n<p>So, as soon as the function is called, <code>foo</code> is removed from the event listeners on the 'scroll' event. In practive, the event listener is just used once, and then discarded.</p>\n\n<p>In my solution, it is a bit different because we only discard the listener IF the element is within viewport. </p>\n\n<p><strong>2) use a data store</strong></p>\n\n<p>This one is quite simple, in fact. Imagine you have :</p>\n\n<pre><code> <div class=\"foo\" id=\"foo1\" />\n <div class=\"foo\" id=\"foo2\" />\n</code></pre>\n\n<p>... and so on. Now you have a data store that is a simple object :</p>\n\n<pre><code> dataStore = {\n \"foo1\" : \"data for foo1\",\n \"foo2\" : \"data for foo2\"\n }\n\nto retrieve data associated to each element, you just do :\n\n dataStore[ idOfTheElement ]\n</code></pre>\n\n<p><strong>3) extending jquery</strong></p>\n\n<p>Ok, that one was optional. You could see <code>MyLazyLinePainter</code> as a simple function that takes a single jquery element ( as $('#foo1') ) as argument. The idea of this function is to craft specific handlers (closures) that <em>reference</em> the element that was passed as an argument. The <code>MyLazyLinePainter</code> function is called once per element grabbed by the selector i propose in the end of the solution.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T11:49:00.797",
"Id": "41990",
"Score": "0",
"body": "I have to study this deeper, but isn't \"bind\" and \"unbind\" outdated functions ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T12:06:12.683",
"Id": "41992",
"Score": "0",
"body": "my bad, new syntax uses `on()` and `off()`, but the logic is the same."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T12:12:33.067",
"Id": "41994",
"Score": "0",
"body": "note : i don't know what your `scrollStopped` event is, just assumed it was a custom event."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T12:18:05.853",
"Id": "41995",
"Score": "0",
"body": "-> with a bit of searching, someone implemented such events : https://code.google.com/p/jquery-scroll-events/wiki/Reference"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T14:18:39.307",
"Id": "42017",
"Score": "0",
"body": "It was a plugin, I didn't put it there because I didn't think it was relevant. I'm trying to get your code, but I begin to have a headache."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T15:20:11.010",
"Id": "42027",
"Score": "0",
"body": "what part does hurt ? :D"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T15:25:55.267",
"Id": "42028",
"Score": "0",
"body": "I know it may seem a bit confusing, because i introduce two concepts at once : 1) using a data store for svg data 2) using a \"fire-once\" event"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T15:47:09.937",
"Id": "42029",
"Score": "0",
"body": "updated my answer in an attempt to clarify."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T09:40:08.727",
"Id": "27080",
"ParentId": "27062",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-05T21:01:33.017",
"Id": "27062",
"Score": "0",
"Tags": [
"javascript"
],
"Title": "Tips to refactor code : very repetitive code"
}
|
27062
|
<p>I have a data-structure class in C++ with an accessor to some object (may be large) and I have const and non-const methods using this accessor so I need to overload it. I am looking for a <strong>critique</strong> of the code below - maybe there is a way to accomplish the same thing that is cleaner?</p>
<p>The way I understand it, there are two ways to achieve this without duplicating the code in the accessor in the following case, the method get(). I am not sure if there are serious issues with either of these two methods and I would like some guidance here.</p>
<p>I like method A because:</p>
<ul>
<li>only one const_cast</li>
<li>const-version of the method get() returns a copy</li>
<li>the non-const method gets the non-const reference directly</li>
</ul>
<p>I don't like method A because:</p>
<ul>
<li>the non-const method get() is const only by contract, (not checked by compiler)</li>
<li>harder to get a const-reference, though not impossible</li>
</ul>
<p>I like method B because:</p>
<ul>
<li>the const-ness of the const method get() is checked by compiler</li>
<li>copy of the returned object is controlled by the user</li>
</ul>
<p>I don't like method B because:</p>
<ul>
<li>requires two const_casts which is hard to read</li>
</ul>
<p>here is the (minimal) example code of the two cases.</p>
<pre class="lang-cpp prettyprint-override"><code>/**
* summary:
* Two classes with an overloaded method which is
* guaranteed (by contract) not to change any
* internal part of the class. However, there is a
* version of this method that will return a non-const
* reference to an internal object, allowing the user
* to modify it. Don't worry about why I would ever
* want to do this, though if you want a real-world
* example, think about std::vector<>::front()
*
* The difference between A and B can be summarized
* as follows. In both cases, the second method merely
* calls the first, wrapped with the needed
* const_cast's
*
* struct A {
* int& get();
* int get() const;
* };
*
* struct B {
* const int& get() const;
* int& get();
* };
*
**/
struct A
{
int _val;
A() : _val(7) {};
// non-const reference returned here
// by a non-const method
int& get()
{
// maybe lots of calculations that you do not
// wish to be duplicated in the const version
// of this method...
return _val;
}
// const version of get() this time returning
// a copy of the object returned
int get() const
{
// CONST-CAST!!?? SURE.
return const_cast<A*>(this)->get();
}
// example of const method calling the
// overloaded get() method
int deep_get() const
{
// gets a copy and makes
// a copy when returned
// probably optimized away by compiler
return this->get();
}
};
struct B
{
int _val;
B() : _val(7) {};
// const reference returned here
// by a const method
const int& get() const
{
// maybe lots of calculations that you do not
// wish to be duplicated in the non-const
// version of this method...
return _val;
}
// non-const version of get() this time returning
// a copy of the object returned
int& get()
{
// CONST-CAST!? TWO OF THEM!!?? WHY NOT...
return const_cast<int&>(const_cast<const B*>(this)->get());
}
// example of const method calling the
// overloaded get() method
int deep_get() const
{
// gets reference and makes
// a copy when returned
return this->get();
}
};
int main()
{
A a;
a.get() = 8; // call non-const method
a.deep_get(); // indirectly call const method
B b;
b.get() = 8; // call non-const method
b.deep_get(); // indirectly call const method
}
</code></pre>
|
[] |
[
{
"body": "<blockquote>\n <p>const-version of the method get() returns a copy</p>\n</blockquote>\n\n<p>Why is this a good thing?</p>\n\n<blockquote>\n <p>the non-const method get() is const only by contract, (not checked by compiler)\n harder to get a const-reference, though not impossible</p>\n</blockquote>\n\n<p>What?</p>\n\n<blockquote>\n <p>the const-ness of the const method get() is checked by compiler\n copy of the returned object is controlled by the user</p>\n</blockquote>\n\n<p>What does it matter if it is const if you have to go to the effort of making a copy.</p>\n\n<blockquote>\n <p>requires two const_casts which is hard to read</p>\n</blockquote>\n\n<p>Really!</p>\n\n<p>PS. getters and setters are an anti pattern (unless you are a container).<br>\nExposing the internal implementation like this tightly couples your class to any code that uses it. This makes modifying your code in the future much harder. It is best to make your methods do the work rather than expose the members and do the work outside the class.</p>\n\n<pre><code>class X\n{\n Y value;\n\n public:\n // Why over complicate things.\n // This has the same functionality.\n Y& get() {return value;}\n Y const& get() const {return value;}\n };\n</code></pre>\n\n<p>OK so you want the code to get the value in one location:</p>\n\n<pre><code>class Z\n{\n Y value;\n\n public:\n Y& get() {return value;}\n\n\n // Only really need one cast.\n // We know that get() is not modifying the object.\n // If it was you can't share functions anyway.\n // Thus it is safe to cast away const-ness before calling get.\n // Because you are returning a const& from this function it is\n // fine and you don't need to add const-ness back anyway.\n Y const& get() const {return const_cast<Z&>(*this).get();}\n };\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-08T07:17:22.623",
"Id": "42172",
"Score": "0",
"body": "+1 this was cross-posted from SO, see [my answer](http://stackoverflow.com/a/16950360/819272) there"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-08T06:45:48.700",
"Id": "27161",
"ParentId": "27064",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "27161",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-05T21:39:59.003",
"Id": "27064",
"Score": "2",
"Tags": [
"c++",
"classes"
],
"Title": "overloaded const and non-const class methods returning references in C++"
}
|
27064
|
<p>I recently asked <a href="https://codereview.stackexchange.com/questions/27013/how-can-i-speed-up-access-to-an-unordered-map">this question about performance of an unordered_map</a>, but I realize my question is probably more about this piece of code here.</p>
<p>I create a 8 x 10 x 30 x 30 x 24000 nested vectors of floats. This structure is used to keep track of votes in this 5D space. Many of the bins are never actually incremented, though (0 votes). The structure takes up 7.2GB of memory.</p>
<p>I initially thought to switch to a hash map (hence, <a href="https://codereview.stackexchange.com/questions/27013/how-can-i-speed-up-access-to-an-unordered-map">my other question</a>), but there's memory overhead in storing the 5D keys, and it's actually slower.</p>
<p>How can I improve this solution? I'd like to reduce the memory used, without giving up much speed.</p>
<p>Things I've thought of:</p>
<ul>
<li><a href="https://codereview.stackexchange.com/questions/27013/how-can-i-speed-up-access-to-an-unordered-map">Switching to an unordered_map</a> (was slower and used more memory)</li>
<li>Dropping to half-precision floats (I only need about 3-4 digits of precision, and the votes accumulated in any of the bins are in approximately [-3,3]) - haven't tried this</li>
<li>Replacing the inner <code>vector<float></code> with <code>map<float></code> - haven't tried this</li>
</ul>
<p>I'd appreciate feedback about any of these ideas.</p>
<pre><code>#include <random>
#include <vector>
int main(int argc, char** argv) {
std::default_random_engine generator;
std::uniform_int_distribution<int> random_z(1,24000);
std::uniform_real_distribution<float> random_vote(0.0, 1.0);
// This makes an 8 x 10 x 30 x 30 x 24000 vector of vectors... of vectors.
std::vector<std::vector<std::vector<std::vector<std::vector<float> > > > > votes;
for (size_t a = 0; a < 8; ++a) {
std::vector<std::vector<std::vector<std::vector<float> > > > a_grid;
for (size_t b = 0; b < 10; ++b) {
std::vector<std::vector<std::vector<float> > > b_grid;
for (size_t y = 0; y < 30; ++y) {
std::vector<std::vector<float> > y_grid;
for (size_t x = 0; x < 30; ++x) {
y_grid.push_back(std::vector<float>(24000, 0));
}
b_grid.push_back(y_grid);
}
a_grid.push_back(b_grid);
}
votes.push_back(a_grid);
}
for (int i = 0; i < 200000; ++i) {
int z = random_z(generator); // z in [1,24000]
for (int a = 0; a < 8; ++a) {
for (int b = 0; b < 10; ++b) {
for (int x = 0; x < 30; ++x) {
for (int y = 0; y < 30; ++y) {
float this_vote = random_vote(generator);
if (this_vote > 0.8) {
votes[a][b][y][x][z] += this_vote;
}
}
}
}
}
}
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-05T23:41:28.040",
"Id": "41951",
"Score": "0",
"body": "How sparse (i.e. what % of populated entries) do you expect your structure to be?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-05T23:53:27.790",
"Id": "41953",
"Score": "0",
"body": "@microtherion About 20% of the bins are populated."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T00:53:25.197",
"Id": "41956",
"Score": "0",
"body": "That’s probably too populated for any sparse solution to be really effective. Maybe you should just use an 8- or 16-bit fixed point representation with a dense map."
}
] |
[
{
"body": "<p>Since your overall number of indices just fits into 31 bits, you could try a <code>std::map</code>:</p>\n\n<pre><code>uint32_t keyFrom5DIndex(uint32_t a, uint32_t b, \n uint32_t x, uint32_t y, uint32_t z)\n{\n return z+24000*(x+30*(y+30*(b+10*a)));\n}\n\nstd::map<uint32_t, float> votes;\n// Compute indices\nvotes[keyFrom5DIndex(a,b,z,y,z)] += this_vote;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-01T00:07:34.233",
"Id": "63933",
"Score": "0",
"body": "A tree-based map likely has more memory usage than a hashtable based container. I'd use a hashtable if available."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-01T04:55:38.617",
"Id": "63936",
"Score": "0",
"body": "Interesting thought. In my tests (clang on a Mac, latest C++ library), `std::map<uint32_t,float>` consistently uses less memory than `std::unordered_map<uint32_t,float>` (presumably because hash tables need a certain amount of free space to give decent performance). On the other hand, `std::unordered_map` was about twice as fast."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-01T11:01:13.713",
"Id": "63945",
"Score": "0",
"body": "Maybe map does some clever allocation strategy. If every tree node was a malloc-backed allocation there would be lots of overhead. Good to know."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-05T23:51:46.567",
"Id": "27070",
"ParentId": "27066",
"Score": "3"
}
},
{
"body": "<p>Very minor point, but possibly still worth pointing out since you're using C++11.</p>\n\n<p><a href=\"http://www.stroustrup.com/C++11FAQ.html#brackets\" rel=\"nofollow\">In C++11, you no longer need to separate the right-angle brackets</a>:</p>\n\n<blockquote>\n<pre><code>std::vector<std::vector<std::vector<std::vector<std::vector<float> > > > > votes;\n</code></pre>\n</blockquote>\n\n<p>You can now put them together:</p>\n\n<pre><code>std::vector<std::vector<std::vector<std::vector<std::vector<float>>>>> votes;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-25T20:44:11.123",
"Id": "55272",
"ParentId": "27066",
"Score": "2"
}
},
{
"body": "<p>I'm not sure whether it'll reduce memory usage as much as you'd like, but one obvious possibility would be to use a single vector, and overload an operator to provide 5D addressing into that vector.</p>\n\n<pre><code>template <class T>\nclass vector5 { \n std::vector<T> data;\n size_t a, b, c, d;\npublic:\n vector5(size_t a, size_t b, size_b c, size_t d, size_t e) \n : data(a*b*c*d*e),\n a(a), b(b), c(c), d(d)\n {}\n\n T &operator()(size_t one, size_t two, size_t three, size_t four, size_t 5) {\n one*(a+b+c+d) + two*(a+b+c) + three * (a + b) + four * (a) + five;\n }\n};\n</code></pre>\n\n<p>Although this should require less overall memory, it does have one shortcoming: it needs to allocate a single, contiguous block of memory to hold all the data. If your heap is fragmented, that could fail outright.</p>\n\n<p>Assuming you do successfully allocate the memory, this should give faster access as a general rule. Instead of chasing through five levels of pointers to get to an object, it does everything on the CPU to figure out the address of an object, then uses that object directly.</p>\n\n<p>Oh -- one minor detail: since this the addressing using an overload of <code>operator()</code> instead of <code>operator[]</code>, you address it like <code>m(1,2,3,4,5)</code> instead of <code>m[1][2][3][4][5]</code>. You <em>can</em> support the latter if you really want to badly enough, but it's pretty ugly. I posted code for a 3D version of this in a <a href=\"https://stackoverflow.com/a/2216055/179910\">previous answer</a>, but it's ugly enough that you'd have to be <em>really</em> set on using square brackets instead of parentheses to bother (especially for 5D addressing).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-26T21:32:54.073",
"Id": "55383",
"ParentId": "27066",
"Score": "3"
}
},
{
"body": "<p>It's not entirely clearer whether the primary issue is speed or memory. 7.2G is a fair bit, but depending on your setup, my in itself be acceptable.</p>\n\n<p>Firstly, memory considerations:</p>\n\n<p>I think about 18.1% of the cells are occupied and I do not see a way to get an efficient sparse approach.</p>\n\n<p>How do you use your data? Can you actually move the <code>a</code> loop out, and run trials for each <code>a</code> separately? That would immediately cut the memory usage by a factor of 8.</p>\n\n<p>I think the idea of using 2-byte floats should also be good. Actually, for ease of implementation, I'd work with 2-byte integers (probably <code>short</code>s), and then map back to a float as required.</p>\n\n<p>Using more complex data structures than <code>vector</code> and <code>array</code> is inevitably going to cost you in some way. For example, using a <code>map<></code> for this problem will result in a lot of dynamic memory allocation which will cripple performance.</p>\n\n<p>On the speed side, I think there is a possible 5x speed up. </p>\n\n<p>You run a very large number of trials, but only 20% of these are counted. Naively, reduce the outer loop from <code>200000</code> to <code>40000</code> and you'll get the same result. Well, not exactly:</p>\n\n<p>The total number of events that are counted has mean 200000 * 8*10*30*30*0.2. </p>\n\n<p>This may be enough for you. Alternatively, this is a binomial distribution, and the variance will be 200000 * 8*10*30*30*(0.2*0.8). The normal distribution to the binomial is valid here, so you could sample from:</p>\n\n<p>normal(mean = 200000 * 8*10*30*30*0.2, variance = 200000 * 8*10*30*30*(0.2*0.8)) to get the number of events.</p>\n\n<p>A small one on the speed side is that array look-up will be fractionally faster than vector, so one could use a mix of vectors and arrays.</p>\n\n<p>Putting this together (have not done the 2 byte float!):</p>\n\n<pre><code>static const unsigned dimA = 8;\nstatic const unsigned dimB = 10;\nstatic const unsigned dimY = 30;\nstatic const unsigned dimX = 30;\nstatic const unsigned dimZ = 24000;\n\ntypedef std::vector<float> ZTable;\ntypedef std::vector<ZTable> XTable;\ntypedef XTable ATable[dimA][dimB][dimY];\n\nvoid voting()\n{\n ATable votes;\n for (size_t a = 0; a < dimA; ++a)\n for (size_t b = 0; b < 10; ++b)\n for (size_t y = 0; y < 30; ++y)\n {\n votes[a][b][y].resize(dimX);\n for (size_t x = 0; x < 30; ++x)\n votes[a][b][y][x].resize(dimZ);\n }\n std::cout << \"alloc complete\" << std::endl;\n\n double mean = 200000.0 * 8 * 10 * 30 * 30 *0.2;\n double variance = 200000.0 * 8 * 10 * 30 * 30 * 0.2 * (1-0.2);\n double sd = sqrt(variance);\n\n std::default_random_engine generator;\n std::uniform_int_distribution<int> random_z(1, dimZ);\n std::uniform_int_distribution<int> random_y(1, dimX);\n std::uniform_int_distribution<int> random_x(1, dimY);\n std::uniform_int_distribution<int> random_a(1, dimA);\n std::uniform_int_distribution<int> random_b(1, dimB);\n std::uniform_real_distribution<float> random_vote(0.8, 1.0);\n std::normal_distribution<double> eventDistribution(mean, sd);\n\n double events = eventDistribution(generator);\n int loops = (int)(events / (8 * 10 * 30 * 30));\n double lostEvents = events - (8.0 * 10 * 30 * 30)*loops;\n std::cout << \"Running \" << loops << \" loops\" << std::endl;\n std::cout << \"Lost events \" << lostEvents << std::endl;\n\n for (int i = 0; i < loops; ++i) {\n int z = random_z(generator); // z in [1,24000]\n std::cout << i << \" \";\n for (int a = 0; a < 8; ++a) \n for (int b = 0; b < 10; ++b) \n for (int x = 0; x < 30; ++x) \n for (int y = 0; y < 30; ++y) {\n float this_vote = random_vote(generator);\n votes[a][b][y][x][z-1] += this_vote;\n\n }\n }\n // Still need to cast votes equal to `lostEvents`\n std::cout << \"Lost events \" << lostEvents << std::endl;\n for (unsigned i = 0; i < lostEvents; ++i)\n {\n int z = random_z(generator);\n int y = random_y(generator);\n int x = random_x(generator);\n int a = random_a(generator);\n int b = random_b(generator);\n float this_vote = random_vote(generator);\n votes[a-1][b-1][y-1][x-1][z-1] += this_vote;\n }\n std::cout << \"votes complete\" << std::endl;\n}\n</code></pre>\n\n<p>EDIT: Corrected array indices to run from 0.</p>\n\n<p>This runs in about 10 minutes on my machine (in debug mode). </p>\n\n<p>Note that depending on your system , you can readily thread this as well. \nDoing this in release mode, and I get a run in less than minute.</p>\n\n<p>Having done all this, some remarks on using 16 bits for the vote storage.\nAs noted above, rather the using an actual 16-bit float, I'd just map into a short; effectively this is a fixed point with a maximum value of <code>16</code>. Analysis of the table gives an actual maximum of 8.1 or so.</p>\n\n<pre><code>typedef std::vector<short> ZTable;\n\nconst unsigned short maxVote = 1 << 12;\nfloat shortToFloat(unsigned short vote)\n{\n return vote*1.0 / maxVote;\n}\nunsigned short floatToShort(float vote )\n{\n float this_vote = vote * maxVote;\n unsigned short vote = (unsigned short)this_vote;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-27T04:18:16.533",
"Id": "55411",
"ParentId": "27066",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-05T22:15:08.613",
"Id": "27066",
"Score": "4",
"Tags": [
"c++",
"performance",
"c++11",
"memory-management",
"vectors"
],
"Title": "Reducing memory usage of nested vectors"
}
|
27066
|
<p>In my controller I had the idea to do something like the following:</p>
<pre><code>// retrieve fields from form
$firstname = $form->getInput('firstname');
$lastname = $form->getInput('lastname');
[...]
// create Member object
$member = new Member($firstname, $lastname, [...]);
// save Member in DB
$this->_daoFactory->get('Member')->save($member);
</code></pre>
<p>In this example, the DAO factory would create an instance of the MemberDAO class, which (I guess) acts like a data mapper? And allows me to save the Member object in DB, to update a Member, get a Member from id, and other db requests probably.</p>
<p>What do you think about this code?</p>
<p>Thank you for your review!</p>
|
[] |
[
{
"body": "<p>A lot of MVC frameworks do the datamapping in the same class (usually with static methods). I would also avoid creating hard links between controllers and models (like having each model property as a parameter in the class constructor). Something like this is a little more elegant, IMO:</p>\n\n<pre><code><?php\n\n// Model\nclass Member\n{\n public static function forge(array $data = array())\n {\n return new static($data);\n }\n\n public function __construct(array $data = array())\n {\n foreach ($data as $k => $v)\n {\n // consider checking here for expected properties,\n // sanitizing input, etc.\n $this->$k = $v;\n }\n }\n\n public function save()\n {\n // If primary key exists, run DB update query\n // Otherwise, run insert query\n\n // Return success/failure information (and/or throw exceptions)\n }\n}\n\n// Controller action\n$member = Member::forge($form->get_sanitized_postdata());\n$member->save();\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-21T00:09:19.097",
"Id": "43047",
"Score": "0",
"body": "Why didn't you instantiate with \"new\" operator instead?\n$member = new Member($form->get_sanitized_postdata());"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-11T23:51:14.570",
"Id": "27285",
"ParentId": "27067",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-05T22:33:18.887",
"Id": "27067",
"Score": "1",
"Tags": [
"php",
"mvc"
],
"Title": "Is this a good way for Controller to interact with Model ? (MVC)"
}
|
27067
|
<p>I have a block of C# code here that stores data to an <code>ArrayList</code> from the database and compares each with the values from the <code>GridView</code>.</p>
<p>Is there a way to reduce the line of code and improve its readability?</p>
<pre><code> while (DataReader.Read())
{
arrHostName.Add(DataReader.GetString(0));
arrUsers.Add(DataReader.GetString(2));
arrPSName.Add(DataReader.GetString(3));
}
foreach (Infragistics.Win.UltraWinGrid.UltraGridRow row in Grid2.Rows)
{
string rowHostName = row.Cells["HostName"].Value.ToString();
string rowUsers = row.Cells["Users"].Value.ToString();
string rowPSName= row.Cells["PS_NAME"].Value.ToString();
foreach (string a in arrHostName)
{
if (rowHostName == a.ToString())
{
row.Appearance.BackColor = Color.Yellow;
row.Appearance.FontData.Bold = Infragistics.Win.DefaultableBoolean.True;
}
}
foreach (string a in arrUsers)
{
if (rowUsers == a.ToString())
{
row.Appearance.BackColor = Color.Yellow;
row.Appearance.FontData.Bold = Infragistics.Win.DefaultableBoolean.True;
}
}
foreach (string a in arrPSName)
{
if (rowPSName == a.ToString())
{
row.Appearance.BackColor = Color.Yellow;
row.Appearance.FontData.Bold = Infragistics.Win.DefaultableBoolean.True;
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>for improvement, to reduce no of iterations</p>\n\n<pre><code> foreach (Infragistics.Win.UltraWinGrid.UltraGridRow row in Grid2.Rows)\n {\n string rowHostName = row.Cells[\"HostName\"].Value.ToString();\n string rowUsers = row.Cells[\"Users\"].Value.ToString();\n string rowPSName= row.Cells[\"PS_NAME\"].Value.ToString();\n\n foreach (string a in arrHostName)\n {\n if (rowHostName == a)\n { \n row.Appearance.BackColor = Color.Yellow;\n row.Appearance.FontData.Bold = Infragistics.Win.DefaultableBoolean.True;\n goto Outer;\n }\n }\n foreach (string a in arrUsers)\n {\n if (rowUsers == a)\n {\n row.Appearance.BackColor = Color.Yellow;\n row.Appearance.FontData.Bold = Infragistics.Win.DefaultableBoolean.True;\n goto Outer;\n }\n }\n foreach (string a in arrPSName)\n {\n if (rowPSName == a)\n {\n row.Appearance.BackColor = Color.Yellow;\n row.Appearance.FontData.Bold = Infragistics.Win.DefaultableBoolean.True;\n goto Outer;\n }\n }\n Outer:\n continue;\n } \n</code></pre>\n\n<p>And if all <code>arraylist</code> having same <code>length</code>, then you could reduce no of <code>for loops</code></p>\n\n<pre><code>foreach (Infragistics.Win.UltraWinGrid.UltraGridRow row in Grid2.Rows)\n {\n string rowHostName = row.Cells[\"HostName\"].Value.ToString();\n string rowUsers = row.Cells[\"Users\"].Value.ToString();\n string rowPSName= row.Cells[\"PS_NAME\"].Value.ToString();\n\n for (int i = 0; i < arrHostName.Length; i++)\n {\n if (arrHostName[i].ToString() == rowHostName || arrUsers[i].ToString() == rowUsers || arrPSName[i].ToString() == rowPSName)\n {\n row.Appearance.BackColor = Color.Yellow;\n row.Appearance.FontData.Bold = Infragistics.Win.DefaultableBoolean.True;\n break;\n }\n }\n\n } \n</code></pre>\n\n<p><strong>Edited</strong> </p>\n\n<pre><code>if (arrHostName[i] == rowHostName || arrUsers[i] == rowUsers || arrPSName[i] == rowPSName)\n</code></pre>\n\n<p><strong>Updated</strong></p>\n\n<pre><code>foreach (Infragistics.Win.UltraWinGrid.UltraGridRow row in Grid2.Rows)\n {\n string rowHostName = row.Cells[\"HostName\"].Value.ToString();\n string rowUsers = row.Cells[\"Users\"].Value.ToString();\n string rowPSName= row.Cells[\"PS_NAME\"].Value.ToString();\n\n if(arrHostName.Contains(rowHostName) || arrUsers.Contains(rowUsers) || arrPSName.Contains(rowPSName))\n {\n row.Appearance.BackColor = Color.Yellow;\n row.Appearance.FontData.Bold = Infragistics.Win.DefaultableBoolean.True;\n }\n\n\n } \n</code></pre>\n\n<p><strong>Further improvement -- reduced more no of lines</strong></p>\n\n<pre><code>foreach (Infragistics.Win.UltraWinGrid.UltraGridRow row in Grid2.Rows)\n {\n if(arrHostName.Contains(row.Cells[\"HostName\"].Value.ToString()) || arrUsers.Contains(row.Cells[\"Users\"].Value.ToString()) || arrPSName.Contains(row.Cells[\"PS_NAME\"].Value.ToString()))\n {\n row.Appearance.BackColor = Color.Yellow;\n row.Appearance.FontData.Bold = Infragistics.Win.DefaultableBoolean.True;\n }\n } \n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T06:23:50.987",
"Id": "41964",
"Score": "1",
"body": "the reason why I have added `goto Outer;` is- if you changes the back color of a row in first `for`, then there is no need to go to other `for`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T06:29:40.390",
"Id": "41965",
"Score": "0",
"body": "But is there another way to reduce the 3 foreach?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T06:31:30.327",
"Id": "41966",
"Score": "1",
"body": "@QKWS length of arraylist are not same right? I mean all having same length or ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T06:33:05.097",
"Id": "41967",
"Score": "1",
"body": "@QKWS arraylist length would be same as the no of rows coming from datareader right?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T06:34:52.273",
"Id": "41968",
"Score": "0",
"body": "yes.. they will be the same."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T06:45:07.310",
"Id": "41969",
"Score": "1",
"body": "@QKWS edited `if` logic, so It would work"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T06:47:17.717",
"Id": "41970",
"Score": "0",
"body": "I got an error of Error: ArrayList does not contain a definition for 'Length'"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T06:50:26.970",
"Id": "41971",
"Score": "1",
"body": "use `Count` instead of `length`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T06:54:55.920",
"Id": "41973",
"Score": "0",
"body": "For some reason, your code is not working for me. Rows doesn't change into Yellow Background."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T06:58:12.497",
"Id": "41975",
"Score": "1",
"body": "Check the values in `if` statement"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T07:00:08.473",
"Id": "41977",
"Score": "1",
"body": "`if (arrHostName[i].ToString() == rowHostName || arrUsers[i].ToString() == rowUsers || arrPSName[i].ToString() == rowPSName)`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T08:08:22.163",
"Id": "41982",
"Score": "1",
"body": "Does this code solve your prob"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-15T00:59:50.893",
"Id": "133847",
"Score": "0",
"body": "I suggest you make your edits more *seamless* - readers can use the edit history to see all the revisions; posts are easier to read if they *look* like they were written in one shot ;)"
}
],
"meta_data": {
"CommentCount": "13",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T06:18:13.420",
"Id": "27075",
"ParentId": "27074",
"Score": "1"
}
},
{
"body": "<p>It looks like what you want is <a href=\"http://msdn.microsoft.com/en-us/library/system.collections.arraylist.contains.aspx\"><code>ArrayList.Contains</code></a>.</p>\n\n<pre><code>string rowHostName = row.Cells[\"HostName\"].Value.ToString();\nstring rowUsers = row.Cells[\"Users\"].Value.ToString();\nstring rowPSName= row.Cells[\"PS_NAME\"].Value.ToString();\n\nif (arrHostName.Contains(rowHostName) \n || arrUsers.Contains(rowUsers) \n || arrPSName.Contains(rowPSName))\n{ \n row.Appearance.BackColor = Color.Yellow;\n row.Appearance.FontData.Bold = Infragistics.Win.DefaultableBoolean.True;\n}\n</code></pre>\n\n<p>And if you only use the collections above to check if they contain some values, you should prefer <a href=\"http://msdn.microsoft.com/en-us/library/bb359438.aspx\"><code>HashSet</code></a> over <code>ArrayList</code>.</p>\n\n<p>Of course, you should then change the names of the local variables accordingly, from <code>arrHostName</code> to <code>hostNames</code> and so on. It is always better not to clutter variable names with type information in C#, whose type system is good enough.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T07:16:54.107",
"Id": "27076",
"ParentId": "27074",
"Score": "8"
}
},
{
"body": "<p>It would be best way to do this.</p>\n\n<pre><code>foreach (Infragistics.Win.UltraWinGrid.UltraGridRow row in Grid2.Rows)\n {\n if(arrHostName.Contains(row.Cells[\"HostName\"].Value.ToString()) || arrUsers.Contains(row.Cells[\"Users\"].Value.ToString()) || arrPSName.Contains(row.Cells[\"PS_NAME\"].Value.ToString()))\n {\n row.Appearance.BackColor = Color.Yellow;\n row.Appearance.FontData.Bold = Infragistics.Win.DefaultableBoolean.True;\n }\n } \n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T18:46:07.113",
"Id": "27111",
"ParentId": "27074",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "27076",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T06:15:52.177",
"Id": "27074",
"Score": "6",
"Tags": [
"c#"
],
"Title": "Comparing database values with values from a GridView"
}
|
27074
|
<p>I need to test performance of a function in PHP. This has to happen accurately, of course. In the end I need to know how long it takes for a function to perform. What I'm doing now:</p>
<pre class="lang-php prettyprint-override"><code><?php
$start = microtime(true);
while (microtime(true) != $start + 1); // Wait a second to start up
$loops = 10;
$avg = 0;
for ($i = 0; $i < $loops; $i++) {
$start = microtime(true);
for ($c = 0; $c < 1000; $c++) { // the 1000 may vary depending on the function
theFunction();
}
$end = microtime(true);
echo "Take $i: " . ($end-$start) . "s\n";
$avg *= $i;
$avg += $end - $start;
$avg /= $i + 1;
}
echo "Average: " . $avg . "s\n";
?>
</code></pre>
<p>Is this a good way to test performance of a function in PHP? It returns about the same result all the time, within a margin of ~5% when the server does nothing else.</p>
<p>Let's assume the environment is clean (i.e. the server doesn't have to do anything else in the meanwhile), would this code be good for testing, or does it count too much or too little?</p>
|
[] |
[
{
"body": "<p>I don't see any immediate problems with it, but I would probably simplified it a bit. Not sure why you're doing it in two loops like that, but I might be missing something of course :)</p>\n\n<pre><code><?php\n$loops = 10000;\n\n$start = microtime(true);\n\nfor ($i = 0; $i < $loops; $i++)\n theFunction();\n\n$total = microtime(true) - $start;\n$avg = $total / $loops;\n\necho \"Average: \" . $avg . \"s\\n\";\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T08:45:05.320",
"Id": "41984",
"Score": "0",
"body": "But now the loop takes time too! :) I have the two loops to check if something else happens on the server, which might give an extreme."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T08:48:10.363",
"Id": "41985",
"Score": "0",
"body": "The loop takes time? The for statement itself should take close to zero amount of time compared to your function. How are you checking if something else happens on the server exactly? The only technical difference I see between these two is that yours does more arithmetic."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T08:50:01.403",
"Id": "41986",
"Score": "0",
"body": "It would depend on the function how much time the loop takes. If you're comparing, say, single or double quotation marks, this might give problems. When you see all results like 50ms and one like 500ms, you'd know that line isn't trustworthy."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T09:58:32.510",
"Id": "41987",
"Score": "1",
"body": "If you're comparing things like singe vs double quotation marks I'd recommend you spend your time on something else :p Seriously, the `for` loop really shouldn't matter. If you're looking for speeds requiring this level of optimization you'd probably be better off using a different language than PHP."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-11T14:31:48.133",
"Id": "42346",
"Score": "0",
"body": "I wrote a class that will take care of the timing for you: (https://github.com/jsanc623/PHPBenchTime). Will add an answer below using my benchmark timer class mixed with the answer from @Svish"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T08:44:00.483",
"Id": "27079",
"ParentId": "27078",
"Score": "2"
}
},
{
"body": "<p>Extending Svish's answer to utilize my <a href=\"https://github.com/jsanc623/PHPBenchTime\" rel=\"nofollow\">PHP benchmark timer class</a>:</p>\n\n<pre><code><?php\nrequire('PHPBenchTime.php');\nuse PHPBenchTime\\Timer as Timer;\n$Benchmark = new Timer;\n\n$Benchmark->Start();\n\nfor ($i = 0; $i < 10000; $i++){\n theFunction();\n }\n\n$time = $Benchmark->End();\n\necho \"Total: \" . $time['Total'] . \"s\\n\";\necho \"Average: \" . $time['Total'] / 10000 . \"s\\n\";\n</code></pre>\n\n<p>or, using named laps:</p>\n\n<pre><code><?php\nrequire('PHPBenchTime.php');\nuse PHPBenchTime\\Timer as Timer;\n$Benchmark = new Timer;\n\n$Benchmark->Start();\n\nfor ($i = 0; $i < 10000; $i++){\n theFunction();\n $Benchmark->Lap(\"Lap #\" . $i);\n }\n\n$time = $Benchmark->End();\n\necho \"Total: \" . $time['Total'] . \"s\\n\";\necho \"Average: \" . $time['Total'] / 10000 . \"s\\n\";\necho \"Laps: \\n\";\nforeach($time['Laps'] as $key => $value){\n echo $key . \" \" . $value . \"s\\n\";\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-11T19:28:55.160",
"Id": "42364",
"Score": "1",
"body": "Won't these method calls and stuff kind of affect the timing though? At least considering he's worried about the `for` loop..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-11T20:40:25.713",
"Id": "42369",
"Score": "0",
"body": "The second example (with the named laps) will affect timing, but not that greatly. I've had success with 250k loops and a deviation of about a quarter to a half a second. The first sample without the named laps will not affect timing. But like you said - if he's worried about the for loop or the performance gains between using single and double quotes, he's better off looking at other avenues of optimization (language, stack, jit, hardware, refactoring, etc)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-11T14:38:18.407",
"Id": "27270",
"ParentId": "27078",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "27079",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T08:19:44.217",
"Id": "27078",
"Score": "1",
"Tags": [
"php",
"optimization",
"performance",
"php5"
],
"Title": "Performance testing in PHP"
}
|
27078
|
<p>I am an amateur programmer and I tried coding <a href="http://www.codechef.com/problems/RGPVR302" rel="nofollow">this problem</a> using the TurboC++ IDE (though my code is in C), but the site's compiler throws a "TIME LIMIT EXCEEDED" error. How can I optimize my code further?</p>
<pre><code>#include<stdio.h>
#include<math.h>
int main()
{
long int n,j,k,sqt,tot,t,i,c;
scanf("%ld",&t);
for(i=0;i<t;i++)
{
scanf("%ld",&n); tot=n;
for(k=1;;k++)
{c=0;
for(j=k;j>=2;j--)
{
if((k%j)==0)
{ if(((long)sqrt(j)*(long)sqrt(j)!=j))
{c=0;}
else {c++;break; }
}
}
if(c==0)
{tot--;}
if(tot==0) {printf("%ld\n",k);break;}
}
}
return 0;
}
</code></pre>
<p>Please do tell me if the code is wrong.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T13:54:37.617",
"Id": "42012",
"Score": "0",
"body": "Have you tried your code on some sample inputs? Does it seem to work?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T14:17:39.117",
"Id": "42016",
"Score": "0",
"body": "@svick yes it does work for all those that i tried"
}
] |
[
{
"body": "<ol>\n<li>You need to pre-calculate all square-free integers below the greatest in input (in test it's 100) and don't calculate that for every input value. </li>\n<li>You need a very fast precalculation algorithm like a modified Sieve of Eratosthenes. </li>\n<li><p>Don't forget about the time limit - it's 8 sec. only (and not on the top hardware, I assume). Benchmark your code using the following testcase:</p>\n\n<pre><code>1\n10000000\n</code></pre></li>\n<li><p>If you want to find past solutions, <a href=\"http://www.codechef.com/RGPV3/problems/RGPVR302/\" rel=\"nofollow\">take it here</a>.</p></li>\n<li>If you want to see the explanation, read <a href=\"http://community.topcoder.com/tc?module=Static&d1=match_editorials&d2=srm190\" rel=\"nofollow\">this topcoder editorial about the problem SquareFree</a>.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T14:20:20.760",
"Id": "42018",
"Score": "0",
"body": "thanks a lot for ur response and for introducing me to the Sieve of Eratosthenes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T14:23:04.317",
"Id": "42020",
"Score": "0",
"body": "and thanks for taking the trouble to find all this..."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T13:50:02.197",
"Id": "27092",
"ParentId": "27085",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "27092",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T12:53:17.990",
"Id": "27085",
"Score": "1",
"Tags": [
"optimization",
"c",
"beginner",
"programming-challenge"
],
"Title": "Square free Integer"
}
|
27085
|
<p>I am creating a C# service that will be doing some specialized processing of data coming into our ODS (Operational Data Store) DB. To support this, I’m building a DAL that will be used to access our ODS. In my DAL, I’ll have a number of GetItem (get a single item) and GetList (get a list of items) methods with a number of overrides to support a number of combinations of parameters for each method. </p>
<p>I was think that instead of having a number of overrides, I would do the following, using GetList as an example, using an Expression as the only parameter:</p>
<pre><code>/// <summary>
/// Gets a list of Marker entities based on a predicate.
/// </summary>
/// <param name="predicate">The predicate</param>
/// <returns>List of Marker entities</returns>
public List<Entities.Marker> GetList(Expression<Func<MarkerRecord, bool>> predicate)
{
return this.Database.Marker.Where(predicate).Map();
}
</code></pre>
<p>And it would be called like this:</p>
<pre><code>MarkerData markerData = new MarkerData();
var markerList = markerData.GetList(row => row.ReadTime >= new DateTime(2012, 1, 7));
</code></pre>
<p>I could even modify this to make it generic to handle any data type. While this solution offers flexibility and saves some coding, something tells me I'm violating one or more best practices, perhaps like separation of concerns by passing code as data. Do you see any problems with this approach?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T13:12:53.027",
"Id": "42003",
"Score": "0",
"body": "This is just my opinion, but this kind of expression passing should be handled outside of the DAL in a separate layer. When you introduce this kind of thing into the DAL is can harm maintainability."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T13:13:40.103",
"Id": "42004",
"Score": "0",
"body": "I don't think you are violating anything with that code, but you do lose something with that approach: explicitness. Where in the overloads variant you know exactly which way your ODS will be called, now you are moving that knowledge/responsibility further up the chain. Is there a specific reason you want to do this? Are there too many overloads?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T13:22:07.987",
"Id": "42005",
"Score": "0",
"body": "IMO this is a flexible variant of the Specification pattern, and many of the repository patterns on L2SQL or EF use this approach.\nThe only downside is that it does allow the caller to execute fairly arbitrary queries against the database and is can be difficult to 'constrain' (e.g. to prevent too much data being returned, or non-indexed columns from being searched), so I would use internal to your app, but not expose it as an external service etc.\nAnother potential consideration is whether to materialize the result (as you've done), or leave the result as an `IQueryable<>`, to allow chaining."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T13:22:59.643",
"Id": "42006",
"Score": "0",
"body": "Have a look here: http://www.dofactory.com/Patterns/Patterns.aspx. These are .Net \"gang of four\" design patterns. Tried and tested, may help you find something to fit your need? Your probably after the **creational patterns**"
}
] |
[
{
"body": "<p>As you've discovered complex DALs are ugly to build because they are just an uninteresting hard to maintain bunch of plumbing :(</p>\n\n<p>Fortunately some smart guys have built <strong>generics DALs</strong> that you can leverage to do almost all the operations like <strong>projecting</strong> and <strong>filtering</strong> you want.</p>\n\n<p>When possible they will be processed on the <strong>server side</strong> which can be a huge gain in performance because you don't have to pass enormous quantity of data around, just the result you want to further process or display to the user.</p>\n\n<p>Have a look at <strong>NHibernate</strong> which offers the kind of stuff you're building plus many more.</p>\n\n<p>In my opinion he is the best on the market but there is some interesting challengers like <strong>Entity framework</strong> from the fourth version.</p>\n\n<p>And before asking yourself if you're violating any good practices, principle or dogma, rather ask if it could cause any issue in term of code quality (readability, maintainability, robustness...).</p>\n\n<p>We other geeks are too focused on what is best rather than on what should be done now, it personally took me (a lot of) years, and some experience in front office development, to realize that ... but I'm not completely cured. ;)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T13:29:32.227",
"Id": "27089",
"ParentId": "27088",
"Score": "2"
}
},
{
"body": "<p>If the alternative is having overloads like:</p>\n\n<pre><code>public List<Entities.Marker> GetListByReadTime(DateTime minReadTime)\n</code></pre>\n\n<p>or something like that, then I think your approach is better. Though it's also going to be more difficult to implement (because you have to parse the <code>Expression</code>), so you should consider if the effort is worth it (it most likely will be).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T13:59:49.813",
"Id": "27093",
"ParentId": "27088",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T13:09:50.977",
"Id": "27088",
"Score": "4",
"Tags": [
"c#",
"design-patterns"
],
"Title": "Am I violating any sound coding principles with this approach?"
}
|
27088
|
<p>Below you'll find a Symfony2 service I wrote to assist in handling the Library entity. Each user in my app has a personal library where one can upload items to and a purchased library, that contains items one has purchased. Both libraries fall under a parent library.</p>
<p>At several points in my controller, I need to get the library for the user to save data. If the library doesn't exist yet, I want to create it.</p>
<p>The two <code>switch</code>es in the <code>getUserLibrary()</code> function especially bother me. </p>
<pre><code><?php
namespace Smoovi\SmooviBundle\Entity\Manager;
use Doctrine\ORM\EntityManager;
use Smoovi\SmooviBundle\Entity\Library,
Smoovi\UserBundle\Entity\User;
class LibraryManager
{
const TYPE_PURCHASED = 1;
const TYPE_PERSONAL = 2;
protected $em;
public function __construct(EntityManager $em)
{
$this->em = $em;
}
/**
* Get a user's personal library
*
* @param \Smoovi\UserBundle\Entity\User $user
* @return Library
*/
protected function getPersonalLibrary($user)
{
return $this->getUserLibrary($user, self::TYPE_PERSONAL);
}
/**
* Get a user's library for purchased objects
*
* @param \Smoovi\UserBundle\Entity\User $user
* @return Library
*/
public function getPurchasedLibrary($user)
{
return $this->getUserLibrary($user, self::TYPE_PURCHASED);
}
/**
* Get or create a library based on $type
*
* @param User $user
* @param $type
* @return Library
* @throws \Exception
*/
protected function getUserLibrary(User $user, $type)
{
$libRepo = $this->em->getRepository('SmooviSmooviBundle:Library');
// we first try to find the user's parent library
// if not, create it
/** @var \Smoovi\SmooviBundle\Entity\Library $topLibrary */
$topLibrary = $libRepo->findOneBy(array('user' => $user, 'parent' => null));
if (is_null($topLibrary)) {
$library = new Library();
$library
->setUser($user)
->setName($user->getFirstname()."'s Library")
->setIndex(1)
;
$this->em->persist($library);
}
// look for the sublibrary
// create it if necessary
$where = array('user' => $user, 'parent' => $topLibrary);
switch($type) {
case self::TYPE_PURCHASED:
$where['purchased'] = true;
$libraryName = 'Purchases';
break;
case self::TYPE_PERSONAL:
$where['personal'] = true;
$libraryName = 'Objects';
break;
default:
throw new \Exception('Library subtype not implemented');
}
/** @var \Smoovi\SmooviBundle\Entity\Library $subLibrary */
$subLibrary = $libRepo->findOneBy($where);
if (is_null($subLibrary)) {
$subLibrary = new Library();
$subLibrary
->setParent($topLibrary)
->setUser($user)
->setName($libraryName)
->setIndex(1)
;
switch($type) {
case self::TYPE_PURCHASED:
$subLibrary->setPurchased(true);
break;
case self::TYPE_PERSONAL:
$subLibrary->setPersonal(true);
break;
default:
throw new \Exception('Library subtype not implemented');
}
$this->em->persist($subLibrary);
}
$this->em->flush();
return $subLibrary;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T13:52:10.067",
"Id": "42011",
"Score": "0",
"body": "I don't know PHP much, but can't these persist methods throw exceptions? How are they dealt with?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T14:09:19.220",
"Id": "42014",
"Score": "0",
"body": "They can throw exceptions indeed. They are not handled in this class yet (it's something I'm keeping for later)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T14:21:18.373",
"Id": "42019",
"Score": "0",
"body": "Well, I generally go the other way and handle them as soon as possible; when you do it \"after the fact\", you often find that your identation levels become a nightmare ;) Personal policy, of course, YMMV."
}
] |
[
{
"body": "<p>Switch statements can often be a sign that you need an extended class. Doctrine supports <a href=\"http://docs.doctrine-project.org/en/latest/reference/inheritance-mapping.html\" rel=\"nofollow\">Inheritance Mapping</a>. With some liberal re-factoring I created a PersonalLibrary and PurchasedLibrary, each which extend \"Library\". The various classes might look like this:</p>\n\n<pre><code>/**\n * @Entity(repositoryClass=\"LibraryRepository\")\n * @InheritanceType(\"SINGLE_TABLE\")\n * @DiscriminatorColumn(name=\"libraryType\", type=\"string\")\n * @DiscriminatorMap({1 = \"PurchasedLibrary\", 2 = \"PersonalLibrary\"})\n */\nclass Library\n{\n //abbreviated class. add the properties and setters/getters as needed\n\n /**\n * @param \\Smoovi\\UserBundle\\Entity\\User $user\n * @param null|Library $parent\n */\n public function __construct(User $user, Library $parent = null)\n {\n $this->setUser($user);\n $this->setParent($parent);\n $this->setIndex(1);\n }\n\n public function setUser(User $user)\n {\n $this->user = $user;\n $this->setName($user->getFirstname().\"'s Library\");\n }\n}\n\nclass PurchasedLibrary extends Library\n{\n public function __construct(User $user, Library $parent = null)\n {\n parent::__construct($user, $parent);\n $this->setLibraryType(1);\n }\n\n public function setUser(User $user)\n {\n $this->setUser($user);\n $this->setName('Objects');\n }\n}\n\nclass PersonalLibrary extends Library\n{\n public function __construct(User $user, Library $parent = null)\n {\n parent::__construct($user, $parent);\n $this->setLibraryType(2);\n }\n\n public function setUser(User $user)\n {\n $this->setUser($user);\n $this->setName('Purchases');\n }\n}\n\nclass LibraryRepository extends EntityRepository\n{\n /**\n * Get a user's library. If unable to create, return null.\n *\n * @param \\Smoovi\\UserBundle\\Entity\\User $user\n * @param int $type\n * @return null\\Library\n */\n public function getOrCreateLibrary(User $user, $type)\n {\n $parent = $this->getOrCreateParentLibrary($user);\n\n $sub = $this->findOneBy(array(\n 'user' => $user,\n 'parent' => $parent,\n 'libraryType' => $type\n ));\n if (! $sub) {\n $sub = $this->createNewLibrary($user, $type, $parent);\n if (! $sub) {\n return null;\n }\n }\n\n $this->persist($sub);\n\n return $sub;\n }\n\n public function createNewLibrary(User $user, $type, $parent = null)\n {\n switch ($type) {\n case 1:\n return new PersonaLibrary($user, $parent);\n break;\n case 2:\n return new PurchasedLibrary($user, $parent);\n break;\n }\n\n return null;\n }\n\n private function getOrCreateParentLibrary(User $user)\n {\n $parent = $this->findOneBy(array(\n 'user' => $user,\n 'parent' => null,\n 'libraryType' => null,\n ));\n if (! $parent) {\n $parent = new Library($user);\n }\n\n return $parent;\n }\n}\n</code></pre>\n\n<p><strong>Notes</strong>:</p>\n\n<ul>\n<li>I'm using a Library Repository instead of a Library Manager. It's how I'd do it but, your LibraryManager may be just fine too.</li>\n<li>I moved much of the behavior (deriving name, etc) into the setters of the Entities. This free's your Manager/Repository from this concern.</li>\n<li>I added user and parent to the base Library Entity constructor. I'm assuming that in your domain, a Library <em>must</em> have a user.</li>\n<li>It seems odd that \"Index\" is always 1</li>\n<li>It seems odd that a \"Top Level\" table does not seem to be purchased or personal.</li>\n<li>I would not flush the entity manager inside the those methods. Instead, I would let my calling code do it. The reason is that you may have other db operations to perform along with these. Postponing the flush operation allows you to do everything in 1 transaction.</li>\n<li>I renamed your method names to indicate that there could be side effects as a result of calling the method (get OR create).</li>\n<li>No need to persist parent. Persisting the sub (assuming associations are set up) should persist the parent.</li>\n<li>I think you'll always need at least 1 switch in there somewhere that is used to construct the new entity based on it's type.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-07T08:00:33.787",
"Id": "42099",
"Score": "0",
"body": "Thank you for your time and your answer. I really learned something from this! Concerning your \"odd\" remarks, absolutely right. There are some things that still need fixing. The index for example is something that's used with other Libraries, to order them. The top level is indeed, not purchased or personal."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T22:56:45.753",
"Id": "27119",
"ParentId": "27091",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T13:48:18.223",
"Id": "27091",
"Score": "2",
"Tags": [
"php",
"symfony2"
],
"Title": "Handling library entity"
}
|
27091
|
<p>One of the servlet in my web app takes parameters in the form <code>www.service.com/servletname/parameter1/parameter2</code>.</p>
<p>The first parameter is required and the second parameter is an integer.
I've made some code to validate the parameters but it looks really really messy. Is there a nicer and cleaner way I can write the following:</p>
<p>Thanks :)</p>
<pre><code>protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType(CONTENT_TYPE);
PrintWriter out = resp.getWriter();
int maximumResults = defaultMaxResults;
// check that parameters were provided
if (req.getPathInfo() == null)
{
out.println( JSONHelper.writeStatus(false, Status.TOO_FEW_ARGS.getMessage()));
return;
}
// seperate parameters
String[] parameters = req.getPathInfo().split(PARAMETER_SEPERATOR);
if (parameters.length < MIN_NUM_PARAMETERS)
{
out.println( JSONHelper.writeStatus(false, Status.TOO_FEW_ARGS.getMessage()));
return;
}
// validate parameters
if (parameters.length > MIN_NUM_PARAMETERS)
{
try
{
maximumResults = Integer.parseInt(parameters[2]);
} catch (NumberFormatException nfe)
{
out.println( JSONHelper.writeStatus(false, Status.INVALID_MAX_RESULTS.getMessage()));
return;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>In my opinion you could use the Regex to solve this</p>\n\n<pre><code>protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {\n\n resp.setContentType(CONTENT_TYPE);\n PrintWriter out = resp.getWriter();\n int maximumResults = defaultMaxResults;\n\n // you could create pathPattern as a Class field\n Pattern pathPattern = Pattern.compile(\"http://www.hostname.com/servletname/([^/]+)(/(\\\\d+))?$\");\n\n Matcher m = pathPattern.matcher(req.getPathInfo());\n if(m.find()) {\n String param1 = m.group(1);\n String param2 = m.group(2); // NOTE param2 may be null\n // TODO your business here\n return;\n } else {\n // TODO throw your exception here\n }\n\n}\n</code></pre>\n\n<p>You can change the pathPattern to meet your need. Hope this help. Feel free to response.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-09T14:00:26.443",
"Id": "42211",
"Score": "0",
"body": "It's a viable solution but I'd like to quote: `Some people, when confronted with a problem, think “I know, I'll use regular expressions.” Now they have two problems.` I think it's a little too much to check parameters."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-10T03:02:36.480",
"Id": "42244",
"Score": "0",
"body": "That's right, but I think this regexp is simple enough for you to test, it is not a real problem here.\nIs your second parameter required too? If not, you can change the regexp to `http://www.hostname.com/servletname/([^/]+)/(\\\\d+)$`, you have **one** check now."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-10T08:11:12.717",
"Id": "42263",
"Score": "0",
"body": "Your code worked perfect. I used it with another page and got the regex wrong which was a bit of a hassle. In the end, I'd prefer something that's easy to read though I do think your answer is a valid way of cleaning up the code."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-07T03:00:32.790",
"Id": "27129",
"ParentId": "27094",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "27129",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T14:08:33.410",
"Id": "27094",
"Score": "2",
"Tags": [
"java",
"servlets"
],
"Title": "How can I tidy up this servlet parameter check code?"
}
|
27094
|
<p>I found this code in our project and it just feels like the wrong way to do what it seems to be doing</p>
<pre><code>id<NSFastEnumeration> results = [info objectForKey: ZBarReaderControllerResults];
ZBarSymbol *symbol = nil;
for (symbol in results) {
// this just selects the first symbol in the results
}
</code></pre>
<p>Presumably it actually doesn't select the first symbol - instead it selects the last one!</p>
<p>But there must be a better way. I don't quite know what</p>
<pre><code>[info objectForKey: ZBarReaderControllerResults]
</code></pre>
<p>returns, but I'm not too bothered either. Is there a way that I can do the above code without having to loop through all possible results?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T16:20:07.943",
"Id": "42526",
"Score": "0",
"body": "I'd have to see the rest of the code (inside the for loop) to tell you what it is doing, but if you simply put a `break;` command in the loop, then it selects the first symbol."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-14T13:17:00.873",
"Id": "42611",
"Score": "0",
"body": "Hey, there is nothing in the loop. That's just it. Is that the best way? Add a \"break\"? Is there no way to just select the first object?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-14T14:05:25.393",
"Id": "42615",
"Score": "0",
"body": "Yeah, the best way to get the first object would be to add a break in the loop, unless you know more about the object. I.e. if the results is always an array, then you could cast it to that and use the firstObject method. Unfortunately, the NSFastEnumeration protocol doesn't provide anything like that."
}
] |
[
{
"body": "<p>ZBarSDK is the only place I've ever seen <code>NSFastEnumeration</code>. I don't know a whole lot about it, nor do I know exactly why ZBarSDK was designed to be used in this way.</p>\n\n<p><code>NSFastEnumeration</code> isn't any faster than using a <code>forin</code> loop. It is faster than a regular <code>for</code> or <code>while</code> (or <code>do-while</code>) loop, but not faster than a <code>forin</code>.</p>\n\n<p>In a <code>forin</code> loop, we're using regular Objective-C collections, and <code>NSArray</code> has a <code>firstObject</code> and <code>lastObject</code>.</p>\n\n<p>But if the real question is (and should be) how do I improve this code (more than just specifically grabbing a single object out of an <code>NSFastEnumeration</code>), then the answer is to use <a href=\"https://developer.apple.com/library/ios/documentation/AVFoundation/Reference/AVCaptureMetadataOutput/Reference/Reference.html\" rel=\"nofollow\">AVCaptureMetadataOutput (official documentation)</a>, which was introduced in iOS7.</p>\n\n<p>ZBarSDK has an iOS7 memory leak. Also, I don't know about compiled on-device size, but when I removed it from my project, it saved about 1.4mb from the project size.</p>\n\n<p>Meanwhile, <code>AVCaptureMetadataOutput</code> has many advantages over <code>ZBarSDK</code>.</p>\n\n<ul>\n<li>It's slightly easier to use... and it's simple to use if you're already familiar with video capture in iOS.</li>\n<li>It leaves a smaller footprint in terms of storage space your app takes up on a device.</li>\n<li>Even without ZBarSDK's memory leak, <code>AVCaptureMetadataOutput</code> has a smaller memory footprint.</li>\n<li><code>AVCaptureMetadataOutput</code> seems to scan barcodes faster and a farther distances than what I could manage with <code>ZBarSDK</code>.</li>\n<li>ZBarSDK doesn't support 64-bit processors at all. <code>AVCaptureMetadataOutput</code> however does.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T12:24:42.937",
"Id": "72737",
"Score": "0",
"body": "For an example on using `AVCaptureMetadataOutput`: http://codereview.stackexchange.com/questions/42252/how-can-i-improve-this-avcapturemetadataoutputobjects-wrapper"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T03:06:13.250",
"Id": "42099",
"ParentId": "27096",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T15:48:54.967",
"Id": "27096",
"Score": "3",
"Tags": [
"objective-c",
"ios"
],
"Title": "Select first or last object from id<NSFastEnumeration>"
}
|
27096
|
<p>I have to create a program in which <code>t</code> sets of <code>m</code> and <code>n</code> will be given by the user. For each set, we have to generate all prime numbers between <code>m</code> and <code>n</code>. This code is successfully executed with the correct output, but I have to reduce the time limit for a large data range.</p>
<pre><code>#include<math.h>
#include<stdio.h>
int isPrime(int k);
int j;
int isPrime(int k)
{
for(j=2; j<=(int)sqrt(k); j++)
{
if(k%j==0)
return 0;
}
return 1;
}
int main()
{
int u,i,t,m,n,k;
scanf("%d", &t);
while(t--)
{
scanf("%d %d", &m, &n);
for(i=m;i<=n;i++)
{
u = isPrime(i);
if (u == 1)
printf("%d\n", i);
}
}
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T17:19:17.133",
"Id": "42036",
"Score": "2",
"body": "First off, indent your program properly."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T22:03:19.060",
"Id": "42056",
"Score": "2",
"body": "@WilliamMorris, when people format their code badly, that's something that should be pointed out in a review, not silently corrected."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-07T11:31:33.570",
"Id": "89647",
"Score": "0",
"body": "Dunno if this is a SPOJ question but I myself had hard time with this.\nFirst look into [Seive of Eratosthenes](http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes).\nAlso have a look at my [code and question about the same](http://codereview.stackexchange.com/questions/26916/decreasing-the-running-time).\nIt is still getting timed out but lets see if we can help each other."
}
] |
[
{
"body": "<p>The main problem is: the algorithm contains a lot of divisions and a lot of function calls. A division can be very time consuming.</p>\n\n<p>As Harish Ved said, the key is the <a href=\"http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes\" rel=\"nofollow\">sieve of Eratosthenes</a>. It is one of the simplest and fastest way do determine if a number is prime. With that method, the problem can be solved by zero division and function call.</p>\n\n<p>You should implement the sieve in the main function. You can find a lot of optimized examples on the internet. When You are done with that, You'll have an array, which contains the result of every <code>IsPrime()</code> method you can call. From that point, you only have to check an element of the array to know of a number is prime.</p>\n\n<p>Here You can find a sample sieve (this can be optimized, but probably this will be able to solve the problem in the given time limit too).</p>\n\n<p>You need a maximum value (<code>MAXVAL</code>), the primes smaller than that will be computed. </p>\n\n<pre><code>char *primes = (char*)malloc(MAXVAL*sizeof(char));\nprimes[0]=primes[1]=0;\nfor(i=2;i<MAXVAL;i++)\n primes[i]=1; //allocating memory and filling with 1\n\nfor (i=2;i<MAXVAL;i++)\n{\nif(primes[i])\nfor(j=i*2;j<MAXVAL;j+=i)\n primes[j]=0;\n} //setting the multiples of prime numbers to 0\n</code></pre>\n\n<p>This little algorithm will generate an array in wich the values at the primeth indexes will be 1, and other values will be 0. So after this, instead of calling Your <code>IsPrime</code> function with a lot of divisions, the prime check of <code>n</code> will look like</p>\n\n<pre><code>if(primes[n])\n</code></pre>\n\n<p>You can find a little working demonstration <a href=\"http://ideone.com/ncXu3t\" rel=\"nofollow\">HERE</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-07T21:18:47.417",
"Id": "27151",
"ParentId": "27097",
"Score": "1"
}
},
{
"body": "<p>For <a href=\"http://www.spoj.com/problems/PRIME1/\" rel=\"nofollow\">this SPOJ problem</a> with <code>(1 <= m <= n <= 1000000000, n-m<=100000)</code> limits you will have to use an <em>offset</em> <a href=\"http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes\" rel=\"nofollow\">sieve of Eratosthenes</a>. </p>\n\n<p>Since <code>n <= 10^9</code>, to sieve any range under <code>n</code> it is sufficient to have just the primes below its square root, <code>31622</code>, pre-calculated. There are <a href=\"http://www.wolframalpha.com/input/?i=PrimePi%5b31622%5d\" rel=\"nofollow\">only 3401 such primes</a>, the <a href=\"http://www.wolframalpha.com/input/?i=Prime%5b3401%5d\" rel=\"nofollow\">biggest being 31607</a>. </p>\n\n<p>So, <strong>A.</strong> <em>pre-calculate the 3401 primes below 31622.</em></p>\n\n<p>Since <code>n-m<=100000</code>, you can <strong>B.</strong> <em>have one array of 100000 booleans preallocated, and sieve it by those primes, as in sieve of Eratosthenes, for each pair <code>m,n</code>.</em></p>\n\n<p>As an easy optimization, use that sieve segment to represent just odds, without evens: an entry at position <code>i</code> will represent <code>odd(m) + 2*i</code> where <code>odd(m)</code> is the lowest odd number not below <code>m</code> in value. <a href=\"http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes#Implementation\" rel=\"nofollow\">Sieve</a> this segment by odd primes only. No even number above 2 is ever a prime:</p>\n\n<pre><code>for i = 3, 5 ... √n in primes:\n for j = i^2, i^2+2*i, i^2+4*i ... inside the segment m ... n:\n A{j} := false\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-11T09:41:27.147",
"Id": "27260",
"ParentId": "27097",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T15:55:16.140",
"Id": "27097",
"Score": "2",
"Tags": [
"c",
"primes",
"time-limit-exceeded"
],
"Title": "Reducing time limit for prime number program"
}
|
27097
|
<p>This code parses a text file, replacing special tokens marked as $(token) with some replaced text. The $ symbol can be escaped by entering a double $$. In the example a user enters a text file containing tokens to replace and a separate mapping file with, for instance, colour:red to denote how to replace a token.</p>
<p>Some remarks I have is that is is not using any OO really. Does it need to be?</p>
<pre><code>#include <fstream>
#include <iostream>
#include <vector>
#include <map>
#include <string>
static void readToken(std::istream& strm, std::vector<char>& token)
{
while(strm) {
int c (strm.get());
token.push_back(c);
if(')' == c) break;
}
}
static void lookup_replacement(const std::map<std::string,std::string>& token_map,
const std::vector<char>& key, std::vector<char>& value) {
if(key.size() > 3) { //3 chars min are '$', '(' and ')'
std::map<std::string,std::string>::const_iterator it = token_map.find(std::string(key.begin()+2, key.end()-1));
if(it != token_map.end())
value.insert(value.end(), it->second.begin(), it->second.end());
}
}
static bool readTo(std::istream& strm, std::vector<char>& buf, const char term[])
{
bool ret(false);
while(strm) {
int c (strm.peek());
if(strchr(term, c)) {
strm.get();
int c2(strm.peek());
if(c != c2) {
strm.unget();
ret = true;
break;
}
}
strm.get();
buf.push_back(c);
}
return ret;
}
static void create_mapping(std::ifstream& strm, std::map<std::string,std::string>& tokens) {
if(strm.good()) {
std::string line;
while(std::getline(strm, line)) {
std::string::size_type pos = line.find_first_of(':');
if(pos != std::string::npos)
tokens.insert(std::make_pair<std::string, std::string>(line.substr(0, pos), line.substr(pos+1)));
}
}
}
int main() {
std::map<std::string,std::string> token_map;
typedef std::map<std::string,std::string>::iterator map_iter;
std::cout << "Enter path to text file to replace\nTokens to be replaced should be of form: $(token)\n";
std::string file;
std::cin >> file;
std::cout << "Enter path to file with target token <-> replacement token in format:\n"
"<toreplace1>:<replacement1>\n<toreplace2>:<replacement2>\netc\n";
std::string mapfile;
std::cin >> mapfile;
std::ifstream strmmap(mapfile.c_str());
create_mapping(strmmap, token_map);
// replaced text
std::vector<char> replaced;
std::ifstream strm(file.c_str());
if(!strm.bad()) {
while(!strm.eof()) {
if(readTo(strm, replaced, "$")) {
std::vector<char> token;
readToken(strm, token);
std::vector<char> replace_tok;
lookup_replacement(token_map, token, replace_tok);
if(!replace_tok.empty())
replaced.insert(replaced.end(), replace_tok.begin(), replace_tok.end());
}
}
}
//print out replaced text
std::cout << "your replaced text file\n";
std::vector<char>::iterator pit = replaced.begin();
while(pit != replaced.end())
std::cout << *pit++;
return 0;
}
</code></pre>
<p>The example input file I was using:</p>
<blockquote>
<p>Once upon a $(place1) there was a $(adjective1) $(colour) $(animal).</p>
<p>Do you have a $$</p>
<p>You have enemies? Good. That means you've stood up for something,
sometime in your life. by $(author) on $(date)</p>
<p>A fanatic is one who can't change his mind and won't change the
subject. By $(author)</p>
</blockquote>
<p>And the mapping file:</p>
<blockquote>
<pre class="lang-none prettyprint-override"><code>place1:time
adjective1:cunning
colour:brown
animal:fox
author:Winston Churchill
date:06/06/2013
</code></pre>
</blockquote>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-08T00:39:55.520",
"Id": "42163",
"Score": "0",
"body": "Why are you using vector<char> instead of string for the token etc?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-08T04:49:01.837",
"Id": "42169",
"Score": "0",
"body": "So what happens with `$X`? You replacement thing is `$(<X>)`. So the questions are: 1) What is `$()` 2) what is `$<Y>` (Y => any character not '('). 3) What happens when the replacement is not terminated `$(<Z>\\n`"
}
] |
[
{
"body": "<p>This looks pretty good as it is. No project strictly \"needs\" OOP, especially one of this size. But here is one way to frame it in OOP -</p>\n\n<p>Create a <code>Mapped</code> class and a <code>Mapper</code> class, both accepting stream references in their constructors. Perhaps constructor overloads accepting filenames. <code>Mapped.Map</code> could accept a <code>Mapper</code> instance reference, and use it to do the string replacement. When both objects are destroyed, both streams are closed.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T19:51:59.967",
"Id": "27115",
"ParentId": "27098",
"Score": "0"
}
},
{
"body": "<p>Its a little heavy on the code side.</p>\n\n<p>Your definition of a token still leaves possibilities that you have not defined.</p>\n\n<pre><code>$$ : Replace with $ Fine\n$(<X>) : Replace with the mapped `<X>` Fine.\n\n$(<stuff>\\n : No closing ')' Error\n$() : What happens with no identifier. Error\n$<X> : Some other character after '$' that is not '(' or '$' Error\n</code></pre>\n\n<p>Especially your stream handling.<br>\nIts usually bad practice to test for <code>.good()</code>, <code>.bad()</code> or <code>.eof()</code> during normal processing. You want to test these after things go wrong to generate the appropriate error message or not. Usually stream code looks like this:</p>\n\n<pre><code>while(std::getline(stream, line))\n{\n // correctly read a line\n}\n\n// or\n\nwhile(stream >> value >> value2 >> value3 >> etc)\n{\n // correctly read a value from the stream\n}\n</code></pre>\n\n<p>You can use OO to compartmentalize your mapping.<br>\nPersonally I would combine your <code>mapper</code> and <code>mapped</code> class into a single class.</p>\n\n<pre><code>class Mapper\n{\n // Class contains a map from tokens => value\n // used via replace() to replace all tokens $(<X>) in string\n // with the values contained in the map.\n\n std::map<std::string, std::string> replaceMap;\n public:\n Mapper(std::string const& fileName)\n {\n // Read all the mapping values from the file.\n\n std::ifstream mapFile(fileName.c_str());\n std::string line;\n\n while(std::getline(mapFile, line))\n {\n // Each line in the file contains a token/value mapping\n std::stringstream linestream(line);\n\n std::string token;\n std::string value;\n\n std::getline(linestream, token, ':');\n std::getline(linestream, value);\n\n // Save the token and value\n replaceMap[token] = value;\n }\n }\n\n std::string replace(std::string const& line)\n {\n std::string result;\n std::size_t last = 0;\n\n // Search for the '$' char repeatedly.\n for(std::size_t find = line.find('$');find != std::string::npos;last=find, find=line.find('$', find))\n {\n // Copy the inert text from line\n // into the result\n result += line.substr(last, (find-last));\n\n // If the next character is a '(' then search for the closing ')'\n //\n // If we don't find a token `$(<X>)` then ignore the '$' and treat\n // it like a normal character. Note If <X> has no mapping then\n // we replace it with the empty string. Note if <X> is empty it is\n // is still value.\n\n bool hit = false \n if ((find + 1 < line.size()) && line[find + 1] == '(')\n {\n std::size_t end = line.find(')', find);\n if (end != std::string::npos)\n {\n std::string key = line.substr(find+2, end-find-2);\n result += replaceMap[key];\n find = end + 1;\n hit = true;\n }\n }\n\n if (!hit)\n {\n // Token was not found.\n // Put the '$' on the output and move on.\n result += '$';\n find++;\n }\n }\n // Add the rest of the inert string to the output\n result += line.substr(last);\n\n return result;\n }\n};\n</code></pre>\n\n<p>This makes it easy to use:</p>\n\n<pre><code>int main(int argc, char* argv[])\n{\n Mapper mapper(argv[1]);\n\n std::ifstream input(argv[2]);\n std::string line;\n while(std::getline(input, line))\n {\n std::string result = mapper.replace(line);\n std::cout << result << \"\\n\";\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-08T05:42:07.740",
"Id": "27160",
"ParentId": "27098",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "27160",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T16:43:44.660",
"Id": "27098",
"Score": "2",
"Tags": [
"c++",
"parsing"
],
"Title": "Replacing tokens in a text file with replaced text"
}
|
27098
|
<p>I have recently started using Ruby and would like to hear your take on the following piece of code.</p>
<pre><code>class Generator
def initialize
@context = nil
end
def start(params)
@context = Context.new params
image = create_image
if cache_update_request?
upload image
end
return image
end
def create_image
composer = Composer.new @context
execution_context = ExecutionContext.new(@context, composer)
execution_context.render
end
def upload(image)
uploader = CompositorCommons::CacheUpdater.new
filename = @context.parameters[:cache]
location = 'dual/' + filname
type = 'image/jpeg'
uploader.upload(image,location,type)
end
def cache_update_request?
@context.parameters.has_key?(:cache)
end
end
</code></pre>
|
[] |
[
{
"body": "<p>Looks OK, except for a few small notes on style.</p>\n\n<ul>\n<li><p>Don't <code>return</code>, just let things fall off the end of methods:</p>\n\n<p>This...</p>\n\n<pre><code>def start(params)\n @context = Context.new params\n image = create_image\n if cache_update_request?\n upload image\n end\n return image\nend\n</code></pre>\n\n<p>Could be this:</p>\n\n<pre><code>def start(params)\n @context = Context.new params\n image = create_image\n upload image if cache_update_request?\n image\nend\n</code></pre></li>\n<li><p>Drop some of the temporary variables</p>\n\n<p>While I'm not generally a fan of excessively long one-liners, I think several of your multiline methods could be written using a fraction of the characters as one-liners:</p>\n\n<p>This...</p>\n\n<pre><code>def create_image\n composer = Composer.new @context\n execution_context = ExecutionContext.new(@context, composer)\n execution_context.render\nend\n</code></pre>\n\n<p>Could be this:</p>\n\n<pre><code>def create_image\n ExecutionContext.new(@context, Composer.new @context).render\nend\n</code></pre>\n\n<p>This...</p>\n\n<pre><code>def upload(image)\n uploader = CompositorCommons::CacheUpdater.new\n filename = @context.parameters[:cache]\n location = 'dual/' + filname\n type = 'image/jpeg'\n uploader.upload(image,location,type)\nend\n</code></pre>\n\n<p>Coule be this:</p>\n\n<pre><code>def upload(image)\n uploader = CompositorCommons::CacheUpdater.new\n filename = @context.parameters[:cache]\n uploader.upload(image, \"dual/#{filename}\", \"image/jpeg\")\nend\n</code></pre></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T17:43:09.103",
"Id": "27102",
"ParentId": "27099",
"Score": "1"
}
},
{
"body": "<p>Your code is nice overall, but here are my two cents : </p>\n\n<ul>\n<li>initializing instance variables before using them is not mandatory, so <code>initialize</code> as you implemented it is useless. A call to <code>@context</code> if it is not initialized will return <code>nil</code>.</li>\n<li><p>Since uninitialized instance variables return <code>nil</code>, you may have have problem when doing things like <code>@context.parameters[:cache]</code>. As such, i would advise to initialize them... in <code>initialize</code> :</p>\n\n<pre><code>class Generator\n def initialize( params )\n @context = Context.new( params )\n end\nend\n</code></pre></li>\n</ul>\n\n<p>This also leaves you the latitude to inspect the params and throw an <code>ArgumentError</code> if some usefull params are not present.</p>\n\n<ul>\n<li><p>I think your object has mixed responsibilities. What does it represent ? It is not clear at first glance. Is it an uploader, an image ? It looks like a Service to me (the process is stateless), or maybe a \"context\" in DCI slang. Maybe your structure could more accurately represent this :</p>\n\n<pre><code>module ImageGeneratorService\n\n def self.start( params )\n cache = params.delete( :cache )\n image = ImageFactory.create_from_params( params )\n CacheService.cache_image( image, cache ) if cache\n image\n end\n\nend\n</code></pre></li>\n</ul>\n\n<p>... ok, it's a bit too much, but i think you get the spirit. YMMV</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T19:21:23.970",
"Id": "42051",
"Score": "0",
"body": "+1 for pointing out that `initialize` should be doing what it's in `start`. But -1 for those terribly unidiomatic spaces around parentheses."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-07T07:11:03.517",
"Id": "42095",
"Score": "0",
"body": "I used not to use parentheses at all... But then, there a are times you have to use them, and when you do it (when chaining ActiveRecord query methods, for instance) in my experience it is much more readable to add spaces, because arguments stand out. Then again, it's just a matter of taste... I usually adapt to whatever conventions my team use."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T18:34:01.223",
"Id": "27108",
"ParentId": "27099",
"Score": "2"
}
},
{
"body": "<p>It also feels like unless you really want to expose the <code>create_image</code>, <code>upload</code>, and <code>cache_update_request?</code> in a public interface, you should encapsulate them and make them private.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-14T05:07:40.397",
"Id": "27391",
"ParentId": "27099",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "27108",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T16:48:44.657",
"Id": "27099",
"Score": "1",
"Tags": [
"beginner",
"ruby",
"image"
],
"Title": "Image uploader and manager"
}
|
27099
|
<p>I am writing web application using flask framework + mongodb. I have an issue, should I use classes for my mongo entities or just use dictionaries for them.</p>
<pre><code>class School:
def __init__(self, num, addr, s_type):
self.num = num
self.addr = addr
self.s_type = s_type
</code></pre>
<p>or just create dictionary for any entity like:</p>
<pre><code>school = { "number" : request['number'] ,
"address": request['address'],
"type" : request['type'] }
</code></pre>
|
[] |
[
{
"body": "<p>I'm not familiar with that framework, but if there is more than one school and you are going to use Python to access those values (such as the school's address), I'd use a class. Think of it this way: Classes are usually meant to be instantiated, or at least to be a group of functions for a specific purpose.</p>\n\n<p>Instead of creating a dict for each school you simply instantiate the class:</p>\n\n<pre><code>MIT=School(1,'Cambridge','university')\nHarvard=School(2,'Cambridge','university')\n>>> MIT.address\n'Cambridge'\n>>> Harvard.s_type\n'university'\n</code></pre>\n\n<p>Or whatever pattern you are using.</p>\n\n<p>This way you can also add functions to it:</p>\n\n<pre><code>class School:\n def __init__(self, name, num, addr, s_type):\n self.num = num\n self.name = name\n self.addr = addr\n self.s_type = s_type\n def describe(self):\n print \"%s is a %s located at %s.\" % (self.name, self.s_type, self.address)\n def request(self,arg):\n request[arg] # I'm not sure if that's what you want, I copied it from the dict you had there\n\n>>> MIT.describe()\nMIT is a university located at Cambridge.\n>>> MIT.request('name')\n# Whatever that thing does\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T21:20:55.610",
"Id": "42055",
"Score": "1",
"body": "I understand your point. Also I can perform some functions like `def asDictionary():` or `def save():` to save it in mongo or than write function for saving in SQL database. Thank you :D"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T21:08:03.797",
"Id": "27116",
"ParentId": "27105",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "27116",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T18:09:24.143",
"Id": "27105",
"Score": "2",
"Tags": [
"python",
"mongodb",
"flask"
],
"Title": "Python flask web app, simplification"
}
|
27105
|
<p>We know when we call <code>HttpContext.Current.Response.Redirect("http://tvrowdy.in");</code> It throw an exception. Can we do it this way(working fine). Need suggestions and improvements.</p>
<pre><code>public static void ReferToPage(string strPageName)
{
try
{
HttpContext.Current.Response.Redirect(strPageName, false);
}
catch
{
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-07T03:09:37.703",
"Id": "42086",
"Score": "0",
"body": "It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, see the FAQ. http://codereview.stackexchange.com/faq#close"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-07T16:03:24.907",
"Id": "42126",
"Score": "1",
"body": "The code that you show is pointless, because sending `false` as the second parameter keeps the `Redirect` method from throwing an exception. There will never be any exception to catch (unless you call it too late so that the redirection is not possible any more)."
}
] |
[
{
"body": "<p>I'd recommend against using 'catch-all' blocks unless absolutely necessary. </p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/a8wa7sdt.aspx\" rel=\"nofollow\"><code>Response.Redirect</code></a> always throws a <code>ThreadAbortedException</code> by design (like it or not), unless you pass in the <code>false</code> for the second parameter. </p>\n\n<blockquote>\n <p>If you specify true for the <code>endResponse</code> parameter, this method calls the <code>End</code> method for the original request, which throws a <code>ThreadAbortException</code> exception when it completes. This exception has a detrimental effect on Web application performance, which is why passing false for the <code>endResponse</code> parameter is recommended. </p>\n</blockquote>\n\n<p>Any other exceptions it throws indicate a invalid parameter or bad program state. You probably don't want to just ignore these errors and move on as though nothing has happened. I recommend you just do this:</p>\n\n<pre><code>public static void ReferToPage(string strPageName)\n{\n HttpContext.Current.Response.Redirect(strPageName, false);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-07T08:17:58.087",
"Id": "42100",
"Score": "1",
"body": "Would removing try catch block impact on performance?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-07T13:30:34.190",
"Id": "42120",
"Score": "0",
"body": "@vikas It won't impact performance at all. Catch-all blocks are just bad practice."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T23:52:35.263",
"Id": "27127",
"ParentId": "27110",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T18:41:06.113",
"Id": "27110",
"Score": "-1",
"Tags": [
"c#",
".net",
"asp.net"
],
"Title": "How to optimize response.redirect in ASP.net"
}
|
27110
|
<p>Not so long ago I learned how to implement the minimax algorithm with alpha beta pruning, and even created a perfect Tic Tac Toe player. How can I improve this?</p>
<pre><code>public Best chooseMove(boolean side,int[]board,int alpha,int beta,int depth,int maxDepth){
Best myBest = new Best();
Best reply;
int num;
if(Board.checkGameOver(board)||depth==maxDepth){
Best fakeBest = new Best();
fakeBest.setScore(returnPositionScore(board));
return fakeBest;
}
if(side){
myBest.setScore(alpha);
num = numberOfEngine;
}
else{
myBest.setScore(beta);
num = numberOfOpponent;
}
ArrayList<Integer> availableMoves = new ArrayList<Integer>(searchAvailableMoves(board));
for(Integer move:availableMoves){
board[move.intValue()] = num;
reply = chooseMove(!side,board,alpha,beta,depth+1,maxDepth);
board[move.intValue()] = 0;
if(side&&reply.getScore()>myBest.getScore()){
myBest.setMove(move.intValue());
myBest.setScore(reply.getScore());
alpha = reply.getScore();
}
else if(!side&&reply.getScore()<myBest.getScore()){
myBest.setMove(move.intValue());
myBest.setScore(reply.getScore());
beta = reply.getScore();
}
if(alpha>=beta){
return myBest;
}
}
return myBest;
}
</code></pre>
|
[] |
[
{
"body": "<p>OK, here is a first cleanup...</p>\n\n<pre><code>public Best chooseMove(final boolean side, final int[] board, \n int alpha, int beta, final int depth, final int maxDepth)\n{\n final Best myBest = new Best();\n Best reply;\n final int num;\n\n if (Board.checkGameOver(board) || depth == maxDepth) {\n final Best fakeBest = new Best();\n fakeBest.setScore(returnPositionScore(board));\n return fakeBest;\n }\n\n if (side) {\n myBest.setScore(alpha);\n num = numberOfEngine;\n } else {\n myBest.setScore(beta);\n num = numberOfOpponent;\n }\n\n for (final int move: searchAvailableMoves(board)) {\n board[move] = num;\n reply = chooseMove(!side, board, alpha, beta, depth + 1, maxDepth);\n board[move] = 0;\n if (side && reply.getScore() > myBest.getScore()) {\n myBest.setMove(move);\n myBest.setScore(reply.getScore());\n alpha = reply.getScore();\n\n } else if (!side && reply.getScore() < myBest.getScore()) {\n myBest.setMove(move);\n myBest.setScore(reply.getScore());\n beta = reply.getScore();\n\n }\n if (alpha >= beta) {\n return myBest;\n }\n }\n\n return myBest;\n}\n</code></pre>\n\n<p>Main differences:</p>\n\n<ul>\n<li>method parameters/variables which can are now <code>final</code>;</li>\n<li>remove unnecessary unboxing and array creation near <code>searchAvailableMoves(board)</code>.</li>\n</ul>\n\n<p>In order to do better than that, more code is needed ;)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-07T00:13:51.280",
"Id": "42073",
"Score": "0",
"body": "thank you for the tips. yeah i know i did some unnecessary unboxing,before that i did it like you did and than i changed my mind.. but i guess that it doesn't make bad performance is it?\nanyway..in fact i was actually looking to get some very different code than mine because i know that there are shorter and more \"Elegant\" ways to write this function. \nso i found a little snippest of code on the net,and now i am trying to work with that instead. it is much less OOP but in this case i don't mind. \nbut can you please look at this code and tell me how can i get the actual move out of it??"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-07T00:23:45.360",
"Id": "42074",
"Score": "0",
"body": "What is really needed here though is the data structures, and preferrably documented. As the saying goes, \"show me your data, I'll show you the code\" ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-07T00:36:16.203",
"Id": "42077",
"Score": "0",
"body": "In any event, this kind of construct --> `searchAvailableMoves(EngineTask.newBoard)` is fishy... There is a design problem somewhere in the library used."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-07T00:44:12.870",
"Id": "42078",
"Score": "0",
"body": "can you explain to me why it is a bad form? the searchAvailableMoves() gets a int[] (some board position) and generate all the legal moves from that board. than it return an arrayList with all the legal moves. \nthe Engine.newBoard is a public static board (not the actual board which is the board class,but a subtitude..i simply don't want to change the original board)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-07T00:46:43.317",
"Id": "42079",
"Score": "0",
"body": "In my previews code (see the chooseMove() above) i passed a board[] to the function as a parameter..but now i do this a little differently"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-07T00:48:33.480",
"Id": "42080",
"Score": "0",
"body": "Why don't you just make a `Board` class with the necessary methods?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-07T00:53:06.103",
"Id": "42081",
"Score": "0",
"body": "I have a board class,and it has a load of methods..including the original board which is a int[42]. the reason i put this newBoard in the engineTask class (a seperate thread) is because when i start the run() of that thread, i initialize this board to take the exact original board form ( with array.copy) its just more comfortable that's all. but this is not the point..now i have another problem that i can't figure out how to extract the actual best move from this new function."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-07T00:55:02.080",
"Id": "42082",
"Score": "0",
"body": "by the way, why is it good to make some variables final? like showd in the answer above. what is the benefit of it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-07T00:57:51.637",
"Id": "42083",
"Score": "1",
"body": "Well, especially in long methods, it helps you spot immediately which variables will never be modified (for instance, I know from the get go that the method reuses `alpha` and `beta` internally by just spotting the signature). As instance variables, they are also a precondition to make immutable objects."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-07T00:04:46.483",
"Id": "27128",
"ParentId": "27113",
"Score": "2"
}
},
{
"body": "<p>As a starting point, address the issue you have: instead of returning an <code>int</code> (which is not sufficient for your needs), return an object that contains everything you WANT to get as a <code>returnvalue</code>.</p>\n\n<p>In your case, that is:</p>\n\n<ol>\n<li>an <code>int</code> (the return value of the alfabeta code)</li>\n<li>a bestmove-object</li>\n</ol>\n\n<p>So, define a return value class like this:</p>\n\n<pre><code>class MySpecialReturnvalueClass {\n int alfabetavalue;\n Best bestmove;\n}\n</code></pre>\n\n<p>Of course you make the fields private, with getter-methods and 1 constructor with the 2 values, or setters, but that's a lower-level detail. The point is, if you NEED something to be returned, then just go and DO return it.</p>\n\n<p>From that starting point, you change your code, then step back, look at the resulting code - and then you may see in which direction you could re-arrange. Maybe it turns out that class <code>Best</code> can contain the alfabeta value, thus the need for the new class vanishes, and you can return <code>Best</code> instead.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-03-20T08:54:34.120",
"Id": "84557",
"ParentId": "27113",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T19:15:18.030",
"Id": "27113",
"Score": "2",
"Tags": [
"java",
"ai"
],
"Title": "Minimax Alpha-beta code for Java"
}
|
27113
|
<p>I am building a 2d dictionary with an altered list at the end Afterwords I want to find the min of each list. Is there a better way to do it? Better being faster or at least less of an eyesore.</p>
<pre><code>#dummy function, will be replaced later so don't worry about it.
def alter(x, y, z,):
a = list(x)
for i, val in enumerate(x):
a[i] = val + y + z
return a
masterStats = {}
askStats = [0, 1, 2]
for numberServed in range(3):
masterStats[numberServed] = {}
for timeToServe in range(3):
masterStats[numberServed][timeToServe] = alter(askStats, numberServed, timeToServe)
for numberServed in masterStats.keys():
for timeToServe in masterStats[numberServed].keys():
print(min(masterStats[numberServed][timeToServe]))
for numberServed in masterStats.keys():
print(numberServed)
for timeToServe in masterStats[numberServed].keys():
print(" " + str(timeToServe))
print(" " + str(masterStats[numberServed][timeToServe]))
</code></pre>
|
[] |
[
{
"body": "<p>Python's variable names are conventionally named lowercase_width_underscores.</p>\n\n<p>Loop using .items() not .keys() if you will need the values, so your final loop can be:</p>\n\n<pre><code>for numberServed, numberServedStats in masterStats.items():\n print(numberServed)\n for timeToServe, timeToServeStats in numberServedStats,items():\n print(\" \" + str(timeToServe))\n print(\" \" + str(timeToServeStats))\n</code></pre>\n\n<p>The whole thing can be made more efficient by using numpy:</p>\n\n<pre><code>askStats = numpy.array([0, 1, 2])\n\nx = askStats[None,None,:] # put askStats in the third dimension\ny = numpy.arange(3)[:, None, None] # put number served in the first dimension\nz = numpy.arange(3)[None, :, None] # put time to serve in the second dimension\n\nstats = x + y + z # same as in alter\n</code></pre>\n\n<p>We create a new array by adding together three existing arrays. The <code>[:,None, None]</code> parts control how they are added. Essentially, the colon indicates the column the data will be spread across. The None indicates where the data will be duplicated. So <code>numpy.arange(3)[:,None]</code> gets treated like</p>\n\n<pre><code>[ \n [0, 0, 0],\n [1, 1, 1],\n [2, 2, 2]\n]\n</code></pre>\n\n<p>Whereas <code>numpy.arange(3)[None, :]</code> gets treated like</p>\n\n<pre><code>[\n [0, 1, 2],\n [0, 1, 2],\n [0, 1, 2]\n]\n</code></pre>\n\n<p>This lets us do the complete loop and adjust function in just that one expression.</p>\n\n<pre><code>for line in stats.min(axis=2).flatten():\n print(line)\n</code></pre>\n\n<p>The min method reduces the 3 dimensional array to 2d array by minimizing along dimension 2. Flatten() converts that 2d array into one long one dimensional array.</p>\n\n<pre><code>for row_index, row in enumerate(stats):\n print(row_index)\n for col_index, col in enumerate(row):\n print(\" \", col_index)\n print(\" \", col)\n</code></pre>\n\n<p>It probably won't help much here, but for bigger cases using numpy will be more efficient.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-07T00:09:39.923",
"Id": "42071",
"Score": "0",
"body": "You lost me on that second part, can you explain a bit of what you're doing with numpy and flatten?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-07T00:24:32.783",
"Id": "42075",
"Score": "0",
"body": "@EasilyBaffled, I've added some explanation."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-07T01:12:33.487",
"Id": "42084",
"Score": "0",
"body": "So to alter it to accept larger data sets, I replace 3 with x in numpy.arange(x) but how do I alter the [None,:,None] to take any amount?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-07T01:20:09.057",
"Id": "42085",
"Score": "0",
"body": "And how is the alter function run in it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-07T03:43:34.543",
"Id": "42089",
"Score": "0",
"body": "@EasilyBaffled, edited to hopefully clarify things a bit."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-07T03:43:53.317",
"Id": "42090",
"Score": "0",
"body": "@EasilyBaffled, alter function isn't run, its logic is replaced, (edit should make this a bit clearer)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-07T03:44:36.240",
"Id": "42091",
"Score": "0",
"body": "@EasilyBaffled, you don't need to change the `[None,:,None]`, that just means to put the array into the second dimension. As long as you still want to do that you don't need to change it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-08T16:15:22.007",
"Id": "42188",
"Score": "0",
"body": "The edits are helping a lot thanks, but just one more question where in this, would I put the alter function?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-08T17:31:23.567",
"Id": "42189",
"Score": "0",
"body": "@EasilyBaffled, the get the full advantage, you need to rewrite the alter function to use numpy. The `stats = x + y + z` does the same thing your alter function does, but faster. Your real function is more complicated I guess, but without knowing more I can't really provide much hints as to how."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-09T01:35:42.543",
"Id": "42199",
"Score": "0",
"body": "The function I'm using runs x*y times and uses all of the variables from list z along with a lot of randomization to produce a new number so sorta like for i in range(x*y): z[i] = (askStats[0] + randomInt(askStats[1], askStats[2]))"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-09T02:52:44.293",
"Id": "42202",
"Score": "0",
"body": "See http://docs.scipy.org/doc/numpy/reference/routines.random.html, for the random functions that numpy supports. I'm not sure what range your example is suppose to produce but I think you'll find one of the options there to be what you want."
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T23:28:24.307",
"Id": "27124",
"ParentId": "27120",
"Score": "1"
}
},
{
"body": "<p><code>alter</code> is equivalent to a list comprehension:</p>\n\n<pre><code>def alter(x, y, z):\n return [val + y + z for val in x]\n</code></pre>\n\n<p><code>collections.defaultdict(dict)</code> is a convenient 2-level dictionary. You could also make use of <code>itertools.product</code> for 2D looping:</p>\n\n<pre><code>masterStats = collections.defaultdict(dict)\naskStats = [0, 1, 2]\nfor numberServed, timeToServe in itertools.product(range(3), range(3)):\n masterStats[numberServed][timeToServe] = alter(askStats, numberServed, timeToServe)\n</code></pre>\n\n<p>Iterate over <code>values()</code>:</p>\n\n<pre><code>for subdict in masterStats.values():\n for lst in subdict.values():\n print(min(lst))\n</code></pre>\n\n<p>Iterate over <code>items()</code>, like Winston already mentioned:</p>\n\n<pre><code>for numberServed, subdict in masterStats.items():\n print(numberServed)\n for timeToServe, lst in subdict.items():\n print(\" \" + str(timeToServe))\n print(\" \" + str(lst))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-07T06:13:24.373",
"Id": "27131",
"ParentId": "27120",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "27124",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T23:04:09.643",
"Id": "27120",
"Score": "1",
"Tags": [
"python",
"hash-map"
],
"Title": "Making a 2D dict readable"
}
|
27120
|
<p>Okay, I'm under the impression that my current jQuery can be simplified (don't worry! It's short!) and I'm curious to know how this can be achieved. I think a solution to this will help produce a lot less code.</p>
<p>I currently have a list menu set up, with class names referring to their titles (HTML below) and if you click a list item, the menu item slides out and it's relevant content fades in. If you click the main heading again, the content fades out and the menu item slides back in.</p>
<p>Here's an <strong>example</strong> of my HTML</p>
<pre><code><ul class="wwd-filters">
<li><a class="corporate"><span>Corporate</span></a></li>
<li><a class="commercial"><span>Commercial</span></a></li>
<li><a class="construction"><span>Construction</span></a></li>
</ul>
<div class="wwd-content-each corporate">
<h2>Corporate</h2>
<div class="wwd-slides">
<div class="slides_container">
<p>Lorem ipsum lorem ipsum lorem ipsum</p>
</div>
</div>
</div>
<div class="wwd-content-each commercial">
<h2>Commercial</h2>
<div class="wwd-slides">
<div class="slides_container">
<p>Lorem ipsum lorem ipsum lorem ipsum</p>
</div>
</div>
</div>
</code></pre>
<p>Here's some <strong>example</strong> JS:</p>
<pre><code>jQuery('.wwd-choices-container ul.wwd-filters li a.corporate').click(function () {
jQuery('.wwd-content-container .wwd-content-each').fadeOut();
jQuery('.wwd-content-container .wwd-content-each.corporate').fadeIn();
});
</code></pre>
<p>My problem is that I don't want to have to repeat the jQuery code for each list item and it's content (e.g. <code>li a.corporate</code>, <code>li a.commercial</code>, <code>li a.li a.corporate</code>). As the class names for both the list item anchor and each content, is there an easy way to simplify this?</p>
<p>Everything is built via a CMS, so new sections and menu items would be added as time goes on so it has to remain as dynamic as possible. I'm thinking some form of array would work... and if it matches each other then it connections.</p>
|
[] |
[
{
"body": "<p>In the click handler you have a reference to the link that was clicked, so you can just select the relevant item from <code>this</code>. Here I've used the href of the link to point at an ID for each item, which makes it simple to do <code>jQuery(this.hef)</code> to select the item to fade in. It might not be convenient for you to use the ID element, in which case you can put them in a data attribute or something.</p>\n\n<pre><code><ul class=\"wwd-filters\">\n <li><a href=\"#corporate\"><span>Corporate</span></a></li>\n <li><a href=\"#commercial\"><span>Commercial</span></a></li>\n <li><a href=\"#construction\"><span>Construction</span></a></li>\n</ul>\n\n<div class=\"wwd-content-each\" id=\"corporate\">\n <h2>Corporate</h2>\n <div class=\"wwd-slides\">\n <div class=\"slides_container\">\n <p>Lorem ipsum lorem ipsum lorem ipsum</p> \n </div>\n </div>\n</div>\n<div class=\"wwd-content-each\" id=\"commercial\">\n <h2>Commercial</h2>\n <div class=\"wwd-slides\">\n <div class=\"slides_container\">\n <p>Lorem ipsum lorem ipsum lorem ipsum</p> \n </div>\n </div>\n</div>\n</code></pre>\n\n<p>Then you should just need this one snippet:</p>\n\n<pre><code>jQuery('.wwd-choices-container ul.wwd-filters li a').click(function () {\n jQuery('.wwd-content-container .wwd-content-each').fadeOut();\n jQuery(this.href).fadeIn();\n return false;\n});\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T15:07:06.490",
"Id": "27122",
"ParentId": "27121",
"Score": "1"
}
},
{
"body": "<p>I would recommend using the .on() for <code>click</code> event delegation:</p>\n\n<pre><code>$('.wwd-filters').on('click', 'a', function(e) {\n e.preventDefault();\n var id = $(this).data('id');\n jQuery('.wwd-content-container .wwd-content-each').fadeOut();\n jQuery('.wwd-content-container .wwd-content-each.' + id).fadeIn();\n});\n</code></pre>\n\n<p>This implementation grabs the id of the section you wish to show via the data attribute in the <code>a</code> elements:</p>\n\n<pre><code><ul class=\"wwd-filters\">\n <li><a data-id=\"corporate\" href=\"#corporate\"><span>Corporate</span></a></li>\n <li><a data-id=\"commercial\" href=\"#commercial\"><span>Commercial</span></a></li>\n <li><a data-id=\"construction\" href=\"#construction\"><span>Construction</span></a></li>\n</ul>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T15:23:39.220",
"Id": "42068",
"Score": "0",
"body": "Many thanks for the help! This doesn't seem to do it just yet, although I can't see why? Quick JS: http://jsfiddle.net/uR9nU/1/"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T15:10:26.823",
"Id": "27123",
"ParentId": "27121",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2013-06-06T15:00:44.397",
"Id": "27121",
"Score": "1",
"Tags": [
"javascript",
"jquery"
],
"Title": "JS arrays to simplify jQuery filtering"
}
|
27121
|
<p>I have written a java code to transfer files from one server to another using the concept of socket programming. Now, I also want to check for the network connection availability before each file is transferred. I also want that the files transferred should be transferred according to their numerical sequence, and while the files are being transferred, the transfer progress of each file i.e the progress percentage bar should also be visible on the screen.</p>
<p>I would really appreciate if someone can help me with the code. This is the code I have written for the file transfer.</p>
<p>ClientMain.java</p>
<pre><code>import java.io.*;
import java.net.Socket;
import java.net.SocketException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class ClientMain {
private DirectoryTxr transmitter = null;
Socket clientSocket = null;
private boolean connectedStatus = false;
private String ipAddress;
String srcPath = null;
String dstPath = "";
public ClientMain() {
}
public void setIpAddress(String ip) {
this.ipAddress = ip;
}
public void setSrcPath(String path) {
this.srcPath = path;
}
public void setDstPath(String path) {
this.dstPath = path;
}
private void createConnection() {
Runnable connectRunnable = new Runnable() {
public void run() {
while (!connectedStatus) {
try {
clientSocket = new Socket(ipAddress, 3339);
connectedStatus = true;
transmitter = new DirectoryTxr(clientSocket, srcPath, dstPath);
} catch (IOException io) {
io.printStackTrace();
}
}
}
};
Thread connectionThread = new Thread(connectRunnable);
connectionThread.start();
}
public static void main(String[] args) {
ClientMain main = new ClientMain();
main.setIpAddress("10.6.3.92");
main.setSrcPath("C:/chirashree");
main.setDstPath("C:/java");
main.createConnection();
}
}
</code></pre>
<p>DirectoryTxr.java</p>
<pre><code>import java.io.*;
import java.net.Socket;
import java.net.SocketException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class DirectoryTxr {
Socket clientSocket = null;
String srcDir = null;
String dstDir = null;
byte[] readBuffer = new byte[1024];
private InputStream inStream = null;
private OutputStream outStream = null;
int state = 0;
final int permissionReqState = 1;
final int initialState = 0;
final int dirHeaderSendState = 2;
final int fileHeaderSendState = 3;
final int fileSendState = 4;
final int fileFinishedState = 5;
private boolean isLive = false;
private int numFiles = 0;
private int filePointer = 0;
String request = "May I send?";
String respServer = "Yes,You can";
String dirResponse = "Directory created...Please send files";
String fileHeaderRecvd = "File header received ...Send File";
String fileReceived = "File Received";
String dirFailedResponse = "Failed";
File[] opFileList = null;
public DirectoryTxr(Socket clientSocket, String srcDir, String dstDir) {
try {
this.clientSocket = clientSocket;
inStream = clientSocket.getInputStream();
outStream = clientSocket.getOutputStream();
isLive = true;
this.srcDir = srcDir;
this.dstDir = dstDir;
state = initialState;
readResponse(); //starting read thread
sendMessage(request);
state = permissionReqState;
} catch (IOException io) {
io.printStackTrace();
}
}
private void sendMessage(String message) {
try {
sendBytes(request.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
/**
* Thread to read response from server
*/
private void readResponse() {
Runnable readRunnable = new Runnable() {
public void run() {
while (isLive) {
try {
int num = inStream.read(readBuffer);
if (num > 0) {
byte[] tempArray = new byte[num];
System.arraycopy(readBuffer, 0, tempArray, 0, num);
processBytes(tempArray);
}
} catch (SocketException se) {
System.exit(0);
} catch (IOException io) {
io.printStackTrace();
isLive = false;
}
}
}
};
Thread readThread = new Thread(readRunnable);
readThread.start();
}
private void sendDirectoryHeader() {
File file = new File(srcDir);
if (file.isDirectory()) {
try {
String[] childFiles = file.list();
numFiles = childFiles.length;
String dirHeader = "$" + dstDir + "#" + numFiles + "&";
sendBytes(dirHeader.getBytes("UTF-8"));
} catch (UnsupportedEncodingException en) {
en.printStackTrace();
}
} else {
System.out.println(srcDir + " is not a valid directory");
}
}
private void sendFile(String dirName) {
File file = new File(dirName);
if (!file.isDirectory()) {
try {
int len = (int) file.length();
int buffSize = len / 8;
//to avoid the heap limitation
RandomAccessFile raf = new RandomAccessFile(file, "rw");
FileChannel channel = raf.getChannel();
int numRead = 0;
while (numRead >= 0) {
ByteBuffer buf = ByteBuffer.allocate(1024 * 100000);
numRead = channel.read(buf);
if (numRead > 0) {
byte[] array = new byte[numRead];
System.arraycopy(buf.array(), 0, array, 0, numRead);
sendBytes(array);
}
}
System.out.println("Finished");
} catch (IOException io) {
io.printStackTrace();
}
}
}
private void sendHeader(String fileName) {
try {
File file = new File(fileName);
if (file.isDirectory())
return;//avoiding child directories to avoid confusion
//if want we can sent them recursively
//with proper state transitions
String header = "&" + fileName + "#" + file.length() + "*";
sendHeader(header);
sendBytes(header.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
private void sendBytes(byte[] dataBytes) {
synchronized (clientSocket) {
if (outStream != null) {
try {
outStream.write(dataBytes);
outStream.flush();
} catch (IOException io) {
io.printStackTrace();
}
}
}
}
private void processBytes(byte[] data) {
try {
String parsedMessage = new String(data, "UTF-8");
System.out.println(parsedMessage);
setResponse(parsedMessage);
} catch (UnsupportedEncodingException u) {
u.printStackTrace();
}
}
private void setResponse(String message) {
if (message.trim().equalsIgnoreCase(respServer) && state == permissionReqState) {
state = dirHeaderSendState;
sendDirectoryHeader();
} else if (message.trim().equalsIgnoreCase(dirResponse) && state == dirHeaderSendState) {
state = fileHeaderSendState;
if (LocateDirectory()) {
createAndSendHeader();
} else {
System.out.println("Vacant or invalid directory");
}
} else if (message.trim().equalsIgnoreCase(fileHeaderRecvd) && state == fileHeaderSendState) {
state = fileSendState;
sendFile(opFileList[filePointer].toString());
state = fileFinishedState;
filePointer++;
} else if (message.trim().equalsIgnoreCase(fileReceived) && state == fileFinishedState) {
if (filePointer < numFiles) {
createAndSendHeader();
}
System.out.println("Successfully sent");
} else if (message.trim().equalsIgnoreCase(dirFailedResponse)) {
System.out.println("Going to exit....Error ");
// System.exit(0);
} else if (message.trim().equalsIgnoreCase("Thanks")) {
System.out.println("All files were copied");
}
}
private void closeSocket() {
try {
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private boolean LocateDirectory() {
boolean status = false;
File file = new File(srcDir);
if (file.isDirectory()) {
opFileList = file.listFiles();
numFiles = opFileList.length;
if (numFiles <= 0) {
System.out.println("No files found");
} else {
status = true;
}
}
return status;
}
private void createAndSendHeader() {
File opFile = opFileList[filePointer];
String header = "&" + opFile.getName() + "#" + opFile.length() + "*";
try {
state = fileHeaderSendState;
sendBytes(header.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
}
}
private void sendListFiles() {
createAndSendHeader();
}
}
</code></pre>
<p>ServerMain.java</p>
<pre><code>public class ServerMain {
public ServerMain() {
}
public static void main(String[] args) {
DirectoryRcr dirRcr = new DirectoryRcr();
}
}
</code></pre>
<p>DirectoryRcr.java</p>
<pre><code>import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
public class DirectoryRcr {
String request = "May I send?";
String respServer = "Yes,You can";
String dirResponse = "Directory created...Please send files";
String dirFailedResponse = "Failed";
String fileHeaderRecvd = "File header received ...Send File";
String fileReceived = "File Received";
Socket socket = null;
OutputStream ioStream = null;
InputStream inStream = null;
boolean isLive = false;
int state = 0;
final int initialState = 0;
final int dirHeaderWait = 1;
final int dirWaitState = 2;
final int fileHeaderWaitState = 3;
final int fileContentWaitState = 4;
final int fileReceiveState = 5;
final int fileReceivedState = 6;
final int finalState = 7;
byte[] readBuffer = new byte[1024 * 100000];
long fileSize = 0;
String dir = "";
FileOutputStream foStream = null;
int fileCount = 0;
File dstFile = null;
public DirectoryRcr() {
acceptConnection();
}
private void acceptConnection() {
try {
ServerSocket server = new ServerSocket(3339);
socket = server.accept();
isLive = true;
ioStream = socket.getOutputStream();
inStream = socket.getInputStream();
state = initialState;
startReadThread();
} catch (IOException io) {
io.printStackTrace();
}
}
private void startReadThread() {
Thread readRunnable = new Thread() {
public void run() {
while (isLive) {
try {
int num = inStream.read(readBuffer);
if (num > 0) {
byte[] tempArray = new byte[num];
System.arraycopy(readBuffer, 0, tempArray, 0, num);
processBytes(tempArray);
}
sleep(100);
} catch (SocketException s) {
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException i) {
i.printStackTrace();
}
}
}
};
Thread readThread = new Thread(readRunnable);
readThread.start();
}
private void processBytes(byte[] buff) throws InterruptedException {
if (state == fileReceiveState || state == fileContentWaitState) {
//write to file
if (state == fileContentWaitState)
state = fileReceiveState;
fileSize = fileSize - buff.length;
writeToFile(buff);
if (fileSize == 0) {
state = fileReceivedState;
try {
foStream.close();
} catch (IOException io) {
io.printStackTrace();
}
System.out.println("Received " + dstFile.getName());
sendResponse(fileReceived);
fileCount--;
if (fileCount != 0) {
state = fileHeaderWaitState;
} else {
System.out.println("Finished");
state = finalState;
sendResponse("Thanks");
Thread.sleep(2000);
System.exit(0);
}
System.out.println("Received");
}
} else {
parseToUTF(buff);
}
}
private void parseToUTF(byte[] data) {
try {
String parsedMessage = new String(data, "UTF-8");
System.out.println(parsedMessage);
setResponse(parsedMessage);
} catch (UnsupportedEncodingException u) {
u.printStackTrace();
}
}
private void setResponse(String message) {
if (message.trim().equalsIgnoreCase(request) && state == initialState) {
sendResponse(respServer);
state = dirHeaderWait;
} else if (state == dirHeaderWait) {
if (createDirectory(message)) {
sendResponse(dirResponse);
state = fileHeaderWaitState;
} else {
sendResponse(dirFailedResponse);
System.out.println("Error occurred...Going to exit");
System.exit(0);
}
} else if (state == fileHeaderWaitState) {
createFile(message);
state = fileContentWaitState;
sendResponse(fileHeaderRecvd);
} else if (message.trim().equalsIgnoreCase(dirFailedResponse)) {
System.out.println("Error occurred ....");
System.exit(0);
}
}
private void sendResponse(String resp) {
try {
sendBytes(resp.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
private boolean createDirectory(String dirName) {
boolean status = false;
dir = dirName.substring(dirName.indexOf("$") + 1, dirName.indexOf("#"));
fileCount = Integer.parseInt(dirName.substring(dirName.indexOf("#") + 1, dirName.indexOf("&")));
if (new File(dir).mkdir()) {
status = true;
System.out.println("Successfully created directory " + dirName);
} else if (new File(dir).mkdirs()) {
status = true;
System.out.println("Directories were created " + dirName);
} else if (new File(dir).exists()) {
status = true;
System.out.println("Directory exists" + dirName);
} else {
System.out.println("Could not create directory " + dirName);
status = false;
}
return status;
}
private void createFile(String fileName) {
String file = fileName.substring(fileName.indexOf("&") + 1, fileName.indexOf("#"));
String lengthFile = fileName.substring(fileName.indexOf("#") + 1, fileName.indexOf("*"));
fileSize = Integer.parseInt(lengthFile);
dstFile = new File(dir + "/" + file);
try {
foStream = new FileOutputStream(dstFile);
System.out.println("Starting to receive " + dstFile.getName());
} catch (FileNotFoundException fn) {
fn.printStackTrace();
}
}
private void writeToFile(byte[] buff) {
try {
foStream.write(buff);
} catch (IOException io) {
io.printStackTrace();
}
}
private void sendBytes(byte[] dataBytes) {
synchronized (socket) {
if (ioStream != null) {
try {
ioStream.write(dataBytes);
} catch (IOException io) {
io.printStackTrace();
}
}
}
}
}
</code></pre>
<ol>
<li><p>ClientMain.java and DirectoryTxr.java are the two classes under client application. ServerMain.java and DirectoryRcr.java are the two classes under Server application.</p></li>
<li><p>run the ClientMain.java and ServerMain.java</p></li>
</ol>
|
[] |
[
{
"body": "<p>General advice here:</p>\n\n<ul>\n<li>All your created object instances look like they can be immutable: make them so (for instance by using builders instead of beans -- God do I <em>hate</em> beans).</li>\n<li>You should not embed thread starting logic in a method call -- how do you know anything about the thread after that? Use a method returning a <code>Runnable</code> or <code>Callable</code> (ideally a <code>FutureTask</code> since you get both) and manage threads in a separate <code>ExecutorService</code>.</li>\n<li>You have many constants: make them <code>private static final</code>.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-07T11:50:06.620",
"Id": "27139",
"ParentId": "27138",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-07T11:44:32.593",
"Id": "27138",
"Score": "4",
"Tags": [
"java",
"network-file-transfer"
],
"Title": "Program to transfer files from one server to another in java and also display a progress bar on each file transfer"
}
|
27138
|
<p>I am currently working on a site where I have a bunch of tiles "fly in" to the screen. I need to add a class to each tile on a delay so they come in one after another. I have the following code that works, but if I want to add more tiles, I will have to edit the jQuery each time.</p>
<p>Is there a way to trim this script down so I don't have to manually add new animations to the new tiles?</p>
<pre><code>function tilesAnimation() {
setInterval(function () {
$("ul.homepageTabs li").eq(0).css("display", "inline-block");
$("ul.homepageTabs li").eq(0).addClass('animated fadeInDown');
$(".loader").fadeOut();
}, 1800);
setInterval(function () {
$("ul.homepageTabs li").eq(1).css("display", "inline-block");
$("ul.homepageTabs li").eq(1).addClass('animated fadeInDown');
}, 2100);
setTimeout(function () {
$("ul.homepageTabs li").eq(2).css("display", "inline-block");
$("ul.homepageTabs li").eq(2).addClass('animated fadeInDown');
}, 2400);
setTimeout(function () {
$("ul.homepageTabs li").eq(3).css("display", "inline-block");
$("ul.homepageTabs li").eq(3).addClass('animated fadeInDown');
}, 2700);
setTimeout(function () {
$("ul.homepageTabs li").eq(4).css("display", "inline-block");
$("ul.homepageTabs li").eq(4).addClass('animated fadeInDown');
}, 3000);
setTimeout(function () {
$("ul.homepageTabs li").eq(5).css("display", "inline-block");
$("ul.homepageTabs li").eq(5).addClass('animated fadeInDown');
}, 3300);
setTimeout(function () {
$("ul.homepageTabs li").eq(6).css("display", "inline-block");
$("ul.homepageTabs li").eq(6).addClass('animated fadeInDown');
}, 3600);
setTimeout(function () {
$("ul.homepageTabs li").eq(7).css("display", "inline-block");
$("ul.homepageTabs li").eq(7).addClass('animated fadeInDown');
}, 3900);
setTimeout(function () {
$("ul.homepageTabs li").eq(8).css("display", "inline-block");
$("ul.homepageTabs li").eq(8).addClass('animated fadeInDown');
}, 4200);
}
</code></pre>
|
[] |
[
{
"body": "<p>One simple solution would be to extract your common functionality into a method. We'll also cache the selector for speed (don't do this if the elements change).</p>\n\n<pre><code>var tabs = $(\"ul.homepageTabs li\");\n\nfunction animateAfter(index,timeout){\n\n setTimeout(function () {\n tabs.eq(index).css(\"display\", \"inline-block\");\n tabs.eq(index).addClass('animated fadeInDown');\n }, timeout); \n}\n</code></pre>\n\n<p>Then we can call it like so:</p>\n\n<pre><code>for(var i=3;i<8;i++){\n animateAfter(i,2400+300*i);\n}\n</code></pre>\n\n<p>I noticed the first two are intervals, was that a mistake? If it was, you can start the loop at 0 (and a smaller timeout). If it wasn't you can can create a similar function for intervals.</p>\n\n<p>Also, consider using queued animations. </p>\n\n<p>We want all our animations to occur 300 mili-seconds (after each other) right?</p>\n\n<pre><code>(function(){\n var i=3; //the start index\n\n function myAnimEffect(next){\n $(this).eq(i).css(\"display\", \"inline-block\").\n eq(i).addClass('animated fadeInDown');\n next();\n }\n var $el = $('ul.homepageTabs li'); \n $el.delay(1800);\n for(var j=0;j<5;j++){ //5 is the number of lis\n $el.queue(myAnimEffect).delay(300);\n } \n});\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-12T01:06:33.107",
"Id": "56985",
"Score": "0",
"body": "Why not chain .addClass to avoid re-querying?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-07T13:16:24.160",
"Id": "27143",
"ParentId": "27142",
"Score": "1"
}
},
{
"body": "<p>If I am getting you right, you are looking for something like:</p>\n\n<pre><code>var titles=$(\"ul\").children();\nfunction fadeInTitles(titles, timeOut){\n var timeOut=timeOut || 1500;\n var len=titles.length, currentItem=0;\n function showTitle(){\n $(titles[currentItem]).fadeIn(\"slow\");\n currentItem+=1;\n if(currentItem<len) setTimeout(showTitle, timeOut);\n }\n showTitle();\n}\nfadeInTitles(titles);\n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/znEw9/\" rel=\"nofollow\">Play with me</a> on jsFiddle.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-07T20:17:46.863",
"Id": "27149",
"ParentId": "27142",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-07T12:51:55.583",
"Id": "27142",
"Score": "1",
"Tags": [
"javascript",
"jquery"
],
"Title": "Shortening Script - Add new class/css to an li in setIntervals"
}
|
27142
|
<p>I'm having trouble structuring the logic of OAuth integration into my web app. In the app, a user creates a <code>Report</code> that consists of data from their Google Analytics account.</p>
<p>User steps:</p>
<ol>
<li>User clicks 'New Report'</li>
<li>Google presents the 'Allow Access' page for OAuth access</li>
<li>User is presented with a list of their GA web properties and selects one</li>
<li>A report is created using data from the selected web property</li>
</ol>
<p>My issue is in structuring the code below.</p>
<p>When the user clicks "New Report", they are actually redirected to <code>google_analytics#ga_session</code> to begin the authorization process. The code to retrieve the user's web properties succeeds, but the code at the bottom needs to be refactored so it is reusable when retrieving web property data. The main two issues I can't figure out is how to make the Google Analytics instance reusable and how to structure the OAuth redirects. </p>
<p><strong>Retrieve web properties:</strong></p>
<p>GoogleAnalyticsController</p>
<pre><code>def ga_session
client = OAuth2::Client.new(ENV['GA_CLIENT_ID'], ENV['GA_SECRET_KEY'], {
:authorize_url => 'https://accounts.google.com/o/oauth2/auth',
:token_url => 'https://accounts.google.com/o/oauth2/token'
})
redirect_to client.auth_code.authorize_url({
:scope => 'https://www.googleapis.com/auth/analytics.readonly',
:redirect_uri => ENV['GA_OAUTH_REDIRECT_URL'],
:access_type => 'offline'
})
end
def oauth_callback
session[:oauth_code] = params[:code]
redirect_to new_report_path
end
</code></pre>
<p>ReportsController</p>
<pre><code>def new
@report = Report.new
ga_obj = GoogleAnalytics.new
ga_obj.initialize_ga_session(session[:oauth_code])
@ga_web_properties = ga_obj.fetch_web_properties
end
</code></pre>
<p>GoogleAnalytics model</p>
<pre><code>def initialize_ga_session(oauth_code)
client = OAuth2::Client.new(ENV['GA_CLIENT_ID'], ENV['GA_SECRET_KEY'], {
:authorize_url => 'https://accounts.google.com/o/oauth2/auth',
:token_url => 'https://accounts.google.com/o/oauth2/token'
})
access_token_obj = client.auth_code.get_token(oauth_code, :redirect_uri => ENV['GA_OAUTH_REDIRECT_URL'])
self.user = Legato::User.new(access_token_obj)
end
def fetch_web_properties
self.user.web_properties
end
</code></pre>
<p><strong>Retrieve web property data:</strong> when creating the report</p>
<p>ReportsController</p>
<pre><code>def create
@report = Report.new(params[:report])
@report.get_top_traffic_keywords(session[:oauth_code])
create!
end
</code></pre>
<p>Report Model</p>
<pre><code>def get_keywords(oauth_code)
ga = GoogleAnalytics.new
ga.initialize_ga_session(oauth_code) # this is a problem b/c the user will be redirected the new_report_path after the callack
self.url = ga.fetch_url(self.web_property_id)
self.keywords = # Get keywords for self.url from another service
keyword_revenue_data(oauth_code)
end
def keyword_revenue_data(oauth_code)
ga = GoogleAnalytics.new
ga.initialize_ga_session(oauth_code)
revenue_data = # Get revenue data
end
</code></pre>
|
[] |
[
{
"body": "<p>The first step would be to refactor out the instanciation of the Oauth2 client:</p>\n\n<pre><code># lib/analytics_oauth2_client\nclass AnalyticsOAuth2Client > OAuth2::Client\n def initialize(client_id, client_secret, options = {}, &block)\n client_id || = ENV['GA_CLIENT_ID']\n client_secret || = ENV['GA_SECRET_KEY']\n options.merge!(\n authorize_url: 'https://accounts.google.com/o/oauth2/auth',\n token_url: 'https://accounts.google.com/o/oauth2/token'\n ) \n super(client_id, client_secret, options, &block)\n end \nend\n</code></pre>\n\n<p>And then maybe we should devise a strategy to save those pesky oauth tokens:</p>\n\n<pre><code>class AccessToken < ActiveRecord::Base\n # @expires_at [Int]\n # @access_token [String]\n # @refresh_token [String]\nend\n\nclass GoogleAnalyticsController\n\n # ...\n def oauth_callback\n @client = AnalyticsOAuth2Client.new\n token = @client.auth_code.get_token(params[:code], :redirect_uri => ENV['GA_OAUTH_REDIRECT_URL'])\n @saved_token = AccessToken.create!(token.to_hash)\n session[:oauth_token] = @saved_token.id\n redirect_to new_report_path\n end\nend\n</code></pre>\n\n<p>And we need a controller method to get the access token from the session:</p>\n\n<pre><code>def authorize!\n # ... @todo redirect to back to authentication if no `session[:oauth_token]`\n stored_token = Token.find!(session[:oauth_token])\n @token = OAuth2::AccessToken(AnalyticsOAuth2Client.new, stored_token.attributes)\n @client = GoogleAnalytics.new(token: @token)\nend\n</code></pre>\n\n<p>And we need to shove the token into <code>GoogleAnalytics</code>:</p>\n\n<pre><code>class GoogleAnalytics\n include ActiveModel::Model\n\n attr_writer :token\n attr_accessor :user\n\n def initialize(attrs: {})\n super\n @user ||= Legato::User.new(@token) if @token\n end\nend\n</code></pre>\n\n<p>Then we consider the separation of concerns - models should not deal with authentication - thats a controller concern. You should pass whatever authorized object the models needs\nfrom the controller. Dependency injection is commonly used for this:</p>\n\n<pre><code>class Report\n attr_writer :client\n\n def get_keywords(oauth_code)\n self.url = @client.fetch_url(self.web_property_id)\n self.keywords = # Get keywords for self.url from another service\n keyword_revenue_data(oauth_code)\n end\nend\n\nclass ReportsController\n # ...\n\n def create\n @report = Report.new(client: @client, params[:report])\n @report.get_top_traffic_keywords\n create!\n end\n\n # ...\nend\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-05-08T14:11:07.887",
"Id": "163460",
"Score": "0",
"body": "Disclaimer: I have never done OAuth with google, this is general advice from doing other OAuth projects. Its not guaranteed to be complete or even runnable but rather point in the correct direction."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-05-08T14:16:59.623",
"Id": "163461",
"Score": "0",
"body": "I would also use [OmniAuth](https://github.com/intridea/omniauth) with [omniauth-google-oauth2](https://github.com/zquestz/omniauth-google-oauth2) instead of reinventing the wheel."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-05-08T14:09:04.417",
"Id": "90158",
"ParentId": "27144",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-07T14:17:25.370",
"Id": "27144",
"Score": "4",
"Tags": [
"ruby",
"ruby-on-rails",
"oauth"
],
"Title": "Rails service + OAuth"
}
|
27144
|
<p>The working and functional code below is a simplification of a real test application I've written. It acts as a client which asynchronously sends UDP data from a local endpoint and listens for an echo'ed response from a server implemented elsewhere. </p>
<p>The requirements are:</p>
<ol>
<li>Send and listen on the same port number;</li>
<li>The port number must be able to change (simulates data coming in from various
sources)</li>
</ol>
<p>The program does what I want, but I have doubts about its correctness. Specifically regarding the class members of <code>listenThread</code> and <code>udpClient</code> which are reused when the port number changes. Are they implemented, closed and cleaned-up correctly. </p>
<pre><code>using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace cs_console
{
class Tester
{
public void Send(string message, int localPort)
{
PrepareClient(localPort);
SendBytes(System.Text.Encoding.UTF8.GetBytes(message));
}
private void PrepareClient(int localPort)
{
if (localEP == null || localEP.Port != localPort)
{
localEP = new IPEndPoint(IPAddress.Parse(localHost), localPort);
listenThread = new Thread(StartListening);
listenThread.Start();
}
}
private void StartListening()
{
udpClient = new UdpClient();
udpClient.ExclusiveAddressUse = false;
udpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
udpClient.Client.Bind(localEP);
var s = new UdpState(localEP, udpClient);
currentAsyncResult = udpClient.BeginReceive(new AsyncCallback(ReceiveCallback), s);
}
private void ReceiveCallback(IAsyncResult ar)
{
if (ar == currentAsyncResult)
{
UdpClient c = (UdpClient)((UdpState)(ar.AsyncState)).c;
IPEndPoint e = (IPEndPoint)((UdpState)(ar.AsyncState)).e;
Byte[] buffer = c.EndReceive(ar, ref e);
if (buffer.Length > 0)
System.Console.WriteLine(System.Text.Encoding.UTF8.GetString(buffer));
UdpState s = new UdpState(e, c);
currentAsyncResult = udpClient.BeginReceive(new AsyncCallback(ReceiveCallback), s);
}
}
private void SendBytes(byte[] messageData)
{
var sender = new UdpClient();
sender.ExclusiveAddressUse = false;
sender.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
sender.Client.Bind(localEP);
sender.Send(messageData, messageData.Length, remoteEP);
sender.Close();
}
private static string localHost = "10.27.21.109";
private IPEndPoint localEP = null;
private IPEndPoint remoteEP = new IPEndPoint(IPAddress.Parse(localHost), 11000);
private Thread listenThread = null;
private UdpClient udpClient = null;
private IAsyncResult currentAsyncResult = null;
private class UdpState : Object
{
public UdpState(IPEndPoint e, UdpClient c) { this.e = e; this.c = c; }
public IPEndPoint e;
public UdpClient c;
}
}
class Program
{
static void Main(string[] args)
{
Tester tester = new Tester();
int localPort = 2532;
while (true)
{
++localPort;
var message = Console.ReadLine();
tester.Send(message, localPort);
}
}
}
}
</code></pre>
<p>This is as compact a working example as I could make.</p>
|
[] |
[
{
"body": "<ol>\n<li><p>I find a better naming convention for private fields on a class is <code>_PascalCase</code> or <code>_camelCase</code>. This makes it easy to see whether you are using a field or a local variable.</p></li>\n<li><p>It is completely unnecessary to create a new <code>Thread</code> to call <code>StartListening</code>. The thread will terminate once <code>udpClient.BeginReceive()</code> has been called as this is async. You might as well call <code>StartListening()</code> directly in <code>PrepareClient()</code>.</p></li>\n<li><p><a href=\"http://msdn.microsoft.com/en-us/library/system.net.sockets.udpclient%28v=vs.110%29.aspx\" rel=\"nofollow noreferrer\"><code>UdpClient</code></a> is <code>IDisposable</code> and should therefor be disposed when not needed anymore. You do not clean up the existing <code>UdpClient</code> at all.</p>\n\n<p><a href=\"https://stackoverflow.com/questions/4662553/how-to-abort-sockets-beginreceive\">The answer to this question</a> indicates that when you call <code>Dispose</code> or <code>Close</code> on a socket then the callback is invoked but will throw an <code>ObjectDisposedException</code> when calling <code>EndReceive</code> . Because you are storing the <code>currentAsyncResult</code> you can probably get around this by changing <code>StartListening()</code> to this:</p>\n\n<pre><code>private readonly object _clientLock = new object();\n\nprivate void StartListening()\n{\n lock (_clientLock)\n {\n if (udpClient != null)\n {\n currentAsyncResult = null;\n updClient.Dispose();\n }\n udpClient = new UdpClient();\n udpClient.ExclusiveAddressUse = false;\n udpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);\n udpClient.Client.Bind(localEP);\n\n var s = new UdpState(localEP, udpClient);\n currentAsyncResult = udpClient.BeginReceive(new AsyncCallback(ReceiveCallback), s);\n }\n}\n</code></pre>\n\n<p>Plus you should lock the inner block of your receive callback. This should ensure that you don't kill the client in the middle of receiving.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-29T08:18:22.027",
"Id": "36339",
"ParentId": "27145",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "36339",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-07T15:12:23.760",
"Id": "27145",
"Score": "5",
"Tags": [
"c#",
".net",
"multithreading",
"socket"
],
"Title": "Reusing thread and UdpClient for sending and receiving on same port"
}
|
27145
|
<p>I'll write a small simulation of my actual class first to request insights on unit testing one of the behaviors of this class. Here is my class A:</p>
<pre><code>public class A {
private final String a;
private final String b;
private String c;
public A(final String a, final String b) {
this.a = a;
this.b = b;
this.c = null;
}
public getC() {
if (this.c==null) {
// Logic to compute value of this.c using this.a and this.b
// set this.c
}
return this.c;
}
}
</code></pre>
<p>In the above class I'm doing lazy initialization of a data member c. Responsibility of class A is to compute this.c from this.a and this.b and cache it so that there is no need to compute it again on future invocation of getC. Class A has only this responsibility.</p>
<p>I want to write a unit test to verify that on Multiple invocations of getC() method on the same instance of class A, logic for computing this.c should be executed only once. Could anyone please help in figuring out, how can I write this unit test ? One way I can see is delegating the logic of computing this.c to another class B and then making class A dependent on class B so that a mock of class B can be injected during testing. After injection of mock of B, Mockito's feature to verify number of times method invocation happens on a mock can be used. But Class A has only one responsibility of computing this.c and delegating that responsibility to another object is looking like an overkill to me.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-07T17:27:19.680",
"Id": "42131",
"Score": "0",
"body": "Is this logic in a method of the class or not?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-07T17:28:43.503",
"Id": "42132",
"Score": "0",
"body": "Lets put the logic in a private method if it makes it easier to test how many times the method will be invoked on multiple invocations of getC on same instance of class A"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-07T17:29:41.053",
"Id": "42133",
"Score": "0",
"body": "The problem here is with `private`. While you can spy them, it is extremely painful to do... But hold on, I am writing an answer"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-07T17:31:43.407",
"Id": "42134",
"Score": "0",
"body": "Btw I'm not aiming at testing the logic to compute this.c, that can be tested by testing getC itself. I'm interested in making sure that logic is executed only once on multiple invocations of getC on same instance of class A"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-07T17:32:05.490",
"Id": "42135",
"Score": "0",
"body": "Yes, and `private` is a problem here"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-07T17:35:06.137",
"Id": "42136",
"Score": "0",
"body": "See my answer. There are, of course, other ways to compute `c` as you mention."
}
] |
[
{
"body": "<p>Delegate the computation of <code>a</code> and <code>b</code> to a method, say, <code>.compute()</code>. Since we want to spy this method's execution, we will suppose that we have Guava and its useful <code>@VisibleForTesting</code> annotation, and make the method <code>protected</code>:</p>\n\n<pre><code>@VisibleForTesting\nprotected String compute(String a, String b) { // code here }\n</code></pre>\n\n<p>Now, code written using Mockito and TestNG (with test file in same package than class <code>A</code>, so that the <code>compute()</code> method is visible):</p>\n\n<pre><code>@Test\npublic void computationOfCHappensOnlyOnce()\n{\n final String a = \"whatever\";\n final String b = \"you want\";\n\n final A spy = spy(new A(a, b));\n\n for (int i = 0; i < 10; i++)\n spy.getC();\n\n verify(spy, times(1)).compute(eq(a), eq(b));\n}\n</code></pre>\n\n<p>Note: the way your class is currently written, it is NOT thread safe. The quick, coarse way to fix it is to make <code>.getC()</code> <code>synchronized</code>.</p>\n\n<p><strong>EDIT</strong> Discussion on a different design to get the value of <code>c</code></p>\n\n<p>This requires a creation of a new factory class for instances of class <code>A</code>; it would have the responsibility to create new instances and compute <code>c</code>:</p>\n\n<pre><code>// if the class is a singleton...\nfinal FactoryForA factory = FactoryForA.getInstance();\n\nfinal A a = factory.newA(a, b);\n\n// This calls back to the factory to compute c:\na.getC();\n</code></pre>\n\n<p>The <code>A</code> class needs to implement <code>.equals()</code> and <code>.hashCode()</code> (on fields <code>a</code> and <code>b</code> but obviously not <code>c</code>!). Also, it has a constructure which is now package private (so that the factory can access it) and whose prototype is:</p>\n\n<pre><code>final String a, b;\nfinal FactoryForA factory;\n// No `c` member, see below\n\nA(String a, String b, FactoryForA factory) \n{\n this.a = a; this.b = b; this.factory = factory;\n}\n\npublic getC()\n{\n return factory.computeC(this);\n}\n</code></pre>\n\n<p>Now for the factory itself: it has an <code>ExecutorService</code> and a <code>Map<A, FutureTask<String>></code>. Here is the code of <code>computeC()</code>:</p>\n\n<pre><code>// instance variables of the factory\nprivate final ExecutorService service\n = Executors.newFixedThreadPool(5); // for example\nprivate final Map<A, FutureTask<String>> map = new HashMap<>();\n\n// package private\nString computeC(final A a)\n{\n FutureTask<String> task;\n // Synchronized map access\n synchronized(map) {\n // If there is no task created for that instance of A, create it\n // and submit it for execution\n task = map.get(a);\n if (task == null) {\n task = createFutureTask(a); // TODO, but nothing too complicated\n // IMPORTANT! If you don't do this, the task is not executed\n // and .get() below will block indefinitely\n service.execute(task);\n map.put(a, task);\n }\n }\n // A FutureTask will keep its status! We can therefore call .get()\n // as much as we like; the computation will only have happened once\n return task.get();\n}\n</code></pre>\n\n<p>One advantage is that if two instances created for <code>A</code> are equal (ie, the same <code>a</code> and <code>b</code> parameters), computation for <code>c</code> happens only once!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-07T18:02:14.837",
"Id": "42137",
"Score": "0",
"body": "Thanks for your answer. I guess making compute method package-private instead of protected should also work.Also it looks like there is no need for compute method to take a and b as input because they are already member of class A. On a larger picture do you see a need for redesigning this class. Mockito documentation is hinting towards the fact that if you are spying in unit tests, there is some code smell around."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-07T18:06:50.347",
"Id": "42138",
"Score": "0",
"body": "Well, you need to verify that `.compute()` is called with the correct arguments ;) Out of the class you cannot know that. As to redesign, yes I do have an idea... I'll edit the post and tell you when done. Will take a little time though ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-07T18:31:46.297",
"Id": "42139",
"Score": "0",
"body": "OK, done. Note that if you use Guava, you can advantageously this crude cache of mine by a `LoadingCache`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-07T18:47:48.257",
"Id": "42146",
"Score": "0",
"body": "I guess FactoryForA which you mentioned is same as class B which I mentioned in my question.Delegating the logic of computation of c to other class B aka factory is looking like an overkill to me because class A has a single responsibility i.e. to generate c.If we remove this logic of computation from class A, there will be nothing left in class A apart from one line of code of delegation of responsibility to class B aka FactoryA."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-07T18:53:13.297",
"Id": "42147",
"Score": "0",
"body": "Ah, I didn't know that this was class A's only purpose... But you want to keep the results of `c` cached, is that right?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-07T18:53:24.280",
"Id": "42148",
"Score": "0",
"body": "And I have verified, package-private will work with compute method in the Unit Test code you wrote above."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-07T18:57:45.233",
"Id": "42149",
"Score": "0",
"body": "yes caching part is right"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-07T19:00:51.200",
"Id": "42151",
"Score": "0",
"body": "Then I'd do a cache like the one I did above (you'd need to create an inner class much as `A` for keys to the map) instead of a class. You can make it `abstract`, and take a `Callable<String>` as a constructor argument so as to compute. You can then mock that callable in your unit tests."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-07T19:03:55.370",
"Id": "42152",
"Score": "0",
"body": "Or use Guava and a `LoadingCache` ;) Even better, since you can input an expiry time etc."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-07T19:07:07.413",
"Id": "42153",
"Score": "0",
"body": "sure, will explore Guava and LoadingCache as well. Thanks for your suggestions."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-07T19:10:43.413",
"Id": "42154",
"Score": "0",
"body": "\"explore\" is the word. Guava has a LOT of niceties. To the point that Java 8 will salvage a good part of its interfaces for its own use!"
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-07T17:34:21.797",
"Id": "27147",
"ParentId": "27146",
"Score": "2"
}
},
{
"body": "<p>Why not keep this simple and test wether subsequent invocations really do return the same instance as before :</p>\n\n<pre><code>A a = new A(\"a\", \"b\");\nassertTrue(a.compute() == a.compute());\n</code></pre>\n\n<p>This way, there is no need to delegate to another class, nor the need to make implementation details public or protected.</p>\n\n<p>Remember that you should test behaviour, and not implementation.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-08T12:29:25.690",
"Id": "27170",
"ParentId": "27146",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "27147",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-07T17:21:52.493",
"Id": "27146",
"Score": "1",
"Tags": [
"java",
"unit-testing",
"dependency-injection"
],
"Title": "Unit Test to verify number of times lazy initialization logic is executed for a data member"
}
|
27146
|
<p>I'm creating a simple generic <code>Map</code>-wrapper with multiple keyed values. </p>
<p>I'm intending to use it with storing edges in a graph, where an edge goes from one vertex to another. Thus, I can fetch any of the two vertices in constant time instead of having to loop to find either to/from.</p>
<pre><code>public class MultiMap<K1 extends Object, K2 extends Object, V extends Object> {
private Map<K1, V> map1;
private Map<K2, V> map2;
/**
* @param map1
* @param map2
*/
public MultiMap() {
this.map1 = new HashMap<K1, V>();
this.map2 = new HashMap<K2, V>();
}
public void put(K1 key1, K2 key2, V value) {
this.map1.put(key1, value);
this.map2.put(key2, value);
}
...
public V removeByKey1(K1 key) {
V res = this.map1.remove(key);
K2 k = null;
for (Map.Entry<K2, V> entry : this.map2.entrySet()) {
if (entry.getValue() == res) {
k = entry.getKey();
break;
}
}
this.map2.remove(k);
return res;
}
public V removeByKey2(K2 key) {
V res = this.map2.remove(key);
K1 k = null;
for (Map.Entry<K1, V> entry : this.map1.entrySet()) {
if (entry.getValue() == res) {
k = entry.getKey();
break;
}
}
this.map1.remove(k);
return res;
}
...
}
</code></pre>
<p>Is there better way of removing? E.g. using <code>LinkedHashMap</code> and then using the key index to do it in constant time instead of linear?</p>
<p>If there's something else not sitting right with you, tell me. All feedback appreciated.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-07T16:57:20.570",
"Id": "42144",
"Score": "0",
"body": "I would use an adjacency matrix, or sparse adjacency matrix."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-07T19:21:38.520",
"Id": "42155",
"Score": "1",
"body": "You can use the Guava Collection Table (https://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#Table), even the site example refers to what you want to do! :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-07T21:33:03.920",
"Id": "42157",
"Score": "0",
"body": "I've had a brain fart. If you have read the comment where I explain the class's purpose above, the edge from vertex a to b is different from vertex b to a. Since the keys refer to same vertex, it doesn't work out. I'll look into Guava and adjacency matrixes!"
}
] |
[
{
"body": "<p>Some notes about the current code:</p>\n\n<ol>\n<li><p><code>extends Objects</code> looks unnecessary in the class declaration:</p>\n\n<pre><code>public class MultiMap<K1 extends Object, K2 extends Object, V extends Object> {\n</code></pre>\n\n<p>I'm not completely sure but the following seems to be the same:</p>\n\n<pre><code>public class MultiMap<K1, K2, V> {\n</code></pre></li>\n<li><p>I'd rename <code>res</code> to <code>oldValue</code> or something more descriptive.</p></li>\n<li><p>Modern IDEs use highlighting to separate local variables from fields, so don't need to use <code>this.</code>. It's rather noise.</p></li>\n<li><p>Comments like this are just noise:</p>\n\n<pre><code> /**\n * @param map1\n * @param map2\n */\n</code></pre>\n\n<p>It doesn't say anything more than the code says. Furthermore, the constructor does not have any parameter like <code>map1</code> or <code>map2</code>. (<em>Clean Code</em> by <em>Robert C. Martin</em>: <em>Chapter 4: Comments, Noise Comments</em>)</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T20:25:08.000",
"Id": "42533",
"ParentId": "27148",
"Score": "2"
}
},
{
"body": "<p>Another approach: create a compound class which stores both <code>key1</code> and <code>key2</code> and put this into the maps as value. With that <code>remove</code> will be iteration-free.</p>\n\n<pre><code>import static com.google.common.collect.Maps.newHashMap;\n\nimport java.util.Map;\n\npublic class MultiMap<K1, K2, V> {\n\n private final Map<K1, CompoundValue<K1, K2, V>> map1 =\n newHashMap();\n private final Map<K2, CompoundValue<K1, K2, V>> map2 =\n newHashMap();\n\n public MultiMap() {\n }\n\n public void put(final K1 key1, final K2 key2, final V value) {\n final CompoundValue<K1, K2, V> compoundValue =\n new CompoundValue<K1, K2, V>(key1, key2, value);\n map1.put(key1, compoundValue);\n map2.put(key2, compoundValue);\n }\n\n public V removeByKey1(final K1 key1) {\n final CompoundValue<K1, K2, V> oldCompoundValue =\n map1.remove(key1);\n map2.remove(oldCompoundValue.key2);\n\n return oldCompoundValue.value;\n }\n\n public V removeByKey2(final K2 key2) {\n final CompoundValue<K1, K2, V> oldCompoundValue =\n map2.remove(key2);\n map1.remove(oldCompoundValue.key1);\n return oldCompoundValue.value;\n }\n\n private static class CompoundValue<K1, K2, V> {\n private final K1 key1;\n private final K2 key2;\n private final V value;\n\n public CompoundValue(final K1 key1, final K2 key2, \n final V value) {\n this.key1 = key1;\n this.key2 = key2;\n this.value = value;\n }\n }\n}\n</code></pre>\n\n<p><code>newHashMap</code> is from Google Guava.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-22T20:28:42.453",
"Id": "42535",
"ParentId": "27148",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-07T16:35:36.333",
"Id": "27148",
"Score": "3",
"Tags": [
"java",
"generics"
],
"Title": "Tips on multiple key Map-wrapper"
}
|
27148
|
<p><em>This may be a better fit for another board, but here goes:</em></p>
<p>I've made <a href="https://github.com/Flambino/week_sauce" rel="nofollow noreferrer">a very simple gem</a> that acts as a days-of-the-week bitmask. To be hip, I registered it on CodeClimate, <a href="https://codeclimate.com/github/Flambino/week_sauce" rel="nofollow noreferrer">where it's currently scoring a B/3.0 grade</a>.</p>
<p>Since there's only 1 extremely simple class, the B is bugging me. CodeClimate's reason is that there's too much code outside methods. This is no doubt due to my use of <code>define_method</code> to programmatically add read/write accessor methods like <code>monday</code>, <code>tuesday</code> and so on to the class.</p>
<p>The methods are currently being added like so:</p>
<pre><code>DAY_NAMES = %w(sunday monday tuesday wednesday thursday friday saturday).map(&:to_sym).freeze
DAY_BITS = Hash[ DAY_NAMES.zip(Array.new(7) { |i| 2**i }) ].freeze
# ...
# Create the day=, day, and day? methods
DAY_BITS.each do |day, bit|
define_method(day) do
get_bit bit
end
alias_method :"#{day}?", day
define_method(:"#{day}=") do |bool|
set_bit bit, bool
end
end
</code></pre>
<p>Note that the class supports two reader syntaxes (with and without <code>?</code>).</p>
<p>Now, I could use <code>method_missing</code> instead to make CodeClimate happy, but as I see it, that's only <em>more</em> complex. The method names are all known in advance, so <code>method_missing</code> seems unnecessary, and much less efficient than defining the methods on the class once.</p>
<p>If I were to use <code>method_missing</code> I'd do something like this (<code>get_bit</code> and <code>set_bit</code> already accept both strings and symbols):</p>
<pre><code>DAY_NAME_PATTERN = "((?:sun|mon|tues|wednes|thurs|fri|satur)day)".freeze
# ...
def method_missing(method, *args)
case method.to_s
when %r{\A#{DAY_NAME_PATTERN}\??\Z}
get_bit $1
when %r{\A#{DAY_NAME_PATTERN}=\Z}
set_bit $1, args.first
else
super
end
end
</code></pre>
<p>I'll still need the <code>DAY_NAMES</code> and <code>DAY_BITS</code> constants, so <code>DAY_NAME_PATTERN</code> would be yet another const - one that seems somewhat like duplication (though I could build it from <code>DAY_NAMES</code> of course, though that would be <em>more</em> expressions outside methods).</p>
<p>So to my mind, using <code>method_missing</code> would only improve the CodeClimate score, yet (ironically) make the code worse. Would you agree? Or do you know some clever 3rd way?</p>
<hr>
<p>Aside: <a href="https://codereview.stackexchange.com/a/27153/14370">As Tokland rightly notes in his answer</a> a bitmask is a fairly low-level approach to all of this compared to using sets. </p>
<p>I'm using a bitmask because the class is primarily intended to be used as an ActiveRecord serializer in a Rails app. That's where I extracted it from (partly as an exercise for myself). In the case of my app, the database already had a bitmask column, and this was an encapsulation of that logic. It seemed to me a good way to store the value (even if it is a little arcane for Ruby), as it allows for fast but complex day intersection/union queries at the SQL layer.</p>
<p>All of that could still be accomplished using sets, and only calculating the bitmask when necessary. Regardless of the specifics, however, my question is still valid on its own. Tokland's answer is great, but not quite an answer to the specific question.</p>
|
[] |
[
{
"body": "<p>Notes:</p>\n\n<ul>\n<li><p>I am afraid I'd propose a very boring solution: don't use meta-programming. I mean, why add methods and more methods, polluting the class, when you can add just one method and use symbols for the days? Add validations if you're worried about invalid values for days.</p></li>\n<li><p>The usual trick of using powers of two as a mask is that, a trick, very handy in low-level languages (C, assembler, ...). In a higher-level language you strive for writing code as declarative as possible, with data structures like lists, hashes, trees, or sets, not masks of powers of 2 :-) Here I'd use a set.</p></li>\n<li><p>I prefer functional solutions even with OOP, just return new instances instead of modifying the existing ones. Referential transparency, idempotence, all the goodies follow.</p></li>\n</ul>\n\n<p>I'd write (orientative, you get the idea):</p>\n\n<pre><code>class WeekSauce\n DAY_NAMES = [:sunday, :monday, :tuesday, :wednesday, :thursday, :friday, :saturday]\n\n def initialize(days)\n @days = days.to_set & DAY_NAMES\n end\n\n def has_day?(name)\n @days.include?(name)\n end\n\n def add_days(names)\n WeekSauce.new(@days.union(names))\n end\nend\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-07T21:33:25.277",
"Id": "42158",
"Score": "0",
"body": "I see your point, however: This class is intended to be used as an ActiveRecord serializer. It was extracted (mostly for the heck of it) from a Rails app, and serializes to a simple integer column. Furthermore, the bitmask is sent as-is to JSON API consumers (which seems more precise and easier for any language to devour, than sending an array of stringified symbols). I agree it'd be a lot more straight forward to just use symbol arrays, but it started as an int bitmask thing. So this class is, in a way, the high-level data structure. I could do everything different, but... eh"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-09T09:24:03.397",
"Id": "42207",
"Score": "0",
"body": "Fair enough, but sets or not sets, the main point of my answer (apart from data-structures and FP) was that IMHO grouping methods by task instead of adding individual methods simplifies the API. If you want to add them, well, I don't think there is a better way that what you did (the first, definitely not `method_missing`, no matter what a linter says)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-09T15:56:46.260",
"Id": "42218",
"Score": "0",
"body": "Gotcha. As I said, I partly extracted the gem for the heck of it. I agree I probably went overboard on the API, but I wanted it flexible as possible. Not a great way of doing things compared to having a more focussed API, but that's where the \"for the heck of it\" comes in. In any case, you've answered the main question: Given the circumstances `method_missing` would be worse than what I did, CodeClimate's opinion notwithstanding. Thanks!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-07T21:22:27.283",
"Id": "27153",
"ParentId": "27150",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "27153",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-07T20:30:47.260",
"Id": "27150",
"Score": "2",
"Tags": [
"ruby",
"meta-programming"
],
"Title": "define_method vs method_missing and CodeClimate scores"
}
|
27150
|
<p>This code was first critiqued here (without the Card class): <a href="https://codereview.stackexchange.com/questions/22805/please-critique-my-c-deck-class">Card Deck class for a Poker game</a></p>
<p>After learning more about data structures both online and in class, I wanted to revisit my <code>Card</code> and <code>Deck</code> classes and see if I can still make them better. Based on my driver tests, they are doing nearly everything I want them to do.</p>
<p>However, I'm not sure if all my operations between these two classes and the interface are proper, even though they do give proper results.</p>
<p>For instance:</p>
<ol>
<li><p>Is it still (theoretically) okay to return a blank <code>Card</code> if there are no more cards to return from the empty <code>Deck</code>?</p></li>
<li><p>Do I still need to maintain my Rule of Three, even though I don't do any memory allocation in either class?</p></li>
</ol>
<p>These are my main concerns, but I'd like a review of all the code in case there's something I've overlooked and/or if some parts can be cleaned.</p>
<p><strong>Card.h</strong></p>
<pre><code>#ifndef CARD_H
#define CARD_H
#include <iostream>
#include <string>
class Card
{
private:
unsigned rankValue;
char rank;
char suit;
std::string card;
public:
Card();
Card(char, char);
Card::Card(const Card&);
Card::~Card();
char getRank() const {return rank;}
char getSuit() const {return suit;}
std::string getCard() const {return card;}
bool operator<(const Card &rhs) const {return (rank < rhs.rank);}
bool operator>(const Card &rhs) const {return (rank > rhs.rank);}
bool operator==(const Card &rhs) const {return (suit == rhs.suit);}
bool operator!=(const Card &rhs) const {return (suit != rhs.suit);}
Card& operator=(const Card &obj);
friend std::ostream& operator<<(std::ostream&, const Card&);
};
#endif
</code></pre>
<p><strong>Card.cpp</strong></p>
<pre><code>#include "Card.h"
Card::Card() : rankValue(0), rank('*'), suit('*'), card("**") {}
Card::Card(const Card &obj)
{
rankValue = obj.rankValue;
rank = obj.rank;
suit = obj.suit;
card = obj.card;
}
Card::~Card() {}
Card::Card(char rank, char suit)
{
this->rank = rank;
this->suit = suit;
card += rank;
card += suit;
if (rank == 'A')
rankValue = 1;
else if (rank == '2')
rankValue = 2;
else if (rank == '3')
rankValue = 3;
else if (rank == '4')
rankValue = 4;
else if (rank == '5')
rankValue = 5;
else if (rank == '6')
rankValue = 6;
else if (rank == '7')
rankValue = 7;
else if (rank == '8')
rankValue = 8;
else if (rank == '9')
rankValue = 9;
else if (rank == 'T')
rankValue = 10;
else if (rank == 'J')
rankValue = 11;
else if (rank == 'Q')
rankValue = 12;
else if (rank == 'K')
rankValue = 13;
}
Card &Card::operator=(const Card &obj)
{
// if not self-assignment and lhs is a Blank card
if (this != &obj && this->card == "**")
{
this->card = obj.card;
}
return *this;
}
std::ostream& operator<<(std::ostream &out, const Card &aCard)
{
out << '[' << aCard.card << ']';
return out;
}
</code></pre>
<p><strong>Deck.h</strong></p>
<pre><code>#ifndef DECK_H
#define DECK_H
#include <array>
#include "Card.h"
class Deck
{
private:
static const unsigned MAX_SIZE = 52;
int topCardIndex;
std::array<Card, MAX_SIZE> cards;
void build();
public:
Deck();
void shuffle();
Card deal();
unsigned size() const {return topCardIndex+1;}
bool empty() const {return topCardIndex == -1;}
friend std::ostream& operator<<(std::ostream&, const Deck&);
};
#endif
</code></pre>
<p><strong>Deck.cpp</strong></p>
<pre><code>#include <algorithm>
#include "Deck.h"
Deck::Deck() : topCardIndex(-1)
{
build();
shuffle();
}
void Deck::build()
{
const unsigned NUMBER_OF_RANKS = 13;
const unsigned NUMBER_OF_SUITS = 4;
const char RANKS[NUMBER_OF_RANKS] = {'A','2','3','4','5','6','7','8','9','T','J','Q','K'};
const char SUITS[NUMBER_OF_SUITS] = {'H','D','C','S'};
for (unsigned rank = 0; rank < NUMBER_OF_RANKS; ++rank)
{
for (unsigned suit = 0; suit < NUMBER_OF_SUITS; ++suit)
{
Card newCard(RANKS[rank], SUITS[suit]);
topCardIndex++;
cards[topCardIndex] = newCard;
}
}
}
void Deck::shuffle()
{
topCardIndex = MAX_SIZE-1;
std::random_shuffle(&cards[0], &cards[topCardIndex]);
}
Card Deck::deal()
{
if (empty())
{
std::cerr << "\nDECK IS EMPTY\n";
Card blankCard;
return blankCard;
}
topCardIndex--;
return cards[topCardIndex+1];
}
std::ostream& operator<<(std::ostream &out, const Deck &aDeck)
{
for (unsigned iter = aDeck.size(); iter--> 0;)
{
out << aDeck.cards[iter] << "\n";
}
return out;
}
</code></pre>
|
[] |
[
{
"body": "<p>No pointing defining methods where the compiler generated versions does the same:</p>\n\n<pre><code>Card::Card(const Card &obj)\n{\n rankValue = obj.rankValue;\n rank = obj.rank;\n suit = obj.suit;\n card = obj.card;\n}\n\nCard::~Card() {}\n\nCard &Card::operator=(const Card &obj)\n{\n // if not self-assignment and lhs is a Blank card\n if (this != &obj && this->card == \"**\")\n {\n this->card = obj.card;\n }\n\n return *this;\n}\n</code></pre>\n\n<p>You can get rid of both the above. The compiler generated versions work fine.</p>\n\n<p>For the assignment operator. Why care if it is self assignment. In this case it makes no difference. But why are you only copying the string. Don't you want to copy all the members?</p>\n\n<p>In <code>Card::Card(char rank, char suit)</code></p>\n\n<p>There is no range checking for rank and suit.<br>\nWhat happens to <code>rankValue</code> if I call:</p>\n\n<pre><code> Card c('X', '4');\n</code></pre>\n\n<p>With simple output operators I like to make it a single line:</p>\n\n<pre><code>out << '[' << aCard.card << ']';\nreturn out;\n\n// can be:\n\nreturn out << '[' << aCard.card << ']';\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-09T02:03:36.987",
"Id": "42200",
"Score": "0",
"body": "I also meant to add a third point to that list: is it impractical to try to prevent cards being assigned or constructed from other existing cards, except for cards coming from the deck? Seems secure to me, but I may just be getting nitpicky."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-08T07:20:03.117",
"Id": "27162",
"ParentId": "27154",
"Score": "5"
}
},
{
"body": "<ul>\n<li><p>There's no reason to have a <code>card</code> member in <code>Card</code>. The other fields already make up this type, so it's quite redundant. With this removed, <code><string></code> can be removed from the header as well.</p></li>\n<li><p><code>MAX_SIZE</code> could be of type <code>std::size_t</code> since it's a size.</p></li>\n<li><p>Since <code>std::array</code> is accessible, it should replace all the C-arrays in <code>build()</code>.</p></li>\n<li><p>With C++11, <code>std::random_shuffle()</code> should be replaced with <code>std::shuffle()</code>, which is found in <code><random></code>. Its randomization is considered an improvement over that of <code>std::rand()</code>.</p></li>\n<li><p>It's not necessary for <code>deal()</code> to display something. The calling code should display an instead error if needed.</p></li>\n<li><p>It may be better to have a separate size member instead of using <code>topCardIndex</code> to maintain the current size. This would also make <code>size()</code> and <code>empty()</code> more readable.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-15T02:22:23.800",
"Id": "73661",
"ParentId": "27154",
"Score": "2"
}
},
{
"body": "<p>One thing I would consider doing here is to make the ranks and suits enumerations then store those in your class:</p>\n\n<pre><code>enum class rank_t: char {\n TWO = '2',\n THREE = '3',\n FOUR = '4',\n FIVE = '5',\n SIX = '6',\n SEVEN = '7',\n EIGHT = '8',\n NINE = '9',\n TEN = 'T',\n JACK = 'J',\n QUEEN = 'Q',\n KING = 'K',\n ACE = 'A'\n};\n\nenum class suit_t: char{\n CLUBS = 'C',\n DIAMONDS = 'D',\n HEARTS = 'H',\n SPADES = 'S'\n};\n\nclass Card{\n rank_t rank;\n suit_t suit;\n};\n</code></pre>\n\n<p>I think this is a more type safe way than just using characters. This also has the benefit of recovering the string representation by casting to the underlying type via <code>static_cast</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-15T03:18:03.583",
"Id": "133860",
"Score": "0",
"body": "Did you mean to use `enum class suit_t : char {`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-15T03:26:47.783",
"Id": "133861",
"Score": "0",
"body": "@RSahu, yes I did mean that. Thanks for pointing that out!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-15T02:22:44.370",
"Id": "73662",
"ParentId": "27154",
"Score": "2"
}
},
{
"body": "<p>To add to the already suggested improvements:</p>\n\n<p>You have:</p>\n\n<pre><code>bool operator<(const Card &rhs) const {return (rank < rhs.rank);}\n</code></pre>\n\n<p>This does not sound right to me.</p>\n\n<p>If you ever decide to create a set of <code>Card</code>s or sort a collection of <code>Card</code>s, I assume you are going to rely on this function. In order to sort a collection of <code>Card</code>s, you have to answer the following questions:</p>\n\n<ol>\n<li>Is an Ace is to be put before a Two or after a King?</li>\n<li>Is an Ace of Diamonds to be equal in ordering to an Ace of Clubs?</li>\n<li>Is Two of Diamonds to be less or greater than Three of Clubs?</li>\n</ol>\n\n<p>Assuming the following answers:</p>\n\n<ol>\n<li>An Ace is to be put before a Two.</li>\n<li>Use the following order of Suites: Clubs, Diamonds, Hearts, Spades (the ordering used in the game Bridge). By that logic, Ace of Diamonds is greater than an Ace of Clubs.</li>\n<li>Using the ordering used in Bridge, Two of Diamonds is greater than Thee of Clubs.</li>\n</ol>\n\n<p>You'll have to update your <code>operator<</code> function to:</p>\n\n<pre><code>bool operator<(const Card &rhs) const\n{\n if ( this->suite != rhs.suite )\n {\n // Suites are 'C', 'D', 'H', and 'S'.\n // Lucky coincidence.\n return (this->suite < rhs.suite);\n }\n\n // Need to use rankValue, which are ordered 1-13, not rank.\n return (this->rankValue < rhs.rankValue);\n}\n</code></pre>\n\n<p>Also, I would change the implementation of the constructor</p>\n\n<pre><code>Card::Card(char rank, char suit)\n</code></pre>\n\n<p>to</p>\n\n<pre><code>Card::Card(char rank, char suit) : rank(rank),\n suit(suit),\n rankValue(getRankValue(rank))\n // Initialize members in\n // the initializer list whenever possible. \n{\n}\n</code></pre>\n\n<p>And move the logic of getting the ordered rank value from the input rank to a helper function. In the function, use a <code>switch</code> instead of an <code>if-elseif</code> logic.</p>\n\n<pre><code>static int Card::getRankeValue(int rank)\n{\n switch (rank)\n {\n case 'A':\n return 1;\n case '2':\n case '3':\n case '4':\n case '5':\n case '6':\n case '7':\n case '8':\n case '9':\n return rank-'0';\n case 'T':\n return 10;\n case 'J':\n return 11;\n case 'Q':\n return 12;\n case 'K':\n return 13;\n default:\n return -1;\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-15T03:35:33.280",
"Id": "73671",
"ParentId": "27154",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "73671",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-07T21:39:44.287",
"Id": "27154",
"Score": "3",
"Tags": [
"c++",
"c++11",
"classes",
"playing-cards"
],
"Title": "Card Deck class for a Poker game - version 2"
}
|
27154
|
<p>I'm a newbie to javascript, and day after day, I try to write better code with jQuery.</p>
<p>For example, I wrote this code earlier:</p>
<pre><code>$$foo= $(".foo");
$$foo.mouseenter(function() {
$(this).find('h1').addClass("hover");
});
$$foo.mouseleave(function() {
$("h1").removeClass("hover");
});
</code></pre>
<p>What I want to happen with this code is when the mouse enters <code>.foo</code> the <code>h1</code> gets a new background color or any style applying on class, <code>hover</code>.</p>
<p>Another example:</p>
<pre><code>$$foo= $(".foo");
$$foo.mouseenter(function() {
$(this).find('h1').addClass("hover");
$(this).find('input').focus();
});
$$foo.mouseleave(function() {
$("h1").removeClass("hover");
$(".foo input").val('');
});
</code></pre>
<p>What I want to happen here is when the mouse enters <code>.foo</code> the input gets focus, and when mouse out the input's values are removed.</p>
<p>Both cases are working perfect, but I want to know if there is a better way to do this (mouse enter and mouse out)?</p>
|
[] |
[
{
"body": "<p>First of all you can use <a href=\"http://api.jquery.com/hover/\" rel=\"nofollow\">jQuery hover</a> and passing 2 functions (mouseenter, mouseleave)\nand u can shorten it also with <a href=\"http://api.jquery.com/end/\" rel=\"nofollow\">jQuery end</a></p>\n\n<pre><code>$('.foo').hover(\n function () {\n $(this).find('h1').addClass(\"hover\").end().find('input').focus(); \n },\n function () {\n $(this).find('h1').removeClass(\"hover\").end().find('input').val(''); \n }\n);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-08T18:25:27.343",
"Id": "42191",
"Score": "0",
"body": "Thank you @Shlomi, what about if the same code happen after click not hover"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-09T07:34:45.813",
"Id": "42206",
"Score": "0",
"body": "@JimmyTodd then u can use replace the **hover** with **toggle**"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T12:37:51.500",
"Id": "42502",
"Score": "0",
"body": "Note that the [`.toggle()` event binding function](http://api.jquery.com/toggle-event/) was removed in v1.9."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-04-09T22:33:40.083",
"Id": "367907",
"Score": "0",
"body": "@StefanBob - according to the doco the `.hover()` event binding method is still supported. Do you have a link to doco that says otherwise?"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-08T17:32:29.980",
"Id": "27175",
"ParentId": "27155",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "27175",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-07T23:39:48.720",
"Id": "27155",
"Score": "2",
"Tags": [
"javascript",
"beginner",
"jquery",
"event-handling"
],
"Title": "Attaching both mouseenter and mouseleave event handlers using jQuery"
}
|
27155
|
<p>I am just beginning to dabble in C++. Would you implement this as a <code>class</code> like I did, or a <code>struct</code>? What are the pros and cons?</p>
<pre><code>class Point
{
private:
double _x;
double _y;
public:
Point();
Point(double x, double y);
~Point();
Point(Point& other);
double GetX();
void SetX(double x);
double GetY();
void SetY(double y);
};
Point::Point() : _x(0.0), _y(0.0)
{
}
Point::Point(double x, double y) : _x(x), _y(y)
{
}
Point::Point(Point& other) : _x(other._x), _y(other._y)
{
}
Point::~Point()
{
}
double Point::GetX()
{
return _x;
}
void Point::SetX(double x)
{
_x = x;
}
double Point::GetY()
{
return _y;
}
void Point::SetY(double y)
{
_y = y;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-10T06:22:13.773",
"Id": "42248",
"Score": "1",
"body": "This should give you an idea of the differences between the two: [When should you use a class vs a struct in C++?](http://stackoverflow.com/questions/54585/when-should-you-use-a-class-vs-a-struct-in-c)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-12T03:14:21.403",
"Id": "42384",
"Score": "0",
"body": "I am not sure whether I would use a class or a struct, but I would declare `x` and `y` `const` so that my objects were immutable, and all my multi-threading issues go away."
}
] |
[
{
"body": "<p>If you are using point as a property bag (like this).</p>\n\n<p>Then just make it a struct (leave the members public). If you think there is a slight possibility of modifying the implementation then use get/set (ers) to access the memebrs but this class is so simple it seems over kill.</p>\n\n<p>If this is part of a school class then your professor is going to say use member accessors so that the internal implementation can change and the internal implementation can change without the class interface being changed.</p>\n\n<p>Though true in this simplistic case its just not going to happen.</p>\n\n<p>Though I would add constructors to make sure the members are correctly initialized.</p>\n\n<p>PS. Try not to use a leading underscore on identifiers. Though in this case it is not a problem the rules are non trivial and not well known so best avoided. see <a href=\"https://stackoverflow.com/a/228797/14065\">https://stackoverflow.com/a/228797/14065</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-08T07:28:41.117",
"Id": "27163",
"ParentId": "27156",
"Score": "5"
}
},
{
"body": "<p>As they stand right now, your destructor and copy constructor accomplish nothing that the compiler won't do just as well on its own. You're probably better off eliminating them. </p>\n\n<p>You might also <em>consider</em> merging your two constructors:</p>\n\n<pre><code>Point::Point() : _x(0.0), _y(0.0)\n{\n}\n\nPoint::Point(double x, double y) : _x(x), _y(y)\n{\n}\n</code></pre>\n\n<p>...into a single constructor with default arguments:</p>\n\n<pre><code>explicit Point::Point(double x = 0, double y = 0) : _x(x), _y(y) {}\n</code></pre>\n\n<p>Note the <code>explicit</code> though -- without it, the single constructor can support implicit conversions, so if (for example) you had something like:</p>\n\n<pre><code>void f(Point const &a);\n</code></pre>\n\n<p>...the compiler wouldn't stop you from a mistake like <code>f(1)</code>, because it sees the constructor that allows it to do <code>f(Point(1, 0.0))</code>. Even with the explicit, using two separate constructors is arguably a bit safer. Just for example, if you were creating a temporary point object in some deeply nested set of function calls:</p>\n\n<pre><code>f(g(h(Point(a,b))));\n</code></pre>\n\n<p>and accidentally typed that as:</p>\n\n<pre><code>f(g(h(Point(a),b)))\n</code></pre>\n\n<p>...with two separate constructors, the compiler would diagnose the problem fairly directly, but with one constructor and default arguments, it might not be quite so direct (especially if <code>h</code> could also take a second argument). Frankly, however, I think that's a remote enough possibility I'd probably live with it.</p>\n\n<p>Then we get to the age-old question of whether you gain anything from using get/set pairs for your <code>x</code> and <code>y</code>. For a point, there's a better theoretical argument than with most types that you might eventually want to change representation and use polar coordinates instead of Cartesian coordinates. While theoretically sound, my experience is that this basically just doesn't happen. In code where it makes sense to <em>store</em> polar coordinates, you're generally working with polar coordinates externally as well, so your Cartesian-based interface is wrong anyway.</p>\n\n<p>At the same time, using a <code>getter</code> means that (for example) to translate a point to the right by four units, you end up with something ugly like <code>my_point.set_x(my_point.get_x() + 4);</code> instead of just <code>my_point.x += 4;</code>.</p>\n\n<p>Bottom line: using a getter/setter (accessor/mutator, if you prefer) for this job does a great deal more harm than good. The benefit runs right on the ragged edge between \"purely theoretical\" and \"completely imaginary\" while the harm happens essentially all the time in every piece of real code that uses such a class.</p>\n\n<p>Based on what it actually accomplishes, you'd probably be better off with something much simpler, like:</p>\n\n<pre><code>struct Point {\n double x;\n double y;\n\n explicit Point(double x = 0.0, double y=0.0) : x(x), y(y) {}\n};\n</code></pre>\n\n<p>That assures the members are initialized, and the compiler-synthesized copy constructor, destructor, copy assignment, move constructor, move assignment will all work fine. Direct access to the <code>x</code> and <code>y</code> members will clean up client code considerably.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-10T14:13:36.590",
"Id": "27236",
"ParentId": "27156",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "27236",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-08T01:27:37.443",
"Id": "27156",
"Score": "4",
"Tags": [
"c++",
"beginner"
],
"Title": "Should this Point class remain a class, or become a struct?"
}
|
27156
|
<p>I have this PHP script below that requests data from the Twitter API. The script then displays it on a page according to the information that I have in my local database. I stored Twitter real usernames so I can pass them to the API and display the profile images of those twitter users. The script works fine to display my request from the API but it is awfully slow, so I was wondering what could cause the script to be so slow.</p>
<p>The first part of my script seems to execute fine.</p>
<pre><code>/* Create a TwitterOauth object with consumer/user tokens. */
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token['oauth_token'], $access_token['oauth_token_secret']);
$url = $connection->get('statuses/user_timeline', array('screen_name' => $row['Twitter'],count=>'1'));
$results = json_encode($url);
$data = json_decode($results, true);
$image = '';
if(is_array($data)){
$image = $data[0]['user']['profile_image_url'];
$image_bigger = str_replace('_normal', '_bigger',$image);
}
echo "<h1 align='middle' id = $id> $name Vs Opposition </h1>";
echo "<img src='".$image_bigger."' width= '100' height ='100' class= 'image' align='middle' />";
?>
</code></pre>
<p>This part of the script below seems to be the culprit of the page. It takes lot of time to display the info because it loops through all the Twitter IDs returned by the query in order to display the images of the API's requested authors. The <code>$data2</code> variable is a very long array of info regarding the Twitter user. From that array, I pick the key of the array containing the value that stores the picture of every Twitter user inside a loop.</p>
<p>How could I dynamically optimize this so the page can load faster? </p>
<pre><code> <?php
$select2 = "SELECT * FROM AUTHORS WHERE ID <> $id";
$result2 = mysql_query($select2);
$result_count = mysql_num_rows($result2);
$image_array = array();
$unique_id = array();
$counter = 0;
if($result_count > 0) {
while ($row2 = mysql_fetch_array($result2, MYSQL_ASSOC)) {
array_push($unique_id, $row2['ID']);
$url2 = $connection->get('statuses/user_timeline', array('screen_name' => $row2['Twitter'],count=>'1'));
$results2 = json_encode($url2);
$data2 = json_decode($results2, true); // data through is a very long array
$image2 = $data2[$counter]['user']['profile_image_url'];
$image3 = str_replace('_normal', '_bigger',$image2);
array_push($image_array,$image3);
}
}
// the while loop above seems to be the culprit in the page taking too long to load. Is there anyway I could optimize this?
?>
<div id ="opposition">
<?php
$unique_image = array_unique($image_array);
$id_array = array_unique($unique_id);
$i = 0;
foreach($unique_image as $content) {
echo "<a id ='".$id_array[$i]."' href ='#'><img src='".$content."' width= '100' height ='100' class='image' /></a>";
$i++;
}
?>
</div>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-11T14:42:23.000",
"Id": "42349",
"Score": "0",
"body": "Please consider using PDO prepared statements instead of the now deprecated mysql_* functions"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T14:00:20.733",
"Id": "42506",
"Score": "0",
"body": "Have you considered caching the API response and only updating again from twitter every so often? Would make the initial page load lengthy, but subsequent requests very fast. Better yet! Offload the API call to a cronjob and it wont affect the frontend load times."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-08T08:34:08.023",
"Id": "27166",
"Score": "1",
"Tags": [
"php",
"performance",
"php5",
"api",
"twitter"
],
"Title": "Requesting data from the Twitter API"
}
|
27166
|
<p>I built a simple PHP spellchecker and suggestions app that uses PHP's similar_text() and levenshtein() functions to compare words from a dictionary that is loaded into an array.</p>
<ul>
<li>How it works is first I load the contents of the dictionary into an
array.</li>
<li>I split the user's input into words and spell check each of the
words.</li>
<li>I spell check by checking if the word is in the array that is the
dictionary.</li>
<li>If it is, then I echo a congratulations message and move on.</li>
<li>If not, I iterate through the dictionary-array comparing each word, in the dictionary-array, with the assumed misspelling.</li>
<li>If the inputted word, in lower-case and without punctuation, is 90%
or more similar to a word in the dictionary array, then I copy that
word from the dictionary array into an array of suggestions.</li>
<li>If no suggestions were found using the 90% or higher similarity
comparison, then I use levenshtein() to do a more liberal comparison
and add suggestions to the suggestions array.</li>
<li>Then I iterate through the suggestions array and echo each
suggestion.</li>
</ul>
<p>I noticed that this is running slowly. Slow enough to notice. And I was wondering how I could improve the speed and efficiency of this spell checker.</p>
<p>Any and all changes, improvements, suggestions, and code are welcome and appreciated.</p>
<p>Here is the code (For syntax highlighted code, please <a href="http://pastebin.com/sjR2p41w">visit here</a>):</p>
<pre><code><?php
function addTo($line){
return strtolower(trim($line));
}
$words = array_map('addTo', file('dictionary.txt'));
$words = array_unique($words);
function checkSpelling($input, $words){
$suggestions = array();
if(in_array($input, $words)){
echo "you spelled the word right!";
}
else{
foreach($words as $word){
$percentageSimilarity=0.0;
$input = preg_replace('/[^a-z0-9 ]+/i', '', $input);
similar_text(strtolower(trim($input)), strtolower(trim($word)), $percentageSimilarity);
if($percentageSimilarity>=90 && $percentageSimilarity<100){
if(!in_array($suggestions)){
array_push($suggestions, $word);
}
}
}
if(empty($suggestions)){
foreach($words as $word){
$input = preg_replace('/[^a-z0-9 ]+/i', '', $input);
$levenshtein = levenshtein(strtolower(trim($input)), strtolower(trim($word)));
if($levenshtein<=2 && $levenshtein>0){
if(!in_array($suggestions)){
array_push($suggestions, $word);
}
}
}
}
echo "Looks like you spelled that wrong. Here are some suggestions: <br />";
foreach($suggestions as $suggestion){
echo "<br />".$suggestion."<br />";
}
}
}
if(isset($_GET['check'])){
$input = trim($_GET['check']);
$sentence='';
if(stripos($input, ' ')!==false){
$sentence = explode(' ', $input);
foreach($sentence as $item){
checkSpelling($item, $words);
}
}
else{
checkSpelling($input, $words);
}
}
?>
<!Doctype HTMl>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Spell Check</title>
</head>
<body>
<form method="get">
<input type="text" name="check" autocomplete="off" autofocus />
</form>
</body>
</html>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-12T16:49:36.987",
"Id": "42447",
"Score": "0",
"body": "Any reason why you aren't using an existing spellchecker? Spellcheck for PHP has already been solved a number of times."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T00:42:53.607",
"Id": "42484",
"Score": "1",
"body": "@DaveJarvis I wanted to invent a solution myself / code it myself even if I was using other's code or algorithms. It is the journey I was looking for. And where? All the solutions I found had a restricted number of API calls or were outdated as of PHP 5.3"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-14T00:05:49.400",
"Id": "42567",
"Score": "1",
"body": "@DaveJarvis In the sample code, it says it requires a license key."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-14T04:00:30.077",
"Id": "42574",
"Score": "0",
"body": "So it does, which is a shame. I was planning to use it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-19T17:21:40.137",
"Id": "83540",
"Score": "0",
"body": "Use [this API](http://xspell.tk/?page=api) with SSL also. Easy for translation API also. It'll give you direct access by Curl."
}
] |
[
{
"body": "<p>Here are a couple of tweaks that could help performance:</p>\n\n<ol>\n<li><p>Rather than storing the dictionary in-memory, <strong>offload that to a database</strong> (potentially even caching commonly misspelled words as an optimization)</p></li>\n<li><p><strong>Ignore words under a certain length</strong>\n(for example, MySQL's fulltext searching ignores words with fewer than 4 characters by default)</p></li>\n</ol>\n\n<p>The thing that concerns me most with your algorithm is how much time it would take to compare <em>every single word</em> in the dictionary. This problem compounds with more words in the search query.</p>\n\n<p>There has to be a way to quickly filter the dictionary to a smaller list of higher probability similarities (i.e. by word length, first letter, etc. ?)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T13:58:08.507",
"Id": "42505",
"Score": "1",
"body": "MySQL will also allow for `SOUNDEX` expressions which help on spellcheckers too!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T14:00:38.413",
"Id": "42507",
"Score": "0",
"body": "@phpisuber01 That would be a great way to limit potential matches"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-11T23:42:56.850",
"Id": "27284",
"ParentId": "27173",
"Score": "3"
}
},
{
"body": "<p>Try loading the words into a Binary Search Tree instead of an Array, a BST is much faster when it comes to search compared to the array</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-05T11:47:31.177",
"Id": "29395",
"ParentId": "27173",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-08T15:04:40.573",
"Id": "27173",
"Score": "5",
"Tags": [
"php",
"strings",
"php5"
],
"Title": "PHP spell checker with suggestions for misspelled words"
}
|
27173
|
<p>I want to implement in my code a cache mechanism with a fixed duration. For example an iframe will be cached for one hour, or a script file will be cached for 24 hours.</p>
<p>This is how I implemented it, with a rounded timestamp (simplified code assuming that the url doesn't have any query or hash part):</p>
<pre><code>var duration=86400000; // example for 1 day = 86400000 milliseconds
url=url+"?_ts="+ getTimeStamp(duration);
function getTimeStamp(roundTime) {
var timeStamp=new Date().getTime();
if (roundTime) {timeStamp=Math.floor(timeStamp/roundTime);}
return timeStamp;
}
</code></pre>
<p>My questions:</p>
<ul>
<li>Are there any traps to watch for, or is the above code going to work just fine in all situations (dynamic script tag, iframe, ajax)?</li>
<li>Is there a better way to do it, for example with a JavaScript library? </li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-08T20:28:35.980",
"Id": "42193",
"Score": "0",
"body": "Cache at what level?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-08T21:17:19.727",
"Id": "42194",
"Score": "0",
"body": "@fge this is for client side JavaScript, so I am talking about browser cache."
}
] |
[
{
"body": "<p>I suggest you read more about rules on <a href=\"http://blog.httpwatch.com/2007/12/10/two-simple-rules-for-http-caching/\" rel=\"nofollow\">simple rules for HTTP caching</a>, and <a href=\"http://blog.httpwatch.com/2009/08/07/ajax-caching-two-important-facts/\" rel=\"nofollow\">simple rules for AJAX caching</a>. These should give you a heads up on gotchas, especially in IE as well as the right headers to send for HTTP caching.</p>\n\n<p>A more proper way to do this is to send the right headers. This would mean some server-side action and using the <code>Expires</code> header.</p>\n\n<p>Anyways, let's do cache busting instead. This is the method you are trying to do, which is to append a variable value into a query string. This assumes that your resources are \"forever cached\" and needs busting to bring in a new version.</p>\n\n<p>Here's a few gotchas in your code:</p>\n\n<ul>\n<li><p>It doesn't persist during page load.</p>\n\n<p>Since you don't have any persistence layer in your code, each page load will generate a new time stamp for the resource, and will reload them from the server instead of the cache.</p></li>\n<li><p>What happens when it expires?</p>\n\n<p>I don't seem to see code that tells if the resource has already expired, unless you have other code that does that for you.</p>\n\n<p>If without it, you should build a collection that records the urls and their times. Then you refer to that collection to get the url of the resource. If the resource has not expired, then return the previously generated url. If it has expired, then generate a new url with a new time stamp and hand it for use.</p></li>\n</ul>\n\n<p>Here's code that should get you on the right track. This assumes that the resources never expire, so that you need the cache-buster mechanism going.</p>\n\n<pre><code>(function(ns){\n\n //Read from local storage, if any, or use an empty object\n var collection = /*read from local storage*/ || {};\n\n ns.generate(url,duration){\n\n //return a runnable function that generates either an existing url\n //or a newly generated url\n return function(){\n var currentDate = Date.now();\n\n //if URL isn't in collection or has already expired\n if(!collection.hasOwnProperty(url) || collection[url].expires < currentDate){\n //generate the url and store\n collection[url] = {\n url : url,\n expires : currentDate + duration;\n stampedUrl : url += '?_ts='+ (currentDate + duration)\n }\n\n /*save in local storage*/\n\n }\n\n //return the url\n return collection[url].stampedUrl;\n }\n }\n}(this.StampedUrl = this.StampedUrl || {}));\n</code></pre>\n\n<p>Sample usage:</p>\n\n<pre><code>//Generate and store our URL. This should return a runnable function\n//that returns an unexpired URL or a newly generated url\nvar myScript = StampedUrl.generate('http://example.com/someScript.js',3600);\n\n//Use function to generate the URL.\n$.get(myScript(),function(){...});\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-09T06:31:48.960",
"Id": "42205",
"Score": "0",
"body": "Thanks for the detailed reply! I'll take a look at the links. One thing I don't agree with (and that's the point of the code): if you reload within the duration interval, the timestamp in my code will remain the same, no need to keep track of it in local storage. I have built a quick fiddle to demonstrate it: http://jsfiddle.net/h835X/1/ . There was actually a mistake in my initial post (I used seconds instead of milliseconds), I have corrected it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-07T00:31:57.587",
"Id": "54510",
"Score": "0",
"body": "Someone has to make the inevitable quote; might as well be me. \"There are only two hard things in Computer Science: cache invalidation and naming things.\" – Phil Karlton"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-09T03:50:07.217",
"Id": "27185",
"ParentId": "27177",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-08T18:27:53.400",
"Id": "27177",
"Score": "1",
"Tags": [
"javascript",
"ajax",
"cache"
],
"Title": "Cache mechanism with duration"
}
|
27177
|
<p>I think I'd like to learn Clojure eventually, but at the moment am having fun with <a href="http://docs.hylang.org/en/latest/" rel="nofollow">Hy</a>, a "dialect of Lisp that's embedded in Python." </p>
<pre><code>(import socket)
(defn echo-upper (sock)
(.send c (.upper (.recv c 10000)))
(.close c)
)
(def s socket.socket)
(.bind s (tuple ["" 8000]))
(.listen s 5)
(while True
(echo-upper (.__getitem__ (s.accept) 0))
)
</code></pre>
<p>Python generated from ABS with <a href="https://pypi.python.org/pypi/astor/0.2.1" rel="nofollow">astor</a>:</p>
<pre><code>import socket
def echo_upper(sock):
c.send(c.recv(10000).upper())
return c.close()
s = socket.socket
s.bind(tuple([u'', 8000]))
s.listen(5)
while True:
echo_upper(s.accept().__getitem__(0))
</code></pre>
<p>I'm not worried about not dealing with connections properly etc, I'd just like feedback on using lispy syntax. I'm tempted to do things like <code>((getattr s "bind") (tuple ["" 8000]))</code> because it looks more like simple Scheme, the only lisp I have a little experience with.</p>
<p>Any thoughts on syntax and style? Any guidelines for dealing with Python APIs in a lispy way, something that apparently happens a lot in Clojure with Java?</p>
|
[] |
[
{
"body": "<p>algernon in freenode/#hy says:</p>\n\n<blockquote>\n <p>Looks lispy enough to me, except for the <code>__getitem__</code> line.</p>\n \n <p>...and the closing braces.</p>\n</blockquote>\n\n<p>I'm think this is fix for the braces and using <code>get</code> instead of <code>__getitem__</code>:</p>\n\n<pre><code>(import socket)\n\n(defn echo-upper (sock)\n (.send c (.upper (.recv c 10000)))\n (.close c))\n\n(def s socket.socket)\n(.bind s (tuple [\"\" 8000]))\n(.listen s 5)\n(while True\n (echo-upper (get (s.accept) 0)))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-08T19:41:50.500",
"Id": "27180",
"ParentId": "27179",
"Score": "0"
}
},
{
"body": "<p>As suggested by the Hy docs, I'm trying the threading macro here:</p>\n\n<pre><code>(.send c (.upper (.recv c 10000)))\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>(-> (.recv c 10000) (.upper) (c.send))\n</code></pre>\n\n<p>I'm not sure I like it.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-08T19:55:54.813",
"Id": "27181",
"ParentId": "27179",
"Score": "0"
}
},
{
"body": "<p>I wouldn't use the threading macro here. That's most useful when you want to see the data flow, but you're using <code>c</code> two times in this expression, there's no clear flow that <code>-></code> could make easier to untangle. It makes it more complicated in this case...</p>\n\n<p>If you'd decouple the receive and the send part, then it'd be different, but then the expression becomes so simple you don't even need the macro:</p>\n\n<pre><code>(let [[received (.recv c 10000)]]\n (.send c (.upper received)))\n</code></pre>\n\n<p>With the threading macro, the inner part would become <code>(-> received (.upper) (.send c))</code> - doesn't make it much clearer, either.</p>\n\n<p>What you could do, however, is abstract away the accept -> do something -> close thing into a macro:</p>\n\n<pre><code>(defmacro with-accepted-connection [listening-socket & rest]\n (quasiquote (let [[*sock* (get (.accept (unquote listening-socket)) 0)]]\n (unquote-splice rest)\n (.close *sock*))))\n\n(with-accepted-connection s (.send *sock* (upper (.recv *sock* 10000))))\n</code></pre>\n\n<p>The above may or may not work out of the box, I just conjured it up. But something similar may make the code lispier and easier to understand the intent later.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T23:09:33.750",
"Id": "27378",
"ParentId": "27179",
"Score": "1"
}
},
{
"body": "<p>So, yeah, the threading macro is a great way of writing it - using it is a borrowed bit of syntax from Clojure :)</p>\n\n<p>FYI, using a tupple in Hy is:</p>\n\n<pre><code>(, 1 2 3)\n; (1, 2, 3)\n</code></pre>\n\n<p>If you'd like, I can help you through another version of this in a more \"Hythonic\" way (like Algernon's!)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-14T02:24:07.703",
"Id": "27384",
"ParentId": "27179",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "27378",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-08T19:25:32.130",
"Id": "27179",
"Score": "1",
"Tags": [
"python",
"lisp",
"socket",
"hy"
],
"Title": "Echoing back input in uppercase over a socket with Hy, a Python Lisp dialect"
}
|
27179
|
<p>My program will fork, launching $n children. When a child finishes, the parent will launch a new one, if we have more to launch.</p>
<pre><code>#!/usr/bin/perl
use strict;
use warnings;
use POSIX ":sys_wait_h";
#function, that every child will run
sub func
# {{{
{
my $i = shift;
my $delay = shift;
print "$i started\n";
sleep($delay);
print "$i finished\n";
}
# }}}
#max number of concurrent children
my $max_n = 2;
#number of seconds each child will sleep
my @delays = (8, 5, 5);
my $n_elements = scalar(@delays);
#number of currently running children
my $n;
if ($n_elements > $max_n) {
$n = $max_n;
}
else {
$n = $n_elements;
}
#initial children creation
my $i;
for ($i = 0; $i < $n; $i++) {
my $pid = fork();
if ($pid == 0) {
#child runs the function
func($i, $delays[$i]);
exit(0);
}
}
#any children still running?
while ($n > 0) {
#wait until one of them dies
my $dead_child_pid = wait();
print "$dead_child_pid done\n";
#do we need to create new children?
if ($i < $n_elements) {
#create a child
my $pid = fork();
if ($pid == 0) {
func($i, $delays[$i]);
exit(0);
}
else {
#move pointer to the next element of @delays
++$i;
}
}
else {
#decrease number of running children
$n--;
}
}
print "parent finished\n";
</code></pre>
<p>When I run it, it prints:</p>
<pre><code>1 started
0 started
</code></pre>
<p>Here I check the processes:</p>
<pre><code>bash-4.2$ ps -A | grep perl
3433 pts/2 00:00:00 perl
3434 pts/2 00:00:00 perl
3435 pts/2 00:00:00 perl
</code></pre>
<p>So, it created 3 processes: 3433 - parent, 3434 and 3435 - children. Then:</p>
<pre><code>1 finished
3435 done
2 started
</code></pre>
<p>Now again:</p>
<pre><code>bash-4.2$ ps -A | grep perl
3433 pts/2 00:00:00 perl
3434 pts/2 00:00:00 perl
3438 pts/2 00:00:00 perl
</code></pre>
<p>It launched the 3-rd child with pid 3438 after the death of the 2-nd.</p>
<pre><code>0 finished
3434 done
2 finished
3438 done
parent finished
</code></pre>
<p>So, everything seems to be correct with the exception of the reversed launching order of children in the 1-st loop.</p>
<p>Maybe, it's possible to unite children creation from the both loops into a function. As their code has similar parts:</p>
<pre><code> my $pid = fork();
if ($pid == 0) {
#child runs the function
func($i, $delays[$i]);
exit(0);
}
</code></pre>
<p>Do you see any more drawbacks in my code?</p>
|
[] |
[
{
"body": "<p>I think this can be improved by using queues as the main construct to convey what is going on.</p>\n\n<p>First, you have a pending queue:</p>\n\n<pre><code>my @pending = (8, 8, 5);\n</code></pre>\n\n<p>Second, you have an empty queue with the currently active workers:</p>\n\n<pre><code>my @workers;\n</code></pre>\n\n<p>And this queue has a size limit:</p>\n\n<pre><code>my $max_workers = 2;\n</code></pre>\n\n<p>This can all be run by a single <code>while</code> loop:</p>\n\n<pre><code>while(@workers < $max_workers) {\n ... add one more worker ...\n ... remove all workers that are done ...\n ... break out of loop is @pending and @workers are both empty\n ... wait for a worker to exit (or sleep) ...\n}\n</code></pre>\n\n<p>When this loop exits, you're all done.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-09T12:25:45.767",
"Id": "27195",
"ParentId": "27183",
"Score": "1"
}
},
{
"body": "<p>Here are some changes,</p>\n\n<ul>\n<li>only one while looping until children are dead</li>\n<li>new children are launched if @queue has jobs</li>\n<li>waiting for children if empty queue or max allowed forks is reached</li>\n<li>forkit function which takes worker function as first parameter</li>\n</ul>\n\n<p>Most of the time child launching is in correct order, but sometimes as you noticed, they're reversed (<code>time()</code> shows time difference for each event)</p>\n\n<pre><code>#!/usr/bin/perl\n\nuse strict;\nuse warnings;\nuse POSIX \":sys_wait_h\";\nuse Time::HiRes qw/time /;\n\nsub forkit(&) {\n my ($worker) = @_;\n\n my $pid = fork();\n if ($pid == 0) {\n $worker->();\n exit(0);\n }\n return $pid;\n}\n#function, that every child will run\nsub func {\n my $i = shift;\n my $delay = shift;\n\n print time(), \":$i started\\n\";\n sleep($delay);\n print time(), \":$i finished\\n\";\n}\n\n#max number of concurrent children\nmy $max_n = 2;\n#number of seconds each child will sleep\nmy @delays = (8, 5, 5);\n\nmy @queue = @delays;\nmy @dead_child;\n\nmy $active = 0;\nwhile (@dead_child < @delays) {\n\n if (!@queue or $active == $max_n) {\n push @dead_child, wait();\n print time(), \":$dead_child[-1] done\\n\";\n $active--;\n }\n if (@queue) {\n my $i = @delays - @queue;\n my $delay = shift @queue;\n forkit {\n func($i, $delay);\n };\n $active++;\n }\n}\n\nprint time(), \":parent finished\\n\";\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-09T13:18:48.297",
"Id": "27198",
"ParentId": "27183",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "27198",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-08T21:18:10.070",
"Id": "27183",
"Score": "2",
"Tags": [
"multithreading",
"perl"
],
"Title": "Perl mutiple children creation"
}
|
27183
|
<p>I'm new to SQLite but have programmed in BASIC (and other languages) for pushing 50 years.</p>
<p>Given the sample code extract, please offer suggestions for improvement:</p>
<pre><code> Sub addAuthor(ByVal authorlnf As String, ByVal authorfnf As String)
Dim objConn As SQLiteConnection
Dim objCommand As SQLiteCommand
objConn = New SQLiteConnection(CONNECTION_STR)
objConn.Open()
objCommand = objConn.CreateCommand()
objCommand.CommandText = "INSERT INTO [author] ([authorlnf], [authorfnf]) VALUES ('" & authorlnf & "', '" & authorfnf & "');"
Try
objCommand.ExecuteNonQuery()
Catch ex As InvalidOperationException
MessageBox.Show("An error has occurred: " & ex.Message)
Catch ex As SQLiteException
MessageBox.Show("An error has occurred: " & ex.Message)
End Try
If Not IsNothing(objConn) Then objConn.Close()
End Sub
</code></pre>
<p>This is an index of book authors and this routine will be called several thousand times. I'm replacing VB dictionaries as memory is becoming a limiting factor.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-09T12:39:15.823",
"Id": "42208",
"Score": "0",
"body": "You should consider opening a database connection to be an extremely costly operation. You really don't want to do that often at all. Also look into prepared statements and bulk inserts - I don't know VB or that API, so can't give specific advice, sorry."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-09T13:54:37.187",
"Id": "42210",
"Score": "0",
"body": "I'm beginning to come to that conclusion. The impression I had gotten probably from those using sqlite in multi-user situations is to open/close it to avoid deadlock situations. Since this a single user instance I think it's time to look at how/when I'm opening \"things\". The real acid test is when I start to do look up on the tables. I expect some degradation over dictionaries - but if I can reduce that impact to a tolerable level then I'm open to any ideas."
}
] |
[
{
"body": "<p>You aren't closing the connection inside of a <code>finally</code> statement which means that in the case your application hits one of those exceptions it will not close the connection. this isn't good.</p>\n\n<p>I recommend using a <code>using</code> block to surround the code that you need performed by a connection. something like this</p>\n\n<pre><code> Sub addAuthor(ByVal authorlnf As String, ByVal authorfnf As String)\n Dim cmdText = \"INSERT INTO [author] ([authorlnf], [authorfnf]) VALUES ('\" & authorlnf & \"', '\" & authorfnf & \"');\"\n\n Using objConn As New SQLiteConnection(CONNECTION_STR)\n Dim objCommand As New SQLiteCommand(cmdText,objConn)\n objConn.Open()\n Try\n objCommand.ExecuteNonQuery()\n Catch ex As InvalidOperationException\n MessageBox.Show(\"An error has occurred: \" & ex.Message)\n Catch ex As SQLiteException\n MessageBox.Show(\"An error has occurred: \" & ex.Message)\n End Try\n End Using\nEnd Sub\n</code></pre>\n\n<p>The syntax for the SQLite VB code may be incorrect, I was basing it off of the Syntax for SQL Server commands thinking that they would be similar.</p>\n\n<hr>\n\n<p>If SQLite follows the same usage as SQL Server then @Mat'sMug is right and command also implements <code>IDisposable</code> so you could write it like this</p>\n\n<pre><code> Sub addAuthor(ByVal authorlnf As String, ByVal authorfnf As String)\n Dim cmdText = \"INSERT INTO [author] ([authorlnf], [authorfnf]) VALUES ('\" & authorlnf & \"', '\" & authorfnf & \"');\"\n\n Using objConn As New SQLiteConnection(CONNECTION_STR)\n Using objCommand As New SQLiteCommand(cmdText, objConn)\n objConn.Open()\n Try\n objCommand.ExecuteNonQuery()\n Catch ex As InvalidOperationException\n MessageBox.Show(\"An error has occurred: \" & ex.Message)\n Catch ex As SQLiteException\n MessageBox.Show(\"An error has occurred: \" & ex.Message)\n End Try\n End Using\n End Using\nEnd Sub\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T21:54:27.373",
"Id": "57187",
"Score": "0",
"body": "I assumed that you already take care of possible SQL Injection in other code before sending the parameters to this sub"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T23:26:44.790",
"Id": "57194",
"Score": "1",
"body": "Screening strings for offensive sql is just partly addressing potential sql injection. Using full-fledged parameters is the safest way I know. That said I don't know sqlite either :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T21:52:03.347",
"Id": "35314",
"ParentId": "27184",
"Score": "6"
}
},
{
"body": "<p>I have never used SQLite either, but something is jumping at me in your code: the <code>addAuthor()</code> procedure <strong>owns the connection</strong>, which means if you're calling it 10,000 times in a loop you're going to be opening and closing 10,000 connections, which is ..well to be honest, <em>nuts</em>.</p>\n\n<p>Looking at the method's signature:</p>\n\n<pre><code>Sub addAuthor(ByVal authorlnf As String, ByVal authorfnf As String)\n</code></pre>\n\n<h3>Naming nitpicks</h3>\n\n<ul>\n<li>I believe <strong>PascalCasing</strong> is the convention for naming just about everything in VB, but what really matters is <em>consistency</em>. Try to be consistent with the language you're using - the VB API uses PascalCasing for methods.</li>\n<li>Names <code>authorlnf</code> and <code>authorfnf</code> could just as well be named <code>authorwtf</code> - they tell the reader it's something about an <em>author</em>, but to find out <em>what</em> exactly, one has to dig deeper than the method's signature. <strong>Avoid disemvoweling at all costs</strong> - it ruins reading even the best-written code base.\n<sub>well now that I think of it I'd say <code>authorlnf</code> would be author's <em>last name</em> and <code>authorfnf</code> would be author's <em>first name</em>.. still scratching my head as for what the last <code>f</code> is standing for...</sub></li>\n</ul>\n\n<hr>\n\n<h3>Serious stuff</h3>\n\n<p>What happens when <code>authorlnf</code> contains the value <code>\"Robert'); DROP TABLE author;--\"</code>?</p>\n\n<p><img src=\"https://i.stack.imgur.com/bRxGS.png\" alt=\"little bobby tables\">\n<sub>credits: xkcd/Randall Munroe</sub></p>\n\n<p>Your <code>insert</code> fails and the <code>author</code> table gets dropped (if your user has the permissions <em>and</em> there's no FK constraint involved, but that's not the point). This is called <em>SQL Injection</em> and, depending on where, how and by whom your code is being used, it may or may not be a concern - nevertheless, it's a <em>flaw</em> in your design.</p>\n\n<p>You could write yourself some <a href=\"https://stackoverflow.com/questions/910465/avoiding-sql-injection-without-parameters\">parameter-cleansing function</a> and think you're protected, but that would leave <em>you</em> the burden of proving that <em>your</em> cleansing function is undeniably safe. And you must never forget to call it!</p>\n\n<p>Or you could <a href=\"https://stackoverflow.com/questions/13477872/inserting-into-sqlite-database-with-parameters-from-vb-net\">use parameters</a>, <em>that take the value of the user input</em>. That's <strong>much</strong> harder to mess with!</p>\n\n<hr>\n\n<h3>Connection ownership</h3>\n\n<p>I think the <code>AddAuthor()</code> method shouldn't create (/own) the connection it's using. Consider this:</p>\n\n<pre><code>Sub AddAuthor(ByVal connection As SQLiteConnection, ByVal authorlnf As String, ByVal authorfnf As String)\n</code></pre>\n\n<p>All of a sudden, opening, closing and disposing the connection is no longer a concern here: you put that burden on the caller, where you're looping 10,000 times - so you open up the connection, create and execute 10,000 commands inside <code>AddAuthor()</code>, and then close the connection. That puts the <em>lite</em> in SQLite, no?</p>\n\n<hr>\n\n<p>I'll only add that you're catching known & relevant exceptions and letting unknown ones bubble up, <strong>and that's excellent</strong>. The only thing is, as @Malachi correctly pointed out, you should be closing the connection in a <code>Finally</code> block, but if your method doesn't own the connection, that's moot. However I believe a <code>Command</code> would implement <code>IDisposable</code>, so it should be <code>.Dispose()</code>'d.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-16T03:48:59.020",
"Id": "57497",
"Score": "0",
"body": "And now I understand that cartoon strip. :-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-27T18:30:18.033",
"Id": "67554",
"Score": "0",
"body": "using parameters is nice, but if they do enter something like `'); DROP TABLE Students;--` that just means that the insert or update to the Database won't cause an issue, what if that column is used in another query that isn't as safe as the input from the application/website? it could still cause issues, so you still need to filter out some characters and limit the input into the database."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-27T18:35:51.170",
"Id": "67555",
"Score": "1",
"body": "@Malachi `\"'); DROP TABLE Students;--\"` would be treated as any other string.. if all *executable* SQL statements use parameters, it shouldn't be an issue."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-14T00:14:28.473",
"Id": "35321",
"ParentId": "27184",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-09T02:31:14.473",
"Id": "27184",
"Score": "6",
"Tags": [
"vb.net",
"sqlite"
],
"Title": "Adding to an index of authors"
}
|
27184
|
<p>I've building a multi-step form that saves data in multiple models. The "base" or parent model is the Venue, and <em>has_one</em> or <em>has_many</em> other models. In the screen below, the "Basic Information" tab is the only one which is mandatory to fill. Once that is saved, a row is generated in the Venue table in the database, and the Venue.id is used in the remaining tabs for the associations. The other tabs are "good to have" data. When I click on <em>Save Changes</em>, the form data is POSTed via ajax and a success message div is shown, and I avoid reloading the page.</p>
<p><img src="https://i.stack.imgur.com/MLrlQ.png" alt="Page with 5 tabs and a form in each tab"></p>
<p>In order to render only the form when the different tabs are clicked, I've used Ajax. My _form.html.erb looks like this:</p>
<pre><code><div class="row-fluid">
<ul id="venueEditNav" class="nav nav-pills nav-stacked span3">
<li class="active"><%= link_to 'Basic Information', {:action => 'new_basic'}, remote: true %></li>
<li><%= link_to 'Function Spaces', {:action => 'new_halls'}, remote: true %></li>
<li><%= link_to 'Pricing & Terms', {:action => 'new_pricing'}, remote: true %></li>
<li><%= link_to 'Amenities', {:action => 'new_amenities'}, remote: true %></li>
<li><%= link_to 'Account Settings', {:action => 'new_settings'}, remote: true %></li>
</ul>
<div class="span7">
<div id="venueContent">
<%= render partial: 'venues/basic', locals: { :venue => @venue } %> <!-- default -->
</div>
</div>
</div>
</code></pre>
<p>For each tab, I created:</p>
<ol>
<li>Two .js.erb files - e.g: new_basic.js.erb, edit_basic.js.erb </li>
<li>One partial - e.g: _basic.html.erb</li>
</ol>
<p>Both the .js.erb files have the same one liner code plus any javascript specific to that form:</p>
<pre><code>$("#venueContent").html('<%=j render partial: 'venues/basic', locals: { :venue => @venue } %>')
</code></pre>
<p>The partial file will have the actual form code. The files for the other tabs are similar.</p>
<p>My controller looks like this:</p>
<pre><code>class VenuesController < ApplicationController
#new, index, show and other actions are unchanged from default, snipped here for brevity
def new_basic
@venue = Venue.new
@venue.build_address
@venue.build_contact
respond_to do |format|
format.js #new_basic.js.erb
end
end
def new_halls
@venue = Venue.new
@hall = Hall.new
#@hall.venue_id = @venue.id
respond_to do |format|
format.js #new_halls.js.erb
end
end
def create
@venue = Venue.new(params[:venue])
respond_to do |format|
if @venue.save
format.html { redirect_to @venue, notice: 'Venue was successfully created.' }
format.json { render json: @venue, status: :created, location: @venue }
else
format.html { render action: "new" }
format.json { render json: @venue.errors, status: :unprocessable_entity }
end
end
end
def edit_basic
@venue = Venue.find(params[:id])
respond_to do |format|
format.js #edit_basic.js.erb
end
end
def edit_halls
@venue = Venue.find(params[:id])
respond_to do |format|
format.js #edit_halls.js.erb
end
end
end
</code></pre>
<p>I did this in my routes.rb:</p>
<pre><code>resources :venues do
member do #member - requires an ID
get 'edit_basic'
get 'edit_halls'
...
end
collection do #works on a collection, does not require an ID
get 'new_basic'
get 'new_halls'
...
end
end
</code></pre>
<p>This works so far, but for 5 tabs, I've 15 files. Also, in my _form.html.erb, I've to write code to distinguish between new and edit and link to that action correctly. I'm not sure how well it will work, but before I go down that route, this whole approach looks hackish. Am I doing this the RAILS way? Is there a better way to do this?</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-09T10:11:53.713",
"Id": "27188",
"Score": "2",
"Tags": [
"beginner",
"ruby",
"ruby-on-rails",
"form",
"ajax"
],
"Title": "Multi-page form with each step loaded via Ajax"
}
|
27188
|
<p>I am fairly new at writing jQuery plugins. Moreover, I am a huge fan of best practice. </p>
<p>I have written a plugin which centers an element inside its parent. I would love some feedback on how I could have written it better.</p>
<pre><code>(function( $ ){
$.fn.verticalCenter = function(options) {
var settings = $.extend({
min: 0, // Minimum width of the viewport for the centering to take effect
max: 10000 // Maximum width of the viewport
}, options);
var center_element = function(element, parent){
var elementHeight = element.height();
parent.css({
position:'relative'
});
element.css({
position: 'absolute',
top: "50%",
marginTop:-elementHeight/2
});
}
var remove_style = function(element, parent){
parent.css({ position:'' });
element.css({ position: '', top: '', marginTop: '' });
}
var determine_action = function(element, parent){
$(window).on('load resize orientationchange', function() {
var windowWidth = window.innerWidth
if (windowWidth > settings.min && windowWidth < settings.max) {
center_element(element, parent);
}
else {
remove_style(element, parent);
}
});
}
return this.each(function(){
var $elementToCenter = $(this);
var $parent = $elementToCenter.parent();
determine_action($elementToCenter, $parent);
});
};
})( jQuery );
</code></pre>
<p>The plugin is supposed to be responsive, and it allows the user to pass in viewport min and max values. These values determine if the centering should occur.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-12T17:28:02.157",
"Id": "42453",
"Score": "0",
"body": "Could you set up a jsFiddle? Just include an example of how you see this plugin being used."
}
] |
[
{
"body": "<p>Interesting question, from a once over:</p>\n\n<ul>\n<li>Consider a <code>'use strict'</code> after <code>(function( $ ){</code></li>\n<li>You are mixing lowerCamelCase and snake_case, you should stick to lowerCamelCase</li>\n<li>I am not a fan of <code>remove_style</code>, it might cause all kinds of unintended consequences, it would be better to store the original values of <code>element</code> and <code>parent</code> and then restore them if we don't center.</li>\n<li>I am also not a fan of having 1 listener function per element ( however, if you were to keep the original css info in a closure, then that's fine )</li>\n<li>The code would probably be cleaner if you let <code>center_element</code> determine the parent.</li>\n<li>The newlines before closing curly braces make the code a bit too sparse towards the end</li>\n</ul>\n\n<p>I would probably try something like this:</p>\n\n<pre><code>(function($){\n 'use strict';\n $.fn.verticalCenter = function(options) {\n\n var settings = $.extend({\n min: 0, // Minimum width of the viewport for centering to take effect\n max: 10000 // Maximum width of the viewport\n }, options);\n\n var centerElement = function(element,parent){\n\n parent.css({ position:'relative' });\n element.css({\n position: 'absolute',\n top: \"50%\",\n marginTop:-element.height() / 2\n });\n };\n\n var determine_action = function(element){\n\n var parent = element.parent(),\n originalParentStyle = parent.style(['position']),\n originalElementStyle = element.style(['position','top','marginTop']);\n\n $(window).on('load resize orientationchange', function() {\n\n var windowWidth = window.innerWidth;\n\n if (windowWidth > settings.min && windowWidth < settings.max) {\n centerElement(element, parent);\n }\n else {\n parent.css(originalParentStyle);\n element.css(originalElementStyle);\n }\n });\n };\n\n return this.each(function(){\n determine_action($(this));\n });\n };\n})(jQuery);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T19:29:54.257",
"Id": "46954",
"ParentId": "27189",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-09T10:16:50.247",
"Id": "27189",
"Score": "2",
"Tags": [
"javascript",
"jquery",
"beginner",
"plugin"
],
"Title": "jQuery plugin authoring: Vertical Center example"
}
|
27189
|
<p>I am currently writing a simple PHP script that uses themes and I found myself writing these methods as part of a class that handles theme config files:</p>
<pre><code>public function getArrayOfThemeNames()
{
$this->loadUnfilteredDirectoryListing();
$this->loadThemeFiles();
return $this->theme_files;
}
private function loadUnfilteredDirectoryListing()
{
$this->unfiltered_dir_listing = scandir($this->theme_config_directory);
}
private function loadThemeFiles()
{
foreach($this->unfiltered_dir_listing as $file)
{
if($file != ".." and $file != ".")
$this->theme_files[] = $file;
}
}
</code></pre>
<p>Does the <code>getArrayOfThemeNames()</code> method violate SRP, as it could be argued it does two (or potentially even three)? It loads the theme files array and then returns it.</p>
<p>Am I over-thinking this or should this be split into two methods -- one that fills the themes array, and another that returns it?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-11T14:31:07.863",
"Id": "42344",
"Score": "1",
"body": "I'm no PHP guru, but is there any reason why you're using class members to pass values around instead of just local variables?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-11T16:36:38.473",
"Id": "42359",
"Score": "0",
"body": "My view -- and it may be wrong, I'd be happy to have thoughts on this -- was that it avoiding unnecessary use of parameters which wouldn't contribute anything."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-11T18:57:49.520",
"Id": "42363",
"Score": "0",
"body": "On further consideration -- I am now edging towards using arguments, as the variables are modified and used only in one place."
}
] |
[
{
"body": "<p>Well, the function kind-of sort-of violates SRP...but according to <a href=\"http://butunclebob.com/ArticleS.UncleBob.SrpInRuby\" rel=\"nofollow\">Uncle Bob</a>, I think your class violates the SRP moreso than the function. </p>\n\n<p>Your class above, has three functions within it: <code>getArrayOfThemeNames(), loadUnfilteredDirectoryListing(), and loadThemeFiles()</code>. One of them scans the directory, one of theme creates an array of theme names, and another loads the theme files. One of those methods should not be in there: <code>loadUnfilteredDirectoryListing</code> should be in its own class called <code>DirectoryLister{}</code> or something. Which means, by extension, that <code>getArrayOfThemeNames()</code> is in violation of SRP. To quote Atwood - SRP is about \"choosing a single, clearly defined goal for any particular bit of code: Do One Thing ... But in choosing one thing, you are ruling out an infinite universe of other possible things you could have done. It also means consciously choosing what your code won't do.\". So in the end, its up to you whether this violates SRP and whether you would choose to follow SRP so deeply that you violate OOP or DRY. </p>\n\n<p>Perhaps someone with more experience can chime in or prove me wrong (heck, always good to learn something from someone else)</p>\n\n<p><strong>EDIT:</strong> See (<a href=\"http://www.oodesign.com/single-responsibility-principle.html\" rel=\"nofollow\">http://www.oodesign.com/single-responsibility-principle.html</a>) article as well for clarification. </p>\n\n<p><strong>REVISIT 01/26/2015</strong>: Revisiting this answer, I would rewrite the code as follows:</p>\n\n<pre><code>class Theme {\n public $theme_directory;\n public $theme_files;\n\n public function __construct($theme_directory){\n $this->theme_directory = $theme_directory;\n }\n\n public function get_theme_names() /* Array */ {\n $this->load_theme_files();\n return $this->theme_files;\n }\n\n private function load_theme_files(Directory $directory) /* Null */ {\n $directory->directory = $this->theme_directory;\n foreach($directory->load_unfiltered() as $file) {\n if($file != '..' && $file != '.') {\n $this->theme_files[] = $file;\n }\n }\n }\n}\n\nclass Directory {\n public $directory;\n\n public function __construct() {\n $this->directory = $directory;\n }\n\n private function load_unfiltered() /* array */ {\n return scandir($this->directory);\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-11T14:25:29.187",
"Id": "27269",
"ParentId": "27194",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "27269",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-09T12:19:48.260",
"Id": "27194",
"Score": "2",
"Tags": [
"php"
],
"Title": "Loading array of themes"
}
|
27194
|
<p>I have recently written the following Pong game in Java:</p>
<p><code>Pong</code> class:</p>
<pre><code>import java.awt.Color;
import javax.swing.JFrame;
public class Pong extends JFrame {
private final static int WIDTH = 700, HEIGHT = 450;
private PongPanel panel;
public Pong() {
setSize(WIDTH, HEIGHT);
setTitle("Pong");
setBackground(Color.WHITE);
setResizable(false);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
panel = new PongPanel(this);
add(panel);
}
public PongPanel getPanel() {
return panel;
}
public static void main(String[] args) {
new Pong();
}
}
</code></pre>
<p><code>PongPanel</code> class:</p>
<pre><code>import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JPanel;
import javax.swing.Timer;
public class PongPanel extends JPanel implements ActionListener, KeyListener {
private Pong game;
private Ball ball;
private Racket player1, player2;
private int score1, score2;
public PongPanel(Pong game) {
setBackground(Color.WHITE);
this.game = game;
ball = new Ball(game);
player1 = new Racket(game, KeyEvent.VK_UP, KeyEvent.VK_DOWN, game.getWidth() - 36);
player2 = new Racket(game, KeyEvent.VK_W, KeyEvent.VK_S, 20);
Timer timer = new Timer(5, this);
timer.start();
addKeyListener(this);
setFocusable(true);
}
public Racket getPlayer(int playerNo) {
if (playerNo == 1)
return player1;
else
return player2;
}
public void increaseScore(int playerNo) {
if (playerNo == 1)
score1++;
else
score2++;
}
public int getScore(int playerNo) {
if (playerNo == 1)
return score1;
else
return score2;
}
private void update() {
ball.update();
player1.update();
player2.update();
}
public void actionPerformed(ActionEvent e) {
update();
repaint();
}
public void keyPressed(KeyEvent e) {
player1.pressed(e.getKeyCode());
player2.pressed(e.getKeyCode());
}
public void keyReleased(KeyEvent e) {
player1.released(e.getKeyCode());
player2.released(e.getKeyCode());
}
public void keyTyped(KeyEvent e) {
;
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawString(game.getPanel().getScore(1) + " : " + game.getPanel().getScore(2), game.getWidth() / 2, 10);
ball.paint(g);
player1.paint(g);
player2.paint(g);
}
}
</code></pre>
<p><code>Ball</code> class:</p>
<pre><code>import java.awt.Graphics;
import java.awt.Rectangle;
import javax.swing.JOptionPane;
public class Ball {
private static final int WIDTH = 30, HEIGHT = 30;
private Pong game;
private int x, y, xa = 2, ya = 2;
public Ball(Pong game) {
this.game = game;
x = game.getWidth() / 2;
y = game.getHeight() / 2;
}
public void update() {
x += xa;
y += ya;
if (x < 0) {
game.getPanel().increaseScore(1);
x = game.getWidth() / 2;
xa = -xa;
}
else if (x > game.getWidth() - WIDTH - 7) {
game.getPanel().increaseScore(2);
x = game.getWidth() / 2;
xa = -xa;
}
else if (y < 0 || y > game.getHeight() - HEIGHT - 29)
ya = -ya;
if (game.getPanel().getScore(1) == 10)
JOptionPane.showMessageDialog(null, "Player 1 wins", "Pong", JOptionPane.PLAIN_MESSAGE);
else if (game.getPanel().getScore(2) == 10)
JOptionPane.showMessageDialog(null, "Player 2 wins", "Pong", JOptionPane.PLAIN_MESSAGE);
checkCollision();
}
public void checkCollision() {
if (game.getPanel().getPlayer(1).getBounds().intersects(getBounds()) || game.getPanel().getPlayer(2).getBounds().intersects(getBounds()))
xa = -xa;
}
public Rectangle getBounds() {
return new Rectangle(x, y, WIDTH, HEIGHT);
}
public void paint(Graphics g) {
g.fillRect(x, y, WIDTH, HEIGHT);
}
}
</code></pre>
<p><code>Racket</code> class:</p>
<pre><code>import java.awt.Graphics;
import java.awt.Rectangle;
public class Racket {
private static final int WIDTH = 10, HEIGHT = 60;
private Pong game;
private int up, down;
private int x;
private int y, ya;
public Racket(Pong game, int up, int down, int x) {
this.game = game;
this.x = x;
y = game.getHeight() / 2;
this.up = up;
this.down = down;
}
public void update() {
if (y > 0 && y < game.getHeight() - HEIGHT - 29)
y += ya;
else if (y == 0)
y++;
else if (y == game.getHeight() - HEIGHT - 29)
y--;
}
public void pressed(int keyCode) {
if (keyCode == up)
ya = -1;
else if (keyCode == down)
ya = 1;
}
public void released(int keyCode) {
if (keyCode == up || keyCode == down)
ya = 0;
}
public Rectangle getBounds() {
return new Rectangle(x, y, WIDTH, HEIGHT);
}
public void paint(Graphics g) {
g.fillRect(x, y, WIDTH, HEIGHT);
}
}
</code></pre>
<p>How can I improve/optimize my code? Any thoughts are appreciated.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-09T13:13:12.200",
"Id": "42209",
"Score": "0",
"body": "There are many instance variables which can be made `final`, you can start with this"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-09T15:40:02.103",
"Id": "42216",
"Score": "0",
"body": "Just curious - what is the advantage of making variable names ``final`` in this context?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-10T07:31:30.973",
"Id": "42256",
"Score": "0",
"body": "@MichaelZedeler: The main advantage is that you show your intentions \"this will never change and is not supposed to change\"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-10T07:32:49.230",
"Id": "42257",
"Score": "0",
"body": "I'm not sure, but have you considered not fixing the size of the elements (including the JFrame), and instead make them relative?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-10T12:38:33.847",
"Id": "42272",
"Score": "0",
"body": "and @ZeroOne to commented only side effects, forgot for most important, 1) don't use KeyListener, use KeyBindings 2) override getPreferredSize for JPanel instead of hardcoding setSize, PreferredSize, getBounds, Rectangle.whatever ...., are uselless, all coordinates for custom painting came from getHeight/Weight, 3) apply these coordinates in paintComponent 4) Ball doesn't required own paint, 5) Timer timer = new Timer(5, this); 5miliseconds is under latency in Native OS, hard by painted in Win8 with 2GPUs, I'd use 25-33 ms 6) [could be starting with](http://stackoverflow.com/q/8614972/714968)"
}
] |
[
{
"body": "<p>Overall I find your code quite good as it stands. :) You've got sensible classes with sane, short methods. However, there were a few points that you could improve. Let's look at your solution class by class:</p>\n\n<p><strong>Pong class:</strong></p>\n\n<p>When you turn on strict enough compiler warnings in your IDE, you'll notice it warns about the fields WIDTH and HEIGHT hiding other fields. This is indeed true: <code>public static final int WIDTH</code> and <code>HEIGHT</code> are defined in the <code>ImageObserver</code> interface high up in the inheritance hierarchy of your class. You'll notice you get no errors even if you delete the line where you define those constants. You should come up with unique names for those variables, perhaps something like PLAYING_AREA_WIDTH. That'd also be more descriptive than just plain \"WIDTH\", which could be the width of the window, or that of the playing area if it wasn't as big as the window, but as of now nobody can know it for sure without inspecting the code more closely and trying the program.</p>\n\n<p>Constructors should also be used just for light weight initialization stuff, but here it starts the entire game by initializing the PongPanel class. This is as much a fault of the PongPanel class, though. I'd add a start() method into both and change the main method of the Pong class to say \"<code>Pong game = new Pong(); game.start();</code>\". Ignoring new instances of classes, like the main method currently does, is quite confusing. Did the developer just forget to assign it into a variable? What is supposed to happen? <code>game.start()</code> would make it explicit.</p>\n\n<p><strong>PongPanel class:</strong></p>\n\n<p>Here my attention first turned to the actionPerformed, keyPressed, keyReleased and keyTyped methods, as they are all missing an @Override annotation. It's really recommendable to use one, because then you know right away that the method signature is enforced elsewhere. Interfaces are more forgiving with this, as you always get a warning if you lack a required method, but suppose you wanted to override a method that already has an implementation in a super class. Then, without an @Override annotation, someone might change the signature of the method and everything would appear to be just fine, but something would still break somewhere when the subclass's implementation wouldn't be used anymore.</p>\n\n<p>My second observation was the <code>int</code> parameter of the <code>getPlayer</code>, <code>increaseScore</code> and <code>getScore</code> methods. In Pong you aren't likely to have Integer.MAX_VALUE amount of players, or even more than two, so I find an enum would be pretty good here. Init it like <code>enum PlayerId {ONE, TWO};</code> next to the class fields, and change the method signatures from something like <code>getPlayer(int playerNo)</code> to <code>getPlayer(PlayerId player)</code>.</p>\n\n<p>This would also make the <code>increaseScore</code> method more readable, as currently <code>increaseScore(2)</code> looks like you'd increase the score by two points, whereas actually you are increasing the score for player two. Contrast that with <code>increaseScore(PlayerId.TWO)</code>, or perhaps with even renaming the method: <code>increaseScoreForPlayer(PlayerId.TWO)</code>. Remember, bits and bytes aren't expensive to store, you can use as many of them as is required to get clear and self explaining method names. :)</p>\n\n<p>At the end of the class there's the <code>paintComponent</code> method that correctly does have the @Override annotation. The problem with the method is that it asks the ball and the players for them to paint themselves. This is against the principle of separating the business logic and the presentation logic. The ball and the rackets should not need to know how they are rendered, the user interface should take care of that. The logic of the game stays the same no matter how fancy or crude the game actually looks, and this should be reflected in the design so that the classes with the logic should not change when the appearance of the game changes. I won't go into this with any more detail, but you should think this through and read about it.</p>\n\n<p><strong>Ball class:</strong></p>\n\n<p>In this class the update method looks rather confusing with all the if-statements and the math in their conditions. I'd create methods of the conditions: instead of writing <code>else if (y < 0 || y > game.getHeight() - HEIGHT - 29)</code>, I'd write <code>else if (hasHitTopOrBottom())</code> and then define method like this: </p>\n\n<pre><code>private boolean hasHitTopOrBottom() {\n return y < 0 || y > game.getHeight() - HEIGHT - 29;\n}\n</code></pre>\n\n<p>Do that for all the conditions and now, when you read the if-statement, you do not need to stop for a second to immediately understand what's happening in which branch.</p>\n\n<p>Also note that the first two branches of the if-statement, the ones that check the ball hitting the left or right side of the playing area, have two lines of duplicate code, which you should refactor into a new method named, say, <code>resetToMiddle()</code>.</p>\n\n<p>After that if - else if -set the game checks whether either player has won. I find this should happen in a separate method, say, <code>checkVictoryConditions()</code>. Now it's there as if it was comparable to the action of checking if the ball hit the walls. The final method call in <code>update()</code>, <code>checkCollision()</code>, also has a misleading name, as collisions with walls have already been checked and now it's time to only check collisions with the rackets. Actually, your <code>update()</code> method should probably just look like this: </p>\n\n<pre><code>public void update() {\n updateLocation();\n checkCollisionWithSides();\n checkVictoryConditions();\n checkCollisionWithRackets();\n}\n</code></pre>\n\n<p>Also, this class fails to reset the score when the game ends, so after either player wins, the game gets stuck showing the message box on every tick of the timer, even if you try to dismiss it. With this I also recommend you start using curly braces with if-statements, because then it's explicit where the branch block starts and ends. Currently someone who didn't use an IDE with auto formatting might break the code by trying to add the score resets within the if-statements that did not have curly braces.</p>\n\n<p><strong>Racket class:</strong> </p>\n\n<p>This class has the same issue as the Ball class: the <code>update()</code> method looks confusing. Turning the conditions into methods and giving them descriptive names will help a lot.</p>\n\n<p>Also, giving the Racket the entire Pong object in the constructor looks suspicious. A Racket implemented by a malicious player could, for example, do <code>game.getPanel().increaseScore(1)</code> calls every time its <code>update()</code> method was called. Just pass the racket its maximum and minimum height and you also avoid doing those \"game.getHeight() - HEIGHT - 29\" calculations in this class. All in all this would then add two parameters into the constructor and remove one, and externalize some calculations into the PongPanel class that creates those Rackets. Also, isn't it the Panel's responsibility to know the magic number \"29\", rather than the Racket's? You should also introduce new constants with descriptive names for magic numbers like that.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-09T22:47:31.373",
"Id": "27211",
"ParentId": "27197",
"Score": "15"
}
}
] |
{
"AcceptedAnswerId": "27211",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-09T12:54:28.910",
"Id": "27197",
"Score": "16",
"Tags": [
"java",
"game",
"swing",
"pong"
],
"Title": "Pong game in Java"
}
|
27197
|
<p>I've created <a href="http://jsfiddle.net/Cone/fAz7p/1/" rel="nofollow">this script</a> and I want to use it for website navigation in my project. As my knowledge of jQuery is quite poor, I'm not sure that code is correct and enough optimized. Could you help me to find out if there are any ways to optimize the code, and indicate mistakes I've made?</p>
<pre><code>$(function () { //scroll to the section, section's id is equal to li href attribute
$("li a").click(function () {
var liC = $(this).attr("href");
var liD = $("#" + liC).offset().top;
$("html, body").stop().animate({
scrollTop: liD
}, 'slow');
return false;
});
$(window).scroll(function () { //on scrolling defines the closets section gets it's id finds li item the href of which is equal to section's id and adds padding to it
$('.dober').each(function () {
var hRt = $(this).attr('id');
if ($(this).offset().top <= $(window).scrollTop()) {
$('li a').css({ padding: 0 });
$('a[href=' + hRt + ']').css({
padding: 10
});
} else {
$('a[href=' + hRt + ']').css({
padding: 0
});
}
});
});
});
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-09T14:02:55.920",
"Id": "42212",
"Score": "1",
"body": "I've read your code a couple of times and must say that I don't really understand what it is doing. It would probably be more readable if you used more verbose variable names in stead of names like ``liC``, ``liD`` and ``hRt``."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-09T19:18:37.580",
"Id": "42230",
"Score": "0",
"body": "Here is the fiddle that shows how the script works. http://jsfiddle.net/Cone/fAz7p/1/"
}
] |
[
{
"body": "<p><strong>- Cache your selectors:</strong> 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 has to jump into the DOM and look through all elements that would match that selection. So you should really do a search only once, and save your results for future use. This way you can look and play with them whenever you want. Ex.:</p>\n\n<pre><code>$(\"a[href=\" + hRt + \"]\").css({\n padding: 10\n});\n\n//Should be like this:\nvar whichLink = $(\"a[href=\" + hRt + \"]\"); //Saved my search to a variable, which I use later.\nwhichLink.css({\n padding: 10\n});\n\n//...\n\nwhichLink.css({\n padding: 0\n});\n</code></pre>\n\n<p><strong>- Save function calls:</strong> If you read the jQuery source code you'll see that shortcut methods like <code>.click()</code>, <code>.scroll()</code>, and etc. all reference the <code>.on()</code> method. All they do is basically call the <code>.on()</code> method with some parameters. Well why not just go straight to the meat and potatoes? Check this out:</p>\n\n<pre><code>$(\"#foo\").click(function() {\n //Do your awesomeness\n});\n\n//That does the same thing as this:\n$(\"foo\").on(\"click\", function() {\n //Do your awesomeness even awesomener.\n});\n\n//Or try this:\n\n$(window).on(\"scroll\", function () {\n //Wicked!\n});\n</code></pre>\n\n<p>That just makes the syntax so easy to rememeber as well. If you're going to use jQuery on a regular basis, I recommend that you take some time and read through the source code of the methods you're using. To find them quickly just use <code>CTRL+F</code> and type <code>methodName:</code>. That should jump you straight to what you want to know. This way you can understand what and how you are doing things, and even find better ways to do them on your own. Also if you see something you think should be done better or differently, you know how it works and you can contribute to jQuery.</p>\n\n<p>In your click functions you also might want to prevent the default browser action on a link, which is to direct the page to that link. Since you just want to perform something on your page and don't actually want the browser to leave the page you should prevent that action.\nYou can do it by passing in <code>e</code> for <code>event</code> and running <code>e.preventDefault();</code>. I see you've used <code>return false;</code> which does that, but if you want to read more on the difference between the two I would suggest [this article by Chris Coyier][1].</p>\n\n<p><strong>-Playing with visible elements:</strong> You're if statements from what I can tell are trying to detect scroll position and etc. I highly recommend you check out [this tiny plugin][2]. It basically detects if an element is visible or not at any given time. This may or may not help you out but I just thought I'd throw that out there.</p>\n\n<p><strong>-Performance Wise:</strong> Focus on the <code>.scroll()</code> event for now. The way you have it now, the code runs hundreds of times since it is called each time the window scrolls, even if the user isn't done scrolling. That's an increadible ammount of times your code will run for no reason. Not only that but then you run code on each element with the class of <code>.dober</code> - more code that gets run.\nNow we don't want to do that since it can really slow down the browser, if not crash it all together. What you'll want to do is wait for when the user stops or is done scrolling, then run the code.</p>\n\n<pre><code>var $window = $(window); //Remember, if you use a selection more than once, you should cache it\n\n$window.on(function() {\n //Here we check if there has been a call already\n //If the check is true that means the code was already called\n //So we cancel any previous calls, this way the code is only called once\n if(this.scrollEnd) clearTimeout(this.scrollEnd);\n\n //If you've made it here, the code hasn't been called, or the call has been canceled.\n this.scrollEnd = setTimeout(function() {\n $(this).trigger('scrollEnd'); //Call the actual code with a 500ms delay\n }, 500);\n});\n\n$window.on('scrollEnd', function() {\n//This is a custom event that is triggered after the timeout\n//This will only run on the last time the scroll method was called\n $('.dober').each(function () {\n var hRt = $(this).attr('id');\n var paddingAmt = 0; //Here I just slightly optimized your code\n\n if ($(this).offset().top <= $window.scrollTop()) {\n paddingAmt = 10;\n $('li a').css({ padding: 0 });\n }\n\n $('a[href=' + hRt + ']').css({\n padding: paddingAmt\n }, function(){ //Callback to set padding back to zero\n paddingAmt = 0;\n });\n });\n});\n\n\n[1]: http://css-tricks.com/return-false-and-prevent-default/\n[2]: https://github.com/teamdf/jquery-visible/\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-10T17:40:52.127",
"Id": "42292",
"Score": "0",
"body": "Dear Jonny, thx a lot for your comments and clear explanations, that was really helpful for me!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-10T15:03:51.227",
"Id": "27238",
"ParentId": "27199",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "27238",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-09T13:39:46.597",
"Id": "27199",
"Score": "2",
"Tags": [
"javascript",
"jquery"
],
"Title": "jQuery single page navigation"
}
|
27199
|
<p>I'm trying to learn learning javascript and jQuery plugin standards, and after some googling and testing I've come up with this pattern:</p>
<pre><code>;(function(window, document, $, undefined){
var plugin = function(element){
var instance = this,
somePrivateFunc = function(){
console.log(instance.options);
};
this.options = $(element).data();
this.publicFunc = function(){
somePrivateFunc();
};
}
$.fn.myplugin = function(){
return this.each(function(){
if(!$(this).data('_myplugin')){
var myplugin = new plugin(this);
myplugin.publicFunc();
$(this).data('_myplugin', myplugin);
}
});
}
}(window, document, jQuery));
</code></pre>
<p>Example</p>
<p><a href="http://jsfiddle.net/4NAXb/" rel="nofollow">http://jsfiddle.net/4NAXb/</a></p>
<p>Is this OK? Do you have any suggestions on improving it? Thanks!</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-09T16:46:18.033",
"Id": "42220",
"Score": "0",
"body": "I suggest you take a look at [jQuery Boilerplate](http://jqueryboilerplate.com/)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-09T17:24:21.800",
"Id": "42224",
"Score": "0",
"body": "What is the leading `;` for?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-09T18:41:07.560",
"Id": "42226",
"Score": "0",
"body": "idk.. i've just seen ppl do it :s"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-09T18:50:05.513",
"Id": "42229",
"Score": "1",
"body": "@svick It's explaned on the boilerplate: *The semi-colon before function invocation is a safety net against concatenated scripts and/or other plugins which may not be closed properly.*"
}
] |
[
{
"body": "<p>Here are some suggestions:</p>\n\n<ol>\n<li><p>Use <code>$.data(this, '_myplugin')</code> & <code>$.data(this, '_myplugin', myplugin)</code>. They're SO MUCH faster.</p></li>\n<li><p>Since you call <code>.publicFunc</code> every time you instantiate your plugin, you should probably move the call into your constructor instead.</p></li>\n<li><p>Public functions should be assigned to the prototype, so that we don't create a new function every time we create a new instance.</p></li>\n<li><p>Likewise, define a private function outside of the constructor, in the parent closure. Again, we don't want to have to re-create the same function over and over again.</p></li>\n</ol>\n\n<pre class=\"lang-js prettyprint-override\"><code>;(function ( window, document, $ ) {\n\n function somePrivateFunc ( instance ) {\n console.log( instance.options );\n }\n\n var Plugin = function( element ) {\n // What is this?\n this.options = $(element).data();\n this.publicFunc();\n }\n\n Plugin.prototype.publicFunc = function () { \n somePrivateFunc( this );\n };\n\n $.fn.myplugin = function () {\n return this.each(function () {\n if ( ! $.data(this, '_myplugin') ) {\n $.data( this, '_myplugin', new Plugin(this) );\n }\n }); \n };\n\n}(window, document, jQuery));\n</code></pre>\n\n<p><strong>P.S.</strong> You haven't described how you're exposing the plugin's additional methods. For that you should read the <a href=\"http://learn.jquery.com/plugins/advanced-plugin-concepts/\" rel=\"nofollow\">jQuery plugin creation tutorial</a>.</p>\n\n<p>Find the section titled <strong>Provide Public Access to Secondary Functions as Applicable</strong>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-09T21:37:04.973",
"Id": "27208",
"ParentId": "27200",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "27208",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-09T15:28:33.700",
"Id": "27200",
"Score": "1",
"Tags": [
"javascript",
"jquery",
"plugin"
],
"Title": "Review my jQuery plugin structure"
}
|
27200
|
<p>There are 10 threads and I have 15 tasks. Now I have submitted all these tasks to these threads. I need to write all these threads output to a file which I was not successful.</p>
<p>I am getting output by running all the threads.</p>
<p><strong>ThreadPool.java</strong> (Creates a Thread pool and adds all the tasks to the Blocking queue and submits)</p>
<pre><code>public class ThreadPool {
ExecutorService execService = null;
BlockingQueue<Callable<String[]>> tasks = null;
BlockingQueue<String> queue = null;
// Get a list of Employee ID's
public ThreadPool(List<String> empIDList) {
try {
tasks = new ArrayBlockingQueue<Callable<String[]>>(empIDList.size());
for(String empNum : empIDList) {
tasks.add(new ThreadTask(empNum));
}
performExecution(tasks);
} catch(Exception e) {
e.printStackTrace();
}
}
private void performExecution(BlockingQueue<Callable<String[]>> tasks) {
try {
execService = Executors.newFixedThreadPool(10);
queue = new LinkedBlockingQueue<String>();
Runnable reader = new ReaderEmp(queue);
Thread readerThread = new Thread(reader);
readerThread.start();
for(Callable<String[]> call : tasks) {
queue.add(executeTask(call, 5));
}
execService.shutdown();
} catch(Exception e) {
e.printStackTrace();
}
}
private String executeTask(Callable<String[]> task, int seconds) {
try {
String[] future = execService.submit(task).get(seconds, TimeUnit.SECONDS);
System.out.println("Successfully Executed for " + future[0]);
return future[0];
} catch(TimeoutException toe) {
System.out.println("Time Out for " + ((ThreadTask) task).getEmpID());
} catch (ExecutionException ee) {
System.out.println("Execution Exception for " + ((ThreadTask) task).getEmpID());
} catch (InterruptedException ie) {
System.out.println("Interrupted Exception for " + ((ThreadTask) task).getEmpID());
}
return ((ThreadTask) task).getEmpID() + " - Failed";
}
}
</code></pre>
<p><strong>ReaderEmp.Java</strong> (Gets each Emp_ID from the queue and writes them to the files.)</p>
<pre><code>public class ReaderEmp implements Runnable {
private final String EMP_SUCCESS = "Success.txt";
private final String EMP_FAILURE = "Failure.txt";
private BlockingQueue<String> queue;
private FileWriter writerSuccess;
private FileWriter writerFailure;
private BufferedWriter bufWriterSuccess;
private BufferedWriter bufWriterFailure;
public ReaderEmp(BlockingQueue<String> queue) {
try {
writerSuccess = new FileWriter(EMP_SUCCESS);
writerFailure = new FileWriter(EMP_FAILURE);
} catch (IOException e) {
e.printStackTrace();
}
bufWriterSuccess = new BufferedWriter(writerSuccess);
bufWriterFailure = new BufferedWriter(writerFailure);
this.queue = queue;
}
@Override
public void run() {
// This is the place which I am not able to reach while running.
// But when I keep a debugging point and running in debug mode then I am reaching.
try {
while(!queue.isEmpty()) {
synchronized (this) {
String empID = queue.take();
if(empID != null) {
if(empID.contains("Failed")) {
bufWriterFailure.append(empID.split("-")[0].trim() + ";");
} else {
bufWriterSuccess.append(empID + ";");
}
}
}
}
} catch(Exception e) {
e.printStackTrace();
} finally {
try {
synchronized (bufWriterFailure) {
bufWriterFailure.flush();
bufWriterFailure.close();
}
synchronized (bufWriterSuccess) {
bufWriterSuccess.flush();
bufWriterSuccess.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-09T10:29:16.533",
"Id": "42227",
"Score": "0",
"body": "-1. You are pretty much asking for a code review..."
}
] |
[
{
"body": "<p>I think you've over complicated matters a little.</p>\n\n<p>Some things to be aware of:</p>\n\n<ol>\n<li>new FileWriter(fileName) does not append, new FileWriter(fileName, true) does append.</li>\n<li>If you want multiple threads to write to the same file, you need to synchronize the write.</li>\n</ol>\n\n<p>See the following code which should help you solve your problem. If you really want each thread to write to the same file, then you have options such as use a static synchronized method on a helper class or global ReentrantLock or File locking.</p>\n\n<pre><code>public static void main(String[] args) throws InterruptedException, ExecutionException {\n\n int amountOfThreads = 10;\n ExecutorService threadPool = Executors.newFixedThreadPool(amountOfThreads);\n ExecutorCompletionService<Long> tasks = new ExecutorCompletionService<Long>(threadPool);\n\n //Start all of my tasks which will return long values.\n for(int i=0; i < amountOfThreads; i++) {\n tasks.submit(new Callable<Long>() {\n\n @Override\n public Long call() throws Exception {\n long startTime = System.currentTimeMillis();\n\n for(int i=0; i < 9999999; i++) {\n //Do some stuff.\n }\n\n long endTime = System.currentTimeMillis();\n return endTime-startTime;\n }\n });\n }\n\n FileWriter out = null;\n\n //Output the long values of all my tasks in order of completion.\n try {\n out = new FileWriter(\"Success.txt\");\n for(int i=0; i < amountOfThreads; i++) {\n Future<Long> task = tasks.take();\n out.write(\"Task \" + task.toString() + \" completed in \" + task.get().longValue() + \"ms\" + System.getProperty(\"line.separator\"));\n }\n } catch (IOException e) {\n e.printStackTrace();\n } finally {\n if(out!=null) {\n try {\n out.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n }\n\n threadPool.shutdown();\n\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-09T14:04:19.993",
"Id": "42228",
"Score": "0",
"body": "Thanks for the reply. Here you are doing `tasks.submit(new Callable<Long>() { ... } ` But how to pass all my tasks to it?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-09T08:51:56.033",
"Id": "27202",
"ParentId": "27201",
"Score": "1"
}
},
{
"body": "<p>Quite a few things are wrong with your code.</p>\n\n<ul>\n<li>Several threads are trying to write to the same file simultaneously. Either synchronize on a shared FileWriter or simply have each task write to its own file, and merge them afterwards. Given that the computation itself is trivial, the latter is probably preferable. and if the size of the input is small, it's probably not even worth doing this over multiple threads.</li>\n<li>You mix the use of an ExecutorService, with managing threads yourself. Define all the things you want to do on different threads as <code>Runnable</code> or <code>Callable</code> implementations, and submit those to an ExecutorService.</li>\n<li>You do not <a href=\"http://www.ibm.com/developerworks/java/library/j-jtp05236/index.html\" rel=\"nofollow\">properly handle InterruptedException</a>.</li>\n<li>tasks is a <code>LinkedBlockingQueue</code>, but could simply be an <code>ArrayList</code>.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-12T10:44:42.523",
"Id": "42415",
"Score": "0",
"body": "+1 Thanks for the suggestions. I will look in to all these and update if there are any more issues that I'm facing."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-10T21:07:38.740",
"Id": "27248",
"ParentId": "27201",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-09T06:40:25.477",
"Id": "27201",
"Score": "3",
"Tags": [
"java",
"multithreading",
"concurrency",
"file"
],
"Title": "Reading output from multiple threads and writing to a file"
}
|
27201
|
<p>I am trying to start learning Python using <a href="http://learnpythonthehardway.org" rel="nofollow"><em>Learn Python the Hard Way</em></a>. I wrote my first game that works as far as tested. It was done as an exercise for <a href="http://learnpythonthehardway.org/book/ex45.html" rel="nofollow">this</a>.</p>
<p>Please give me some constructive criticism on this program on sections and areas where I can improve. I realise that my object-oriented programming specifically, and my programming in general, still needs lots of work:</p>
<pre><code>"""
MathChallenge:
A game randomly creating and testing math sums with 4 operators: addition, subtraction, multiplication and division.
Difficulty levels are incremented after each correct answer.
No more than 3 incorrect answers are accepted.
"""
from random import randint, choice
class Math(object):
"""Class to generate different math sums based on operator and difficulty levels"""
def __init__(self):
"""To initialise difficulty on each run"""
self.difficulty = 1
def addition(self, a, b):
"""To return 'addition', '+' sign , and answer of operation"""
return ('addition', '+', a+b)
def subtraction(self, a, b):
"""To return 'subtraction', '-' sign , and answer of operation"""
return ('subtraction', '-', a-b)
def multiplication(self, a, b):
"""To return 'multiplication', '*' sign , and answer of operation"""
return ('multiplication', '*', a*b)
def division(self, a, b):
"""To return 'division', '/' sign , and answer of operation"""
return ('division', '/', a/b)
def mathsum(self, difficulty):
"""Function that generates random operator and math sum checks against your answer"""
print "Difficulty level %d." % difficulty
#let's initialize some random digits for the sum
a = randint(1,5)*difficulty
b = randint(1,5)*difficulty
#Now let's choose a random operator
op = choice(self.operator)(a, b)
print "Now lets do a %s calculation and see how clever you are." % op[0]
print "So what is %d %s %d?" % (a, op[1], b)
correct = False
incorrect_count = 0 #No more than 3 incorrect answers
while not correct and incorrect_count<3:
ans = int(raw_input(">"))
if ans == op[2]:
correct = True
print "Correct!"
self.difficulty += 1
self.mathsum(self.difficulty) #Restart the function with higher difficulty
else:
incorrect_count += 1
if incorrect_count == 3: print "That's 3 incorrect answers. The end."
else: print "That's not right. Try again."
class Engine(Math):
"""Game engine"""
def __init__(self):
"""To initialise certain variables and function-lists"""
#Initialise list of math functions inherited to randomly call from list
self.operator = [
self.addition,
self.subtraction,
self.multiplication,
self.division
]
#Initialise difficulty level
self.difficulty = 1
print "Welcome to the MathChallenge game. I hope you enjoy!"
def play(self):
"""To start game"""
#start game
self.mathsum(self.difficulty)
#print returned difficulty level achieved
print "Difficulty level achieved: ", self.difficulty
# Start game
game = Engine()
game.play()
</code></pre>
|
[] |
[
{
"body": "<p>Some notes:</p>\n\n<ul>\n<li><p>You took a OOP approach. I won't say that's wrong (maybe it was even encouraged by that guide), but when learning a language like Python, where OOP is not compulsory, I'd say it preferable to take a non-OOP approach first.</p></li>\n<li><p><code>return ('addition', '+', a+b)</code>. Those 4 operations are pretty uniform, why don't you use a data structure instead? (a list, a dictionary). Use module <a href=\"http://docs.python.org/3/library/operator.html\" rel=\"nofollow\">operator</a>.</p></li>\n<li><p>You code is for version 2.x. Unless you have some good reason, it's better to use Python 3.x, you won't lose a second re-learning things later on.</p></li>\n<li><p><code>op[0]</code>, <code>op[1]</code>, <code>op[2]</code>. If I had to highlight one single aspect of good programming practices, this would be: be declarative! If your code does not look as if you are writing pseudocode (specially if you are using a high-level language), then you're doing something wrong. What's <code>op[1]</code>? No idea, we'd have to look at the function. So destructure the result giving meaningful names to the variables: <code>op_name, op_symbol, op_function = choice(self.operator)(a, b)</code>.</p></li>\n<li><p>I'd take a more <a href=\"http://docs.python.org/2/howto/functional.html\" rel=\"nofollow\">functional</a> approach, try to organize code so there are as few in-place updates of variables as possible (not always feasible or idiomatic in an imperative language like Python).</p></li>\n</ul>\n\n<p>I'd write:</p>\n\n<pre><code>import operator\nimport random\n\noperations = {\n \"addition\": (\"+\", operator.add),\n \"substraction\": (\"-\", operator.sub),\n \"multiplication\": (\"*\", operator.mul),\n \"division\": (\"/\", operator.floordiv),\n}\n\ndef ask_operation(difficulty, maxtries=3):\n maxvalue = 5 * difficulty\n x = random.randint(1, maxvalue)\n y = random.randint(1, maxvalue)\n op_name, (op_symbol, op_fun) = random.choice(list(operations.items()))\n result = op_fun(x, y)\n\n print(\"Difficulty level %d\" % difficulty)\n print(\"Now lets do a %s calculation and see how clever you are.\" % op_name)\n print(\"So what is %d %s %d?\" % (x, op_symbol, y))\n\n for ntry in range(1, 1+maxtries):\n answer = int(input(\">\"))\n if answer == result:\n print(\"Correct!\")\n return True\n elif ntry == maxtries:\n print(\"That's %s incorrect answers. The end.\" % maxtries)\n else:\n print(\"That's not right. Try again.\")\n return False\n\ndef play(difficulty):\n while ask_operation(difficulty):\n difficulty += 1\n print(\"Difficulty level achieved: %d\" % difficulty)\n\nplay(1)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-10T19:08:43.190",
"Id": "42294",
"Score": "0",
"body": "Thank you for your comments and suggestions. The guide did suggest following a OOP approach. I felt it probably was overkill for something this simple. I am just struggling to understand the For-loop. Will it always run 3 times(I understood that break is the only way to exit a for loop early)? And the \"return True\" inside the first If-statement and the \"Return False\" just outside the For-loop confuse me. I read it as changing the result to True inside the loop and then immediately outside returning False instead of True."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-10T19:14:32.083",
"Id": "42295",
"Score": "0",
"body": "I think I understand the for-loop now. If you get it right it returns True, then effectively restarts the function because the result returned is true. It then continues this until the result returned is false."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-10T20:29:06.850",
"Id": "42298",
"Score": "0",
"body": "@user2466875: exactly. Whenever possible, functions should return a value. Here I return if the user answered correctly so the called can decide what to do next. See how a non-OOP reduced to the line count a lot, and IMO without readability cost. The funcional approach says that: define your data-structures and then the functions that work upon them, but do not mix data and code."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-09T22:15:10.747",
"Id": "27210",
"ParentId": "27203",
"Score": "4"
}
},
{
"body": "<p>Try to conform to the <a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">PEP8 style guide</a>, there is a pep8 package in GNU / Linux repos for easy local checking, or try the <a href=\"http://pep8online.com/\" rel=\"nofollow\">online checker</a></p>\n\n<pre><code>Check results\n=============\n\nE501:3:80:line too long (116 > 79 characters)\nE302:10:1:expected 2 blank lines, found 1\nE501:11:80:line too long (87 > 79 characters)\nW291:21:33:trailing whitespace\nW291:25:36:trailing whitespace\nW291:30:71:trailing whitespace\nE501:34:80:line too long (93 > 79 characters)\nE231:39:22:missing whitespace after ','\nE231:40:22:missing whitespace after ','\nE501:45:80:line too long (80 > 79 characters)\nE262:49:53:inline comment should start with '# '\nE501:49:80:line too long (85 > 79 characters)\nE225:50:46:missing whitespace around operator\nW291:53:29:trailing whitespace\nE262:57:53:inline comment should start with '# '\nE501:57:80:line too long (96 > 79 characters)\nE701:61:40:multiple statements on one line (colon)\nE501:61:80:line too long (86 > 79 characters)\nE701:62:21:multiple statements on one line (colon)\nE303:66:1:too many blank lines (3)\nW291:72:80:trailing whitespace\nE123:78:13:closing bracket does not match indentation of opening bracket's line\nW291:95:13:trailing whitespace\nW292:97:12:no newline at end of file\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-12T13:42:14.640",
"Id": "27305",
"ParentId": "27203",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "27210",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-09T19:13:56.720",
"Id": "27203",
"Score": "8",
"Tags": [
"python",
"game",
"quiz"
],
"Title": "\"MathChallenge\" game for sums with 4 operators"
}
|
27203
|
<h3>TL;DR</h3>
<p>I need a way to refactor a complex user dashboard with several objects and some complex data to display a accounting chart. I have read about both presenters (also called decorators or view models) and service object, but I'm not sure if I should use one or the other, or both? And how to implement this? My model and controller are pretty messy, so if anyone have some hints or suggestions, would I really appreciate it.</p>
<h3>Long version:</h3>
<p>I'm currently working on an application that helps users to coordinate dinner clubs and all related accounting. (A dinner club is where people in a group, take turns to cook for the rest and then you pay a small amount to participate. This is pretty normal in dorms and colleges where I'm from). When you login are you presented to a dashboard with all important information separated in three blocks: the next dinner and option to registrate, the next dinner where you have to cook, and accounting overview like current debt, spendings etc.</p>
<p>This gets pretty messy: a lot of instance variables in my controller, and a lot of methods to present this view in my models.</p>
<p>So now to the real question: can anyone tell me any good hints, design patterns or general advice to help me refactor this code? I have read about presenters, service objects, decorators etc. but I'm not sure which to use and how.</p>
<p>Here are some examples of how bad it looks right now (a kitchen is the group of people that have dinner together):</p>
<pre class="lang-rb prettyprint-override"><code># app/controllers/dashboard_controller.rb
def index
@user = current_user
@kitchen = @user.kitchen
@upcoming_dinner_clubs = @user.upcoming_dinner_clubs # The next dinner clubs where the current user have to cook
@users_next_dinner_club = @user.next_dinner_club # The first of upcoming_dinner_clubs
@unpriced_dinner_clubs = @user.unpriced_dinner_clubs # Old dinner clubs where the user haven't specified a price yet
# The next dinner club in the kitchen
@next_dinner_club = @kitchen.next_dinner_club if @kitchen.next_dinner_club
@todays_dinner_club = @next_dinner_club if @next_dinner_club && @next_dinner_club.date.today?
end
</code></pre>
<p>This view shows some chart of the expenses and spendings of a user, rendered through JavaScript. My views are in HAML.</p>
<pre class="lang-html prettyprint-override"><code># app/views/dashboard/_expenses.html.haml
%h2 Dit forbrug
%p
= t '.usage_html', expenses: number_to_currency(@user.last_month_expenses), spendings: number_to_currency(@user.last_month_spendings), results: number_to_currency(@user.last_month_results)
= content_tag :div, "", id: "revenue_chart", class: "chart dashboard-chart", data: { chart: @user.usage_chart_data }
= t '.results_html', results: number_to_currency(@user.total_results)
= content_tag :div, "", id: "result_chart", class: "chart dashboard-chart", data: { chart: @user.result_chart_data }
</code></pre>
<p>Don't want you to bore you with all the details, and how the methods work, but this is the methods i have, only for displaying the expenses and spendings data in the view:</p>
<pre class="lang-rb prettyprint-override"><code># app/models/user.rb
def last_month_expenses
expenses_for((1.month + 1.day).ago, 1.day.ago)
end
def last_month_spendings
spendings_for((1.month + 1.day).ago, 1.day.ago)
end
def last_month_results
results_for((1.month + 1.day).ago, 1.day.ago)
end
def spendings_for(start_date, end_date, kitchen)
end
def expenses_for(start_date, end_date, kitchen)
end
def fee_for(start_date, end_date, kitchen)
end
def accounting_query_conditions(start_date, end_date, kitchen)
{date: start_date..end_date, kitchen_id: kitchen.id}
end
def results_for(start_date, end_date)
spendings_for(start_date, end_date) - expenses_for(start_date, end_date)
end
def total_fee(date = Date.today, kitchen = primary_kitchen)
end
def total_spendings(date = Date.today, kitchen = primary_kitchen)
end
def total_used_on_dinner_clubs(date = Date.today, kitchen = primary_kitchen)
end
def total_expenses(date = Date.today, kitchen = primary_kitchen)
end
def total_results(date = Date.today, kitchen = primary_kitchen)
total_expenses(date, kitchen) - total_spendings(date, kitchen)
end
</code></pre>
|
[] |
[
{
"body": "<p>There is a lot here and without diving into the pattern based approach, my first question would be have you considered using <a href=\"http://guides.rubyonrails.org/active_record_querying.html#scopes\" rel=\"nofollow\">rails scopes</a>? Maybe that answer is overly simplistic, but using scopes would get rid of a lot of your reporting methods and make you be able to do something like: </p>\n\n<pre><code>Spendings.last_month\nResults.last_month\n</code></pre>\n\n<p>And speaking of Spendings and Results, it sounds like you may want to create a rails class or model for some of these items (like Results and Spendings and Expenses) instead of just querying them from a dashboard view? I have some tableless models in my apps that are used for reporting purposes. It seems like a much cleaner approach than having a long dashboard controller doing the querying for you. In that same vein, another data / reporting centric approach that isn't rails specific is to create reporting tables (these could be rails models) that are divorced from the transactional data just so you aren't querying reports from the live system which can lead to performance hits for both users on the transactional side and the reporting side. </p>\n\n<p>Rails is very \"flat\" from a traditional 3rd normal form database architecture, so it isn't much work to create reporting tables.... Just some thoughts. Good luck.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-18T09:14:20.797",
"Id": "50155",
"Score": "0",
"body": "Thank you for your answer! I have currently added some widgets classes (im using [apotomo](https://github.com/apotonick/apotomo),but it's like presenters) to clean up my controllers, and encapsulate the logic there. The next thing i need to refactor is then the models. I will definitely try your suggestion, it seems like a very good solution :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-25T23:23:50.040",
"Id": "27785",
"ParentId": "27205",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-09T20:24:38.357",
"Id": "27205",
"Score": "1",
"Tags": [
"ruby",
"design-patterns",
"ruby-on-rails",
"haml"
],
"Title": "Complex dashboard using presenters and/or service objects"
}
|
27205
|
<p>This is my first real attempt at a Scala program. I come from a predominantly Java background, so I'd like to know if the program sticks to Scala conventions well. </p>
<p>Is it well readable or should it be formulated differently? To me, there is a lot of lines in the main function which doesn't quite bode right.</p>
<p>It is functioning and I can provide my JUnit tests to prove it. Not all tests pass as those dealing with whitespace are now different.</p>
<p>I didn't want to use any parsing library or support as that doesn't help me learn the core of the language.</p>
<pre><code>package com.wesleyacheson
import scala.io.Source
import scala.annotation.tailrec
class CSVReader2(source: Source) {
val QuoteChar = '"'
val LF = '\n'
val CR = '\r'
val Separator = ','
def readAll(lines:List[List[String]] = Nil):List[List[String]] = {
if (source.hasNext) {
return readAll(readLine()::lines)
}
return lines.reverse;
}
@tailrec final def readUntilQuote(buffered: AnyRef with BufferedIterator[Char], partial:String = ""):String = {
val char = buffered.next()
val next = if(buffered.hasNext) buffered.head else ""
(char, next) match {
case (QuoteChar, QuoteChar) => readUntilQuote(buffered, partial + buffered.next()) //We've read both charachters so skip
case (QuoteChar, _) => partial
case _ => readUntilQuote(buffered, partial + char)
}
}
def readLine():List[String] = {
val buffered = source.buffered
@tailrec def readLine(tokens:List[String] , partialToken:String):List[String] = {
val finished = {() => (partialToken::tokens).reverse}
if (!buffered.hasNext) return finished()
val char=buffered.next()
val subsequentChar = if (buffered.hasNext) buffered.head
(char, subsequentChar) match {
case (QuoteChar, x) if x != QuoteChar =>
readLine(tokens, partialToken + readUntilQuote(buffered))
case (QuoteChar, QuoteChar) =>
buffered.next();
readLine(tokens, partialToken + QuoteChar)
case (Separator, _) =>
readLine(partialToken::tokens, "")
case (CR, LF) =>
buffered.next(); finished()
case (CR, _) =>
finished()
case (LF, _) =>
finished()
case _ =>
readLine(tokens, partialToken + char)
}
}
readLine(Nil, "");
}
}
</code></pre>
<p>If interested, the unit tests are here:</p>
<pre><code>package com.wesleyacheson
import org.junit._
import Assert._
import scala.io.Source
class CsvReader2Test {
val simpleSource = Source.fromString("""abc,def,ghi
jkl, zzz""");
val quotedFields = Source.fromString("foo bar, \"foo bar\"");
@Test def VerifyReaderPassedMustNotBeNull() {
val source: Source = null;
try {
new CSVReader(source)
fail("Should have thrown exception")
} catch {
case e: IllegalArgumentException => //Expected
}
}
@Test def VerifyReadAllReturnsAStringList() {
assertTrue("Expected a List[String]", new CSVReader2(simpleSource).readAll().isInstanceOf[List[String]]);
}
@Test def VerifyNumberOfReadLinesAreCorrect() {
assertEquals(2, new CSVReader2(simpleSource).readAll().size)
}
@Test def VerifyFirstLineContainsExpectedValues() {
val firstLine = new CSVReader2(simpleSource).readAll().head
println(firstLine)
assertEquals("Checking the number of tokens in the first line", 3, firstLine.size)
assertTrue("Checking that the line contains " + "abc", firstLine.contains("abc"))
assertTrue("Checking that the line contains " + "def", firstLine.contains("def"))
assertTrue("Checking that the line contains " + "ghi", firstLine.contains("ghi"))
assertFalse("Checking that the line does not contain" + "jkl", firstLine.contains("jkl"))
}
@Test def verifyBothQuotedFieldsAreTheSame() {
val line = new CSVReader2(quotedFields).readAll().head;
assertEquals("Checking that the number of tokens in the first line", 2, line.size);
assertEquals("foo bar", line(0));
assertEquals("foo bar", line(1));
}
@Test def verifySimpleQuotedValueIsUnchanged {
println(new CSVReader2(Source.fromString("\"foo bar\",")).readLine()(0))
assertEquals("foo bar", new CSVReader2(Source.fromString("\"foo bar\",")).readLine()(0))
}
@Test def verifyDoubleQuotesAreConvertedToQuote {
assertEquals("\"foo bar\"", new CSVReader2(Source.fromString("\"\"foo bar\"\",")).readLine().head)
}
@Test def verify3QuotesAreTreatedAsDoubleQuotesWithinSection {
assertEquals("\"foo bar\"", new CSVReader2(Source.fromString("\"\"\"foo bar\"\"\",")).readLine().head)
}
@Test def verifyQuotedCommasAreReturned {
assertEquals(",", new CSVReader2(Source.fromString("\",\",")).readLine().head)
}
@Test def verifyLeadingWhiteSpaceIsRemoved {
assertEquals("abc def", new CSVReader2(Source.fromString(" abc def")).readLine().head)
}
@Test def verifyTailingWhiteSpaceIsRemoved {
assertEquals("1", new CSVReader2(Source.fromString("1 ")).readLine().head)
}
@Test def verifyQuotedLeadingWhitespaceIsPreserved {
assertEquals(" 1", new CSVReader2(Source.fromString("\" 1\"")).readLine().head)
}
@Test def verifyQuotedTailingWhitespaceIsPreserved {
assertEquals("1 ", new CSVReader2(Source.fromString("\"1 \"")).readLine().head)
}
@Test def verifyQuotedBlankLinesArePreserved{
assertEquals("first\n\rsecond", new CSVReader2(Source.fromString("\"first\n\rsecond\"")).readLine().head)
}
@Test def verifyCellsAreInTheRightOrder{
val returned = new CSVReader2(Source.fromString("first,second")).readLine()
assertEquals("first", returned(0));
assertEquals("second", returned(1));
}
@Test def verifyRowsAreInTheRightOrder{
val returned = new CSVReader2(Source.fromString("first\nsecond")).readAll()
assertEquals("first", returned(0)(0));
assertEquals("second", returned(1)(0));
}
@Test def verifyNewLineCarriageReturnIsOnlyTreatedAsOneBlankLine{
val returned = new CSVReader2(Source.fromString("first\n\rsecond")).readAll()
assertEquals("first", returned(0)(0));
assertEquals("second", returned(1)(0));
}
@Test def verifyReadsUntilFirstQuote {
assertEquals("abc\"defg", new CSVReader2(Source.fromString("")).readUntilQuote(Source.fromString("abc\"\"defg\"hi\"jklmnop").buffered ))
}
@Test def verifyThrowsExceptionIfNoQuoteFound {
try {
new CSVReader2(Source.fromString("")).readUntilQuote(Source.fromString("a").buffered)
fail()
} catch {
case e => //expected
}
}
}
</code></pre>
<p>What I see when I look at this coming from a Java viewpoint. String concatenation isn't usually done with <code>+</code>. However I don't see how to use a string buffer and keep it semi functional.</p>
<p>The program isn't a functional program. I don't think this could have been avoided using a source. Pure functional programming would have meant that I'd have to make concessions like converting the entire input to a string outside and passing that in which isn't practical.</p>
<p>I don't like the argument-less anonymous function but I don't know what else to do for it.</p>
<pre><code>val finished = {() => (partialToken::tokens).reverse}
</code></pre>
<p>I've been told that a lazy <code>val</code> may be more appropriate for this, and I tend to agree.</p>
<p>It may be better for extendability if I returned a list of token objects (or is this my Java head interfering?)</p>
<p>I wonder if any traits could be mixed in to make it more rich. If there was a trait dealing with 2-dimension tabular data for instance.</p>
<p>The buffered iterator was a bit of a cheat. My original was far longer until I added that. Feels like maybe I've skipped a bit of learning for the sake of convenience.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-15T10:44:29.190",
"Id": "108687",
"Score": "0",
"body": "@Jamal I can't agree with the tag edits. This may be a case of reinventing the wheel but the purpose of it is learning. The focus of the question isn't about how to prevent that. Similarly for csv tag, and the unit-testing. The question isn't about that. The purpose isn't to read a CSV. The tests were only in the question to prove the criteria of code review. The body changes are fine, but I'd like to revert the title and tags."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-15T13:40:11.213",
"Id": "108716",
"Score": "0",
"body": "Then you may make these changes."
}
] |
[
{
"body": "<p>Here are a few things, going from smallest to the more significant.</p>\n\n<ol>\n<li>Try to avoid using return. It isn't idiomatic, and for <a href=\"http://scalapuzzlers.com/#pzzlr-018\" rel=\"nofollow\">good reason</a>. So instead of writing <code>if (cond) return a; return b</code> you should prefer <code>if (cond) a else b</code></li>\n<li>Unless I'm missing anything, in <code>readUntilQuote</code>'s signature <code>buffered</code> should be of type <code>BufferedIterator[Char]</code> instead of <code>AnyRef with BufferedIterator[Char]</code>. The <code>AnyRef</code> there doesn't do anything useful.</li>\n<li>You can use <code>Source</code> and still have functional code. Specifically, try looking at <a href=\"http://www.scala-lang.org/api/current/#scala.io.Source\" rel=\"nofollow\"><code>Source.getLines()</code></a>. It returns an <code>Iterator[String]</code> that is lazily-evaluated but can still be used functionally almost like other collections (you can <code>map</code>, <code>fold</code>, <code>filter</code>, etc.)</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-03T08:46:07.513",
"Id": "32170",
"ParentId": "27206",
"Score": "2"
}
},
{
"body": "<p>Below you can see that I've rewritten a bit of your code. For readabilities sake my first suggestion is to attempt to make your function definitions and their parameter lists consistent with the <a href=\"http://docs.scala-lang.org/style/\" rel=\"nofollow\">Scala Style Guide</a>. Next, I would also move the <code>@tailrec</code> annotation one line above the function for which it is intended. Lastly, I would rename your inner function such that people reading your code can quickly see that it is an inner 'Helper' function. </p>\n\n<pre><code> def readLine(): List[String] = {\n // ...\n\n @tailrec\n def readLineHelper(tokens: List[String], partialToken: String): List[String] = {\n // function body\n }\n\n readLineHelper(Nil, \"\")\n }\n</code></pre>\n\n<p>You also mentioned that you didn't like your <code>finished</code> function. It appears to me that you can improve its implementation in one of two ways. At first glance it seems that <code>readLineHelpers</code> parameters <code>partialToken</code> and <code>tokens</code> are never altered throughout the course of the function, in other words they are immutable values. If this is the case than <code>finished</code> can be declared as a reference to data:</p>\n\n<pre><code> val finished = (partialToken :: tokens) reverse\n</code></pre>\n\n<p>If, however, there is some state change to <code>partialToken</code> or <code>tokens</code> then you will need to declare <code>finished</code> as you originally did, as a function value but with the following syntax:</p>\n\n<pre><code> val finished = () => (partialToken :: tokens) reverse\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-14T23:49:00.657",
"Id": "60092",
"ParentId": "27206",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-09T20:28:46.843",
"Id": "27206",
"Score": "5",
"Tags": [
"parsing",
"unit-testing",
"scala",
"reinventing-the-wheel",
"csv"
],
"Title": "Reading and parsing CSV files"
}
|
27206
|
<p>I've been studying compiler construction theory. Right now, I'm studying <a href="http://en.wikibooks.org/wiki/Compiler_Construction/Lexical_analysis#Finite_State_Automaton" rel="nofollow noreferrer">Finite State Automaton</a> and I've tried to create my own implementation. I'm not sure if my implementation is right.</p>
<p><img src="https://i.imgur.com/pDl1VZM.png" alt="State machine transition diagram"></p>
<pre><code><?php
/**
* FINITE STATE AUTOMATON
* ======================
* - states
* - starting state
* - accept state
* - transition table
*
* Input string examples:
* 10112 - Accepted
* 222 - Rejected
*
* Diagram: http://i.imgur.com/pDl1VZM.png
*/
$s1 = 'S1';
$s2 = 'S2';
$states = [];
$starting_state = $s1;
$transition_table = [
'S1' => [
'2' => 'S3',
'1' => 'S1',
'0' => 'S2',
],
'S2' => [
'1' => 'S1',
'0' => 'S2',
],
'S3' => [],
];
$input_string = '10112';
$current_state = $starting_state;
foreach (str_split($input_string) as $character) {
if (isset($transition_table[$current_state][$character])) {
$current_state = $transition_table[$current_state][$character];
$states[] = $current_state;
}
}
if (count($states) == strlen($input_string)) {
echo 'Accepted';
} else {
echo 'Rejected';
}
echo PHP_EOL;
</code></pre>
<p>Did I get the whole idea? Are there something that I've missed?</p>
<p>Is this FSA thing related to regular expressions? It seems to be similar.</p>
|
[] |
[
{
"body": "<p>It's quite good, I especially like the <code>$current_state</code> explanatory variable. Actually, I'd create another one to remove some duplication:</p>\n\n<pre><code>$transitions = $transition_table[$current_state];\nif (isset($transitions[$character])) {\n $current_state = $transitions[$character];\n $states[] = $current_state;\n}\n</code></pre>\n\n<p>Some other notes:</p>\n\n<ol>\n<li><p>The code currently ignores invalid transitions. You could break the loop immediately if a transition is invalid:</p>\n\n<pre><code>foreach (str_split($input_string) as $character) {\n $transitions = $transition_table[$current_state];\n if (isset($transitions[$character])) {\n $current_state = $transitions[$character];\n $states[] = $current_state;\n } else {\n break;\n }\n}\n</code></pre></li>\n<li><p>Inverting the isset would make the code <a href=\"http://www.codinghorror.com/blog/2006/01/flattening-arrow-code.html\" rel=\"nofollow\">flatten</a> a little bit:</p>\n\n<pre><code>foreach (str_split($input_string) as $character) {\n $transitions = $transition_table[$current_state];\n if (!isset($transitions[$character])) {\n break;\n }\n $current_state = $transitions[$character];\n $states[] = $current_state;\n}\n</code></pre></li>\n<li><p><code>$s2</code> is unused, I guess you could remove it:</p>\n\n<blockquote>\n<pre><code>$s2 = 'S2';\n</code></pre>\n</blockquote></li>\n<li><blockquote>\n <p>Are there something that I've missed?</p>\n</blockquote>\n\n<p>The linked page mentions classes and I guess it should have been an object oriented solution. Check <a href=\"http://en.wikipedia.org/wiki/State_pattern#Java\" rel=\"nofollow\">the Wikipedia article about the Java implementation</a>, it shows a great example.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-24T00:21:07.367",
"Id": "45171",
"ParentId": "27209",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-09T22:11:37.543",
"Id": "27209",
"Score": "5",
"Tags": [
"php",
"state"
],
"Title": "Finite State Automaton implementation"
}
|
27209
|
<p>A small <code>struct</code> is sent beforehand to the client that specifies <code>package_size</code> amount of data should be received which is what <code>p->data_value_1</code> contains.</p>
<p>Server side:</p>
<pre><code>void Server::sendDataSingleUser(char *data_in, int user, unsigned int package_size){
package_size_sent_ = 0;
FD_ZERO(&write_set_);
FD_SET(sockets_[user], &write_set_);
while(package_size_sent_ < package_size){
timeout_.tv_sec = 3;
timeout_.tv_usec = 0;
i_result_ = select(0, 0, &write_set_, 0, &timeout_);
// Socket free, send a package
if(i_result_ > 0){
i_result_ = send(sockets_[num_clients_], data_in+package_size_sent_, package_size - package_size_sent_, 0);
// Move buffer pointer
if(i_result_ > 0){
package_size_sent_ += i_result_;
}
// send error
if(i_result_ == SOCKET_ERROR){
// Handle the error
}
}
// Socket still bussy
else{
// Disconnect the client
}
}
}
</code></pre>
<p>Client side:</p>
<pre><code>*size_p = new char[(unsigned int)p->data_value_1];
int temp_count = 0, data_received, package_size = p->data_value_1;
while(temp_count < package_size){
data_received = recv(connect_socket_, size_p+temp_count, package_size - temp_count, 0);
// Move buffer pointer
if(data_received > 0){
temp_count += data_received;
}
}
</code></pre>
<p>What can be improved/what's incorrect?</p>
|
[] |
[
{
"body": "<p>In both read and write you should leave the loop after an error (unless you have explicitly tested and fixed the error).</p>\n\n<pre><code>while(totalRecieved < readSize)\n{\n dataRecieved = recv(socket, date + totalRecieved, readSize - totalRecieved);\n if (dataRecieved > 0)\n {\n totalRecieved += dataRecieved;\n continue;\n }\n if ((dataRecieved == -1) && (errno == EAGAIN || errno == EWOULDBLOCK))\n {\n // Simple error just try again.\n continue;\n }\n if (dataRecieved == -1 && errno == EINTR)\n {\n // An interrupt was received.\n // This is usually a signal by another thread to give up\n // but you can ignore it if you want.\n continue;\n }\n // Any other error is bad.\n // looping is just going to cause infinite loops.\n break;\n}\n\nif (totalRecieved < readSize)\n{\n // BAD THINGS HAVE HAPPENED\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-10T01:03:28.010",
"Id": "42243",
"Score": "0",
"body": "Think I got it fixed up in the server part(if an error occurs it closes the clients socket and then calls return.\n\nWill add the check to the client part, thanks!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-10T00:28:22.553",
"Id": "27214",
"ParentId": "27213",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-09T23:42:29.587",
"Id": "27213",
"Score": "3",
"Tags": [
"c++",
"tcp"
],
"Title": "Sending large data package with TCP - winsock"
}
|
27213
|
<p>I have recently gotten into Java in a Computer Science class at my high school and I am trying to learn more than just the basics I have learned in school. Yesterday, I designed a very simple text editor I named Aqua that is written with Swing. For some reason, my computer drags a little bit when I run these methods. Is it because I have a crappy computer or did I write something wrong? Thanks!</p>
<pre><code>private void save(String content, String name) throws IOException{
System.out.println(dir.toString());
if(firstRun<1){
dirCreation();
firstRun++;
}
try{
String savedText = content;
System.out.println(savedText);
File newTextFile = new File(newDir.toString() + File + name + ".aqua");
System.out.println(newDir.toString() + File.seperator + name + ".aqua");
if (!newTextFile.exists()) {
System.out.println("Created new File");
newTextFile.createNewFile();
}
try (FileWriter fw = new FileWriter(newTextFile)) {
fw.write(savedText);
}
}
catch(IOException x){
System.err.format("IOException: %s%n", x);
}
}
private void load(String name) throws FileNotFoundException, IOException{
if(firstRun<1){
dirCreation();
i++;
}
File loadingFile = new File(newDir + "\\" + name + ".aqua");
Scanner scan = new Scanner(loadingFile);
StringBuilder loadedText = new StringBuilder("");
while (scan.hasNextLine()) {
loadedText.append(scan.nextLine() + "\n");
//Is this correct usage of StringBuilder?
}
jTextArea1.setText(out);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-10T07:01:43.767",
"Id": "42251",
"Score": "3",
"body": "Use [jvisualvm](http://docs.oracle.com/javase/7/docs/technotes/guides/visualvm/profiler.html) to find what actually causes the slowness. Also do not use `+` or `concat` in a loop to build up a string. Use [StringBuilder](http://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html) instead."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-10T07:08:07.963",
"Id": "42253",
"Score": "0",
"body": "@abuzittingillifirca internally the JVM uses a `StringBuilder` to perform string concatenation, so it does not really matter"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-10T08:16:06.237",
"Id": "42265",
"Score": "4",
"body": "@fge The JVM uses internally a `StringBuffer` but it is converted back to `String` after each line. When using `StringBuffer` dedicated you only have one conversion at the end of all operations. But `StringBuilder` has the avantage that it is not synchronied."
}
] |
[
{
"body": "<p>There are formatting and whitespace issues in your code, fix them! You're also switching between declaring variables and initializing them in the next line and initializing them in the same line, be consistent!</p>\n\n<hr>\n\n<pre><code>if(i<1){\n</code></pre>\n\n<p>That hurts! What is <code>i</code>? Where does it come from? Why do you check against less then one? Keep your variable names always clear, f.e. <code>numberOfLinesInFile</code> is way better then <code>i</code> in my opinion.</p>\n\n<hr>\n\n<pre><code>new File(newDir.toString() + \"\\\\\" + name + \".aqua\");\n</code></pre>\n\n<p>This assumes that it is run on a Windows machine (or anything else that uses a backslash as path separator...which I hope no one else does). That will lead lead to problems on *nix machines, but I know that <code>/</code> works on any platform, you could also go full length and use <code>File.separator</code>.</p>\n\n<p>Or you use the constructor-overload that is provided for exactly these means:</p>\n\n<pre><code>new File(newDir.toString(), name + \".aqua\"):\n</code></pre>\n\n<hr>\n\n<pre><code>String out = \"\";\n</code></pre>\n\n<p>That's not a great name for that variable, <code>text</code> or <code>content</code> would be better suited.</p>\n\n<hr>\n\n<pre><code>out+=line + \"\\n\";\n</code></pre>\n\n<p>This has one problem, concatenating strings with the <code>+</code> is slow like whatever-place-of-ternal-pain-you-believe-in-if-any. Use a <code>StringBuilder</code>, that will speed things up considerable.</p>\n\n<hr>\n\n<pre><code>jTextArea1.setText(out);\n</code></pre>\n\n<p>Again, not a good name.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-10T07:47:34.943",
"Id": "42260",
"Score": "1",
"body": "`StringBuilder` is used by string concatenation internally! Your comment on slowness of string concatenation was true on pre 1.5 days, but not anymore"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-10T07:51:24.560",
"Id": "42261",
"Score": "0",
"body": "@fge: Do you have a link to that?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-10T07:53:04.823",
"Id": "42262",
"Score": "0",
"body": "Yep, [here](http://stackoverflow.com/questions/10078912/java-string-concatenation-best-practices-performance)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-10T08:14:32.673",
"Id": "42264",
"Score": "6",
"body": "@fge: Thank you. But that only handles building of one line, not the overall text. [A simple test application](http://pastebin.com/6UDyjdXg) shows a difference: + took 3 seconds vs StringBuilder 0. If I set it to 100,000 iterations, it's at...uhm, + never did finish within 10 minutes, StringBuilder takes 16ms..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-10T13:37:33.497",
"Id": "42279",
"Score": "0",
"body": "Okay, thanks you for the response, I will update the code now."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-10T07:43:34.343",
"Id": "27221",
"ParentId": "27216",
"Score": "6"
}
},
{
"body": "<p>First and most important: you are using Java 1.7 (as the try-with-resource statement proves), so do yourself a favor: use <code>Files</code>! The <code>File</code> API should have been marked as deprecated ever since this new API was here.</p>\n\n<p>In most situations, the <a href=\"http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html\"><code>Files</code> class itself</a> is all you need:</p>\n\n<pre><code>Path dir = Paths.get(\"/path/to/directory\");\nPath file = dir.resolve(\"nameOfFile\");\n// Create a directory, including parents\nFiles.createDirectories(dir);\n// Write the contents of a string to a file\nFiles.copy(new ByteArrayInputStream(text.getBytes(\"UTF-8\")), file);\n</code></pre>\n\n<p>Drop <code>File</code>. Real fast. Among the many, many problems it has, look at this line in your code:</p>\n\n<pre><code>// DOES NOT THROW AN EXCEPTION IF IT FAILS!\nnewTextFile.createNewFile();\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-10T13:39:16.257",
"Id": "42281",
"Score": "0",
"body": "Thanks for the reply, this is really helping me a lot. Also, in another question, do i need and how do i use different threads?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-10T13:50:30.043",
"Id": "42282",
"Score": "0",
"body": "Given what you do, I don't see the need for several threads."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-10T08:00:10.470",
"Id": "27222",
"ParentId": "27216",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "27221",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-10T03:18:23.953",
"Id": "27216",
"Score": "4",
"Tags": [
"java"
],
"Title": "Java Save/Load Optimization"
}
|
27216
|
<p>I'm going to be working on a much larger version of this program and I just wanted to see if there was anything I should change in my style of coding before I made anything larger.</p>
<p>If it wasn't obvious, this code goes through each comic on <a href="http://asofterworld.com/" rel="nofollow">A Softer World</a> and downloads each comic.</p>
<p>Oh and with larger projects, should I try and fit my <code>main()</code> function into a class or is having a large <code>main()</code> function normal with programs?</p>
<pre><code>from BeautifulSoup import BeautifulSoup as bs
from urllib import urlretrieve
from urllib2 import urlopen
from os import path, mkdir
from threading import Thread
from Queue import Queue
class Worker(Thread):
def __init__(self, queue):
self.queue = queue
self.url = 'http://asofterworld.com/index.php?id='
Thread.__init__(self)
def run(self):
while 'running':
number = self.queue.get()
soup = bs(urlopen(self.url + number))
match = soup.find('p', {'id' : 'thecomic'}).find('img')
filename = match['src'].split('/')[-1]
urlretrieve(match['src'], 'Comic/' + filename)
self.queue.task_done()
def main():
queue = Queue()
if not path.isdir('Comic'):
mkdir('Comic')
for number in xrange(1, 977):
queue.put(str(number))
for threads in xrange(20):
thread = Worker(queue)
thread.setDaemon(True)
thread.start()
queue.join()
main()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-10T06:27:56.390",
"Id": "42249",
"Score": "0",
"body": "Can you tell us something about the much larger version, to give more context to this code?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-10T06:38:16.717",
"Id": "42250",
"Score": "0",
"body": "I'm hoping to have it go through multiple sites and follow links from there to download random images. Like a web crawler, but instead of indexing things, it will just randomly download images it finds."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-12T07:56:18.083",
"Id": "42396",
"Score": "0",
"body": "One thing that can be improved is the title of your question. Since all questions here ask for code review, instead try describing what your code does. I've changed it for you, but feel free to improve it further. (We also use proper English here, so please do capitalize correctly: `i-->I`)"
}
] |
[
{
"body": "<ul>\n<li>The names <code>Worker</code> and <code>run</code> are very general, while what they are doing is actually very specific (crawl a single web site for images matching a pattern). It would be better if the names reflected their content.</li>\n<li>The magic numbers and strings in the code should either be parameters or constants. The thread count, for example, would be a good candidate for a parameter (since you might handle threading differently when importing <code>Worker</code>), while the different parts of the URL could be class constants.</li>\n<li>Regarding <code>main</code>, it should IMO only contain that which is necessary for running from a shell (as opposed to importing the functionality in another Python program). That is, when importing everything except <code>main</code> there should be no missing pieces to get the same functionality as when running from a shell.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-10T15:34:09.303",
"Id": "27239",
"ParentId": "27217",
"Score": "1"
}
},
{
"body": "<ul>\n<li><p>The observation made by @l0b0 regarding main is correct. But Ionly makes sense when the module can be imported without executing main. For that use the following pattern:</p>\n\n<pre><code>def main():\n # your actual 'standalone' invocation steps\n\nif __name__ == '__main__':\n main()\n</code></pre></li>\n<li><p>importing BeautifulSoup seems to imply you are still using version 3, which has been replaced with version 4 over a year ago and only receives bugfixes. You should switch to <a href=\"http://www.crummy.com/software/BeautifulSoup/\" rel=\"nofollow\">bs4</a> before expanding the program.</p></li>\n<li><p>you should put the actual url retrieval code in separate class. At some point (for this or other similar sites), the calls to urllib should be done with mechanize (e.g. keeping login state) or even selenium (if you need to have working javascript support to get to your target on your site).</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-12T04:11:05.907",
"Id": "27288",
"ParentId": "27217",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "27239",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-10T04:15:11.483",
"Id": "27217",
"Score": "2",
"Tags": [
"python",
"multithreading"
],
"Title": "Criticize my threaded image downloader"
}
|
27217
|
<p>I'm trying to write a multi-threaded utility that logs some audit trails to the DB every 30 minutes, or whenever my storage data structure (a list in this case) exceeds a certain limit.</p>
<p>The code works well, but having said that, my manager said there <em>could</em> potentially be some issues in the method LogUserUsageData(...) where one thread tries to add a <code>UserUsage</code> object while another thread is in the lock trying to initialize the same list. </p>
<ol>
<li>Should I be declaring my list as volatile?</li>
<li>Should I be thinking about double-locking techniques?</li>
</ol>
<p>Can anybody throw more light on this?</p>
<pre><code>namespace Utilities
{
public class UserUsageStatistics
{
private SynchronizedCollection<UserUsage> _statisticsList;
private readonly Thread _persistenceThread;
private readonly string _flag = String.Empty;
public UserUsageStatistics()
{
_statisticsList = new SynchronizedCollection<UserUsage>();
_persistenceThread = new Thread(ThreadWork);
_persistenceThread.Start();
}
public void LogUserUsageData(UserUsage userUsage)
{
if (_statisticsList.Count >= 100) PersistToDataStore();
_statisticsList.Add(userUsage);
}
void ThreadWork()
{
while (true)
{
PersistToDataStore();
Thread.Sleep(1800000);
}
}
/// <summary>
/// Persist the data to the data store.
/// </summary>
void PersistToDataStore()
{
if (_statisticsList.Count == 0) return;
try
{
SynchronizedCollection<UserUsage> tempList;
lock (_flag)
{
if (_statisticsList.Count == 0) return;
tempList = _statisticsList;
_statisticsList = new SynchronizedCollection<UserUsage>();
}
//TODO: Save to database
}
catch (Exception ex)
{
}
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-12T04:25:19.340",
"Id": "42387",
"Score": "0",
"body": "Apologies for not mentioning in the question early on. I am using .NET 3.5. ConcurrentQueue<T> won't be available here. Plans are to move our projects to 4.5, but only later this year."
}
] |
[
{
"body": "<h2>DO NOT LOCK ON EMPTY STRING</h2>\n\n<p>In .NET every string is stored only once in the AppDomain so if you are locking on empty string everything will stop until you release the lock.</p>\n\n<p>The correct syncroot can be:</p>\n\n<pre><code>private readonly object _flag = new object();\n</code></pre>\n\n<p>And yes you should use double check locking. The other thing is thati would use a ConcurrentQueue instead of SynchronizedCollection.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-10T07:04:13.143",
"Id": "42252",
"Score": "0",
"body": "Thanks for the suggestions. I will read up on ConcurrentQueue."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-10T07:10:49.053",
"Id": "42254",
"Score": "0",
"body": "But why would I be better off using a queue rather than a list?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-10T07:19:32.303",
"Id": "42255",
"Score": "0",
"body": "You can use the TryDequeu method to get elements out in a while(){} statement. If it return fail, you can save the exported objects from the queue so you don't need to create a new SyncronizedCollection when you are saving. If you will use a ConcurrentQueue you would not need to have any locking mechanism."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-10T12:45:24.320",
"Id": "42275",
"Score": "0",
"body": "It's not generally true that every string is stored only once, that applies only to interned strings. But locking on `string.Empty` is a very bad idea nevertheless."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-10T13:20:12.583",
"Id": "42278",
"Score": "0",
"body": "Better yet, in this case, the additional object can be forgone and locking on `_statisticsList` itself should be sufficient."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-10T14:42:14.233",
"Id": "42286",
"Score": "0",
"body": "@JesseC.Slicer I would think twice before locking on a field whose value changes. (I'm not saying it's wrong, but I do think it makes the code harder to reason about.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-10T14:47:41.587",
"Id": "42287",
"Score": "0",
"body": "@svick Oh, ick. Yeah, I didn't see the reassignment at first."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-10T06:47:44.193",
"Id": "27220",
"ParentId": "27219",
"Score": "4"
}
},
{
"body": "<ul>\n<li>As @PeterKiss correctly mentioned you should never lock on objects beyond your control (<a href=\"http://msdn.microsoft.com/en-us/library/c5kehkcz.aspx\" rel=\"nofollow\"><code>lock</code> statement</a>, remarks section).</li>\n<li>your code is not thread-safe as you may loose some of the entries (one thread may be waiting on a call to <code>_statisticsList.Add</code> method while the other starts and runs to completion the <code>PersistToDataStore</code> method)</li>\n<li>Use <code>System.Collections.Concurrent.ConcurrentQueue<T></code>, it will allow you to re-use the same collection instead of creating a new one (causing synchronisation issues)</li>\n<li>Use <code>System.Threading.Timer</code> class to run a method at specified intervals instead of manually creating a new thread.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-12T04:24:09.350",
"Id": "42386",
"Score": "0",
"body": "Thanks. I have modified my code to use System.Threading.Timer instead of Thread.Sleep(), as well as locked on an object instead of an empty string."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-10T09:24:27.430",
"Id": "27223",
"ParentId": "27219",
"Score": "4"
}
},
{
"body": "<pre><code>catch (Exception ex)\n{\n}\n</code></pre>\n\n<p>You should never do this. You should catch only the exceptions that you're expecting. And if you really need to catch any exception, at least log it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-12T06:47:58.310",
"Id": "42389",
"Score": "0",
"body": "Agreed. I was going to take care of that later, once I figured out the threading-related code."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-10T12:47:09.923",
"Id": "27229",
"ParentId": "27219",
"Score": "3"
}
},
{
"body": "<blockquote>\n<pre><code>void ThreadWork()\n{\n while (true)\n {\n PersistToDataStore();\n Thread.Sleep(1800000);\n }\n}\n</code></pre>\n</blockquote>\n\n<p>This is not correct, because such code will span additional Thread in application. I suppose there is more scheduled tasks than only PersistToDataStore every 30 minutes. \nIn a long run there will be a lot of threads that just sleeping. It is a complex task for OS to allocate and execute new Thread. </p>\n\n<p>You should use System.Threading.Timer:</p>\n\n<pre><code> public UserUsageStatistics()\n {\n _statisticsList = new SynchronizedCollection<UserUsage>();\n _persistenceTimer = new System.Threading.Timer(PersistToDataStore, null, TimeSpan.Zero, TimeSpan.FromMinutes(30));\n }\n</code></pre>\n\n<p>In this case ThreadWork method will not be needed anymore. And .Net Framework will execute method on available thread from an application thread pool.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-12T18:42:52.297",
"Id": "27315",
"ParentId": "27219",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-10T06:27:26.030",
"Id": "27219",
"Score": "1",
"Tags": [
"c#",
".net",
"multithreading",
"locking",
"synchronization"
],
"Title": "Multi-threaded utility that logs some audit trails"
}
|
27219
|
<p>I am learning JavaScript and I just wrote a Rock, Paper, Scissors game that will first prompt the two players for their choices and validate them. In the event of a tie, each player will choose their answer again and it will once again be validated. Everything works fine, but it feels like I have a lot of repetition going on here. Since I'm new to this, I can't figure out a way to make this more concise if possible.</p>
<pre><code>var compare = function(choice1, choice2){
while (choice1 != 'rock' && choice1 != 'paper' && choice1 != "scissors"){
choice1 = prompt('Invalid entry. Player 1, please choose rock, paper, or scissors only');
}
while (choice2 != 'rock' && choice2 != 'paper' && choice2 != "scissors"){
choice2 = prompt('Invalid entry. Player 2, please choose rock, paper, or scissors only');
}
while (choice1 == choice2){
choice1 = prompt('Tiebreaker!. Player 1, please choose rock, paper, or scissors only');
while (choice1 != 'rock' && choice1 != 'paper' && choice1 != "scissors"){
choice1 = prompt('Invalid Entry. Player 1, please choose rock, paper, or scissors only');
}
choice2 = prompt('Tiebreaker!. Player 2, please choose rock, paper, or scissors only');
while (choice2 != 'rock' && choice2 != 'paper' && choice2 != "scissors"){
choice2 = prompt('Invalid Entry. Player 2, please choose rock, paper, or scissors only');
}
}
if (choice1 == 'rock'){
if (choice2 == 'scissors'){
return 'rock wins';
}
else{
return 'paper wins';
}
}
if (choice1 == 'paper'){
if (choice2 == 'rock'){
return 'paper wins';
}
else{
return 'scissors wins';
}
}
if (choice1 == 'scissors' ){
if (choice2 == 'rock'){
return 'rock wins';
}
else{
return 'scissors wins';
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Just build an object with the associativity.</p>\n\n<pre><code>// what wins to what\nvar winsTo = {\n 'rock': 'scissors',\n 'paper': 'rock',\n 'scissors': 'paper',\n};\n\n// invalid selected\nif (!(choice1 in winsTo && choice2 in winsTo)) {\n alert(\"bad choice !\");\n return;\n}\n\n// same choice => equality\nif (choice1 == choice2) {\n alert(\"Equality!\");\n} else if (winsTo[choice1] == choice2) {\n alert(\"choice1 won!\");\n} else {\n alert(\"choice2 won!\");\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-10T06:50:48.040",
"Id": "27226",
"ParentId": "27225",
"Score": "11"
}
},
{
"body": "<p>While you can get away with this sort of thing in rock paper scissors, any more options and it becomes unmanageable. (For example, rock paper scissors lizard spock).</p>\n\n<p>There is a general-case solution to this problem and it is called an <em>adjacency matrix</em>.\nAn adjacency matrix is basically the computer's representation of a directed graph.\nThis is useful because your problem actually has a directed graph under the hood.</p>\n\n<p>Consider the following graph:</p>\n\n<p><img src=\"https://i.stack.imgur.com/EUMt1.png\" alt=\"Rock Paper Scissors state machine\">\n . . .</p>\n\n<p>In this situation, we begin at the starting state, then follow the transitions for each player's move (not all transitions are shown).</p>\n\n<p>Now it is a mathematical property of state machines such as this that they can be represented using a matrix (which we call an <code>Array</code> in computer science).</p>\n\n<p>So we create an array with a row and column for each state (1 represents victory for player 1, 0 represents tie, -1 represents victory for player 2)</p>\n\n<pre><code>Player 2 -> Rock Paper Scissors\nPlayer 1:\nRock 0 1 1\nPaper 1 0 -1\nScissors -1 1 0\n</code></pre>\n\n<p>Now if we get the user's input as a number where rock is assigned the value of <code>0</code>, paper the value <code>1</code> and scissors <code>2</code>, we can look up the result of our operation using:</p>\n\n<pre><code>var result = adjacency_matrix[player_1_value][player_2_value];\n\nswitch( result )\n{\n case 0:\n break;\n // Tie\n case 1:\n // Victory player 1\n break;\n\n case 2:\n // Victory player 2\n break;\n}\n</code></pre>\n\n<p>Now there are some nice things that are Javascript specific like dictionaries which make this a little nicer to read in code, but if you understand the fundamentals of this solution you will be able to solve any of this type of problem in any language.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-10T07:08:23.160",
"Id": "42269",
"Score": "0",
"body": "That certainly works, but you don't need that 2nd depth in this case. Let's do it simply!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-10T07:16:10.943",
"Id": "42270",
"Score": "1",
"body": "Actually there is no second depth. If you look again at the diagram you will notice that each state in the \"second depth\" has only one transition to a final state. I included it for the sake of generality."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-10T07:17:33.093",
"Id": "42271",
"Score": "0",
"body": "I mean in the javascript code, actually"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-10T07:02:19.320",
"Id": "27227",
"ParentId": "27225",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "27226",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-10T06:44:11.503",
"Id": "27225",
"Score": "6",
"Tags": [
"javascript",
"beginner",
"game",
"rock-paper-scissors"
],
"Title": "Is there a way to make my Rock, Paper, Scissors game more concise?"
}
|
27225
|
<p>Basically I have a function of the type <code>'a -> 'a</code> (an optimization function on a AST) and I want to call it (passing the previous result) until it returns the same thing as the input.</p>
<p>Right now I have this:</p>
<pre><code>let performOptimizations ast =
Seq.initInfinite (fun _ -> 0)
|> Seq.scan (fun last _ -> optimizeAst last) ast
|> Seq.pairwise
|> Seq.find (fun (first, second) -> first = second)
|> fst
</code></pre>
<p>This seems really convoluted because it is created an infinite sequence of <code>int</code>s just so that the scan will continue until the <code>ast</code> is no longer modified. I realized that I could also do something like this:</p>
<pre><code>let performOptimizations ast =
let mutable newAst = optimizeAst ast
let mutable lastAst = ast
while newAst <> lastAst do
lastAst <- newAst
newAst <- optimizeAst newAst
newAst
</code></pre>
<p>However, I would prefer to avoid mutation.</p>
<p>What's the functional, idiomatic way of doing this in F#?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-10T17:19:27.987",
"Id": "42290",
"Score": "0",
"body": "Is this the sort of situation that could be solved in C# via the `yield` keyword?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-10T17:23:29.530",
"Id": "42291",
"Score": "0",
"body": "@DanNeely I'm not sure what you mean."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-10T22:14:55.410",
"Id": "42300",
"Score": "1",
"body": "@DanNeely I don't think so. The final result here isn't a collection, it's a single item. The usual way to solve this in C# would be to use something like the `while` loop in the question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-03-08T20:28:16.943",
"Id": "150317",
"Score": "0",
"body": "The title of your post should be the function/purpose of your code."
}
] |
[
{
"body": "<p><a href=\"http://blogs.msdn.com/b/fsharpteam/archive/2011/07/08/tail-calls-in-fsharp.aspx\" rel=\"nofollow\">F# supports tail call recursion.</a></p>\n\n<p>Your algorithm would seem a perfect candidate for the approach, something along the lines of:</p>\n\n<pre><code>let performOp ast =\n let rec inner lastAst newAst =\n if lastAst = newAst then\n lastAst\n else\n inner newAst (optimizeAst newAst) \n inner ast (optimizeAst ast)\n</code></pre>\n\n<p>By default tail call optimization is turned off in Debug compiles to ensure you get full stack traces in the case of an exception in the recursive function. If you are debugging with large asts you can override this option in the project properties.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-10T13:48:30.403",
"Id": "27231",
"ParentId": "27230",
"Score": "3"
}
},
{
"body": "<p>I general, I agree with what mavnn said in his answer, I just think the function can be written in a simpler way:</p>\n\n<pre><code>let rec performOptimizations ast =\n let optimized = optimizeAst ast\n if ast = optimized then\n ast\n else\n performOptimizations optimized\n</code></pre>\n\n<p>This method also sounds like a good candidate for making it more generic, something like:</p>\n\n<pre><code>let rec doWhileNotSame seed getNextValue =\n let nextValue = getNextValue seed\n if seed = nextValue then\n seed\n else\n doWhileNotSame nextValue getNextValue\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-10T14:33:46.200",
"Id": "42284",
"Score": "0",
"body": "I think you need a 'rec' in there. But yes, it's probably neater."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-10T14:37:07.493",
"Id": "42285",
"Score": "0",
"body": "@mavnn You're right, I'm always forgetting `rec` in recursive functions."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-10T14:28:41.313",
"Id": "27237",
"ParentId": "27230",
"Score": "6"
}
},
{
"body": "<p>I know, this is an old topic. Since I don't see my approach, I am still going to submit it.</p>\n\n<p>I use a kind of a fixed point operator fix:</p>\n\n<pre><code>let rec fix f x = let y= f x in if x=y then x else fix f y\n</code></pre>\n\n<p>then the function</p>\n\n<pre><code>fix ast\n</code></pre>\n\n<p>will apply <code>ast</code> as many times to the argument as needed (or it will run forever if such an argument isn't hit). However, with this approach one has some flexibility with the \"break-condition\", maybe something along the lines.</p>\n\n<pre><code>let rec fix f condition x =\n if condition f x then x\n else fix f condition (f x)\n</code></pre>\n\n<p>where condition is of type <code>('a -> 'a) -> 'a -> bool</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-03-08T20:01:22.677",
"Id": "83590",
"ParentId": "27230",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "27237",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-10T13:30:55.183",
"Id": "27230",
"Score": "7",
"Tags": [
"f#"
],
"Title": "What's the most idiomatic way to call a function an arbitrary number of times with the previous result?"
}
|
27230
|
<p>I've created this adjacency list, but I don't like the design of the graph. The issue is that there is one pointer in the node to its adjacency list and there is a pointer in an <code>adj_list</code> node to the actual node. I am also using <code>next</code> pointers to traverse the graph in the order in which nodes were added and the list to get the adjacency list of a node.</p>
<p>Any suggestions?</p>
<pre><code>#include <queue>
enum color{
WHITE,
GREY,
BLACK
};
struct adj_list;
struct node{
int id;
int weight;
color visited;
adj_list* adj;
node(int n){
id = n;
weight = _I32_MAX;
visited = WHITE;
}
};
struct adj_list{
adj_list* next; //This next pointer for visiting each node one after another in the order in which the nodes were added to the graph
adj_list* list;
node* n;
adj_list(node& _n){
n = &(_n);
next = NULL;
list = NULL;
}
};
node* add_node(int id,std::queue<int> q , node* root)
{
node* n = new node(id);
adj_list* adj = new adj_list(*n);
n->adj = adj;
if(root == NULL){
return n;
}
std::queue<adj_list*> q1;
while(1){
adj_list* iter = root->adj;
if(q.empty())break;
int k = q.front();
q.pop();
while(iter){
if(iter->n->id == k){
q1.push(iter);
adj_list* temp = iter->list;
iter->list = new adj_list(*n);
iter->list->list = temp;
break;
}
iter = iter->next;
}
}
adj_list* iter = root->adj;
while(iter->next){
iter = iter->next;
}
iter->next = adj;
while(!q1.empty()){
adj_list* temp = q1.front();
q1.pop();
adj_list* new_adj = new adj_list(* temp->n);
adj->list = new_adj;
adj = new_adj;
}
return root;
}
</code></pre>
<p>Adding a new node to the graph:</p>
<pre><code>std::queue<int> q;
q.push(4);
q.push(9);
add_node(20,q , &root);
</code></pre>
<h3>Update:</h3>
<p>I have made some changes here to make it more C++, but an issue here I don't like is that driver has to know about the other vertexes to add to their adjacency list. I'm not sure how to get rid of that if we have to create the graph incrementally.</p>
<p>Another is to provide the graph with a matrix, but that just beats the idea behind adjacency matrix.</p>
<pre><code>#include "iostream"
#include "vector"
#include "list"
struct edge{
int destination_vertex;
edge(int ver){
destination_vertex = ver;
}
};
struct vertex{
int id;
std::list<edge> list;
vertex(int _id){
id = _id;
}
};
class graph
{
private:
std::vector<vertex*> vertexes;
int next;
public:
graph(void){
next = 0;
}
~graph(void){}
void add_node(std::vector<int> edges ){
vertex* v = new vertex(next++);
vertexes.push_back(v);
for(unsigned int i=0;i<edges.size();i++){
vertex* existing_vertex = vertexes[edges[i]];
existing_vertex->list.push_back(*(new edge (v->id)));
edge* e = new edge(edges[i]);
v->list.push_back(*e);
}
}
void print(){
for(unsigned int i = 0 ; i < vertexes.size();i++){
vertex* v = vertexes[i];
std::cout << v->id <<"->";
for(std::list<edge>::iterator iter = v->list.begin() ; iter != (v->list).end();iter++)
{
std::cout << iter->destination_vertex <<",";
}
std::cout << std::endl;
}
}
};
</code></pre>
|
[] |
[
{
"body": "<blockquote>\n <p>e.g. of adding a new node to the graph</p>\n</blockquote>\n\n<p>Well for starters I don't see the graph:</p>\n\n<p>I would expect the code to be:</p>\n\n<pre><code> Graph graph;\n graph.add_node(20,q); // Add nodes to graph.\n</code></pre>\n\n<p>Stop passing pointers around. </p>\n\n<pre><code>node* add_node(int id,std::queue<int> q , node* root)\n</code></pre>\n\n<p>Pointers have no associated ownership semantics. This is normal in C. But if you are writing C++ you should never do this. Ownership symantis defines who owns and thus who is responsible for calling delete on dynamically allocated objects. If it is an automatic variable you should probably be passing a reference (or in the case more likely making <code>add_node()</code> a member of the graph object.</p>\n\n<p>Also you manipulate node and adj_list directly from add_node. Again fine from a C perspective but not from a C++ one. You should ask the object to manipulate itself by asking it to perform some operation (ie method). Since your code is so intertwined without methods it makes it real hard to read and understand. So that's about all I have.</p>\n\n<h3>Update:</h3>\n\n<p>Comment on update section</p>\n\n<p>For every call to <code>new</code> there <strong>MUST</strong> be a call to <code>delete</code>. Without this the code will leak memory. In your case here we don't actually need any calls to new so we can remove all the leaks by just using normal automatic variables.</p>\n\n<pre><code>// might be a bit overkill\n// For just holding a destination vertex.\nstruct edge\n{\n // This should really be private\n // Once created you don't really want it changing.\n // So make it hard to change accidentally by making it private.\n // Alternatively you can make it const (but this makes copying hard\n // so I would make it private and private an accessor)\n private: int destination_vertex;\n public: int getDest() const {return destination_vertex;}\n\n // Prefer to use initializer lists.\n edge(int ver){\n destination_vertex = ver;\n }\n\n // i.e. Prefer to write like this\n edge(int ver)\n : destination_vertex(ver)\n {}\n\n // A friend for printing.\n friend std::ostream& operator<<(std::ostream& s, edge const& e)\n {\n return s << e.destination_vertex;\n }\n};\n\n\nstruct vertex\n{\n int id; // This should probably be const\n // as it never changes.\n // But because this makes copying hard\n // prefer to make it private and provide\n // an accessor.\n std::list<edge> list;\n\n // Prefer initializer lists.\n // Also prefer not to put '_' on the front of your identifers.\n // The rules are non trivial and most people don't know the actual\n // rules so its is easy to get wrong (in this case you got it correct)\n //\n vertex(int id)\n : id(id) // The compiler can easily distinguish between these too.\n {}\n\n friend std::ostream& operator<<(std::ostream& s, vertex const& v)\n {\n s << v.id << \"->\";\n std::copy(v.list.begin(), v.list.end(),\n std::ostream_iterator<edge>(s, \",\"));\n return s;\n }\n};\n</code></pre>\n\n<p>Lets fix some memory leaks.</p>\n\n<pre><code>class graph\n{\n private:\n // No need for this to be vertex*\n std::vector<vertex*> vertexes;\n\n\n // If you just make it a vector of `vetrtex` then everything works\n // as expected and you don't need to call new anywhere.\n std::vector<vertex> vertexes;\n int next;\n\n public:\n // Prefer initializer list\n // Don't put void as the parameter list.\n graph(void)\n : next(0)\n {}\n\n // You should have written this so it cleaned up all the\n // allocated memory. If your destructor does nothing then\n // don't write one, let the compiler generate one do the work\n //\n // Since we are not going to have any dynamic allocation just\n // delete it now.\n //\n // ~graph(void){}\n\n // Comment code that is non trivial it took me a while to\n // figure this out!\n //\n // Add a new node node 'n'\n // The vector of edges defines what node(s) 'n' connects too.\n // add an edge from 'n' to each node in `edges'\n // add an edge from each node in `edges' to 'n'\n //\n // Note It is assumed that `edges` does not contain any nodes\n // larger than (n-1)\n\n // When passing non trivial objects pass by reference\n // If your code is not supposed to change the code make it const\n // as well. Thus the compiler warns you if you try and modify it\n // accidentally.\n void add_node(std::vector<int> const & edges)\n /// ^^^^^ ^\n {\n // no need for dynamic allocation.\n // vector is already doing most of the work\n // vertex* v = new vertex(next++);\n // vertexes.push_back(v);\n\n // Rather just add a new element to vector\n // Then grab a reference to it for convenience.\n vertexes.push_back(vertex());\n vertex& v = vertexes.back(); // a reference to the element you\n // just added.\n\n\n\n for(unsigned int i=0;i<edges.size();i++)\n {\n // Added comment to the beginning about this\n // assumption.\n vertex& existing_vertex = vertexes[edges[i]];\n\n // This: *(new edge (v->id))\n // Dynamically allocates an edge then de-references\n // so it can be copied into a list. You lost all\n // information about the pointer you created with new\n // so the memory is leaked and lost.\n // There is no need to create dynamically allocated object\n // just use the int automatic value.\n\n existing_vertex.list.push_back(v.id);\n\n // This has the same problem as the last line.\n // apart from you are doing it in two steps so keep\n // the pointer (which you should have deleted after use) \n // edge* e = new edge(edges[i]);\n // v->list.push_back(*e);\n\n\n // This can be replaced with\n v.push_back(edges[i]);\n\n\n\n\n // In fact I would get rid of all the above lines and\n // replace with code that looks symmetrical so that you\n // can see that you are adding edges in both directions.\n\n vertexes[edges[i]].list.push_back(v.id);\n vertexes[v.id].list.push_back(edges[i]);\n\n }\n }\n\n // Methods that do not change the state of the object should\n // be marked const. \n\n void print() const\n { /// ^^^^^\n\n // Sure you can iterate by index.\n // But you could just as easily have used an iterator.\n // Also prefer to use ++i rather than i++\n // It makes no difference for integers but if you change\n // changed the way you iterate then you don't need to think\n // am I using the correct increment style.\n for(unsigned int i = 0 ; i < vertexes.size();i++){\n\n // Get a reference for ease of use\n vertex& v = vertexes[i]; \n std::cout << v.id << \"->\";\n\n // Nice use of iterator.\n // But prefer const_iterator if you are not going\n // to modify the container.\n\n for(std::list<edge>::const_ iterator iter = v.list.begin() ; iter != v.list.end();iter++)\n {\n std::cout << iter->destination_vertex <<\",\";\n }\n\n // Prefer '\\n' over std::endl\n // The difference is that std::endl() outputs a '\\n'\n // then calls flush on the stream. This makes it very\n // efficient (as the whole pointer of the buffer is\n // so we only flush to the physical stream rarely).\n std::cout << '\\n';\n }\n }\n\n // Since we have defined output operators for edge and vertex\n // We can do the same for graph:\n friend std::ostream& operator<<(std::ostream& s, graph const& g)\n {\n std::copy(v.vertexes.begin(), v.vertexes.end(),\n std::ostream_iterator<vertex>(s, \"\\n\"));\n return s;\n }\n // Now you can print a graph like this:\n // std::cout << g;\n\n};\n</code></pre>\n\n<p>After cleaning up all the comments.<br>\nIt looks like this:</p>\n\n<h3>Headers</h3>\n\n<pre><code>#include <iostream>\n#include <list>\n#include <vector>\n#include <iterator>\n</code></pre>\n\n<h3>Edge</h3>\n\n<pre><code>class edge\n{ \n int destination_vertex;\n public:\n int getDest() const {return destination_vertex;}\n\n edge(int ver)\n : destination_vertex(ver)\n {} \n\n friend std::ostream& operator<<(std::ostream& s, edge const& e)\n { \n return s << e.destination_vertex;\n } \n}; \n</code></pre>\n\n<h3>Vertex</h3>\n\n<pre><code>class graph;\nclass vertex\n{ \n friend class graph;\n int id; \n std::list<edge> list;\n\n public:\n vertex(int id) \n : id(id)\n {} \n\n friend std::ostream& operator<<(std::ostream& s, vertex const& v)\n { \n s << v.id << \"->\";\n std::copy(v.list.begin(), v.list.end(),\n std::ostream_iterator<edge>(s, \",\"));\n return s;\n } \n}; \n</code></pre>\n\n<h3>Graph</h3>\n\n<pre><code>class graph\n{ \n private:\n std::vector<vertex> vertexes;\n int next;\n\n public:\n graph()\n : next(0)\n {} \n\n //\n // Add a new node node 'n'\n // The vector of edges defines what node(s) 'n' connects too.\n // add an edge from 'n' to each node in `edges'\n // add an edge from each node in `edges' to 'n'\n //\n // Note It is assumed that `edges` does not contain any nodes\n // larger than (n-1)\n void add_node(std::vector<int> const & edges)\n { \n vertexes.push_back(vertex(next));\n\n for(unsigned int i=0;i<edges.size();++i)\n { \n vertexes[edges[i]].list.push_back(next);\n vertexes[next].list.push_back(edges[i]);\n } \n ++next;\n } \n\n friend std::ostream& operator<<(std::ostream& s, graph const& g)\n { \n std::copy(g.vertexes.begin(), g.vertexes.end(),\n std::ostream_iterator<vertex>(s, \"\\n\"));\n return s;\n } \n}; \n</code></pre>\n\n<h3>Main</h3>\n\n<pre><code>int main()\n{\n graph g;\n\n std::vector<int> v;\n g.add_node(v);\n\n v.push_back(0);\n g.add_node(v);\n\n std::cout << g << \"\\n\";\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-11T14:07:36.930",
"Id": "42339",
"Score": "0",
"body": "For there is no graph i thought i will use add_node(id,empty_q , NULL) to create the first node which will be set to root.."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-11T15:08:28.600",
"Id": "42352",
"Score": "0",
"body": "@bapusethi: That's my point. There should be a graph object. Dynamically creating nodes (like the root) enherently leads to issues of ownership and thus to memory management and from their to memory leaks. You need a graph object to encapsulate this and handle ownership concerns."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-11T17:38:50.597",
"Id": "42361",
"Score": "0",
"body": "Yes looks much better and cleaner now.."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-11-26T18:02:20.627",
"Id": "129675",
"Score": "0",
"body": "And if anything, if you want to use pointers, use `std::{unique,shared}_ptr<...>`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-11-26T19:44:07.867",
"Id": "129684",
"Score": "0",
"body": "@Ryan: Though true a vast simplification."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-10T23:41:20.550",
"Id": "27250",
"ParentId": "27241",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "27250",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-10T17:51:28.393",
"Id": "27241",
"Score": "4",
"Tags": [
"c++",
"algorithm",
"graph"
],
"Title": "Creating an adjacency list"
}
|
27241
|
<p>I have the following ajax call:</p>
<pre><code>function getPreviewText() {
$.ajax({
type: 'POST',
url: '@Url.Action("PreviewWiki")',
dataType: 'json',
data: 'source=' + $('#markItUp').val(),
success: function (data) {
$('#previewMode').html(data.RenderedSource);
}
});
};
</code></pre>
<p>Controller action:</p>
<pre><code>[HttpPost]
public ActionResult PreviewWiki(string source) {
return Json(new { RenderedSource = m_wikiEngine.Render(source, GetRenderers()) });
}
</code></pre>
<p>And modal window:</p>
<p><img src="https://i.stack.imgur.com/2B3CU.png" alt="enter image description here"></p>
<p>I can switch between the design and preview tabs instantly which allows me to make changes in "Design Mode" and then instantly preview the effect of those changes before saving it to the Wiki. This works as I expect it to but I suspect that A. somehow I can accomplish this with get instead of post and B. I might not be going about this the right way.</p>
<p>Sure, it works exactly as I want it to but this is my first real web app and I'm confident that I'm "doing things right" here.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-11T02:03:07.373",
"Id": "42304",
"Score": "0",
"body": "I can't vouch for the .NET code, but I don't see anything wrong with the JavaScript. You definitely don't want to use GET, because you'd have to include the data in the URL's query string (GET requests cannot have bodies), and then you're very likely to run into limits on the query string length. I know you've already implemented this with .NET for the rendering, but you might consider CodeMirror instead: codemirror.net"
}
] |
[
{
"body": "<p>Well there's not much code to review here, but for what's here, I'd say it looks okay. I would only make one suggestion. If all you're going to do in your controller action is return single string wrapped up in a JSON object, why not dispose of the JSON and just return the HTML as content?</p>\n\n<p>Ajax call:</p>\n\n<pre><code>function getPreviewText() {\n $.ajax({\n type: 'POST',\n url: '@Url.Action(\"PreviewWiki\")',\n dataType: 'html',\n data: 'source=' + $('#markItUp').val(),\n success: function (result) {\n $('#previewMode').html(result);\n }\n });\n};\n</code></pre>\n\n<p>Controller action:</p>\n\n<pre><code>[HttpPost]\npublic ActionResult PreviewWiki(string source) {\n return Content(m_wikiEngine.Render(source, GetRenderers()));\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-12T20:17:59.207",
"Id": "42465",
"Score": "0",
"body": "Thank you, this is exactly the sort of advice I was looking for. I originally wanted to return Content but settled for the JSON method since it was the only example I came across that I could get to work."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-10T20:45:45.107",
"Id": "27246",
"ParentId": "27245",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "27246",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-10T20:01:43.563",
"Id": "27245",
"Score": "3",
"Tags": [
"javascript",
"jquery",
"ajax",
"asp.net-mvc-4"
],
"Title": "Using AJAX to interact with MVC"
}
|
27245
|
<p>I'm learning ASP.NET and think I figured out ViewState. Can you tell me if I have it right?</p>
<p>The goal of the ViewState in this page is simply to keep the value in a DropDownList.</p>
<p>So first, let's have the aspx page markup:</p>
<pre><code><%@ Page Title="Parameters" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="ParamPage.aspx.cs" Inherits="MyCompany.MyProject.WebGUI.ParamPage" %>
...
<asp:DropDownList ID="UserList" runat="server" AutoPostBack="True" Width="125px" OnSelectedIndexChanged="UserList_SelectedIndexChanged"></asp:DropDownList>
</code></pre>
<p>In <code>Page_Load</code>, the list is populated:</p>
<pre><code>protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
BindUserList(); //Just to give an idea
}
</code></pre>
<p>I store the selection in a property which uses the ViewState:</p>
<pre><code>protected string SelectedUser
{
get { return (string)ViewState["SelectedUser"]; }
set { ViewState["SelectedUser"] = value; }
}
</code></pre>
<p>The property is set when the selected index is changed:</p>
<pre><code>protected void UserList_SelectedIndexChanged(object sender, EventArgs e)
{
if (UserList.SelectedIndex == -1)
SelectedUser = null;
else
SelectedUser = UserList.Text;
}
</code></pre>
<p>And I need to override the <code>SaveViewState()</code> and <code>LoadViewState() functions from</code>Page`:</p>
<pre><code>protected override object SaveViewState()
{
object baseState = base.SaveViewState();
string user = UserList.Text;
return new object[] { baseState, user};
}
protected override void LoadViewState(object savedState)
{
if (savedState != null)
{
object[] stateObjects = (object[])savedState;
if (stateObjects[0] != null)
base.LoadViewState(stateObjects[0]);
}
}
</code></pre>
<p>And, in order to re-select the right user, in <code>BindUserList</code>, I do this:</p>
<pre><code>private void BindUserList()
{
//... get and bind list
if (UserList.Items.Count > 0)
{
var item = UserList.Items.FindByText(SelectedUser);
if (item != null)
item.Selected = true;
}
}
</code></pre>
<p>Is this the proper way to use ViewState? Am I missing something that would make this unsafe? Am I doing anything superfluous?</p>
|
[] |
[
{
"body": "<p>You don't have to maintain the DropDownList's seelcted item becouse it will do it by it's self. The problem will only occur when you have disabled the ViewState for the control.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-11T12:09:19.547",
"Id": "42331",
"Score": "0",
"body": "Even if I rebind the control on postback? I'll try it..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-11T14:25:08.923",
"Id": "42342",
"Score": "0",
"body": "Yeah, nope, I lose my selection."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T08:08:31.597",
"Id": "44450",
"Score": "2",
"body": "You don't need to rebind on postback because the list will also maintain its items for you."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-11T05:15:05.033",
"Id": "27253",
"ParentId": "27247",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-10T21:00:54.533",
"Id": "27247",
"Score": "2",
"Tags": [
"c#",
"asp.net"
],
"Title": "Using ViewState, start-to-end"
}
|
27247
|
<p>I recently learned Haskell, and I am trying to apply it to the code I use in order to get a feeling for the language.</p>
<p>I really like the Repa library since I manipulate a lot of multi-dimensional data. Yet it is, in my sense, missing a lot of signal processing tools. For instance, I use quite a lot of Gaussian filter combinations, and approximate them with the Canny-Deriche recursive filter, so that the complexity remains linear and independent of the deviation.</p>
<p>So, this is the code that I have started to write, only for Gaussian convolutions, but in any dimensions.</p>
<pre><code>import Control.Monad
import Data.List (tails)
import Data.Array.Repa as R hiding ((++), map, zipWith)
import Data.Array.Repa.Eval
import Data.Array.Repa.Eval.Gang
import Data.Array.Repa.Repr.Unboxed
import qualified Data.Vector.Unboxed as U
import qualified Data.Vector.Unboxed.Mutable as UM
-- |Apply a recursive Canny-Deriche filter on one dimension of a Repa array.
deriche :: Shape sh =>
Double -> Int -> Int -> Bool ->
Array U sh Double ->
IO (Array U sh Double)
deriche s o d bc a
-- Convolution with a dirac is a nop
| s == 0 = return a
-- Convolution only make sense for positive sigmas
| s < 0 = error "Sigma for the filter must be positive"
-- Make sure the selected dimension exists
| d >= rank (extent a) =
error "Invalid array dimension selected for the filter"
| otherwise =
case o of
0 -> let k = (1-ena) * (1-ena) / (1 + 2*alpha*ena - ens)
a0 = k
a1 = k * ena * (alpha - 1)
a2 = k * ena * (alpha + 1)
a3 = -k * ens
par = 1
in do
b <- UM.new $ size $ extent a :: IO (UM.IOVector Double)
innerLoop a0 a1 a2 a3 0 [] True b
liftM (fromUnboxed $ extent a) (U.unsafeFreeze b)
otherwise -> error "Unimplemented filter order"
where alpha = 1.695 / s
expAlpha = exp alpha
ena = exp (-alpha)
ens = ena * ena
b1 = -2 * ena
b2 = ens
ndim = rank sha
dims = reverse $ listOfShape sha
ddim = dims!!d
stride = product $ tails dims !! (d+1)
sha = extent a
innerLoop :: Double -> Double -> Double -> Double ->
Int -> [Int] -> Bool -> UM.IOVector Double ->
IO ()
innerLoop a0 a1 a2 a3 l path pl b
| l < ndim && l == d = innerLoop a0 a1 a2 a3 (l+1) (0:path) pl b
| l < ndim && pl =
let len = dims!!l
threads = gangSize theGang
chunkLen = len `quot` threads
chunkOver = len `rem` threads
splitIdx thread
| thread < chunkOver = thread * (chunkLen + 1)
| otherwise = thread * chunkLen + chunkOver
fill :: Int -> Int -> IO ()
fill ix end =
mapM_ (\i -> innerLoop a0 a1 a2 a3 (l+1) (i:path) False b) [ix..end-1]
in gangIO theGang $ \thread ->
let start = splitIdx thread
end = splitIdx (thread + 1)
in fill start end
| l < ndim =
mapM_ (\i -> innerLoop a0 a1 a2 a3 (l+1) (i:path) pl b) [0..dims!!l-1]
| otherwise = do
-- First pass
if bc
then undefined --pass1 0 (a `linearIndex` idx)
else pass1 0 idx 0 0 0
-- Second pass
if bc
then undefined -- pass2 ...
else pass2 (ddim-1) (idx+(ddim-1)*stride) 0 0 0 0
where idx = toIndex sha (shapeOfList $ cop path)
cop = id
pass1 !i !j !xp !yp !yb
| i == ddim = return ()
| otherwise = do
UM.unsafeWrite b j yc
pass1 (i+1) (j+stride) xc yc yp
where yc = a0*xc + a1*xp - b1*yp - b2*yb
xc = a `unsafeLinearIndex` j
{-# INLINE pass1 #-}
pass2 !i !j !xn !xa !yn !ya
| i < 0 = return ()
| otherwise = do
bj <- UM.unsafeRead b j
UM.unsafeWrite b j (bj + yc)
pass2 (i-1) (j-stride) xc xn yc yn
where yc = a2*xn + a3*xa - b1*yn - b2*ya
xc = a `unsafeLinearIndex` j
{-# INLINE pass2 #-}
{-# INLINE innerLoop #-}
-- |Sequentially apply a Canny-Deriche filter on two dimensions.
deriche2D :: Double -> Int -> Bool ->
Array U DIM2 Double ->
IO (Array U DIM2 Double)
deriche2D s o bc = deriche s o 0 bc >=> deriche s o 1 bc
</code></pre>
<p>Since I am a complete novice in Haskell, I would appreciate any comment you might give. In particular the code I developed is quite un-repa-ish due to the recursive filter. Also I have no clue as to when I should use bangs, since adding them to any array variable has no positive effect. Any idea on how to share the arrays for <code>deriche2D</code> would be greatly appreciated.</p>
<p>Also, I am compiling with <code>-rtsopts -O2 -threaded -fllvm</code> and running with <code>+RTS -N4</code>.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-10T21:25:14.517",
"Id": "27249",
"Score": "6",
"Tags": [
"optimization",
"performance",
"array",
"haskell",
"recursion"
],
"Title": "Implementing recursive filters with Haskell/Repa"
}
|
27249
|
<p>I'm refactoring a responsive report builder in JavaScript. Here's what it looks like:
<img src="https://i.stack.imgur.com/g4Djj.png" alt="report builder UI"></p>
<p>This started as a small set of objects that transformed data, rendered the graphs with D3.js, and managed the layout all in the same object. The graphs can be removed by the user, and they resize based on screen width and the layout adapts to smaller screen sizes. I've decided to convert each type of graph to a subview and use a parent view to manage the layout of these subviews. This allows me to centralize the code that inserts the graphs into the DOM based on width, platform, etc.</p>
<p>The subviews are all built from a single, large set of homogenous data. I have a single object that constructs these views based on available data then stores the subviews in a collection object (to be persisted when the report is saved). This collection of subviews is then passed to the layout manager for rendering. Subviews are only constructed if the data is available. The thought here is separating object graph construction from the rest of the business logic will make it easier to write unit tests – a requirement moving forward.</p>
<p>I'm having trouble finding a good way to place the subviews on the page. Currently, they're all in a single collection, but they need to be placed in different places based on what kind of graph it is and which set of data the graph is for. e.g. for each of 1-3 "properties", a graph of growth for the month needs to go at the top of the first page and middle of third, while a single graph of top referrers needs to be drawn only on the last page. The most obvious solution would be to simply iterate over all of the subviews and using a giant switch statement, but I think "giant switch statement" and then immediately think "refactor" and "use polymorphism". </p>
<p>One of the ideas I had were to index the subview collection and create a map to lookup the DOM insertion code based on the index, but this is only a stone throw from a giant switch statement, and I'm essentially coupling my layout manager to the subview builder. Another idea was to check the subview instance name in the layout manager, then insert the graph into the appropriate place in the DOM based on this value; however, this would still require a big switch statement.</p>
<p>Is there a good solution to this problem, or is my design flawed?</p>
<p>Here's how the page is initialized (in a <a href="http://twig.sensiolabs.org/" rel="nofollow noreferrer">Twig</a> template):</p>
<pre><code>// At end of the body...
require([
'/script/views/graphs-builder.js',
'/script/views/report.js'
],
function(GraphsBuilder, ReportView) {
"use strict";
// Bootstrap data
var properties = {{ properties | json_encode | raw }},
reports = {{ reports | json_encode | raw }};
var builder = new GraphsBuilder(properties, reports);
builder.build(); // Iterates over reports to construct subviews
// Stores the subviews in builder.graphs
var report = new ReportView({
graphs: builder.graphs
});
report.render() // Iterate over subviews, using a big ugly switch statement
// to decide where in the DOM to insert the graph?
report.$el.appendTo('.container');
});
</code></pre>
<p>Here's the beef of GraphBuilder:</p>
<pre><code>define([
'/script/graphs/common.js',
'/script/graphs/facebook.js',
'/script/graphs/twitter.js',
'/script/graphs/youtube.js',
'/script/graphs/analytics.js'
],
function(common, facebook, twitter, youtube, analytics) {
'use strict';
function GraphBuilder(properties, reports, social_traffic, keyword_traffic) {
this.properties = properties;
this.reports = reports;
this.social_traffic = social_traffic;
this.keyword_traffic = keyword_traffic;
this.graphs = new Backbone.ChildViewContainer();
}
_.extend(GraphBuilder.prototype, {
build: function() {
var data;
this.sanitizeReports();
this.buildSocialGraphs('facebook');
this.buildSocialGraphs('twitter');
this.buildSocialGraphs('google.youtube');
data = _.filter(this.reports, {network: 'google.analytics'});
if (data.length && _.some(data, this.isDaily)) {
data = _.filter(data, this.isDaily);
this.graphs.add(analytics.TrafficByDay(data));
}
this.graphs.add(common.TotalReach(_.filter(this.reports, this.isDaily), 'Total reach'));
if (this.social_traffic) {
this.graphs.add(analytics.SocialTraffic(this.social_traffic));
}
if (this.keyword_traffic) {
this.graphs.add(analytics.KeywordTraffic(this.keyword_traffic));
}
return this;
},
buildSocialGraphs: function(network) {
var graphModule = network === 'facebook' ? facebook :
network === 'twitter' ? twitter :
network === 'google.youtube' ? youtube : analytics;
var opts;
var data = _.filter(this.reports, {network: network});
if (_.some(data, this.isDaily)) {
var daily = _.filter(data, this.isDaily);
opts = {data: daily};
this.graphs.add(graphModule.CommunitySizeByDay(opts), network + '-community-size-by-day');
this.graphs.add(graphModule.ReachVsEngagementByDay(opts), network + '-reach-vs-engagement-by-day');
}
if (_.some(data, 'month')) {
var monthly = _.filter(data, 'month');
this.graphs.add(graphModule.CommunitySizeByMonth({data: monthly}), network + '-community-size-by-month');
if (monthly.length >= 2) { // Need at least two months of data
opts = {lastMonth: monthly[0], thisMonth: monthly[1]};
this.graphs.add(graphModule.CommunityGrowthThisMonth(opts), network + '-community-growth-this-month');
this.graphs.add(graphModule.BroadcastingThisMonth(opts), network + '-broadcasting-this-month');
}
}
}
});
});
</code></pre>
<p>And here's the report view:</p>
<pre><code>define([
'/script/graphs/common.js',
'/script/graphs/facebook.js',
'/script/graphs/twitter.js',
'/script/graphs/youtube.js',
'/script/graphs/analytics.js'
], function(common, facebook, twitter, youtube, analytics) {
'use strict';
return Backbone.View.extend({
initialize: function() {
this.graphs = this.options.graphs;
},
defaults: {
edit_mode: false,
graphs: new Backbone.ChildViewContainer()
},
render: _.debounce(function() {
this.graphs.each(function(graph) {
// Big giant switch to select/create $container!?
graph.render().$el.appendTo($container);
});
$(window).on('resize', this.draw);
return this;
}, 100)
});
});
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T02:16:53.323",
"Id": "42487",
"Score": "0",
"body": "That's a beautiful example of some libraries that I have never used before. I am curious though, what do the double braces do in `var properties = {{ properties | json_encode | raw }}`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T14:27:41.600",
"Id": "42510",
"Score": "0",
"body": "Oh, I should have included the `<?php` tag in that snippet. The {{ var }} is how Twig denotes variables to be interpolated in a PHP template. twig.sensiolabs.org. I'm bootstrapping my data so you don't have to wait for an AJAX request after pageload."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T17:43:46.700",
"Id": "73031",
"Score": "0",
"body": "This question appears to be off-topic because it is seeking a design review as opposed to a code review."
}
] |
[
{
"body": "<p>I ended up using the <a href=\"http://addyosmani.com/resources/essentialjsdesignpatterns/book/#decoratorpatternjavascript\" rel=\"nofollow\">decorator pattern</a>. The report view and each graph object now implement a <code>decorate()</code> method. When the report view's <code>decorate()</code> is called, it iterates over each graph, calling the graph's <code>decorate()</code>. The latter method receives the report view as a parameter, and this provides access to convenience methods for creating/retrieving DOM elements for the graph to attach itself to.</p>\n\n<p>New report view:</p>\n\n<pre><code>define([\n '/script/graphs/common.js',\n '/script/graphs/facebook.js',\n '/script/graphs/twitter.js',\n '/script/graphs/youtube.js',\n '/script/graphs/analytics.js'\n], function(common, facebook, twitter, youtube, analytics) {\n 'use strict';\n\n return Backbone.View.extend({\n initialize: function() {\n this.graphs = this.options.graphs;\n },\n\n defaults: {\n edit_mode: false,\n graphs: new Backbone.ChildViewContainer()\n },\n\n decorate: function() {\n this.graphs.each(_.bind(function(graph) {\n graph.decorate(this);\n }\n }, this),\n\n render: _.debounce(function() {\n this.graphs.each(function(graph) {\n graph.render();\n }); \n return this;\n }, 100),\n\n getPage: function(name) {\n var $page = this.$el.find('.page.' + name);\n if (!$page.length) {\n $page = $('<div/>').addClass('page ' + name).appendTo(this.$el);\n }\n return $page;\n }\n });\n});\n</code></pre>\n\n<p>Example graph object:</p>\n\n<pre><code>define([], function() {\n 'use strict';\n\n return Backbone.View.extend({\n decorate: function(report_view) {\n $page = report_view.getPage('overview');\n this.$el.appendTo($page);\n },\n\n render: function() {\n // Render graph to this.$el\n }\n });\n});\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-13T01:06:25.343",
"Id": "27330",
"ParentId": "27252",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "27330",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-11T01:38:48.840",
"Id": "27252",
"Score": "1",
"Tags": [
"javascript",
"backbone.js",
"require.js",
"lodash.js"
],
"Title": "Layout manager: decouple DOM insertion from construction and rendering?"
}
|
27252
|
<p>I have two class:</p>
<p>InputForm.java</p>
<pre><code>public class InputForm {
private String brandCode;
private String caution;
public String getBrandCode() {
return brandCode;
}
public void setBrandCode(String brandCode) {
this.brandCode = brandCode;
}
public String getCaution() {
return caution;
}
public void setCaution(String caution) {
this.caution = caution;
}
}
</code></pre>
<p>CopyForm.java</p>
<pre><code>public class CopyForm {
private boolean brandCodeChecked;
private boolean cautionChecked;
public boolean isBrandCodeChecked() {
return brandCodeChecked;
}
public void setBrandCodeChecked(boolean brandCodeChecked) {
this.brandCodeChecked = brandCodeChecked;
}
public boolean isCautionChecked() {
return cautionChecked;
}
public void setCautionChecked(boolean cautionChecked) {
this.cautionChecked = cautionChecked;
}
}
</code></pre>
<p>I want to copy values from an InputForm to another if its corresponding property in CopyForm is true.
This is what I do:</p>
<pre><code>if(copyForm.isBrandCodeChecked()) {
inputForm.setBrandCode(otherInputForm.getBrandCode());
}
if(copyForm.isCautionChecked()) {
inputForm.setCaution(otherInputForm.getCaution());
}
</code></pre>
<p>The problem is I have many many properties. Writing many if statements seems ugly and bad programming practice.
How to solve it? (I know reflection is not a good choice so I don't think about it)</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-11T07:29:19.560",
"Id": "42307",
"Score": "1",
"body": "Actually reflection came to mind when I read this. I am not very good at Java, so I haven't heard why using it is a bad idea. Why is this so?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-11T09:40:16.547",
"Id": "42323",
"Score": "0",
"body": "@UwePlonus Nice tip! I've cleared all my erroneus comments. Thank for your help - It may be helpful to keep your last comment for others."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-11T09:52:11.367",
"Id": "42325",
"Score": "1",
"body": "@cl-r To remove a comment use the red cross beneath your signature."
}
] |
[
{
"body": "<p>You may want a static method in your <code>InputForm</code> class, named, for instance, <code>.fromCopyForm()</code> taking a <code>CopyForm</code> as an argument and returning an <code>InputForm</code>:</p>\n\n<pre><code>public static InputForm fromCopyForm(final CopyForm copyForm)\n{\n final InputForm ret = new InputForm();\n // all tests here\n return ret;\n}\n</code></pre>\n\n<p>Then in your code:</p>\n\n<pre><code>final InputForm form = InputForm.fromCopyForm(copyForm);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-11T13:58:39.053",
"Id": "42333",
"Score": "0",
"body": "where is the magic that fills the fields of the new InputForm depending on the flags in CopyForm?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-11T13:59:15.873",
"Id": "42334",
"Score": "0",
"body": "Nowhere, why need magic? Just simple checks, written once, that's it; and no reflection needed"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-11T14:02:36.113",
"Id": "42335",
"Score": "0",
"body": "\"simple checks\" = many if statements = the thing the op wants to get rid of?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-11T14:03:46.860",
"Id": "42336",
"Score": "0",
"body": "No, simple checks in the static factory method; none where the code is actually _used_."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-11T14:04:52.433",
"Id": "42337",
"Score": "0",
"body": "so how do you check multiple conditions without multiple ifs?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-11T14:06:00.713",
"Id": "42338",
"Score": "0",
"body": "That's not the question. The question is, when you need an input form from a copy form, you just `InputForm.fromCopyForm()` and that's it. The code to obtain that input form does not matter; it may even phone the Moon for all it matters."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-11T14:09:49.077",
"Id": "42340",
"Score": "1",
"body": "i suggest you read the question again..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-11T14:15:13.110",
"Id": "42341",
"Score": "0",
"body": "let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/9197/discussion-between-marco-forberg-and-fge)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-11T15:39:42.867",
"Id": "42353",
"Score": "1",
"body": "I _did_ read the question. And the OP seems to imply that he creates the new input form by hand. Hence the static factory method proposal that I make."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-12T06:32:18.787",
"Id": "42388",
"Score": "0",
"body": "In the last part of the question the OP seems to have a **single** method where he creates a new `InputForm` out of the values of another `InputForm` and the flags of the `CopyForm` and asks how to get rid of the myriads of `if`s that he has to do if he has myriads of properties and corresponding flags."
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-11T08:14:54.680",
"Id": "27256",
"ParentId": "27254",
"Score": "1"
}
},
{
"body": "<p>I think <a href=\"http://commons.apache.org/proper/commons-beanutils/\" rel=\"nofollow\">Apache commons BeanUtils</a> might help you there. It uses reflection. Take this into consideration if performance is an issue...</p>\n\n<p>We need 2 Steps:</p>\n\n<p>1st create a method that copies a property if a condition is met</p>\n\n<p>2nd create a copy method that passes all fields to the first method</p>\n\n<p>Here we go...</p>\n\n<pre><code>public class InputForm {\n [...]\n\n private void copyProperty(InputForm srcForm, String field, boolean condition) {\n if(condition) {\n PropertyUtils.setProperty(this, field, PropertyUtils.getProperty(srcForm, field));\n }\n }\n\n public void copyFromOtherForm(InputForm srcForm, CopyForm conditions) {\n copyProperty(srcForm, \"brandCode\", conditions.isBrandCodeChecked());\n copyProperty(srcForm, \"caution\", conditions.isCautionChecked());\n [...]\n }\n}\n</code></pre>\n\n<p>if you're still not pleased with that you could use reflection to invoke <code>\"is\"+field+\"Checked\"</code> on your <code>CopyForm</code> instance and change the calls to:</p>\n\n<pre><code>copyProperty(srcForm, conditions, \"field\");\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-11T13:55:47.327",
"Id": "42332",
"Score": "1",
"body": "Why using an external package when the language offers you what you need already (see my post)?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-11T09:10:35.197",
"Id": "27259",
"ParentId": "27254",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-11T06:27:43.360",
"Id": "27254",
"Score": "3",
"Tags": [
"java",
"classes",
"form"
],
"Title": "Copy object properties without using many if statements"
}
|
27254
|
<p>In my current project, I am working with a lot of JSON objects that contain arrays, er.. <code>lists</code> so I setup a decorator for convienece when the list is one item or multiple. Even though this is convienent in the current project, is it reusable code?</p>
<pre><code>def collapse(function):
@functools.wraps(function)
def func(*args, **kwargs):
call = function(*args, **kwargs)
if isinstance(call, (list, tuple)) and (len(call) == 1):
return call[0]
return call
return func
@collapse
def get_results(query, wrapper=None):
# get json object.
result = result.json() # using the requests library.
if wrapper:
return result[wrapper]
return result
</code></pre>
<p>So, <code>get_results()</code> has the potential of returning either a <code>list</code> or a <code>dict</code>. In most cases, the code knows when what type is returned, so using the <code>@collapse</code> decorator changes <code>[result_dict]</code> to just <code>result_dict</code></p>
<p>Is this a good practice, or should I write a decorator that takes a <code>limit</code> parameter</p>
<pre><code>@limit(1) # def limit(items=None): ... return data[0:items] if items else data
def get_results(query, wrapper=None):
</code></pre>
<p>Just wrote out the limit decorator...</p>
<pre><code>def limit(items=None, start=0, collapse=False):
if items and (start > 0):
items += start
def wrapper(function):
@functools.wraps(function)
def func(*args, **kwargs):
call = function(*args, **kwargs)
if isinstance(call, (list, tuple)):
results = call[start:items] if items else call
if collapse and (len(results) == 1):
return results[0]
else:
return results
return call
return func
return wrapper
</code></pre>
|
[] |
[
{
"body": "<p>If you expect a list of length 1, raise an exception when that is not the case:</p>\n\n<pre><code>if isinstance(call, (list, tuple)) and (len(call) == 1):\n return call[0]\nelse:\n raise ValueError(\"List of length 1 expected\")\n</code></pre>\n\n<p>A function that may return either a list or an element is hard to use. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T20:44:58.920",
"Id": "44516",
"Score": "0",
"body": "To reinforce this, think of how you would use a function that sometimes returns an object and sometimes returns a list. That would be really messy!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-11T08:50:50.113",
"Id": "27258",
"ParentId": "27255",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-11T07:42:03.317",
"Id": "27255",
"Score": "-1",
"Tags": [
"python"
],
"Title": "Proper use or convenience, or both?"
}
|
27255
|
<p>I have made the following custom defined function in Excel. It works somehow like <code>VLOOKUP()</code>, but it takes two criteria. I think the code is a bit of a mess. Does anyone has any comments, suggestions, or improvements?</p>
<pre><code>Public Function VLOOKUPMC(ByVal return_col_num As Long, ByRef table_array_1 As Range, ByVal lookup_value_1 As Variant, ByRef table_array_2 As Range, ByVal lookup_value_2 As Variant) As Variant
Dim rCell1 As Range
For Each rCell1 In table_array_1
With rCell1
If .Value = lookup_value_1 Then
If .Offset(0, table_array_2.Column - .Column) = lookup_value_2 Then
VLOOKUPMC = .Offset(0, return_col_num - .Column)
Exit Function
End If
End If
End With
Next rCell1
VLOOKUPMC = CVErr(xlErrNA)
End Function
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-11T17:42:25.753",
"Id": "42362",
"Score": "0",
"body": "Do you mean to search through all columns in the range `table_array_1`, or just the first, like a standard `VLOOKUP`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-15T19:29:59.480",
"Id": "42668",
"Score": "1",
"body": "Note that you could use a SUMPRODUCT to simulate a VLOOKUP with several criterias. As a suggestion for improvment, you could use arrays instead of parsing ranges (more powerful and better performance)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-16T18:31:45.637",
"Id": "42693",
"Score": "0",
"body": "Can you give an example? I've used an array formula, but my end users don't know about array formulas, so I thought it was better to use an UDF"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-05T01:26:54.453",
"Id": "48995",
"Score": "1",
"body": "When I used to need a VLOOKUP that used two or more columns, I would simply concatenate those columns into a new one, and do the lookup on the concatenated \"key\"."
}
] |
[
{
"body": "<p>Here's a different version, though I won't claim that it is significantly better. The code seemed to work just fine and was mostly easy to understand (see my comment on the original question). My only big suggestion would be to add some comments to better describe what you are doing and how this works.</p>\n\n<p>For a brief description of my changes, see the comments in the code. I can elaborate more if necessary.</p>\n\n<pre><code>Public Function VLOOKUPMC(ByVal return_col_num As Long, _\n ByRef table_array_1 As Range, ByVal lookup_value_1 As Variant, _\n ByRef search_column_2 As Long, ByVal lookup_value_2 As Variant) As Variant\n 'Changed table_array_2 to search_column_2 because that's all that was used in the code below.\n Dim rCell1 As Range\n VLOOKUPMC = CVErr(xlErrNA)\n 'Left the For loop as-is, but maybe you want it to look only in the first column, like the normal VLOOKUP would?\n For Each rCell1 In table_array_1\n 'Modified logic to all fit on one line/remove nesting. \n 'This organization may not be preferred, but it's one way to clean up the so-called 'mess'.\n VLOOKUPMC = _\n IIf(rCell1.Value = lookup_value_1 And _\n rCell1.Offset(0, search_column_2 - rCell1.Column) = lookup_value_2, _\n rCell1.Offset(0, return_col_num - rCell1.Column), _\n VLOOKUPMC)\n If VarType(VLOOKUPMC) <> vbError Then Exit Function\n Next rCell1\nEnd Function\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-16T18:33:00.610",
"Id": "42694",
"Score": "0",
"body": "I should indeed have commented my code. Your changes looks great. Thank you! :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-11T18:06:43.787",
"Id": "27275",
"ParentId": "27261",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "27275",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-11T10:28:45.677",
"Id": "27261",
"Score": "5",
"Tags": [
"vba",
"excel",
"lookup"
],
"Title": "Multiple criterias in a VLOOKUP in Excel VBA"
}
|
27261
|
<pre><code>Declare @IsExistRoleAR As bit
Declare @IsExistRoleEN As bit
Declare @IsExist AS bit
set @IsExistRoleAR=(SELECT CASE WHEN COUNT(RoleID) > 0 THEN 1 ELSE 0 END AS isExists
FROM Roles
WHERE RoleDescAR='Arabic Name')
set @IsExistRoleEN=(SELECT CASE WHEN COUNT(RoleID) > 0 THEN 1 ELSE 0 END AS isExists
FROM Roles
WHERE RoleDescEN='English Name')
set @IsExist=(@IsExistRoleAR | @IsExistRoleEN)
select @IsExist
</code></pre>
|
[] |
[
{
"body": "<p>You could just use <code>OR</code>:</p>\n\n<pre><code> SELECT CASE WHEN COUNT(RoleID) > 0 THEN 1 ELSE 0 END AS isExists\n FROM Roles\n WHERE RoleDescAR='Arabic Name' OR RoleDescEN='English Name'\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-10T15:43:37.877",
"Id": "42326",
"Score": "0",
"body": "I want to know who is who was exists at table Roles \"Arabic Field\" Or English Field? I don't know how to explain that"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-10T15:49:15.263",
"Id": "42327",
"Score": "0",
"body": "Add columns to select statement like: SELECT RoleDescAR, RoleDescEN, CASE WHEN COUNT(RoleID) > 0 THEN 1 ELSE 0 END AS isExists"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-10T15:37:09.903",
"Id": "27263",
"ParentId": "27262",
"Score": "8"
}
},
{
"body": "<p>You don't really need a CASE statement here, unless I've missed something. (Always possible.)</p>\n\n<pre><code>select count(RoleID)\nfrom roles\nwhere RoleDescEN = 'EnglishName'\n or RoleDescAR = 'ArabicName';\n</code></pre>\n\n<hr>\n\n<p>If you're trying to identify persons who have those roles, you <em>might</em> be looking for something along these lines. </p>\n\n<pre><code>create table roles (\n RoleID integer primary key,\n RoleDescEN varchar(30) ,\n RoledescAR varchar(30) \n );\n\ninsert into roles values\n(1, 'EnglishName', null),\n(2, null, 'ArabicName'),\n(3, 'EnglishName', null),\n(4, 'EnglishName', null),\n(5, null, 'ArabicName'),\n(6, null, 'ArabicName'),\n(7, null, 'OtherName');\n\n\ncreate table persons (\n person_id integer primary key,\n person_name varchar(35) not null,\n person_role integer references roles (RoleID)\n );\n\ninsert into persons values\n(1, 'Obama, Barak', 1),\n(2, 'Obama, Michelle', 2),\n(3, 'Biden, Joe', 7);\n</code></pre>\n\n<p>I would <em>not</em> be surprised if my tables don't match yours. In your question, always include CREATE TABLE statements and INSERT statements to get the best answers.</p>\n\n<pre><code>select *\nfrom persons p\ninner join roles r\n on r.RoleID = p.person_role\nwhere RoleDescEN = 'EnglishName'\n or RoleDescAR = 'ArabicName';\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-10T15:45:34.103",
"Id": "42328",
"Score": "0",
"body": "I want to know who is who was exists at table Roles \"Arabic Field\" Or English Field? I don't know how to explain that"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-10T15:48:57.090",
"Id": "42329",
"Score": "0",
"body": "I think you mean, \"I want to know the names of everyone who has either the role 'Arabic Name' or the role 'English name'.\" (I could easily be wrong about that.) The code you posted makes no attempt to do that, and it doesn't suggest that there might be other tables involved. Edit your question, and paste the CREATE TABLE statements from the relevant tables."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-10T15:43:11.717",
"Id": "27264",
"ParentId": "27262",
"Score": "0"
}
},
{
"body": "<pre><code>Select Case When exists\n (Select * From Roles\n WHERE RoleDescAR='Arabic Name' Or \n RoleDescEN='English Name')\n Then 1 Else 0 End\n</code></pre>\n\n<p>If you want to know the names of the people who meet this criteria, that's a completely different question, then you need to provide the schema for the table that has one row per each person, and the roleId, and then, (assuming that table is named <code>Person</code>) Try:</p>\n\n<pre><code> Select Name\n From Person p\n Where exists\n (Select * From Roles\n Where RoleId = p.RoleId\n And RoleDescAR='Arabic Name' Or \n RoleDescEN='English Name')\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-10T15:45:54.653",
"Id": "42330",
"Score": "0",
"body": "I want to know who is who was exists at table Roles \"Arabic Field\" Or English Field? I don't know how to explain that"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-10T15:44:31.667",
"Id": "27265",
"ParentId": "27262",
"Score": "0"
}
},
{
"body": "<p>Since you haven't accepted any of the other answers, I'm going to take a guess that perhaps you want more information back:</p>\n\n<pre><code>SELECT CASE\n WHEN EXISTS (SELECT * from Roles Where RoleDescAR='Arabic Name') then 'AR'\n WHEN EXISTS (SELECT * from Roles Where RoleDescEN='English Name') then 'EN'\n ELSE 'none' END As whichExists\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-10T16:05:25.390",
"Id": "27266",
"ParentId": "27262",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-10T15:33:02.760",
"Id": "27262",
"Score": "0",
"Tags": [
"sql",
"sql-server"
],
"Title": "How to refactor the following sql statement?"
}
|
27262
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.