text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: Datagridview virtual model combobox how can you dynamically add items to a combobox using the datagridview virtual mode?
A: Well, I assume you are working with a very large set of data, and thus are using virtual mode to implement your own data binding.
If that is the case here is a link that demonstrates the process:
http://msdn.microsoft.com/en-us/library/2b177d6d.aspx
It primarily involves implementing an event handler for the CellValueNeeded event.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/111785",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How would you format multiple properties when using Property Initialization? (.Net) For example:
root.Nodes.Add(new TNode() { Foo1 = bar1, Foo2 = bar2, Foo3 = bar3 });
or:
root.Nodes.Add(new TNode() { Foo1 = bar1,
Foo2 = bar2,
Foo3 = bar3 });
A: I've done it both ways.. IMO it depends on the complexity of the initialization.
If it is simple 2 or 3 properties I will initialize on one line generally, but if i'm setting up an object with values for insertion into a database or something that has alot of properties i'll break it out like your second example.
Income income = new Income
{
Initials = something,
CheckNumber = something,
CheckDate = something,
BranchNumber = something
};
or
return new Report.ReportData { ReportName = something, Formulas = something};
A: Both notations are fine. I would simply suggest to use the first (1-line) notation whenever your line stay within 100 characters, and switch to the second (multi-line) notation whenever the expression is longer.
A: For longer stuff I do it this way:
root.Nodes.Add(new TNode() {
Foo1 = bar1,
Foo2 = bar2,
Foo3 = bar3
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/111792",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Best practice for naming convention of UI controls for referencing in code-behind? What is the best practice for naming UI controls (textboxes, drop-downs, etc.) on forms and reports for reference in the code-behind pages?
I develop a lot of reports and forms in my office. I have several web applications providing about 80+ "live" reports being generated from various and multiple data sources (Access, SQL, Oracle). These reports are considered "live" because they accept user set paramaters from a form, then query the database to produce a report based on the current information available.
So, the process starts with obtaining the values set by the user, passing those to the database query, receiving the dataset, and finally assigning the dataset to the report. In some cases, additional fields displayed on the report need to be calculated from the dataset before the report can be generated. This requires referencing the output controls on the report to assign the calculated value.
While I don't really care to use prefixes in my code for variables or member fields, I do use them to identify the UI controls. For example, txtFirstName to reference the report control to assign the data from the FirstName field in the dataset to the display control on the report. Is there a better practice for naming/referencing UI controls on forms and reports?
A: For GUI controls, I suffix the variable name with the control name:
*
*firstNameTextBox
*lastNameTextBox
*submitButton
This makes the relationship obvious between for example _firstName and firstNameTextBox.Text, and no one has to remember what the hungarian notation equivalent is. I would always choose clarity over brevity in naming variables.
A: The main product I work on at work uses the txt_ pnl_ etc prefixes. This does work, though it is a bit of a pain at times when switching something that just hides/shows controls from say, a tr to a panel because you have to rename it.
What I've started doing in new projects, is naming my UI controls with a ui prefix; for example, uiName. Since I am strongly opposed to anti-hungarian notation, and strive for self-documenting code, this convention works well. In fact, if anything, it is real hungarian notation (ui being the prefix meaning user interface control).
A: I still use Hungarian Notation for Controls but no longer for variables.
btn Button
cbo ComboBox
chk CheckBox
clb CheckedListBox
grp GroupBox
iml ImageList
lbl Label
lnk Hyperlink
mnu Menu
pbr ProgressBar
pic Picture
pnl Panel
rtb RichTextBox
tmr Timer
tvw TreeView
txt TextBox
A: Your answers here will be very subjective. Different tastes and programming backgrounds will give you different preferences.
Perhaps what will be most important to you in the long run is consistency among all of your projects, so that regardless of who developed the code you will be able to understand it when reading.
We outsource a lot, so make certain to communicate our naming conventions to all of our project managers.
Here are some links to naming conventions:
http://www.irritatedvowel.net/Programming/Standards.aspx
http://msdn.microsoft.com/en-us/library/xzf533w0(VS.71).aspx
http://www.visualize.uk.com/resources/asp-net-standards.asp
A: I do similarly to you. When you have tons of controls it all becomes messy, so I prefix each name with the capitals of the control class.
For example:
TextBox -> tbName
DataGrid -> dgName
Panel -> pName
This makes it clear how to handle new controls (i.e. how to derive the prefix)
A: I've always felt that the only real reason for the prefixes was so you could have things like txtFirstName and lblFirstName on the same form/page. Since, the vast majority of the time, I'm really only working with the actual field control itself, I skip the prefix for that, and only use the prefixes for associated controls. For instance, lblMonth & Month, skipping the cbo prefix.
It saves typing, and it will generally be obvious what sort of control you're using in such forms. More complex controls will get the full prefix treatment.
A: 2-char prefixes for iOS UI components I prefer:
bt_ : UIButton
lb_ : UILabel
tx_ : UITextField
tv_ : UITextView
vw_ : UIView
im_ : UIImageView
sc_ : UIScrollView
tb_ : UITableView
cl_ : UICollectionView
st_ : UIStackView
pk_ : UIPickerView
pr_ : UIProgressView
ai_ : UIActivityIndicatorView
wb_ : UIWebView / WKWebView
mp_ : MKMapView
gr_ : UIGestureRecognizer
sw_ : UISwitch
sl_ : UISlider
sp_ : UIStepper
sg_ : UISegmentedControl
pg_ : UIPageControl
dp_ : UIDatePicker
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/111812",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: What is the best way to improve ASP.NET/C# compilation speed? UPDATE: Focus your answers on hardware solutions please.
What hardware/tools/add-in are you using to improve ASP.NET compilation and first execution speed? We are looking at solid state hard drives to speed things up, but the prices are really high right now.
I have two 7200rpm harddrives in RAID 0 right now and I'm not satisfied with the performance anymore.
So my main question is what is the best cost effective way right now to improve ASP.NET compilation speed and overall development performance when you do a lot of debugging?
Scott Gu has a pretty good blog post about this, anyone has anything else to suggest?
http://weblogs.asp.net/scottgu/archive/2007/11/01/tip-trick-hard-drive-speed-and-visual-studio-performance.aspx
A: First make sure your that you are using Web Application Projects (WAP). In our experience, compared to Website Projects, WAP compiles roughly 10x faster.
Then, consider migrating all the logic (including complex UI components) into separate library projects. The C# compiler way faster than the ASP.NET compiler (at least for VS2005).
A: One of the important things to do is keeping projects of not-so-often changed assemblies unloaded. When a change occurs, load it, compile and unload again. It makes huge differences in large solutions.
A: If you have lots of 3rd party "Referenced Assemblies" ensuring that CopyLocal=False on all projects except for the web application project makes quite a big difference.
I blogged about the perf increases I managed to get by making this simple change:
Speeding Up your Desktop Build - Part 1
A: You can precompile the site, which will make the first run experience better
http://msdn.microsoft.com/en-us/library/ms227972.aspx
A: I switched from websites to web applications. Compile time went down by a factor of ten at least.
Also, I try not to use the debugger if possible ("Run without debugging"). This cuts down the time it takes to start the web application.
A: I would recommend adding as much memory to your PC as you can. If your solutions are super large you may want to explore 64bit so that your machine can address more than 3GB of ram.
Also Visual Studio 2008 SP1 seems to be markedly faster than previous versions, make certain you are running the latest release with the Service Packs.
Good Luck!
A: If you are looking purely at hardware you will need to search for benchmarks around the web. There are a few articles written just on the performance of hardware on Visual Studio compilation, I am just too lazy to find them and link them.
Hardware solutions can be endless because you can get some really high end quipment if you have the money. Otherwise its the usual more memory, faster processor, and faster hard drive. Moving to a 64bit OS also helps.
If you want to be even more specific? Just off the top of my head...8GB or more of memory, if you cant afford solid state drives I'd go for 10K to 15K RPM hard drives. There is a debate of whether quad-core makes any difference but look up the benchmarks and see what works for you.
A: If you are looking at just hardware, Multi-core processors, high amounts of ram, and ideally 10K or 15K hard drives.
I personally have noticed a huge improvement in performance with the change to 10K RPM drives.
A: The best way to improve ASP.NET compile time is to throw more hardware at it. An OCZ Vertex Turbo SSD drive and an Intel i7 960 gave me a huge boost. You can see my results here.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/111814",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: What is the easiest way to upgrade a large C# winforms app to WPF I work on a large C# application (approximately 450,000 lines of code), we constantly have problems with desktop heap and GDI handle leaks. WPF solves these issues, but I don't know what is the best way to upgrade (I expect this is going to take a long time). The application has only a few forms but these can contain many different sets of user-controls which are determined programatically.
This is an internal company app so our release cycles are very short (typically 3 week release cycle).
Is there some gradual upgrade path or do we have to take the hit in one massive effort?
A: Do you use a lot of User controls for the pieces? WPF can host winform controls, so you could piecewise bring in parts into the main form.
A: WPF allows you to embed windows forms user controls into a WPF application, which may help you make the transition in smaller steps.
Take a look at the WindowsFormsHost class in the WPF documentation.
A: I assume that you are not just looing for an ElementHost to put your vast Winforms app. That is anyway not a real porting to WPF.
Consider the answers on this Thread What are the bigger hurdles to overcome migrating from Winforms to WPF?, It will be very helpfull.
A: You can start by creating a WPF host.
Then you can use the <WindowsFormHost/> control to host your current application. Then, I suggest creating a library of your new controls in WPF. One at a time, you can create the controls (I suggest making them custom controls, not usercontrols). Within the style for each control, you can start with using the <ElementHost/> control to include the "old" windows forms control. Then you can take your time to refactor and recreate each control as complete WPF.
I think it will still take an initial effort to create your control wrappers and design a WPF host for the application. I am not sure the size of the application and or the complexity of the user controls, so I'm not sure how much effort that would be for you. Relatively speaking, it is significantly less effort and much faster to get you application up and running in WPF this way.
I wouldn't just do that and forget about it though, as you may run into issues with controls overlaying each other (Windows forms does not play well with WPF, especially with transparencies and other visuals)
Please update us on the status of this project, or provide more technical information if you would like more specific guidance. Thanks :)
A: There is a very interesting white paper on migrating a .NET 2.0 winform application toward WPF, see Evolving toward a .NET 3.5 application
Paper abstract:
In this paper, I’m going to outline some of the thought processes, decisions and issues we had to face when evolving a Microsoft .NET application from 1.x/2.x to 3.x. I’ll look at how we helped our client to adopt the new technology, and yet still maintained a release schedule acceptable to the business.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/111817",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
}
|
Q: Free open source asp.net file managers? Any good ones?
So far I have found IZWebFileManager, OXFileManager and AWS File Picker. The file manager should be able to delete, copy, rename, download & upload files.
A: You have WebFileManager created by our very own Jeff Atwood
A: (shameless plug)
The question is old, but it may still help someone:
http://elfinderaspnet.codeplex.com/
Uses elFinder as frontend and IHttpHandler as backend so it is compatible with WebForms and MVC.
A: Try here this manager, it can to you will approach.
http://www.ajaxfilebrowser.com/?CrossDomain
A: I used HTTPCommander. Telerik also has a file manager control in their asp.net suite.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/111851",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Tools to work with stored procedures in Oracle, in a team? What tools do you use to develop Oracle stored procedures, in a team :
*
*To automatically "lock" the current procedure you are working with, so nobody else in the team can make changes to it until you are finished.
*To automatically send the changes you make in the stored procedure, in an Oracle database, to a Subversion, CVS, ... repository
Thanks!
A: I'm not sure if the original poster is still monitoring this, but I'll ask the question anyways.
The original post requested to be able to:
To automatically "lock" the current
procedure you are working with, so
nobody else in the team can make
changes to it until you are finished.
Perhaps the problem here is one of development paradigm more than the inability of a product to "lock" the stored proc. Whenever I hear "I want to lock this so noone else changes it" I immediately get the feeling that people are sharing a schema and everyone is developing in the same space.
If this is the case, why not simply let everyone have their own schema with a copy of the data model? I mean seriously folks, it doesn't "cost" anything to create another schema. That way, each developer can make changes until they're blue in the face without affecting anyone else.
Another trick I've used in the past (on small teams) when it wasn't feasible to let every developer have their own copy of the data because of size, was to have a master schema with all the tables and code in it, with public synonyms pointing to it all. Then, if the developer wants to work on a stored proc, he simply creates it in his schema. That way Oracle name resolution finds that one first instead of the copy in the master schema, allowing them to test their code without affecting anyone else. This does have it's drawbacks, but this was a very specific case where we could live with them. I would NEVER implement something like this in production obviously.
As for the second requirement:
To automatically send the changes you
make in the stored procedure, in an
Oracle database, to a Subversion, CVS,
... repository
I'd be surprised to find tools out there smart enough to do this (perhaps an opportunity :). It would have to connect to your db, query the data dictionary (USER_SOURCE) and pull out the associated text. A tall order for source control systems where are almost universally file based.
A: Oracle's new SQL Developer has version control built-in.
Here is a link to the product.
http://www.oracle.com/technology/products/database/sql_developer/files/what_is_sqldev.html
http://www.oracle.com/technology/products/database/sql_developer/images/what_version.png http://www.oracle.com/technology/products/database/sql_developer/images/what_version.png
A: Treat PL/SQL as usual code : store it in files, and manage these files with your revision control tool and your internal procedures.
If you do not already have a revision control tool, then write your requirements down and pick one up. A lot of people it seems use Subversion, associated to TortoiseSVN as a client on Windows (I do).
The thing is : use your tool as is recommended, and adapt your procedures accordingly. For instance, Subversion uses a copy-modify-merge model by default, as opposed to a lock-modify-unlock model which you seem to favor.
In my case, I like to use TortoiseSVN, as stated above. And as is usual with this tool :
*
*I never lock any files. This is very manageable with small teams, and it requires ahead planning on larger ones, which is always a good thing IMHO.
*I send my changes manually back to the server, because ... I don't think there's another way with Subversion (plus, internal procedures forbid a commit without a message, which is also a good thing IMHO).
And whatever your choice, I recommend reading this post (and related ones) about database versioning.
A: A relatively simple (if slightly old-fashioned) solution might be to use a "locking" rather than "merge" mode version control system.... Subversion or CVS generally use a "merge" mode (although I believe Subversion can be made to "lock" files?)
"Locking" mode version control systems do have their own drawbacks of course.....
The only way I can think of doing in in Oracle might be some of of BEFORE CREATE TRIGGER, maybe referencing a table to look-up who can run a package in. Sounds a bit nasty though?
A: Using Source Control for Oracle you get a lot of what you're looking for.
Stored procedures (as well as packages, functions, tables etc.) can be locked manually using the interface, not automatically, but this does prevent others making changes.
The new SQL to create the object can then be checked into SVN or TFS (no CVS support unfortunately).
The tool is not free but has a free 28-day trial.
A: Using Oracle SQL Developer 1.5, you can easily create and manage connections to CVS or Subversion. To create a CVS connection (for example), click Versioning -> CVS -> Check out Module. You will run through a wizard to create the connection (host, username, etc), then you can check your procedures/functions out and in as normal.
Integration with CVS is also provided in Toad.
A: You may also want to look at Aqua Data Studio. They have built in SVN as well and is a great Stored Proc editor.
A: After searching for a tool to handle version control for Oracle objects with no luck we created the following (not perfect but suitable) solution:
*
*Using dbms_metadata package we create the metadata dump of our Oracle server. We create one file per object, hence the result is not one huge file but a bunch of files. For recognizing deleted object we delete all the files before creating the dump again.
*We copy all the files from the server to the client computer.
*Using Netbeans we recognize the changes, and commit the changes to the CVS server (or check the diffs...). Any CVS-handler software would work here, but we were already using Netbeans for other purposes. And Netbeans also allows to create an ant task for calling the Oracle process mentioned in step 1, copying the files mention in step 2...
Here is the most imporant query for step 1:
SELECT object_type, object_name,
dbms_metadata.get_ddl(object_type, object_name) object_ddl FROM user_objects
WHERE OBJECT_TYPE in ('INDEX', 'TRIGGER', 'TABLE', 'VIEW', 'PACKAGE',
'FUNCTION', 'PROCEDURE', 'SYNONYM', 'TYPE')
ORDER BY OBJECT_TYPE, OBJECT_NAME
One file per object approach helps to identify the changes. If I add a field to table TTTT (not a real table name of course) then only TABLE_TTTT.SQL file will be modified.
Both step 1 and step 3 are slow processes. (several minutes for a few thousand of files)
A: Toad also does this without requiring CVS / SVN.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/111852",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: GWT-EXT - What is the best way to widgets to a specific ContentPanel after an event? first post don't hurt me :)
I am using a BorderLayout with the usual North, West, Center, South Panels. On the West ContentPanel, I've got a Tree. If an event (OnClick)occurs I want a particular dialog box displayed on the Center ContentPanel.
What is the best way for me to do this? Currently I'm using a function called returnPanel() that returns the center ContentPanel. In the event handler I call this function (MainWindow.returnPanel().add(myDialog)).
A: The way you are doing it is intuitive and works, but will start causing hell when the application grows, because different parts of the application are strongly coupled. The solutions to this problems are the MVC design pattern and the observer design pattern.
Ideally, using the MVC pattern, you don't want any widget to 'know' of any other widget. There is only class that knows all the widgets, which is the Controller. Anytime one widget needs to message/signal another widget, it tells it to the Controller class, which relays the message in the appropriate way to the appropriate widget. In this way, the two widgets are decpoupled and one can change without breaking the other. You may want to use an enum to enumerate all possible actions to which the controller has to responsd.
If your widget has to call only the Controller when an event occurs, you may simply call an aptly named (static) method on it and be done with it. However, as soon as multiple other classes needs to be informed of an event, you are better of using the Observer pattern, which allows you to signal multiple other classes, without changing your class. It simply calls notifyPObservers() in the eventHandler and that's it. How many listeners there are, and what type they are, is irrelevant. This way, you also decouple a class from it's listeners. Even if only the Controller listens, it may be advisable to use the pattern, as it clearly seperated the 'call back' code from the other code in the classes.
BTW, this has nothing to do with GWT or even Java in particular.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/111854",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Best way to remove from NSMutableArray while iterating? In Cocoa, if I want to loop through an NSMutableArray and remove multiple objects that fit a certain criteria, what's the best way to do this without restarting the loop each time I remove an object?
Thanks,
Edit: Just to clarify - I was looking for the best way, e.g. something more elegant than manually updating the index I'm at. For example in C++ I can do;
iterator it = someList.begin();
while (it != someList.end())
{
if (shouldRemove(it))
it = someList.erase(it);
}
A: One more variation. So you get readability and good performace:
NSMutableIndexSet *discardedItems = [NSMutableIndexSet indexSet];
SomeObjectClass *item;
NSUInteger index = 0;
for (item in originalArrayOfItems) {
if ([item shouldBeDiscarded])
[discardedItems addIndex:index];
index++;
}
[originalArrayOfItems removeObjectsAtIndexes:discardedItems];
A: In a more declarative way, depending on the criteria matching the items to remove you could use:
[theArray filterUsingPredicate:aPredicate]
@Nathan should be very efficient
A: Here's the easy and clean way. I like to duplicate my array right in the fast enumeration call:
for (LineItem *item in [NSArray arrayWithArray:self.lineItems])
{
if ([item.toBeRemoved boolValue] == YES)
{
[self.lineItems removeObject:item];
}
}
This way you enumerate through a copy of the array being deleted from, both holding the same objects. An NSArray holds object pointers only so this is totally fine memory/performance wise.
A: Add the objects you want to remove to a second array and, after the loop, use -removeObjectsInArray:.
A: this should do it:
NSMutableArray* myArray = ....;
int i;
for(i=0; i<[myArray count]; i++) {
id element = [myArray objectAtIndex:i];
if(element == ...) {
[myArray removeObjectAtIndex:i];
i--;
}
}
hope this helps...
A: This is a very simple problem. You just iterate backwards:
for (NSInteger i = array.count - 1; i >= 0; i--) {
ElementType* element = array[i];
if ([element shouldBeRemoved]) {
[array removeObjectAtIndex:i];
}
}
This is a very common pattern.
A: Some of the other answers would have poor performance on very large arrays, because methods like removeObject: and removeObjectsInArray: involve doing a linear search of the receiver, which is a waste because you already know where the object is. Also, any call to removeObjectAtIndex: will have to copy values from the index to the end of the array up by one slot at a time.
More efficient would be the following:
NSMutableArray *array = ...
NSMutableArray *itemsToKeep = [NSMutableArray arrayWithCapacity:[array count]];
for (id object in array) {
if (! shouldRemove(object)) {
[itemsToKeep addObject:object];
}
}
[array setArray:itemsToKeep];
Because we set the capacity of itemsToKeep, we don't waste any time copying values during a resize. We don't modify the array in place, so we are free to use Fast Enumeration. Using setArray: to replace the contents of array with itemsToKeep will be efficient. Depending on your code, you could even replace the last line with:
[array release];
array = [itemsToKeep retain];
So there isn't even a need to copy values, only swap a pointer.
A: For clarity I like to make an initial loop where I collect the items to delete. Then I delete them. Here's a sample using Objective-C 2.0 syntax:
NSMutableArray *discardedItems = [NSMutableArray array];
for (SomeObjectClass *item in originalArrayOfItems) {
if ([item shouldBeDiscarded])
[discardedItems addObject:item];
}
[originalArrayOfItems removeObjectsInArray:discardedItems];
Then there is no question about whether indices are being updated correctly, or other little bookkeeping details.
Edited to add:
It's been noted in other answers that the inverse formulation should be faster. i.e. If you iterate through the array and compose a new array of objects to keep, instead of objects to discard. That may be true (although what about the memory and processing cost of allocating a new array, and discarding the old one?) but even if it's faster it may not be as big a deal as it would be for a naive implementation, because NSArrays do not behave like "normal" arrays. They talk the talk but they walk a different walk. See a good analysis here:
The inverse formulation may be faster, but I've never needed to care whether it is, because the above formulation has always been fast enough for my needs.
For me the take-home message is to use whatever formulation is clearest to you. Optimize only if necessary. I personally find the above formulation clearest, which is why I use it. But if the inverse formulation is clearer to you, go for it.
A: You can use NSpredicate to remove items from your mutable array. This requires no for loops.
For example if you have an NSMutableArray of names, you can create a predicate like this one:
NSPredicate *caseInsensitiveBNames =
[NSPredicate predicateWithFormat:@"SELF beginswith[c] 'b'"];
The following line will leave you with an array that contains only names starting with b.
[namesArray filterUsingPredicate:caseInsensitiveBNames];
If you have trouble creating the predicates you need, use this apple developer link.
A: I did a performance test using 4 different methods. Each test iterated through all elements in a 100,000 element array, and removed every 5th item. The results did not vary much with/ without optimization. These were done on an iPad 4:
(1) removeObjectAtIndex: -- 271 ms
(2) removeObjectsAtIndexes: -- 1010 ms (because building the index set takes ~700 ms; otherwise this is basically the same as calling removeObjectAtIndex: for each item)
(3) removeObjects: -- 326 ms
(4) make a new array with objects passing the test -- 17 ms
So, creating a new array is by far the fastest. The other methods are all comparable, except that using removeObjectsAtIndexes: will be worse with more items to remove, because of the time needed to build the index set.
A: Either use loop counting down over indices:
for (NSInteger i = array.count - 1; i >= 0; --i) {
or make a copy with the objects you want to keep.
In particular, do not use a for (id object in array) loop or NSEnumerator.
A: For iOS 4+ or OS X 10.6+, Apple added passingTest series of APIs in NSMutableArray, like – indexesOfObjectsPassingTest:. A solution with such API would be:
NSIndexSet *indexesToBeRemoved = [someList indexesOfObjectsPassingTest:
^BOOL(id obj, NSUInteger idx, BOOL *stop) {
return [self shouldRemove:obj];
}];
[someList removeObjectsAtIndexes:indexesToBeRemoved];
A: Nowadays you can use reversed block-based enumeration. A simple example code:
NSMutableArray *array = [@[@{@"name": @"a", @"shouldDelete": @(YES)},
@{@"name": @"b", @"shouldDelete": @(NO)},
@{@"name": @"c", @"shouldDelete": @(YES)},
@{@"name": @"d", @"shouldDelete": @(NO)}] mutableCopy];
[array enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
if([obj[@"shouldDelete"] boolValue])
[array removeObjectAtIndex:idx];
}];
Result:
(
{
name = b;
shouldDelete = 0;
},
{
name = d;
shouldDelete = 0;
}
)
another option with just one line of code:
[array filterUsingPredicate:[NSPredicate predicateWithFormat:@"shouldDelete == NO"]];
A: Why don't you add the objects to be removed to another NSMutableArray. When you are finished iterating, you can remove the objects that you have collected.
A: How about swapping the elements you want to delete with the 'n'th element, 'n-1'th element and so on?
When you're done you resize the array to 'previous size - number of swaps'
A: If all objects in your array are unique or you want to remove all occurrences of an object when found, you could fast enumerate on an array copy and use [NSMutableArray removeObject:] to remove the object from the original.
NSMutableArray *myArray;
NSArray *myArrayCopy = [NSArray arrayWithArray:myArray];
for (NSObject *anObject in myArrayCopy) {
if (shouldRemove(anObject)) {
[myArray removeObject:anObject];
}
}
A: benzado's anwser above is what you should do for preformace. In one of my applications removeObjectsInArray took a running time of 1 minute, just adding to a new array took .023 seconds.
A: I define a category that lets me filter using a block, like this:
@implementation NSMutableArray (Filtering)
- (void)filterUsingTest:(BOOL (^)(id obj, NSUInteger idx))predicate {
NSMutableIndexSet *indexesFailingTest = [[NSMutableIndexSet alloc] init];
NSUInteger index = 0;
for (id object in self) {
if (!predicate(object, index)) {
[indexesFailingTest addIndex:index];
}
++index;
}
[self removeObjectsAtIndexes:indexesFailingTest];
[indexesFailingTest release];
}
@end
which can then be used like this:
[myMutableArray filterUsingTest:^BOOL(id obj, NSUInteger idx) {
return [self doIWantToKeepThisObject:obj atIndex:idx];
}];
A: A nicer implementation could be to use the category method below on NSMutableArray.
@implementation NSMutableArray(BMCommons)
- (void)removeObjectsWithPredicate:(BOOL (^)(id obj))predicate {
if (predicate != nil) {
NSMutableArray *newArray = [[NSMutableArray alloc] initWithCapacity:self.count];
for (id obj in self) {
BOOL shouldRemove = predicate(obj);
if (!shouldRemove) {
[newArray addObject:obj];
}
}
[self setArray:newArray];
}
}
@end
The predicate block can be implemented to do processing on each object in the array. If the predicate returns true the object is removed.
An example for a date array to remove all dates that lie in the past:
NSMutableArray *dates = ...;
[dates removeObjectsWithPredicate:^BOOL(id obj) {
NSDate *date = (NSDate *)obj;
return [date timeIntervalSinceNow] < 0;
}];
A: Iterating backwards-ly was my favourite for years , but for a long time I never encountered the case where the 'deepest' ( highest count) object was removed first. Momentarily before the pointer moves on to the next index there ain't anything and it crashes.
Benzado's way is the closest to what i do now but I never realised there would be the stack reshuffle after every remove.
under Xcode 6 this works
NSMutableArray *itemsToKeep = [NSMutableArray arrayWithCapacity:[array count]];
for (id object in array)
{
if ( [object isNotEqualTo:@"whatever"]) {
[itemsToKeep addObject:object ];
}
}
array = nil;
array = [[NSMutableArray alloc]initWithArray:itemsToKeep];
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/111866",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "198"
}
|
Q: What is your latest useful Perl one-liner (or a pipe involving Perl)? The one-liner should:
*
*solve a real-world problem
*not be extensively cryptic (should be easy to understand and reproduce)
*be worth the time it takes to write it (should not be too clever)
I'm looking for practical tips and tricks (complementary examples for perldoc perlrun).
A: All one-liners from the answers collected in one place:
*
*perl -pe's/([\d.]+)/localtime $1/e;' access.log
*ack $(ls t/lib/TestPM/|awk -F'.' '{print $1}'|xargs perl -e 'print join "|" => @ARGV')
aggtests/ t -l
*perl -e'while(<*.avi>) { s/avi$/srt/; rename <*.srt>, $_ }'
*find . -name '*.whatever' | perl -lne unlink
*tail -F /var/log/squid/access.log | perl -ane 'BEGIN{$|++} $F[6] =~ m{\Qrad.live.com/ADSAdClient31.dll}
&& printf "%02d:%02d:%02d %15s %9d\n", sub{reverse @_[0..2]}->(localtime $F[0]), @F[2,4]'
*export PATH=$(perl -F: -ane'print join q/:/, grep { !$c{$_}++ } @F'<<<$PATH)
*alias e2d="perl -le \"print scalar(localtime($ARGV[0]));\""
*perl -ple '$_=eval'
*perl -00 -ne 'print sort split /^/'
*perl -pe'1while+s/\t/" "x(8-pos()%8)/e'
*tail -f log | perl -ne '$s=time() unless $s; $n=time(); $d=$n-$s; if ($d>=2) { print qq
($. lines in last $d secs, rate ),$./$d,qq(\n); $. =0; $s=$n; }'
*perl -MFile::Spec -e 'print join(qq(\n),File::Spec->path).qq(\n)'
See corresponding answers for their descriptions.
A: The Perl one-liner I use the most is the Perl calculator
perl -ple '$_=eval'
A: One of the biggest bandwidth hogs at $work is download web advertising, so I'm looking at the low-hanging fruit waiting to be picked. I've got rid of Google ads, now I have Microsoft in my line of sights. So I run a tail on the log file, and pick out the lines of interest:
tail -F /var/log/squid/access.log | \
perl -ane 'BEGIN{$|++} $F[6] =~ m{\Qrad.live.com/ADSAdClient31.dll}
&& printf "%02d:%02d:%02d %15s %9d\n",
sub{reverse @_[0..2]}->(localtime $F[0]), @F[2,4]'
What the Perl pipe does is to begin by setting autoflush to true, so that any that is acted upon is printed out immediately. Otherwise the output it chunked up and one receives a batch of lines when the output buffer fills. The -a switch splits each input line on white space, and saves the results in the array @F (functionality inspired by awk's capacity to split input records into its $1, $2, $3... variables).
It checks whether the 7th field in the line contains the URI we seek (using \Q to save us the pain of escaping uninteresting metacharacters). If a match is found, it pretty-prints the time, the source IP and the number of bytes returned from the remote site.
The time is obtained by taking the epoch time in the first field and using 'localtime' to break it down into its components (hour, minute, second, day, month, year). It takes a slice of the first three elements returns, second, minute and hour, and reverses the order to get hour, minute and second. This is returned as a three element array, along with a slice of the third (IP address) and fifth (size) from the original @F array. These five arguments are passed to sprintf which formats the results.
A: @dr_pepper
Remove literal duplicates in $PATH:
$ export PATH=$(perl -F: -ane'print join q/:/, grep { !$c{$_}++ } @F'<<<$PATH)
Print unique clean paths from %PATH% environment variable (it doesn't touch ../ and alike, replace File::Spec->rel2abs by Cwd::realpath if it is desirable) It is not a one-liner to be more portable:
#!/usr/bin/perl -w
use File::Spec;
$, = "\n";
print grep { !$count{$_}++ }
map { File::Spec->rel2abs($_) }
File::Spec->path;
A: In response to Ovid's Vim/ack combination:
I too am often searching for something and then want to open the matching files in Vim, so I made myself a little shortcut some time ago (works in Z shell only, I think):
function vimify-eval; {
if [[ ! -z "$BUFFER" ]]; then
if [[ $BUFFER = 'ack'* ]]; then
BUFFER="$BUFFER -l"
fi
BUFFER="vim \$($BUFFER)"
zle accept-line
fi
}
zle -N vim-eval-widget vimify-eval
bindkey '^P' vim-eval-widget
It works like this: I search for something using ack, like ack some-pattern. I look at the results and if I like it, I press arrow-up to get the ack-line again and then press Ctrl + P. What happens then is that Z shell appends and "-l" for listing filenames only if the command starts with "ack". Then it puts "$(...)" around the command and "vim" in front of it. Then the whole thing is executed.
A: I use this quite frequently to quickly convert epoch times to a useful datestamp.
perl -l -e 'print scalar(localtime($ARGV[0]))'
Make an alias in your shell:
alias e2d="perl -le \"print scalar(localtime($ARGV[0]));\""
Then pipe an epoch number to the alias.
echo 1219174516 | e2d
Many programs and utilities on Unix/Linux use epoch values to represent time, so this has proved invaluable for me.
A: Remove duplicates in path variable:
set path=(`echo $path | perl -e 'foreach(split(/ /,<>)){print $_," " unless $s{$_}++;}'`)
A: Remove MS-DOS line-endings.
perl -p -i -e 's/\r\n$/\n/' htdocs/*.asp
A: Extracting Stack Overflow reputation without having to open a web page:
perl -nle "print ' Stack Overflow ' . $1 . ' (no change)' if /\s{20,99}([0-9,]{3,6})<\/div>/;" "SO.html" >> SOscores.txt
This assumes the user page has already been downloaded to file SO.html. I use wget for this purpose. The notation here is for Windows command line; it would be slightly different for Linux or Mac OS X. The output is appended to a text file.
I use it in a BAT script to automate sampling of reputation on the four sites in the family:
Stack Overflow, Server Fault, Super User and Meta Stack Overflow.
A: I often need to see a readable version of the PATH while shell scripting. The following one-liners print every path entry on its own line.
Over time this one-liner has evolved through several phases:
Unix (version 1):
perl -e 'print join("\n",split(":",$ENV{"PATH"}))."\n"'
Windows (version 2):
perl -e "print join(qq(\n),split(';',$ENV{'PATH'})).qq(\n)"
Both Unix/Windows (using q/qq tip from @j-f-sebastian) (version 3):
perl -MFile::Spec -e 'print join(qq(\n), File::Spec->path).qq(\n)' # Unix
perl -MFile::Spec -e "print join(qq(\n), File::Spec->path).qq(\n)" # Windows
A: Filters a stream of white-space separated stanzas (name/value pair lists),
sorting each stanza individually:
perl -00 -ne 'print sort split /^/'
A: One of the most recent one-liners that got a place in my ~/bin:
perl -ne '$s=time() unless $s; $n=time(); $d=$n-$s; if ($d>=2) { print "$. lines in last $d secs, rate ",$./$d,"\n"; $. =0; $s=$n; }'
You would use it against a tail of a log file and it will print the rate of lines being outputed.
Want to know how many hits per second you are getting on your webservers? tail -f log | this_script.
A: Get human-readable output from du, sorted by size:
perl -e '%h=map{/.\s/;7x(ord$&&10)+$`,$_}`du -h`;print@h{sort%h}'
A: Network administrators have the tendency to misconfigure "subnet address" as "host address" especially while using Cisco ASDM auto-suggest. This straightforward one-liner scans the configuration files for any such configuration errors.
incorrect usage: permit host 10.1.1.0
correct usage: permit 10.1.1.0 255.255.255.0
perl -ne "print if /host ([\w\-\.]+){3}\.0 /" *.conf
This was tested and used on Windows, please suggest if it should be modified in any way for correct usage.
A: Please see my slides for "A Field Guide To The Perl Command Line Options."
A: Squid log files. They're great, aren't they? Except by default they have seconds-from-the-epoch as the time field. Here's a one-liner that reads from a squid log file and converts the time into a human readable date:
perl -pe's/([\d.]+)/localtime $1/e;' access.log
With a small tweak, you can make it only display lines with a keyword you're interested in. The following watches for stackoverflow.com accesses and prints only those lines, with a human readable date. To make it more useful, I'm giving it the output of tail -f, so I can see accesses in real time:
tail -f access.log | perl -ne's/([\d.]+)/localtime $1/e,print if /stackoverflow\.com/'
A: The problem: A media player does not automatically load subtitles due to their names differ from corresponding video files.
Solution: Rename all *.srt (files with subtitles) to match the *.avi (files with video).
perl -e'while(<*.avi>) { s/avi$/srt/; rename <*.srt>, $_ }'
CAVEAT: Sorting order of original video and subtitle filenames should be the same.
Here, a more verbose version of the above one-liner:
my @avi = glob('*.avi');
my @srt = glob('*.srt');
for my $i (0..$#avi)
{
my $video_filename = $avi[$i];
$video_filename =~ s/avi$/srt/; # 'movie1.avi' -> 'movie1.srt'
my $subtitle_filename = $srt[$i]; # 'film1.srt'
rename($subtitle_filename, $video_filename); # 'film1.srt' -> 'movie1.srt'
}
A: You may not think of this as Perl, but I use ack religiously (it's a smart grep replacement written in Perl) and that lets me edit, for example, all of my Perl tests which access a particular part of our API:
vim $(ack --perl -l 'api/v1/episode' t)
As a side note, if you use vim, you can run all of the tests in your editor's buffers.
For something with more obvious (if simple) Perl, I needed to know how many test programs used out test fixtures in the t/lib/TestPM directory (I've cut down the command for clarity).
ack $(ls t/lib/TestPM/|awk -F'.' '{print $1}'|xargs perl -e 'print join "|" => @ARGV') aggtests/ t -l
Note how the "join" turns the results into a regex to feed to ack.
A: The common idiom of using find ... -exec rm {} \; to delete a set of files somewhere in a directory tree is not particularly efficient in that it executes the rm command once for each file found. One of my habits, born from the days when computers weren't quite as fast (dagnabbit!), is to replace many calls to rm with one call to perl:
find . -name '*.whatever' | perl -lne unlink
The perl part of the command line reads the list of files emitted* by find, one per line, trims the newline off, and deletes the file using perl's built-in unlink() function, which takes $_ as its argument if no explicit argument is supplied. ($_ is set to each line of input thanks to the -n flag.) (*These days, most find commands do -print by default, so I can leave that part out.)
I like this idiom not only because of the efficiency (possibly less important these days) but also because it has fewer chorded/awkward keys than typing the traditional -exec rm {} \; sequence. It also avoids quoting issues caused by file names with spaces, quotes, etc., of which I have many. (A more robust version might use find's -print0 option and then ask perl to read null-delimited records instead of lines, but I'm usually pretty confident that my file names do not contain embedded newlines.)
A: Expand all tabs to spaces: perl -pe'1while+s/\t/" "x(8-pos()%8)/e'
Of course, this could be done with :set et, :ret in Vim.
A: I have a list of tags with which I identify portions of text. The master list is of the format:
text description {tag_label}
It's important that the {tag_label} are not duplicated. So there's this nice simple script:
perl -ne '($c) = $_ =~ /({.*?})/; print $c,"\n" ' $1 | sort | uniq -c | sort -d
I know that I could do the whole lot in shell or perl, but this was the first thing that came to mind.
A: Often I have had to convert tabular data in to configuration files. For e.g, Network cabling vendors provide the patching record in Excel format and we have to use that information to create configuration files. i.e,
Interface, Connect to, Vlan
Gi1/0/1, Desktop, 1286
Gi1/0/2, IP Phone, 1317
should become:
interface Gi1/0/1
description Desktop
switchport access vlan 1286
and so on. The same task re-appears in several forms in various administration tasks where a tabular data needs to be prepended with their field name and transposed to a flat structure. I have seen some DBA's waste a lot of times preparing their SQL statements from excel sheet. It can be achieved using this simple one-liner. Just save the tabular data in CSV format using your favourite spreadsheet tool and run this one-liner. The field names in header row gets prepended to individual cell values, so you may have to edit it to match your requirements.
perl -F, -lane "if ($.==1) {@keys = @F} else{print @keys[$_].$F[$_] foreach(0..$#F)} "
The caveat is that none of the field names or values should contain any commas. Perhaps this can be further elaborated to catch such exceptions in a one-line, please improve this if possible.
A: Here is one that I find handy when dealing with a collection compressed log files:
open STATFILE, "zcat $logFile|" or die "Can't open zcat of $logFile" ;
A: At some time I found that anything I would want to do with Perl that is short enough to be done on the command line with 'perl -e' can be done better, easier and faster with normal Z shell features without the hassle of quoting. E.g. the example above could be done like this:
srt=(*.srt); for foo in *.avi; mv $srt[1] ${foo:r}.srt && srt=($srt[2,-1])
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/111868",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
}
|
Q: source control with VB2005 Express Can anyone suggest a good source control system that interfaces with VB2005 Express? As the Express editions of Visual Studio do not allow add-ins does this mean that I will not be able to integrate source control into the IDE? I'm used to the check-in/check-out process of SourceSafe integrated into VB6. Can anyone recommend TortoiseSVN as an alternative?
A: TortoiseSVN is a good choice. Although it won't integrate into the IDE (because of the plug-in problem you mentioned), it's really solid in the Explorer right-button menu.
Also consider Vault from SourceGear. If you're used to SourceSafe, Vault will be easier to learn; Vault was specifically designed for ex-SourceSafe users.
A: Take a look at Perforce. It is lightning fast, rock solid, simple to use and configure, and has features to support pretty much any source control scenario.
If you are working on your own (which seems likely, given that you are using VB 2k5 Express), it is free for up to two users. If / when you switch to VS Pro, it has very good integration, and on its own it has several excellent clients and Windows Explorer integration.
A: I would recommend using Tortoise and do version control through Windows Explorer.
I actually prefer that to Ankh in VS2008.
A: I use TortoiseSVN and windows explorer for all my development projects and believe it works great. I started with SourceSafe, but when I changed jobs I went to an SVN shop and have now incorporated it into my own development projects. You can also use Source Safe without integration. You use Source Safe to check in/out files in a folder and then manage it outside the IDE. While this isn't as "simple" it may work just fine for certain projects. I use a hosted SVN provider, you may want to check them out: Hosted-Projects.
A: No, Source Control systems can't be integrated with the VS Express IDEs by design.
If you want to continue using your existing VSS, you're best option is to upgrade to Visual Studio Standard. Otherwise, check out TortoiseSVN. Here's a good quick start:
http://www.polymorphicpodcast.com/shows/subversion/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/111910",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to access the HttpServerUtility.MapPath method in a Thread or Timer? I use a System.Timers.Timer in my Asp.Net application and I need to use the HttpServerUtility.MapPath method which seems to be only available via HttpContext.Current.Server.MapPath.
The problem is that HttpContext.Current is null when the Timer.Elapsed event fires.
Is there another way to get a reference to a HttpServerUtility object ?
I could inject it in my class' constructor. Is it safe ? How can I be sure it won't be Garbage Collected at the end of the current request?
Thanks!
A: Can you not call the MapPath function before starting the timer, and simply cache the result? Is it absolutely neccessary to have the MapPath call inside the tick event?
A: When the timer elapse, there is no current HTTP context. This is because the timer events are not related to a specific HTTP request.
What you should do is use HttpServerUtility.MapPath where HTTP context is available. You can do it in one of the request pipeline events (such as Page_Load) or in a Global.asax event such as Application_Start.
Assign the MapPath result to a variable accessible from the Timer.Elapsed event, where you could use Path.Combine to get the location of a specific file you need.
A: It's possible to use HostingEnvironment.MapPath() instead of HttpContext.Current.Server.MapPath()
I haven't tried it yet in a thread or timer event though.
Some (non viable) solutions I considered;
*
*The only method I care about on HttpServerUtility is MapPath. So as an alternative I could use AppDomain.CurrentDomain.BaseDirectory and build my paths from this. But this will fail if your app uses virtual directories (Mine does).
*Another approach:
Add all the paths I need to the the Global class. Resolve these paths in Application_Start.
A: I don't know if this will solve your virtual directories issue, but I use this for MapPath:
public static string MapPath(string path)
{
if (HttpContext.Current != null)
return HttpContext.Current.Server.MapPath(path);
return HttpRuntime.AppDomainAppPath + path.Replace("~", string.Empty).Replace('/', '\\');
}
A: HostingEnvironment isn't the perfect solution because it's a very difficult class to mock (see How to unit test code that uses HostingEnvironment.MapPath).
For those who need testability, a better way might be to create your own path-mapper interface as proposed by https://stackoverflow.com/a/1231962/85196, except implement it as
public class ServerPathMapper : IPathMapper {
public string MapPath(string relativePath) {
return HostingEnvironment.MapPath(relativePath);
}
}
The result is easily mockable, uses HostingEnvironment internally, and could even potentially address ase69s's concern at the same time.
A: I think the reason for why it is null at that time (if you think about it), is that the timer elapsed event doesn't occur as part of a HTTP request (hence there is no context). It is caused by something on your server.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/111927",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "91"
}
|
Q: Is there a printf converter to print in binary format? I can print with printf as a hex or octal number. Is there a format tag to print as binary, or arbitrary base?
I am running gcc.
printf("%d %x %o\n", 10, 10, 10); //prints "10 A 12\n"
printf("%b\n", 10); // prints "%b\n"
A: There isn't a binary conversion specifier in glibc normally.
It is possible to add custom conversion types to the printf() family of functions in glibc. See register_printf_function for details. You could add a custom %b conversion for your own use, if it simplifies the application code to have it available.
Here is an example of how to implement a custom printf formats in glibc.
A: Some runtimes support "%b" although that is not a standard.
Also see here for an interesting discussion:
http://bytes.com/forum/thread591027.html
HTH
A: There is no formatting function in the C standard library to output binary like that. All the format operations the printf family supports are towards human readable text.
A: Maybe a bit OT, but if you need this only for debuging to understand or retrace some binary operations you are doing, you might take a look on wcalc (a simple console calculator). With the -b options you get binary output.
e.g.
$ wcalc -b "(256 | 3) & 0xff"
= 0b11
A: You could use a small table to improve speed1. Similar techniques are useful in the embedded world, for example, to invert a byte:
const char *bit_rep[16] = {
[ 0] = "0000", [ 1] = "0001", [ 2] = "0010", [ 3] = "0011",
[ 4] = "0100", [ 5] = "0101", [ 6] = "0110", [ 7] = "0111",
[ 8] = "1000", [ 9] = "1001", [10] = "1010", [11] = "1011",
[12] = "1100", [13] = "1101", [14] = "1110", [15] = "1111",
};
void print_byte(uint8_t byte)
{
printf("%s%s", bit_rep[byte >> 4], bit_rep[byte & 0x0F]);
}
1 I'm mostly referring to embedded applications where optimizers are not so aggressive and the speed difference is visible.
A: The following recursive function might be useful:
void bin(int n)
{
/* Step 1 */
if (n > 1)
bin(n/2);
/* Step 2 */
printf("%d", n % 2);
}
A: I optimized the top solution for size and C++-ness, and got to this solution:
inline std::string format_binary(unsigned int x)
{
static char b[33];
b[32] = '\0';
for (int z = 0; z < 32; z++) {
b[31-z] = ((x>>z) & 0x1) ? '1' : '0';
}
return b;
}
A: Use:
char buffer [33];
itoa(value, buffer, 2);
printf("\nbinary: %s\n", buffer);
For more ref., see How to print binary number via printf.
A: Print bits from any type using less code and resources
This approach has as attributes:
*
*Works with variables and literals.
*Doesn't iterate all bits when not necessary.
*Call printf only when complete a byte (not unnecessarily for all bits).
*Works for any type.
*Works with little and big endianness (uses GCC #defines for checking).
*May work with hardware that char isn't a byte (eight bits). (Tks @supercat)
*Uses typeof() that isn't C standard but is largely defined.
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <limits.h>
#if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
#define for_endian(size) for (int i = 0; i < size; ++i)
#elif __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
#define for_endian(size) for (int i = size - 1; i >= 0; --i)
#else
#error "Endianness not detected"
#endif
#define printb(value) \
({ \
typeof(value) _v = value; \
__printb((typeof(_v) *) &_v, sizeof(_v)); \
})
#define MSB_MASK 1 << (CHAR_BIT - 1)
void __printb(void *value, size_t size)
{
unsigned char uc;
unsigned char bits[CHAR_BIT + 1];
bits[CHAR_BIT] = '\0';
for_endian(size) {
uc = ((unsigned char *) value)[i];
memset(bits, '0', CHAR_BIT);
for (int j = 0; uc && j < CHAR_BIT; ++j) {
if (uc & MSB_MASK)
bits[j] = '1';
uc <<= 1;
}
printf("%s ", bits);
}
printf("\n");
}
int main(void)
{
uint8_t c1 = 0xff, c2 = 0x44;
uint8_t c3 = c1 + c2;
printb(c1);
printb((char) 0xff);
printb((short) 0xff);
printb(0xff);
printb(c2);
printb(0x44);
printb(0x4411ff01);
printb((uint16_t) c3);
printb('A');
printf("\n");
return 0;
}
Output
$ ./printb
11111111
11111111
00000000 11111111
00000000 00000000 00000000 11111111
01000100
00000000 00000000 00000000 01000100
01000100 00010001 11111111 00000001
00000000 01000011
00000000 00000000 00000000 01000001
I have used another approach (bitprint.h) to fill a table with all bytes (as bit strings) and print them based on the input/index byte. It's worth taking a look.
A: void
print_binary(unsigned int n)
{
unsigned int mask = 0;
/* this grotesque hack creates a bit pattern 1000... */
/* regardless of the size of an unsigned int */
mask = ~mask ^ (~mask >> 1);
for(; mask != 0; mask >>= 1) {
putchar((n & mask) ? '1' : '0');
}
}
A: Print the least significant bit and shift it out on the right. Doing this until the integer becomes zero prints the binary representation without leading zeros but in reversed order. Using recursion, the order can be corrected quite easily.
#include <stdio.h>
void print_binary(unsigned int number)
{
if (number >> 1) {
print_binary(number >> 1);
}
putc((number & 1) ? '1' : '0', stdout);
}
To me, this is one of the cleanest solutions to the problem. If you like 0b prefix and a trailing new line character, I suggest wrapping the function.
Online demo
A: Maybe someone will find this solution useful:
void print_binary(int number, int num_digits) {
int digit;
for(digit = num_digits - 1; digit >= 0; digit--) {
printf("%c", number & (1 << digit) ? '1' : '0');
}
}
A: Hacky but works for me:
#define BYTE_TO_BINARY_PATTERN "%c%c%c%c%c%c%c%c"
#define BYTE_TO_BINARY(byte) \
(byte & 0x80 ? '1' : '0'), \
(byte & 0x40 ? '1' : '0'), \
(byte & 0x20 ? '1' : '0'), \
(byte & 0x10 ? '1' : '0'), \
(byte & 0x08 ? '1' : '0'), \
(byte & 0x04 ? '1' : '0'), \
(byte & 0x02 ? '1' : '0'), \
(byte & 0x01 ? '1' : '0')
printf("Leading text "BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(byte));
For multi-byte types
printf("m: "BYTE_TO_BINARY_PATTERN" "BYTE_TO_BINARY_PATTERN"\n",
BYTE_TO_BINARY(m>>8), BYTE_TO_BINARY(m));
You need all the extra quotes unfortunately. This approach has the efficiency risks of macros (don't pass a function as the argument to BYTE_TO_BINARY) but avoids the memory issues and multiple invocations of strcat in some of the other proposals here.
A: No standard and portable way.
Some implementations provide itoa(), but it's not going to be in most, and it has a somewhat crummy interface. But the code is behind the link and should let you implement your own formatter pretty easily.
A: void print_ulong_bin(const unsigned long * const var, int bits) {
int i;
#if defined(__LP64__) || defined(_LP64)
if( (bits > 64) || (bits <= 0) )
#else
if( (bits > 32) || (bits <= 0) )
#endif
return;
for(i = 0; i < bits; i++) {
printf("%lu", (*var >> (bits - 1 - i)) & 0x01);
}
}
should work - untested.
A: I liked the code by paniq, the static buffer is a good idea. However it fails if you want multiple binary formats in a single printf() because it always returns the same pointer and overwrites the array.
Here's a C style drop-in that rotates pointer on a split buffer.
char *
format_binary(unsigned int x)
{
#define MAXLEN 8 // width of output format
#define MAXCNT 4 // count per printf statement
static char fmtbuf[(MAXLEN+1)*MAXCNT];
static int count = 0;
char *b;
count = count % MAXCNT + 1;
b = &fmtbuf[(MAXLEN+1)*count];
b[MAXLEN] = '\0';
for (int z = 0; z < MAXLEN; z++) { b[MAXLEN-1-z] = ((x>>z) & 0x1) ? '1' : '0'; }
return b;
}
A: Here is a small variation of paniq's solution that uses templates to allow printing of 32 and 64 bit integers:
template<class T>
inline std::string format_binary(T x)
{
char b[sizeof(T)*8+1] = {0};
for (size_t z = 0; z < sizeof(T)*8; z++)
b[sizeof(T)*8-1-z] = ((x>>z) & 0x1) ? '1' : '0';
return std::string(b);
}
And can be used like:
unsigned int value32 = 0x1e127ad;
printf( " 0x%x: %s\n", value32, format_binary(value32).c_str() );
unsigned long long value64 = 0x2e0b04ce0;
printf( "0x%llx: %s\n", value64, format_binary(value64).c_str() );
Here is the result:
0x1e127ad: 00000001111000010010011110101101
0x2e0b04ce0: 0000000000000000000000000000001011100000101100000100110011100000
A: I just want to post my solution. It's used to get zeroes and ones of one byte, but calling this function few times can be used for larger data blocks. I use it for 128 bit or larger structs. You can also modify it to use size_t as input parameter and pointer to data you want to print, so it can be size independent. But it works for me quit well as it is.
void print_binary(unsigned char c)
{
unsigned char i1 = (1 << (sizeof(c)*8-1));
for(; i1; i1 >>= 1)
printf("%d",(c&i1)!=0);
}
void get_binary(unsigned char c, unsigned char bin[])
{
unsigned char i1 = (1 << (sizeof(c)*8-1)), i2=0;
for(; i1; i1>>=1, i2++)
bin[i2] = ((c&i1)!=0);
}
A: Here's how I did it for an unsigned int
void printb(unsigned int v) {
unsigned int i, s = 1<<((sizeof(v)<<3)-1); // s = only most significant bit at 1
for (i = s; i; i>>=1) printf("%d", v & i || 0 );
}
A: One statement generic conversion of any integral type into the binary string representation using standard library:
#include <bitset>
MyIntegralType num = 10;
print("%s\n",
std::bitset<sizeof(num) * 8>(num).to_string().insert(0, "0b").c_str()
); // prints "0b1010\n"
Or just: std::cout << std::bitset<sizeof(num) * 8>(num);
A: My solution:
long unsigned int i;
for(i = 0u; i < sizeof(integer) * CHAR_BIT; i++) {
if(integer & LONG_MIN)
printf("1");
else
printf("0");
integer <<= 1;
}
printf("\n");
A: Based on @ideasman42's suggestion in his answer, this is a macro that provides int8,16,32 & 64 versions, reusing the INT8 macro to avoid repetition.
/* --- PRINTF_BYTE_TO_BINARY macro's --- */
#define PRINTF_BINARY_SEPARATOR
#define PRINTF_BINARY_PATTERN_INT8 "%c%c%c%c%c%c%c%c"
#define PRINTF_BYTE_TO_BINARY_INT8(i) \
(((i) & 0x80ll) ? '1' : '0'), \
(((i) & 0x40ll) ? '1' : '0'), \
(((i) & 0x20ll) ? '1' : '0'), \
(((i) & 0x10ll) ? '1' : '0'), \
(((i) & 0x08ll) ? '1' : '0'), \
(((i) & 0x04ll) ? '1' : '0'), \
(((i) & 0x02ll) ? '1' : '0'), \
(((i) & 0x01ll) ? '1' : '0')
#define PRINTF_BINARY_PATTERN_INT16 \
PRINTF_BINARY_PATTERN_INT8 PRINTF_BINARY_SEPARATOR PRINTF_BINARY_PATTERN_INT8
#define PRINTF_BYTE_TO_BINARY_INT16(i) \
PRINTF_BYTE_TO_BINARY_INT8((i) >> 8), PRINTF_BYTE_TO_BINARY_INT8(i)
#define PRINTF_BINARY_PATTERN_INT32 \
PRINTF_BINARY_PATTERN_INT16 PRINTF_BINARY_SEPARATOR PRINTF_BINARY_PATTERN_INT16
#define PRINTF_BYTE_TO_BINARY_INT32(i) \
PRINTF_BYTE_TO_BINARY_INT16((i) >> 16), PRINTF_BYTE_TO_BINARY_INT16(i)
#define PRINTF_BINARY_PATTERN_INT64 \
PRINTF_BINARY_PATTERN_INT32 PRINTF_BINARY_SEPARATOR PRINTF_BINARY_PATTERN_INT32
#define PRINTF_BYTE_TO_BINARY_INT64(i) \
PRINTF_BYTE_TO_BINARY_INT32((i) >> 32), PRINTF_BYTE_TO_BINARY_INT32(i)
/* --- end macros --- */
#include <stdio.h>
int main() {
long long int flag = 1648646756487983144ll;
printf("My Flag "
PRINTF_BINARY_PATTERN_INT64 "\n",
PRINTF_BYTE_TO_BINARY_INT64(flag));
return 0;
}
This outputs:
My Flag 0001011011100001001010110111110101111000100100001111000000101000
For readability you can change :#define PRINTF_BINARY_SEPARATOR to #define PRINTF_BINARY_SEPARATOR "," or #define PRINTF_BINARY_SEPARATOR " "
This will output:
My Flag 00010110,11100001,00101011,01111101,01111000,10010000,11110000,00101000
or
My Flag 00010110 11100001 00101011 01111101 01111000 10010000 11110000 00101000
A: Based on @William Whyte's answer, this is a macro that provides int8,16,32 & 64 versions, reusing the INT8 macro to avoid repetition.
/* --- PRINTF_BYTE_TO_BINARY macro's --- */
#define PRINTF_BINARY_PATTERN_INT8 "%c%c%c%c%c%c%c%c"
#define PRINTF_BYTE_TO_BINARY_INT8(i) \
(((i) & 0x80ll) ? '1' : '0'), \
(((i) & 0x40ll) ? '1' : '0'), \
(((i) & 0x20ll) ? '1' : '0'), \
(((i) & 0x10ll) ? '1' : '0'), \
(((i) & 0x08ll) ? '1' : '0'), \
(((i) & 0x04ll) ? '1' : '0'), \
(((i) & 0x02ll) ? '1' : '0'), \
(((i) & 0x01ll) ? '1' : '0')
#define PRINTF_BINARY_PATTERN_INT16 \
PRINTF_BINARY_PATTERN_INT8 PRINTF_BINARY_PATTERN_INT8
#define PRINTF_BYTE_TO_BINARY_INT16(i) \
PRINTF_BYTE_TO_BINARY_INT8((i) >> 8), PRINTF_BYTE_TO_BINARY_INT8(i)
#define PRINTF_BINARY_PATTERN_INT32 \
PRINTF_BINARY_PATTERN_INT16 PRINTF_BINARY_PATTERN_INT16
#define PRINTF_BYTE_TO_BINARY_INT32(i) \
PRINTF_BYTE_TO_BINARY_INT16((i) >> 16), PRINTF_BYTE_TO_BINARY_INT16(i)
#define PRINTF_BINARY_PATTERN_INT64 \
PRINTF_BINARY_PATTERN_INT32 PRINTF_BINARY_PATTERN_INT32
#define PRINTF_BYTE_TO_BINARY_INT64(i) \
PRINTF_BYTE_TO_BINARY_INT32((i) >> 32), PRINTF_BYTE_TO_BINARY_INT32(i)
/* --- end macros --- */
#include <stdio.h>
int main() {
long long int flag = 1648646756487983144ll;
printf("My Flag "
PRINTF_BINARY_PATTERN_INT64 "\n",
PRINTF_BYTE_TO_BINARY_INT64(flag));
return 0;
}
This outputs:
My Flag 0001011011100001001010110111110101111000100100001111000000101000
For readability you may want to add a separator for eg:
My Flag 00010110,11100001,00101011,01111101,01111000,10010000,11110000,00101000
A: As of February 3rd, 2022, the GNU C Library been updated to version 2.35. As a result, %b is now supported to output in binary format.
printf-family functions now support the %b format for output of
integers in binary, as specified in draft ISO C2X, and the %B variant
of that format recommended by draft ISO C2X.
A: Print Binary for Any Datatype
// Assumes little endian
void printBits(size_t const size, void const * const ptr)
{
unsigned char *b = (unsigned char*) ptr;
unsigned char byte;
int i, j;
for (i = size-1; i >= 0; i--) {
for (j = 7; j >= 0; j--) {
byte = (b[i] >> j) & 1;
printf("%u", byte);
}
}
puts("");
}
Test:
int main(int argv, char* argc[])
{
int i = 23;
uint ui = UINT_MAX;
float f = 23.45f;
printBits(sizeof(i), &i);
printBits(sizeof(ui), &ui);
printBits(sizeof(f), &f);
return 0;
}
A: #include <stdio.h>
#include <conio.h>
void main()
{
clrscr();
printf("Welcome\n\n\n");
unsigned char x='A';
char ch_array[8];
for(int i=0; x!=0; i++)
{
ch_array[i] = x & 1;
x = x >>1;
}
for(--i; i>=0; i--)
printf("%d", ch_array[i]);
getch();
}
A: /* Convert an int to it's binary representation */
char *int2bin(int num, int pad)
{
char *str = malloc(sizeof(char) * (pad+1));
if (str) {
str[pad]='\0';
while (--pad>=0) {
str[pad] = num & 1 ? '1' : '0';
num >>= 1;
}
} else {
return "";
}
return str;
}
/* example usage */
printf("The number 5 in binary is %s", int2bin(5, 4));
/* "The number 5 in binary is 0101" */
A: Next will show to you memory layout:
#include <limits>
#include <iostream>
#include <string>
using namespace std;
template<class T> string binary_text(T dec, string byte_separator = " ") {
char* pch = (char*)&dec;
string res;
for (int i = 0; i < sizeof(T); i++) {
for (int j = 1; j < 8; j++) {
res.append(pch[i] & 1 ? "1" : "0");
pch[i] /= 2;
}
res.append(byte_separator);
}
return res;
}
int main() {
cout << binary_text(5) << endl;
cout << binary_text(.1) << endl;
return 0;
}
A: Yet another approach to print in binary: Convert the integer first.
To print 6 in binary, change 6 to 110, then print "110".
Bypasses char buf[] issues.
printf() format specifiers, flags, & fields like "%08lu", "%*lX" still readily usable.
Not only binary (base 2), this method expandable to other bases up to 16.
Limited to smallish integer values.
#include <stdint.h>
#include <stdio.h>
#include <inttypes.h>
unsigned long char_to_bin10(char ch) {
unsigned char uch = ch;
unsigned long sum = 0;
unsigned long power = 1;
while (uch) {
if (uch & 1) {
sum += power;
}
power *= 10;
uch /= 2;
}
return sum;
}
uint64_t uint16_to_bin16(uint16_t u) {
uint64_t sum = 0;
uint64_t power = 1;
while (u) {
if (u & 1) {
sum += power;
}
power *= 16;
u /= 2;
}
return sum;
}
void test(void) {
printf("%lu\n", char_to_bin10(0xF1));
// 11110001
printf("%" PRIX64 "\n", uint16_to_bin16(0xF731));
// 1111011100110001
}
A: A small utility function in C to do this while solving a bit manipulation problem. This goes over the string checking each set bit using a mask (1<
void
printStringAsBinary(char * input)
{
char * temp = input;
int i = 7, j =0;;
int inputLen = strlen(input);
/* Go over the string, check first bit..bit by bit and print 1 or 0
**/
for (j = 0; j < inputLen; j++) {
printf("\n");
while (i>=0) {
if (*temp & (1 << i)) {
printf("1");
} else {
printf("0");
}
i--;
}
temp = temp+1;
i = 7;
printf("\n");
}
}
A: void DisplayBinary(unsigned int n)
{
int l = sizeof(n) * 8;
for (int i = l - 1 ; i >= 0; i--) {
printf("%x", (n & (1 << i)) >> i);
}
}
A: Here's a version of the function that does not suffer from reentrancy issues or limits on the size/type of the argument:
#define FMT_BUF_SIZE (CHAR_BIT*sizeof(uintmax_t)+1)
char *binary_fmt(uintmax_t x, char buf[static FMT_BUF_SIZE])
{
char *s = buf + FMT_BUF_SIZE;
*--s = 0;
if (!x) *--s = '0';
for (; x; x /= 2) *--s = '0' + x%2;
return s;
}
Note that this code would work just as well for any base between 2 and 10 if you just replace the 2's by the desired base. Usage is:
char tmp[FMT_BUF_SIZE];
printf("%s\n", binary_fmt(x, tmp));
Where x is any integral expression.
A: Here is a quick hack to demonstrate techniques to do what you want.
#include <stdio.h> /* printf */
#include <string.h> /* strcat */
#include <stdlib.h> /* strtol */
const char *byte_to_binary
(
int x
)
{
static char b[9];
b[0] = '\0';
int z;
for (z = 128; z > 0; z >>= 1)
{
strcat(b, ((x & z) == z) ? "1" : "0");
}
return b;
}
int main
(
void
)
{
{
/* binary string to int */
char *tmp;
char *b = "0101";
printf("%d\n", strtol(b, &tmp, 2));
}
{
/* byte to binary string */
printf("%s\n", byte_to_binary(5));
}
return 0;
}
A:
Is there a printf converter to print in binary format?
The printf() family is only able to print integers in base 8, 10, and 16 using the standard specifiers directly. I suggest creating a function that converts the number to a string per code's particular needs.
[Edit 2022] This is expected to change with the next version of C which implements "%b".
Binary constants such as 0b10101010, and %b conversion specifier for printf() function family C2x
To print in any base [2-36]
All other answers so far have at least one of these limitations.
*
*Use static memory for the return buffer. This limits the number of times the function may be used as an argument to printf().
*Allocate memory requiring the calling code to free pointers.
*Require the calling code to explicitly provide a suitable buffer.
*Call printf() directly. This obliges a new function for to fprintf(), sprintf(), vsprintf(), etc.
*Use a reduced integer range.
The following has none of the above limitation. It does require C99 or later and use of "%s". It uses a compound literal to provide the buffer space. It has no trouble with multiple calls in a printf().
#include <assert.h>
#include <limits.h>
#define TO_BASE_N (sizeof(unsigned)*CHAR_BIT + 1)
// v--compound literal--v
#define TO_BASE(x, b) my_to_base((char [TO_BASE_N]){""}, (x), (b))
// Tailor the details of the conversion function as needed
// This one does not display unneeded leading zeros
// Use return value, not `buf`
char *my_to_base(char buf[TO_BASE_N], unsigned i, int base) {
assert(base >= 2 && base <= 36);
char *s = &buf[TO_BASE_N - 1];
*s = '\0';
do {
s--;
*s = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"[i % base];
i /= base;
} while (i);
// Could employ memmove here to move the used buffer to the beginning
// size_t len = &buf[TO_BASE_N] - s;
// memmove(buf, s, len);
return s;
}
#include <stdio.h>
int main(void) {
int ip1 = 0x01020304;
int ip2 = 0x05060708;
printf("%s %s\n", TO_BASE(ip1, 16), TO_BASE(ip2, 16));
printf("%s %s\n", TO_BASE(ip1, 2), TO_BASE(ip2, 2));
puts(TO_BASE(ip1, 8));
puts(TO_BASE(ip1, 36));
return 0;
}
Output
1020304 5060708
1000000100000001100000100 101000001100000011100001000
100401404
A2F44
A: Quick and easy solution:
void printbits(my_integer_type x)
{
for(int i=sizeof(x)<<3; i; i--)
putchar('0'+((x>>(i-1))&1));
}
Works for any size type and for signed and unsigned ints. The '&1' is needed to handle signed ints as the shift may do sign extension.
There are so many ways of doing this. Here's a super simple one for printing 32 bits or n bits from a signed or unsigned 32 bit type (not putting a negative if signed, just printing the actual bits) and no carriage return. Note that i is decremented before the bit shift:
#define printbits_n(x,n) for (int i=n;i;i--,putchar('0'|(x>>i)&1))
#define printbits_32(x) printbits_n(x,32)
What about returning a string with the bits to store or print later? You either can allocate the memory and return it and the user has to free it, or else you return a static string but it will get clobbered if it's called again, or by another thread. Both methods shown:
char *int_to_bitstring_alloc(int x, int count)
{
count = count<1 ? sizeof(x)*8 : count;
char *pstr = malloc(count+1);
for(int i = 0; i<count; i++)
pstr[i] = '0' | ((x>>(count-1-i))&1);
pstr[count]=0;
return pstr;
}
#define BITSIZEOF(x) (sizeof(x)*8)
char *int_to_bitstring_static(int x, int count)
{
static char bitbuf[BITSIZEOF(x)+1];
count = (count<1 || count>BITSIZEOF(x)) ? BITSIZEOF(x) : count;
for(int i = 0; i<count; i++)
bitbuf[i] = '0' | ((x>>(count-1-i))&1);
bitbuf[count]=0;
return bitbuf;
}
Call with:
// memory allocated string returned which needs to be freed
char *pstr = int_to_bitstring_alloc(0x97e50ae6, 17);
printf("bits = 0b%s\n", pstr);
free(pstr);
// no free needed but you need to copy the string to save it somewhere else
char *pstr2 = int_to_bitstring_static(0x97e50ae6, 17);
printf("bits = 0b%s\n", pstr2);
A: const char* byte_to_binary(int x)
{
static char b[sizeof(int)*8+1] = {0};
int y;
long long z;
for (z = 1LL<<sizeof(int)*8-1, y = 0; z > 0; z >>= 1, y++) {
b[y] = (((x & z) == z) ? '1' : '0');
}
b[y] = 0;
return b;
}
A: None of the previously posted answers are exactly what I was looking for, so I wrote one. It is super simple to use %B with the printf!
/*
* File: main.c
* Author: Techplex.Engineer
*
* Created on February 14, 2012, 9:16 PM
*/
#include <stdio.h>
#include <stdlib.h>
#include <printf.h>
#include <math.h>
#include <string.h>
static int printf_arginfo_M(const struct printf_info *info, size_t n, int *argtypes)
{
/* "%M" always takes one argument, a pointer to uint8_t[6]. */
if (n > 0) {
argtypes[0] = PA_POINTER;
}
return 1;
}
static int printf_output_M(FILE *stream, const struct printf_info *info, const void *const *args)
{
int value = 0;
int len;
value = *(int **) (args[0]);
// Beginning of my code ------------------------------------------------------------
char buffer [50] = ""; // Is this bad?
char buffer2 [50] = ""; // Is this bad?
int bits = info->width;
if (bits <= 0)
bits = 8; // Default to 8 bits
int mask = pow(2, bits - 1);
while (mask > 0) {
sprintf(buffer, "%s", ((value & mask) > 0 ? "1" : "0"));
strcat(buffer2, buffer);
mask >>= 1;
}
strcat(buffer2, "\n");
// End of my code --------------------------------------------------------------
len = fprintf(stream, "%s", buffer2);
return len;
}
int main(int argc, char** argv)
{
register_printf_specifier('B', printf_output_M, printf_arginfo_M);
printf("%4B\n", 65);
return EXIT_SUCCESS;
}
A: This code should handle your needs up to 64 bits.
I created two functions: pBin and pBinFill. Both do the same thing, but pBinFill fills in the leading spaces with the fill character provided by its last argument.
The test function generates some test data, then prints it out using the pBinFill function.
#define kDisplayWidth 64
char* pBin(long int x,char *so)
{
char s[kDisplayWidth+1];
int i = kDisplayWidth;
s[i--] = 0x00; // terminate string
do { // fill in array from right to left
s[i--] = (x & 1) ? '1' : '0'; // determine bit
x >>= 1; // shift right 1 bit
} while (x > 0);
i++; // point to last valid character
sprintf(so, "%s", s+i); // stick it in the temp string string
return so;
}
char* pBinFill(long int x, char *so, char fillChar)
{
// fill in array from right to left
char s[kDisplayWidth+1];
int i = kDisplayWidth;
s[i--] = 0x00; // terminate string
do { // fill in array from right to left
s[i--] = (x & 1) ? '1' : '0';
x >>= 1; // shift right 1 bit
} while (x > 0);
while (i >= 0) s[i--] = fillChar; // fill with fillChar
sprintf(so, "%s", s);
return so;
}
void test()
{
char so[kDisplayWidth+1]; // working buffer for pBin
long int val = 1;
do {
printf("%ld =\t\t%#lx =\t\t0b%s\n", val, val, pBinFill(val, so, '0'));
val *= 11; // generate test data
} while (val < 100000000);
}
Output:
00000001 = 0x000001 = 0b00000000000000000000000000000001
00000011 = 0x00000b = 0b00000000000000000000000000001011
00000121 = 0x000079 = 0b00000000000000000000000001111001
00001331 = 0x000533 = 0b00000000000000000000010100110011
00014641 = 0x003931 = 0b00000000000000000011100100110001
00161051 = 0x02751b = 0b00000000000000100111010100011011
01771561 = 0x1b0829 = 0b00000000000110110000100000101001
19487171 = 0x12959c3 = 0b00000001001010010101100111000011
A: There is also an idea to convert the number to hexadecimal format and then to decode each hexadecimal cipher to four "bits" (ones and zeros). sprintf can do bit operations for us:
const char* binary(int n) {
static const char binnums[16][5] = { "0000","0001","0010","0011",
"0100","0101","0110","0111","1000","1001","1010","1011","1100","1101","1110","1111" };
static const char* hexnums = "0123456789abcdef";
static char inbuffer[16], outbuffer[4*16];
const char *i;
sprintf(inbuffer,"%x",n); // hexadecimal n -> inbuffer
for(i=inbuffer; *i!=0; ++i) { // for each hexadecimal cipher
int d = strchr(hexnums,*i) - hexnums; // store its decimal value to d
char* o = outbuffer+(i-inbuffer)*4; // shift four characters in outbuffer
sprintf(o,"%s",binnums[d]); // place binary value of d there
}
return strchr(outbuffer,'1'); // omit leading zeros
}
puts(binary(42)); // outputs 101010
A: void DisplayBinary(int n)
{
int arr[8];
int top =-1;
while (n)
{
if (n & 1)
arr[++top] = 1;
else
arr[++top] = 0;
n >>= 1;
}
for (int i = top ; i > -1;i--)
{
printf("%d",arr[i]);
}
printf("\n");
}
A: Do a function and call it
display_binary(int n)
{
long int arr[32];
int arr_counter=0;
while(n>=1)
{
arr[arr_counter++]=n%2;
n/=2;
}
for(int i=arr_counter-1;i>=0;i--)
{
printf("%d",arr[i]);
}
}
A: My solution returns an int which can then be used in printf. It can also return the bits in big endian or little endian order.
#include <stdio.h>
#include <stdint.h>
int binary(uint8_t i,int bigEndian)
{
int j=0,m = bigEndian ? 1 : 10000000;
while (i)
{
j+=m*(i%2);
if (bigEndian) m*=10; else m/=10;
i >>= 1;
}
return j;
}
int main()
{
char buf[]="ABCDEF";
printf("\nbig endian = ");
for (int i=0; i<5; i++) printf("%08d ",binary(buf[i],1));
printf("\nwee endian = ");
for (int i=0; i<5; i++) printf("%08d ",binary(buf[i],0));
getchar();
return 0;
}
Outputs
big endian = 01000001 01000010 01000011 01000100 01000101 01000110
wee endian = 10000010 01000010 11000010 00100010 10100010 01100010
A: The combination of functions + macro at the end of this answer can help you.
Use it like that:
float float_var = 9.4;
SHOW_BITS(float_var);
Which will output: Variable 'float_var': 01000001 00010110 01100110 01100110
Note that it is very general and can work with pretty much any type.
For instance:
struct {int a; float b; double c;} struct_var = {1,1.1,1.2};
SHOW_BITS(struct_var);
Which will output:
Variable `struct_var`: 00111111 11110011 00110011 00110011 00110011 00110011 00110011 00110011 00111111 10001100 11001100 11001101 00000000 00000000 00000000 00000001
Here's the code:
#define SHOW_BITS(a) ({ \
printf("Variable `%s`: ", #a);\
show_bits(&a, sizeof(a));\
})
void show_uchar(unsigned char a)
{
for(int i = 7; i >= 0; i-= 1)
printf("%d", ((a >> i) & 1));
}
void show_bits(void* a, size_t s)
{
unsigned char* p = (unsigned char*) a;
for(int i = s-1; i >= 0 ; i -= 1) {
show_uchar(p[i]);
printf(" ");
}
printf("\n");
}
A: void print_bits (uintmax_t n)
{
for (size_t i = 8 * sizeof (int); i-- != 0;)
{
char c;
if ((n & (1UL << i)) != 0)
c = '1';
else
c = '0';
printf ("%c", c);
}
}
Not a cover-absolutely-everywhere solution but if you want something quick, and easy to understand, I'm suprised no one has proposed this solution yet.
A: Even for the runtime libraries that DO support %b it seems it's only for integer values.
If you want to print floating-point values in binary, I wrote some code you can find at http://www.exploringbinary.com/converting-floating-point-numbers-to-binary-strings-in-c/ .
A: void PrintBinary( int Value, int Places, char* TargetString)
{
int Mask;
Mask = 1 << Places;
while( Places--) {
Mask >>= 1; /* Preshift, because we did one too many above */
*TargetString++ = (Value & Mask)?'1':'0';
}
*TargetString = 0; /* Null terminator for C string */
}
The calling function "owns" the string...:
char BinaryString[17];
...
PrintBinary( Value, 16, BinaryString);
printf( "yadda yadda %s yadda...\n", BinaryString);
Depending on your CPU, most of the operations in PrintBinary render to one or very few machine instructions.
A: Is there a printf converter to print in binary format?
There's no standard printf format specifier to accomplish "binary" output. Here's the alternative I devised when I needed it.
Mine works for any base from 2 to 36. It fans the digits out into the calling frames of recursive invocations, until it reaches a digit smaller than the base. Then it "traverses" backwards, filling the buffer s forwards, and returning. The return value is the size used or -1 if the buffer isn't large enough to hold the string.
int conv_rad (int num, int rad, char *s, int n) {
char *vec = "0123456789" "ABCDEFGHIJKLM" "NOPQRSTUVWXYZ";
int off;
if (n == 0) return 0;
if (num < rad) { *s = vec[num]; return 1; }
off = conv_rad(num/rad, rad, s, n);
if ((off == n) || (off == -1)) return -1;
s[off] = vec[num%rad];
return off+1;
}
One big caveat: This function was designed for use with "Pascal"-style strings which carry their length around. Consequently conv_rad, as written, does not nul-terminate the buffer. For more general C uses, it will probably need a simple wrapper to nul-terminate. Or for printing, just change the assignments to putchar()s.
A: It might be not very efficient but it's quite simple. Try this:
tmp1 = 1;
while(inint/tmp1 > 1) {
tmp1 <<= 1;
}
do {
printf("%d", tmp2=inint/tmp1);
inint -= tmp1*tmp2;
} while((tmp1 >>= 1) > 0);
printf(" ");
A: Here's is a very simple one:
int print_char_to_binary(char ch)
{
int i;
for (i=7; i>=0; i--)
printf("%hd ", ((ch & (1<<i))>>i));
printf("\n");
return 0;
}
A: void binario(int num) {
for(int i=0;i<32;i++){
(num&(1<i))? printf("1"):
printf("0");
}
printf("\n");
}
A: The following function returns binary representation of given unsigned integer using pointer arithmetic without leading zeros:
const char* toBinaryString(unsigned long num)
{
static char buffer[CHAR_BIT*sizeof(num)+1];
char* pBuffer = &buffer[sizeof(buffer)-1];
do *--pBuffer = '0' + (num & 1);
while (num >>= 1);
return pBuffer;
}
Note that there is no need to explicity set NUL terminator, because buffer repesents an object with static storage duration, that is already filled with all-zeros.
This can be easily adapted to unsigned long long (or another unsigned integer) by simply modifing type of num formal parameter.
The CHAR_BIT requires <limits.h> to be included.
Here is an example usage:
int main(void)
{
printf(">>>%20s<<<\n", toBinaryString(1));
printf(">>>%-20s<<<\n", toBinaryString(254));
return 0;
}
with its desired output as:
>>> 1<<<
>>>11111110 <<<
A: Use below function:
void conbin(int num){
if(num != 0)
{
conbin(num >> 1);
if (num & 1){
printf("1");
}
else{
printf("0");
}
}
}
A: This is my take on this subject.
Advantages to most other examples:
*
*Uses putchar() which is more efficient than printf() or even (although not as much) puts()
*Split into two parts (expected to have code inlined) which allows extra efficiency, if wanted.
*Is based on very fast RISC arithmetic operations (that includes not using division and multiplication)
Disadvantages to most examples:
*
*Code is not very straightforward.
*print_binary_size() modifies the input variable without a copy.
Note: The best outcome for this code relies on using -O1 or higher in gcc or equivalent.
Here's the code:
inline void print_binary_sized(unsigned int number, unsigned int digits) {
static char ZERO = '0';
int digitsLeft = digits;
do{
putchar(ZERO + ((number >> digitsLeft) & 1));
}while(digitsLeft--);
}
void print_binary(unsigned int number) {
int digitsLeft = sizeof(number) * 8;
while((~(number >> digitsLeft) & 1) && digitsLeft){
digitsLeft--;
}
print_binary_sized(number, digitsLeft);
}
A: // m specifies how many of the low bits are shown.
// Replace m with sizeof(n) below for all bits and
// remove it from the parameter list if you like.
void print_binary(unsigned long n, unsigned long m) {
static char show[3] = "01";
unsigned long mask = 1ULL << (m-1);
while(mask) {
putchar(show[!!(n&mask)]); mask >>= 1;
}
putchar('\n');
}
A: Main.c
// Based on https://stackoverflow.com/a/112956/1438550
#include <stdio.h>
#include <stdint.h>
const char *int_to_binary_str(int x, int N_bits){
static char b[512];
char *p = b;
b[0] = '\0';
for(int i=(N_bits-1); i>=0; i--){
*p++ = (x & (1<<i)) ? '1' : '0';
if(!(i%4)) *p++ = ' ';
}
return b;
}
int main() {
for(int i=31; i>=0; i--){
printf("0x%08X %s \n", (1<<i), int_to_binary_str((1<<i), 32));
}
return 0;
}
Expected behavior:
Run:
gcc -pthread -Wformat=0 -lm -o main main.c; ./main
Output:
0x80000000 1000 0000 0000 0000 0000 0000 0000 0000
0x40000000 0100 0000 0000 0000 0000 0000 0000 0000
0x20000000 0010 0000 0000 0000 0000 0000 0000 0000
0x10000000 0001 0000 0000 0000 0000 0000 0000 0000
0x08000000 0000 1000 0000 0000 0000 0000 0000 0000
0x04000000 0000 0100 0000 0000 0000 0000 0000 0000
0x02000000 0000 0010 0000 0000 0000 0000 0000 0000
0x01000000 0000 0001 0000 0000 0000 0000 0000 0000
0x00800000 0000 0000 1000 0000 0000 0000 0000 0000
0x00400000 0000 0000 0100 0000 0000 0000 0000 0000
0x00200000 0000 0000 0010 0000 0000 0000 0000 0000
0x00100000 0000 0000 0001 0000 0000 0000 0000 0000
0x00080000 0000 0000 0000 1000 0000 0000 0000 0000
0x00040000 0000 0000 0000 0100 0000 0000 0000 0000
0x00020000 0000 0000 0000 0010 0000 0000 0000 0000
0x00010000 0000 0000 0000 0001 0000 0000 0000 0000
0x00008000 0000 0000 0000 0000 1000 0000 0000 0000
0x00004000 0000 0000 0000 0000 0100 0000 0000 0000
0x00002000 0000 0000 0000 0000 0010 0000 0000 0000
0x00001000 0000 0000 0000 0000 0001 0000 0000 0000
0x00000800 0000 0000 0000 0000 0000 1000 0000 0000
0x00000400 0000 0000 0000 0000 0000 0100 0000 0000
0x00000200 0000 0000 0000 0000 0000 0010 0000 0000
0x00000100 0000 0000 0000 0000 0000 0001 0000 0000
0x00000080 0000 0000 0000 0000 0000 0000 1000 0000
0x00000040 0000 0000 0000 0000 0000 0000 0100 0000
0x00000020 0000 0000 0000 0000 0000 0000 0010 0000
0x00000010 0000 0000 0000 0000 0000 0000 0001 0000
0x00000008 0000 0000 0000 0000 0000 0000 0000 1000
0x00000004 0000 0000 0000 0000 0000 0000 0000 0100
0x00000002 0000 0000 0000 0000 0000 0000 0000 0010
0x00000001 0000 0000 0000 0000 0000 0000 0000 0001
A: Simple, tested, works for any unsigned integer type. No headaches.
#include <stdint.h>
#include <stdio.h>
// Prints the binary representation of any unsigned integer
// When running, pass 1 to first_call
void printf_binary(unsigned int number, int first_call)
{
if (first_call)
{
printf("The binary representation of %d is [", number);
}
if (number >> 1)
{
printf_binary(number >> 1, 0);
putc((number & 1) ? '1' : '0', stdout);
}
else
{
putc((number & 1) ? '1' : '0', stdout);
}
if (first_call)
{
printf("]\n");
}
}
A: As for me, I wrote some general code for this
#include<stdio.h>
void int2bin(int n, int* bin, int* bin_size, const int bits);
int main()
{
char ch;
ch = 'A';
int binary[32];
int binary_size = 0;
int2bin(1324, binary, &binary_size, 32);
for (int i = 0; i < 32; i++)
{
printf("%d ", binary[i]);
}
return 0;
}
void int2bin(int n, int* bin,int *bin_size,const int bits)
{
int i = 0;
int temp[64];
for (int j = 0; j < 64; j++)
{
temp[j] = 0;
}
for (int l = 0; l < bits; l++)
{
bin[l] = 0;
}
while (n > 0)
{
temp[i] = n % 2;
n = n / 2;
i++;
}
*bin_size = i;
//reverse modulus values
for (int k = 0; k < *bin_size; k++)
{
bin[bits-*bin_size+k] = temp[*bin_size - 1 - k];
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/111928",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "556"
}
|
Q: Why shouldn't I use "Hungarian Notation"? I know what Hungarian refers to - giving information about a variable, parameter, or type as a prefix to its name. Everyone seems to be rabidly against it, even though in some cases it seems to be a good idea. If I feel that useful information is being imparted, why shouldn't I put it right there where it's available?
See also: Do people use the Hungarian naming conventions in the real world?
A: Joel Spolsky wrote a good blog post about this.
http://www.joelonsoftware.com/articles/Wrong.html
Basically it comes down to not making your code harder to read when a decent IDE will tell you want type the variable is if you can't remember. Also, if you make your code compartmentalized enough, you don't have to remember what a variable was declared as three pages up.
A: Isn't scope more important than type these days, e.g.
* l for local
* a for argument
* m for member
* g for global
* etc
With modern techniques of refactoring old code, search and replace of a symbol because you changed its type is tedious, the compiler will catch type changes, but often will not catch incorrect use of scope, sensible naming conventions help here.
A: There is no reason why you should not make correct use of Hungarian notation. It's unpopularity is due to a long-running back-lash against the mis-use of Hungarian notation, especially in the Windows APIs.
In the bad-old days, before anything resembling an IDE existed for DOS (odds are you didn't have enough free memory to run the compiler under Windows, so your development was done in DOS), you didn't get any help from hovering your mouse over a variable name. (Assuming you had a mouse.) What did you did have to deal with were event callback functions in which everything was passed to you as either a 16-bit int (WORD) or 32-bit int (LONG WORD). You then had to cast those parameter to the appropriate types for the given event type. In effect, much of the API was virtually type-less.
The result, an API with parameter names like these:
LRESULT CALLBACK WindowProc(HWND hwnd,
UINT uMsg,
WPARAM wParam,
LPARAM lParam);
Note that the names wParam and lParam, although pretty awful, aren't really any worse than naming them param1 and param2.
To make matters worse, Window 3.0/3.1 had two types of pointers, near and far. So, for example, the return value from memory management function LocalLock was a PVOID, but the return value from GlobalLock was an LPVOID (with the 'L' for long). That awful notation then got extended so that a long pointer string was prefixed lp, to distinguish it from a string that had simply been malloc'd.
It's no surprise that there was a backlash against this sort of thing.
A: Hungarian Notation can be useful in languages without compile-time type checking, as it would allow developer to quickly remind herself of how the particular variable is used. It does nothing for performance or behavior. It is supposed to improve code readability and is mostly a matter a taste and coding style. For this very reason it is criticized by many developers -- not everybody has the same wiring in the brain.
For the compile-time type-checking languages it is mostly useless -- scrolling up a few lines should reveal the declaration and thus type. If you global variables or your code block spans for much more than one screen, you have grave design and reusability issues. Thus one of the criticisms is that Hungarian Notation allows developers to have bad design and easily get away with it. This is probably one of the reasons for hatered.
On the other hand, there can be cases where even compile-time type-checking languages would benefit from Hungarian Notation -- void pointers or HANDLE's in win32 API. These obfuscates the actual data type, and there might be a merit to use Hungarian Notation there. Yet, if one can know the type of data at build time, why not to use the appropriate data type.
In general, there are no hard reasons not to use Hungarian Notation. It is a matter of likes, policies, and coding style.
A: As a Python programmer, Hungarian Notation falls apart pretty fast. In Python, I don't care if something is a string - I care if it can act like a string (i.e. if it has a ___str___() method which returns a string).
For example, let's say we have foo as an integer, 12
foo = 12
Hungarian notation tells us that we should call that iFoo or something, to denote it's an integer, so that later on, we know what it is. Except in Python, that doesn't work, or rather, it doesn't make sense. In Python, I decide what type I want when I use it. Do I want a string? well if I do something like this:
print "The current value of foo is %s" % foo
Note the %s - string. Foo isn't a string, but the % operator will call foo.___str___() and use the result (assuming it exists). foo is still an integer, but we treat it as a string if we want a string. If we want a float, then we treat it as a float. In dynamically typed languages like Python, Hungarian Notation is pointless, because it doesn't matter what type something is until you use it, and if you need a specific type, then just make sure to cast it to that type (e.g. float(foo)) when you use it.
Note that dynamic languages like PHP don't have this benefit - PHP tries to do 'the right thing' in the background based on an obscure set of rules that almost no one has memorized, which often results in catastrophic messes unexpectedly. In this case, some sort of naming mechanism, like $files_count or $file_name, can be handy.
In my view, Hungarian Notation is like leeches. Maybe in the past they were useful, or at least they seemed useful, but nowadays it's just a lot of extra typing for not a lot of benefit.
A: The IDE should impart that useful information. Hungarian might have made some sort (not a whole lot, but some sort) of sense when IDE's were much less advanced.
A: Apps Hungarian is Greek to me--in a good way
As an engineer, not a programmer, I immediately took to Joel's article on the merits of Apps Hungarian: "Making Wrong Code Look Wrong". I like Apps Hungarian because it mimics how engineering, science, and mathematics represent equations and formulas using sub- and super-scripted symbols (like Greek letters, mathematical operators, etc.). Take a particular example of Newton's Law of Universal Gravity: first in standard mathematical notation, and then in Apps Hungarian pseudo-code:
frcGravityEarthMars = G * massEarth * massMars / norm(posEarth - posMars)
In the mathematical notation, the most prominent symbols are those representing the kind of information stored in the variable: force, mass, position vector, etc. The subscripts play second fiddle to clarify: position of what? This is exactly what Apps Hungarian is doing; it's telling you the kind of thing stored in the variable first and then getting into specifics--about the closest code can get to mathematical notation.
Clearly strong typing can resolve the safe vs. unsafe string example from Joel's essay, but you wouldn't define separate types for position and velocity vectors; both are double arrays of size three and anything you're likely to do to one might apply to the other. Furthermore, it make perfect sense to concatenate position and velocity (to make a state vector) or take their dot product, but probably not to add them. How would typing allow the first two and prohibit the second, and how would such a system extend to every possible operation you might want to protect? Unless you were willing to encode all of math and physics in your typing system.
On top of all that, lots of engineering is done in weakly typed high-level languages like Matlab, or old ones like Fortran 77 or Ada.
So if you have a fancy language and IDE and Apps Hungarian doesn't help you then forget it--lots of folks apparently have. But for me, a worse than a novice programmer who is working in weakly or dynamically typed languages, I can write better code faster with Apps Hungarian than without.
A: I think it massively clutters up the source code.
It also doesn't gain you much in a strongly typed language. If you do any form of type mismatch tomfoolery, the compiler will tell you about it.
A: I've always thought that a prefix or two in the right place wouldn't hurt. I think if I can impart something useful, like "Hey this is an interface, don't count on specific behaviour" right there, as in IEnumerable, I oughtta do it. Comment can clutter things up much more than just a one or two character symbol.
A: It's incredibly redundant and useless is most modern IDEs, where they do a good job of making the type apparent.
Plus -- to me -- it's just annoying to see intI, strUserName, etc. :)
A:
If I feel that useful information is being imparted, why shouldn't I put it right there where it's available?
Then who cares what anybody else thinks? If you find it useful, then use the notation.
A: Im my experience, it is bad because:
1 - then you break all the code if you need to change the type of a variable (i.e. if you need to extend a 32 bits integer to a 64 bits integer);
2 - this is useless information as the type is either already in the declaration or you use a dynamic language where the actual type should not be so important in the first place.
Moreover, with a language accepting generic programming (i.e. functions where the type of some variables is not determine when you write the function) or with dynamic typing system (i.e. when the type is not even determine at compile time), how would you name your variables? And most modern languages support one or the other, even if in a restricted form.
A: In Joel Spolsky's Making Wrong Code Look Wrong he explains that what everybody thinks of as Hungarian Notation (which he calls Systems Hungarian) is not what was it was really intended to be (what he calls Apps Hungarian). Scroll down to the I’m Hungary heading to see this discussion.
Basically, Systems Hungarian is worthless. It just tells you the same thing your compiler and/or IDE will tell you.
Apps Hungarian tells you what the variable is supposed to mean, and can actually be useful.
A: It's a useful convention for naming controls on a form (btnOK, txtLastName etc.), if the list of controls shows up in an alphabetized pull-down list in your IDE.
A: I tend to use Hungarian Notation with ASP.NET server controls only, otherwise I find it too hard to work out what controls are what on the form.
Take this code snippet:
<asp:Label ID="lblFirstName" runat="server" Text="First Name" />
<asp:TextBox ID="txtFirstName" runat="server" />
<asp:RequiredFieldValidator ID="rfvFirstName" runat="server" ... />
If someone can show a better way of having that set of control names without Hungarian I'd be tempted to move to it.
A: Joel's article is great, but it seems to omit one major point:
Hungarian makes a particular 'idea' (kind + identifier name) unique,
or near-unique, across the codebase - even a very large codebase.
That's huge for code maintenance.
It means you can use good ol' single-line text search
(grep, findstr, 'find in all files') to find EVERY mention of that 'idea'.
Why is that important when we have IDE's that know how to read code?
Because they're not very good at it yet. This is hard to see in a small codebase,
but obvious in a large one - when the 'idea' might be mentioned in comments,
XML files, Perl scripts, and also in places outside source control (documents, wikis,
bug databases).
You do have to be a little careful even here - e.g. token-pasting in C/C++ macros
can hide mentions of the identifier. Such cases can be dealt with using
coding conventions, and anyway they tend to affect only a minority of the identifiers in the
codebase.
P.S. To the point about using the type system vs. Hungarian - it's best to use both.
You only need wrong code to look wrong if the compiler won't catch it for you. There are plenty of cases where it is infeasible to make the compiler catch it. But where it's feasible - yes, please do that instead!
When considering feasibility, though, do consider the negative effects of splitting up types. e.g. in C#, wrapping 'int' with a non-built-in type has huge consequences. So it makes sense in some situations, but not in all of them.
A: Debunking the benefits of Hungarian Notation
*
*It provides a way of distinguishing variables.
If the type is all that distinguishes the one value from another, then it can only be for the conversion of one type to another. If you have the same value that is being converted between types, chances are you should be doing this in a function dedicated to conversion. (I have seen hungarianed VB6 leftovers use strings on all of their method parameters simply because they could not figure out how to deserialize a JSON object, or properly comprehend how to declare or use nullable types.) If you have two variables distinguished only by the Hungarian prefix, and they are not a conversion from one to the other, then you need to elaborate on your intention with them.
*
*It makes the code more readable.
I have found that Hungarian notation makes people lazy with their variable names. They have something to distinguish it by, and they feel no need to elaborate to its purpose. This is what you will typically find in Hungarian notated code vs. modern: sSQL vs. groupSelectSql (or usually no sSQL at all because they are supposed to be using the ORM that was put in by earlier developers.), sValue vs. formCollectionValue (or usually no sValue either, because they happen to be in MVC and should be using its model binding features), sType vs. publishSource, etc.
It can't be readability. I see more sTemp1, sTemp2... sTempN from any given hungarianed VB6 leftover than everybody else combined.
*
*It prevents errors.
This would be by virtue of number 2, which is false.
A: In the words of the master:
http://www.joelonsoftware.com/articles/Wrong.html
An interesting reading, as usual.
Extracts:
"Somebody, somewhere, read Simonyi’s paper, where he used the word “type,” and thought he meant type, like class, like in a type system, like the type checking that the compiler does. He did not. He explained very carefully exactly what he meant by the word “type,” but it didn’t help. The damage was done."
"But there’s still a tremendous amount of value to Apps Hungarian, in that it increases collocation in code, which makes the code easier to read, write, debug, and maintain, and, most importantly, it makes wrong code look wrong."
Make sure you have some time before reading Joel On Software. :)
A: Several reasons:
*
*Any modern IDE will give you the variable type by simply hovering your mouse over the variable.
*Most type names are way long (think HttpClientRequestProvider) to be reasonably used as prefix.
*The type information does not carry the right information, it is just paraphrasing the variable declaration, instead of outlining the purpose of the variable (think myInteger vs. pageSize).
A: Hungarian notation only makes sense in languages without user-defined types. In a modern functional or OO-language, you would encode information about the "kind" of value into the datatype or class rather than into the variable name.
Several answers reference Joels article. Note however that his example is in VBScript, which didn't support user-defined classes (for a long time at least). In a language with user-defined types you would solve the same problem by creating a HtmlEncodedString-type and then let the Write method accept only that. In a statically typed language, the compiler will catch any encoding-errors, in a dynamically typed you would get a runtime exception - but in any case you are protected against writing unencoded strings. Hungarian notations just turns the programmer into a human type-checker, with is the kind of job that is typically better handled by software.
Joel distinguishes between "systems hungarian" and "apps hungarian", where "systems hungarian" encodes the built-in types like int, float and so on, and "apps hungarian" encodes "kinds", which is higher-level meta-info about variable beyound the machine type, In a OO or modern functional language you can create user-defined types, so there is no distinction between type and "kind" in this sense - both can be represented by the type system - and "apps" hungarian is just as redundant as "systems" hungarian.
So to answer your question: Systems hungarian would only be useful in a unsafe, weakly typed language where e.g. assigning a float value to an int variable will crash the system. Hungarian notation was specifically invented in the sixties for use in BCPL, a pretty low-level language which didn't do any type checking at all. I dont think any language in general use today have this problem, but the notation lived on as a kind of cargo cult programming.
Apps hungarian will make sense if you are working with a language without user defined types, like legacy VBScript or early versions of VB. Perhaps also early versions of Perl and PHP. Again, using it in a modern languge is pure cargo cult.
In any other language, hungarian is just ugly, redundant and fragile. It repeats information already known from the type system, and you should not repeat yourself. Use a descriptive name for the variable that describes the intent of this specific instance of the type. Use the type system to encode invariants and meta info about "kinds" or "classes" of variables - ie. types.
The general point of Joels article - to have wrong code look wrong - is a very good principle. However an even better protection against bugs is to - when at all possible - have wrong code to be detected automatically by the compiler.
A: vUsing adjHungarian nnotation vmakes nreading ncode adjdifficult.
A: I always use Hungarian notation for all my projects. I find it really helpful when I'm dealing with 100s of different identifier names.
For example, when I call a function requiring a string I can type 's' and hit control-space and my IDE will show me exactly the variable names prefixed with 's' .
Another advantage, when I prefix u for unsigned and i for signed ints, I immediately see where I am mixing signed and unsigned in potentially dangerous ways.
I cannot remember the number of times when in a huge 75000 line codebase, bugs were caused (by me and others too) due to naming local variables the same as existing member variables of that class. Since then, I always prefix members with 'm_'
Its a question of taste and experience. Don't knock it until you've tried it.
A: You're forgetting the number one reason to include this information. It has nothing to do with you, the programmer. It has everything to do with the person coming down the road 2 or 3 years after you leave the company who has to read that stuff.
Yes, an IDE will quickly identify types for you. However, when you're reading through some long batches of 'business rules' code, it's nice to not have to pause on each variable to find out what type it is. When I see things like strUserID, intProduct or guiProductID, it makes for much easier 'ramp up' time.
I agree that MS went way too far with some of their naming conventions - I categorize that in the "too much of a good thing" pile.
Naming conventions are good things, provided you stick to them. I've gone through enough old code that had me constantly going back to look at the definitions for so many similarly-named variables that I push "camel casing" (as it was called at a previous job). Right now I'm on a job that has many thousand of lines of completely uncommented classic ASP code with VBScript and it's a nightmare trying to figure things out.
A: I don't think everyone is rabidly against it. In languages without static types, it's pretty useful. I definitely prefer it when it's used to give information that is not already in the type. Like in C, char * szName says that the variable will refer to a null terminated string -- that's not implicit in char* -- of course, a typedef would also help.
Joel had a great article on using hungarian to tell if a variable was HTML encoded or not:
http://www.joelonsoftware.com/articles/Wrong.html
Anyway, I tend to dislike Hungarian when it's used to impart information I already know.
A: Of course when 99% of programmers agree on something, there is something wrong. The reason they agree here is because most of them have never used Hungarian notation correctly.
For a detailed argument, I refer you to a blog post I have made on the subject.
http://codingthriller.blogspot.com/2007/11/rediscovering-hungarian-notation.html
A: I started coding pretty much the about the time Hungarian notation was invented and the first time I was forced to use it on a project I hated it.
After a while I realised that when it was done properly it did actually help and these days I love it.
But like all things good, it has to be learnt and understood and to do it properly takes time.
A: Most people use Hungarian notation in a wrong way and are getting wrong results.
Read this excellent article by Joel Spolsky: Making Wrong Code Look Wrong.
In short, Hungarian Notation where you prefix your variable names with their type (string) (Systems Hungarian) is bad because it's useless.
Hungarian Notation as it was intended by its author where you prefix the variable name with its kind (using Joel's example: safe string or unsafe string), so called Apps Hungarian has its uses and is still valuable.
A: Joel is wrong, and here is why.
That "application" information he's talking about should be encoded in the type system. You should not depend on flipping variable names to make sure you don't pass unsafe data to functions requiring safe data. You should make it a type error, so that it is impossible to do so. Any unsafe data should have a type that is marked unsafe, so that it simply cannot be passed to a safe function. To convert from unsafe to safe should require processing with some kind of a sanitize function.
A lot of the things that Joel talks of as "kinds" are not kinds; they are, in fact, types.
What most languages lack, however, is a type system that's expressive enough to enforce these kind of distinctions. For example, if C had a kind of "strong typedef" (where the typedef name had all the operations of the base type, but was not convertible to it) then a lot of these problems would go away. For example, if you could say, strong typedef std::string unsafe_string; to introduce a new type unsafe_string that could not be converted to a std::string (and so could participate in overload resolution etc. etc.) then we would not need silly prefixes.
So, the central claim that Hungarian is for things that are not types is wrong. It's being used for type information. Richer type information than the traditional C type information, certainly; it's type information that encodes some kind of semantic detail to indicate the purpose of the objects. But it's still type information, and the proper solution has always been to encode it into the type system. Encoding it into the type system is far and away the best way to obtain proper validation and enforcement of the rules. Variables names simply do not cut the mustard.
In other words, the aim should not be "make wrong code look wrong to the developer". It should be "make wrong code look wrong to the compiler".
A: Tacking on cryptic characters at the beginning of each variable name is unnecessary and shows that the variable name by itself isn't descriptive enough. Most languages require the variable type at declaration anyway, so that information is already available.
There's also the situation where, during maintenance, a variable type needs to change. Example: if a variable declared as "uint_16 u16foo" needs to become a 64-bit unsigned, one of two things will happen:
*
*You'll go through and change each variable name (making sure not to hose any unrelated variables with the same name), or
*Just change the type and not change the name, which will only cause confusion.
A: The Hungarian notation was abused, particularly by Microsoft, leading to prefixes longer than the variable name, and showing it is quite rigid, particularly when you change the types (the infamous lparam/wparam, of different type/size in Win16, identical in Win32).
Thus, both due to this abuse, and its use by M$, it was put down as useless.
At my work, we code in Java, but the founder cames from MFC world, so use similar code style (aligned braces, I like this!, capitals to method names, I am used to that, prefix like m_ to class members (fields), s_ to static members, etc.).
And they said all variables should have a prefix showing its type (eg. a BufferedReader is named brData). Which shown as being a bad idea, as the types can change but the names doesn't follow, or coders are not consistent in the use of these prefixes (I even see aBuffer, theProxy, etc.!).
Personally, I chose for a few prefixes that I find useful, the most important being b to prefix boolean variables, as they are the only ones where I allow syntax like if (bVar) (no use of autocast of some values to true or false).
When I coded in C, I used a prefix for variables allocated with malloc, as a reminder it should be freed later. Etc.
So, basically, I don't reject this notation as a whole, but took what seems fitting for my needs.
And of course, when contributing to some project (work, open source), I just use the conventions in place!
A: I think the whole thing of the aesthetical aspect is over-hyped. If that was the most important thing, we would not call ourselves developers, but graphic designers.
One important part, I think, is that you decribe what your objects role is, not what it is. You don't call yourself HumanDustman, becuase in another context, you would not most importantly be a human.
For refactoring-purposes it's really important too:
public string stringUniqueKey = "ABC-12345";
What if you decide to use a GUID instead of a string, your variable name would look stupid after refactoring all refering code.
Or:
public int intAge = 20;
Changing this to a float, you would have the same problem. And so on.
A: *
*They're a humongous eyesore
*Your IDE should be able to tell you all you need to know about a variable's type
*Good names (which HN gets in the way of) should communicate to you everything else you need to know about a variable.
A: See also What kind of prefix do you use for member variables?
A: Hungarian is bad because it takes precious characters away from variable names in exchange for what, some type information?
First of all, in a strongly typed language, the compiler will warn you if you do any truly stupid.
Second, if you believe in good modularized code and don't do too much work in any 1 function, you're variables are probable declared just above the code they are used in anyway (so you have the type right there).
Third, if you prefix every pointer with p and every class with C, your really screwing up your nice modern IDE's ability to do intellisense (you know that feature where it guesses as you type what class name your typing and as soon as it gets it right you can hit enter and it completes it for you? well, if you prefix every class with C, you always have at least 1 extra letter to type)...
A: I cannot find a link but I remember reading somewhere (which I agree with) that avoiding Hungarian notation results in better programming style.
When you program a statement of your program, you should not be thinking about "what type this object is" before calling its method, but rather you should think "what do I want to do with it", "which message to send to it".
Kind of vague concept to explain, but I think it works.
For example, if you have customer name stored in variable customerName, you should not care if it is a string or some other class. More important to think what do you want from this object. Do you want it to print(), getFirstName(), getLastName(), convertToString() etc. Once you make it an instance of String class and take it as granted, you limit yourself and your design since you have to build up all other logic you need elsewhere in the code.
A: For years I used Hungarian notation in my programming. Other than some visual clutter and the task of changing the prefix when I changed the data type, no one could convince me otherwise. Until recently--when I had to combine existing C# and VB.NET assemblies in the same solution.
The result: I had to pass a "fltSomeVariable" to a "sngSomeVariable" method parameter. Even as someone who programs in both C# and VB.NET, it caught me off guard and made me pause for a moment. (C# and VB.NET sometimes use different names to represent the same data type--float and single, for example.)
Now consider this: what if you create a COM component that's callable from many languages? The VB.NET and C# "conversion" was easy for a .NET programmer. But what about someone that develops in C++ or Java? Does "dwSomeVariable" mean anything to a .NET developer not familiar with C++?
A: If you don't know the type of a variable without being told, you probably shouldn't be messing with it anyways
The type might also not be that important. If you know what the methods do, you can figure out what is being done with the variable and then you'll what the program is doing
There may be times you want it; when type is important and the declaration isn't near or the type can't be inferred with ease. But it should never be seen as absolute
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/111933",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "122"
}
|
Q: How do I find out the size of a Canvas text object in tkinter? I want to create some text in a canvas:
myText = self.canvas.create_text(5, 5, anchor=NW, text="TEST")
Now how do I find the width and height of myText?
A: This method seemed to work well if all you are interested in is the width and height of the canvas being considered, using the bounds of the box and then checking the differential works just as well if you want to do it that way.
width = myText.winfo_width()
height = myText.winfo_height()
A: bounds = self.canvas.bbox(myText) # returns a tuple like (x1, y1, x2, y2)
width = bounds[2] - bounds[0]
height = bounds[3] - bounds[1]
See the TkInter reference.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/111934",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: Is there any way to do HTTP PUT in python I need to upload some data to a server using HTTP PUT in python. From my brief reading of the urllib2 docs, it only does HTTP POST. Is there any way to do an HTTP PUT in python?
A: You should have a look at the httplib module. It should let you make whatever sort of HTTP request you want.
A: I needed to solve this problem too a while back so that I could act as a client for a RESTful API. I settled on httplib2 because it allowed me to send PUT and DELETE in addition to GET and POST. Httplib2 is not part of the standard library but you can easily get it from the cheese shop.
A: I also recommend httplib2 by Joe Gregario. I use this regularly instead of httplib in the standard lib.
A: Httplib seems like a cleaner choice.
import httplib
connection = httplib.HTTPConnection('1.2.3.4:1234')
body_content = 'BODY CONTENT GOES HERE'
connection.request('PUT', '/url/path/to/put/to', body_content)
result = connection.getresponse()
# Now result.status and result.reason contains interesting stuff
A: I've used a variety of python HTTP libs in the past, and I've settled on requests as my favourite. Existing libs had pretty useable interfaces, but code can end up being a few lines too long for simple operations. A basic PUT in requests looks like:
payload = {'username': 'bob', 'email': 'bob@bob.com'}
>>> r = requests.put("http://somedomain.org/endpoint", data=payload)
You can then check the response status code with:
r.status_code
or the response with:
r.content
Requests has a lot synactic sugar and shortcuts that'll make your life easier.
A: Have you taken a look at put.py? I've used it in the past. You can also just hack up your own request with urllib.
A: import urllib2
opener = urllib2.build_opener(urllib2.HTTPHandler)
request = urllib2.Request('http://example.org', data='your_put_data')
request.add_header('Content-Type', 'your/contenttype')
request.get_method = lambda: 'PUT'
url = opener.open(request)
A: You can of course roll your own with the existing standard libraries at any level from sockets up to tweaking urllib.
http://pycurl.sourceforge.net/
"PyCurl is a Python interface to libcurl."
"libcurl is a free and easy-to-use client-side URL transfer library, ... supports ... HTTP PUT"
"The main drawback with PycURL is that it is a relative thin layer over libcurl without any of those nice Pythonic class hierarchies. This means it has a somewhat steep learning curve unless you are already familiar with libcurl's C API. "
A: If you want to stay within the standard library, you can subclass urllib2.Request:
import urllib2
class RequestWithMethod(urllib2.Request):
def __init__(self, *args, **kwargs):
self._method = kwargs.pop('method', None)
urllib2.Request.__init__(self, *args, **kwargs)
def get_method(self):
return self._method if self._method else super(RequestWithMethod, self).get_method()
def put_request(url, data):
opener = urllib2.build_opener(urllib2.HTTPHandler)
request = RequestWithMethod(url, method='PUT', data=data)
return opener.open(request)
A: You can use the requests library, it simplifies things a lot in comparison to taking the urllib2 approach. First install it from pip:
pip install requests
More on installing requests.
Then setup the put request:
import requests
import json
url = 'https://api.github.com/some/endpoint'
payload = {'some': 'data'}
# Create your header as required
headers = {"content-type": "application/json", "Authorization": "<auth-key>" }
r = requests.put(url, data=json.dumps(payload), headers=headers)
See the quickstart for requests library. I think this is a lot simpler than urllib2 but does require this additional package to be installed and imported.
A: This was made better in python3 and documented in the stdlib documentation
The urllib.request.Request class gained a method=... parameter in python3.
Some sample usage:
req = urllib.request.Request('https://example.com/', data=b'DATA!', method='PUT')
urllib.request.urlopen(req)
A: You can use requests.request
import requests
url = "https://www.example/com/some/url/"
payload="{\"param1\": 1, \"param1\": 2}"
headers = {
'Authorization': '....',
'Content-Type': 'application/json'
}
response = requests.request("PUT", url, headers=headers, data=payload)
print(response.text)
A: A more proper way of doing this with requests would be:
import requests
payload = {'username': 'bob', 'email': 'bob@bob.com'}
try:
response = requests.put(url="http://somedomain.org/endpoint", data=payload)
response.raise_for_status()
except requests.exceptions.RequestException as e:
print(e)
raise
This raises an exception if there is an error in the HTTP PUT request.
A: Using urllib3
To do that, you will need to manually encode query parameters in the URL.
>>> import urllib3
>>> http = urllib3.PoolManager()
>>> from urllib.parse import urlencode
>>> encoded_args = urlencode({"name":"Zion","salary":"1123","age":"23"})
>>> url = 'http://dummy.restapiexample.com/api/v1/update/15410' + encoded_args
>>> r = http.request('PUT', url)
>>> import json
>>> json.loads(r.data.decode('utf-8'))
{'status': 'success', 'data': [], 'message': 'Successfully! Record has been updated.'}
Using requests
>>> import requests
>>> r = requests.put('https://httpbin.org/put', data = {'key':'value'})
>>> r.status_code
200
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/111945",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "227"
}
|
Q: Using Python's ftplib to get a directory listing, portably You can use ftplib for full FTP support in Python. However the preferred way of getting a directory listing is:
# File: ftplib-example-1.py
import ftplib
ftp = ftplib.FTP("www.python.org")
ftp.login("anonymous", "ftplib-example-1")
data = []
ftp.dir(data.append)
ftp.quit()
for line in data:
print "-", line
Which yields:
$ python ftplib-example-1.py
- total 34
- drwxrwxr-x 11 root 4127 512 Sep 14 14:18 .
- drwxrwxr-x 11 root 4127 512 Sep 14 14:18 ..
- drwxrwxr-x 2 root 4127 512 Sep 13 15:18 RCS
- lrwxrwxrwx 1 root bin 11 Jun 29 14:34 README -> welcome.msg
- drwxr-xr-x 3 root wheel 512 May 19 1998 bin
- drwxr-sr-x 3 root 1400 512 Jun 9 1997 dev
- drwxrwxr-- 2 root 4127 512 Feb 8 1998 dup
- drwxr-xr-x 3 root wheel 512 May 19 1998 etc
...
I guess the idea is to parse the results to get the directory listing. However this listing is directly dependent on the FTP server's way of formatting the list. It would be very messy to write code for this having to anticipate all the different ways FTP servers might format this list.
Is there a portable way to get an array filled with the directory listing?
(The array should only have the folder names.)
A: I found my way here while trying to get filenames, last modified stamps, file sizes etc and wanted to add my code. It only took a few minutes to write a loop to parse the ftp.dir(dir_list.append) making use of python std lib stuff like strip() (to clean up the line of text) and split() to create an array.
ftp = FTP('sick.domain.bro')
ftp.login()
ftp.cwd('path/to/data')
dir_list = []
ftp.dir(dir_list.append)
# main thing is identifing which char marks start of good stuff
# '-rw-r--r-- 1 ppsrt ppsrt 545498 Jul 23 12:07 FILENAME.FOO
# ^ (that is line[29])
for line in dir_list:
print line[29:].strip().split(' ') # got yerself an array there bud!
# EX ['545498', 'Jul', '23', '12:07', 'FILENAME.FOO']
A: The reliable/standardized way to parse FTP directory listing is by using MLSD command, which by now should be supported by all recent/decent FTP servers.
import ftplib
f = ftplib.FTP()
f.connect("localhost")
f.login()
ls = []
f.retrlines('MLSD', ls.append)
for entry in ls:
print entry
The code above will print:
modify=20110723201710;perm=el;size=4096;type=dir;unique=807g4e5a5; tests
modify=20111206092323;perm=el;size=4096;type=dir;unique=807g1008e0; .xchat2
modify=20111022125631;perm=el;size=4096;type=dir;unique=807g10001a; .gconfd
modify=20110808185618;perm=el;size=4096;type=dir;unique=807g160f9a; .skychart
...
Starting from python 3.3, ftplib will provide a specific method to do this:
*
*http://bugs.python.org/issue11072
*http://hg.python.org/cpython/file/67053b135ed9/Lib/ftplib.py#l535
A: There's no standard for the layout of the LIST response. You'd have to write code to handle the most popular layouts. I'd start with Linux ls and Windows Server DIR formats. There's a lot of variety out there, though.
Fall back to the nlst method (returning the result of the NLST command) if you can't parse the longer list. For bonus points, cheat: perhaps the longest number in the line containing a known file name is its length.
A: Try using ftp.nlst(dir).
However, note that if the folder is empty, it might throw an error:
files = []
try:
files = ftp.nlst()
except ftplib.error_perm as resp:
if str(resp) == "550 No files found":
print "No files in this directory"
else:
raise
for f in files:
print f
A: I happen to be stuck with an FTP server (Rackspace Cloud Sites virtual server) that doesn't seem to support MLSD. Yet I need several fields of file information, such as size and timestamp, not just the filename, so I have to use the DIR command. On this server, the output of DIR looks very much like the OP's. In case it helps anyone, here's a little Python class that parses a line of such output to obtain the filename, size and timestamp.
import datetime
class FtpDir:
def parse_dir_line(self, line):
words = line.split()
self.filename = words[8]
self.size = int(words[4])
t = words[7].split(':')
ts = words[5] + '-' + words[6] + '-' + datetime.datetime.now().strftime('%Y') + ' ' + t[0] + ':' + t[1]
self.timestamp = datetime.datetime.strptime(ts, '%b-%d-%Y %H:%M')
Not very portable, I know, but easy to extend or modify to deal with various different FTP servers.
A: This is from Python docs
>>> from ftplib import FTP_TLS
>>> ftps = FTP_TLS('ftp.python.org')
>>> ftps.login() # login anonymously before securing control
channel
>>> ftps.prot_p() # switch to secure data connection
>>> ftps.retrlines('LIST') # list directory content securely
total 9
drwxr-xr-x 8 root wheel 1024 Jan 3 1994 .
drwxr-xr-x 8 root wheel 1024 Jan 3 1994 ..
drwxr-xr-x 2 root wheel 1024 Jan 3 1994 bin
drwxr-xr-x 2 root wheel 1024 Jan 3 1994 etc
d-wxrwxr-x 2 ftp wheel 1024 Sep 5 13:43 incoming
drwxr-xr-x 2 root wheel 1024 Nov 17 1993 lib
drwxr-xr-x 6 1094 wheel 1024 Sep 13 19:07 pub
drwxr-xr-x 3 root wheel 1024 Jan 3 1994 usr
-rw-r--r-- 1 root root 312 Aug 1 1994 welcome.msg
A: That helped me with my code.
When I tried feltering only a type of files and show them on screen by adding a condition that tests on each line.
Like this
elif command == 'ls':
print("directory of ", ftp.pwd())
data = []
ftp.dir(data.append)
for line in data:
x = line.split(".")
formats=["gz", "zip", "rar", "tar", "bz2", "xz"]
if x[-1] in formats:
print ("-", line)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/111954",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "71"
}
|
Q: array.array versus numpy.array If you are creating a 1d array in Python, is there any benefit to using the NumPy package?
A: It all depends on what you plan to do with the array. If all you're doing is creating arrays of simple data types and doing I/O, the array module will do just fine.
If, on the other hand, you want to do any kind of numerical calculations, the array module doesn't provide any help with that. NumPy (and SciPy) give you a wide variety of operations between arrays and special functions that are useful not only for scientific work but for things like advanced image manipulation or in general anything where you need to perform efficient calculations with large amounts of data.
Numpy is also much more flexible, e.g. it supports arrays of any type of Python objects, and is also able to interact "natively" with your own objects if they conform to the array interface.
A: Small bootstrapping for the benefit of whoever might find this useful (following the excellent answer by @dF.):
import numpy as np
from array import array
# Fixed size numpy array
def np_fixed(n):
q = np.empty(n)
for i in range(n):
q[i] = i
return q
# Resize with np.resize
def np_class_resize(isize, n):
q = np.empty(isize)
for i in range(n):
if i>=q.shape[0]:
q = np.resize(q, q.shape[0]*2)
q[i] = i
return q
# Resize with the numpy.array method
def np_method_resize(isize, n):
q = np.empty(isize)
for i in range(n):
if i>=q.shape[0]:
q.resize(q.shape[0]*2)
q[i] = i
return q
# Array.array append
def arr(n):
q = array('d')
for i in range(n):
q.append(i)
return q
isize = 1000
n = 10000000
The output gives:
%timeit -r 10 a = np_fixed(n)
%timeit -r 10 a = np_class_resize(isize, n)
%timeit -r 10 a = np_method_resize(isize, n)
%timeit -r 10 a = arr(n)
1 loop, best of 10: 868 ms per loop
1 loop, best of 10: 2.03 s per loop
1 loop, best of 10: 2.02 s per loop
1 loop, best of 10: 1.89 s per loop
It seems that array.array is slightly faster and the 'api' saves you some hassle, but if you need more than just storing doubles then numpy.resize is not a bad choice after all (if used correctly).
A: For storage purposes, both numpy array and array.array are comparable. Here is the code for benchmark for both comparing storage size of unsigned integer of 4 bytes. Other datatypes can also be used for comparison. Data of list and tuple is also added for comparison
import sys
import numpy as np
from array import array
def getsizeof_deep(obj, seen=None):
"""Recursively finds size of objects"""
size = sys.getsizeof(obj)
if seen is None:
seen = set()
obj_id = id(obj)
if obj_id in seen:
return 0
# Important mark as seen *before* entering recursion to gracefully handle
# self-referential objects
seen.add(obj_id)
if isinstance(obj, dict):
size += sum([getsizeof_deep(v, seen) for v in obj.values()])
size += sum([getsizeof_deep(k, seen) for k in obj.keys()])
elif hasattr(obj, '__dict__'):
size += getsizeof_deep(obj.__dict__, seen)
elif hasattr(obj, '__iter__') and not isinstance(obj, (str, bytes, bytearray)):
size += sum([getsizeof_deep(i, seen) for i in obj])
return size
print("size per element for list, tuple, numpy array, array.array:===============")
for i in range(1, 100, 5):
aa = list(range(i))
n = len(aa)
list_size = getsizeof_deep(aa)
tup_aa = tuple(aa)
tup_size = getsizeof_deep(tup_aa)
nparr = np.array(aa, dtype='uint32')
np_size = getsizeof_deep(nparr)
arr = array('I', aa)#4 byte unsigned integer(in ubuntu)
arr_size = getsizeof_deep(arr)
print('number of element:%s, list %.2f, tuple %.2f, np.array %.2f, arr.array %.2f' % \
(len(aa), list_size/n, tup_size/n, np_size/n, arr_size/n))
This was producing the following ouput in my machine:
size per element for list, tuple, numpy array, array.array:===============
number of element:1, list 88.00, tuple 72.00, np.array 136.00, arr.array 92.00
number of element:6, list 44.67, tuple 42.00, np.array 49.33, arr.array 42.00
number of element:11, list 40.73, tuple 39.27, np.array 41.45, arr.array 37.45
number of element:16, list 39.25, tuple 38.25, np.array 38.50, arr.array 35.75
number of element:21, list 38.48, tuple 37.71, np.array 36.95, arr.array 34.86
number of element:26, list 38.00, tuple 37.38, np.array 36.00, arr.array 34.31
number of element:31, list 37.68, tuple 37.16, np.array 35.35, arr.array 33.94
number of element:36, list 37.44, tuple 37.00, np.array 34.89, arr.array 33.67
number of element:41, list 37.27, tuple 36.88, np.array 34.54, arr.array 33.46
number of element:46, list 37.13, tuple 36.78, np.array 34.26, arr.array 33.30
number of element:51, list 37.02, tuple 36.71, np.array 34.04, arr.array 33.18
number of element:56, list 36.93, tuple 36.64, np.array 33.86, arr.array 33.07
number of element:61, list 36.85, tuple 36.59, np.array 33.70, arr.array 32.98
number of element:66, list 36.79, tuple 36.55, np.array 33.58, arr.array 32.91
number of element:71, list 36.73, tuple 36.51, np.array 33.46, arr.array 32.85
number of element:76, list 36.68, tuple 36.47, np.array 33.37, arr.array 32.79
number of element:81, list 36.64, tuple 36.44, np.array 33.28, arr.array 32.74
number of element:86, list 36.60, tuple 36.42, np.array 33.21, arr.array 32.70
number of element:91, list 36.57, tuple 36.40, np.array 33.14, arr.array 32.66
number of element:96, list 36.54, tuple 36.38, np.array 33.08, arr.array 32.62
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/111983",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "71"
}
|
Q: What are the cons of a web based application I am going to write a database application for the camp I work for. I am thinking about writing it in C# with a Windows GUI interface but using a browser as the application is seeming more and more appelaing for various reasons. What I am wondering is why someone would not choose to write an application as a web application. Ex. The back button can cause you some trouble. Are there other things that ayone can think of?
A: There are plenty of cons:
*
*Speed and responsiveness tend to be significantly worse
*Complicated UI widgets (such as tree controls) are harder to do
*Rendering graphics of any kind is pretty tricky, 3D graphics is even harder
*You have to mess around with logins
*A centralised server means clients always need network access
*Security restrictions may cause you trouble
*Browser incompatibilities can cause a lot of extra work
*UI conventions are less well-defined on the web - users may find it harder to use
*Client-side storage is limited
The question is.. do enough of those apply to your project to make web the wrong choice?
A: One thing that was not mentioned here is the level of complexity and knowledge required to generate a good web application. The problem being unless you are doing something very simple, there is no "Single" knowledge or technology that goes into these applications.
For example if you were to write an application for some client server platform.. you may develop in Java or C++. For a complex web application you may have to have expertise in Java, Java Script, HTML, Flash, CSS, Ajax, SQL, J2EE.. etc. Also the components of a web based application are also more numerous, Web Application Server, HTTP Server, Database, Browser.. are tipical components but there could be more.. a client server app is tipical just what it says.. a client application and a Server application. My experience and personal preference is not web based .. web based is great for many things. But even though I am an IT Architect for a leading company that is completely emersed in Web Apps as the solution for everything... The cons are many still.. I do thing the technology will evolve and the cons will go away over time though.
A: Essentially the real limitations are only through of the platform, being the browser. If you have to account for all browsers in current use that can be a pain due to varying degrees of standards in each of them.
If have control of the which browser to use, that is everyone is on computers that you control on site, and say you install firefox on all of them, you could then leverage the latest Javascript and CSS standards to their fullest in your content delivery.
[edit] You could also look into options like the adobe integrated runtime or "AIR" as an option allowing you to code the front-end with traditional browser based options like xhtml/css/javascript, flash/flex and have the backend hooked up to your database online, only also providing functionality of a traditional desktop app at the same time.
A: The biggest difference and drawback I see with web applications is state management. Since the web is, by nature, stateless every thing you want to maintain has to be sent back and forth from the server with every request and response. How to efficiently store and retrieve it in a matter with respect to page size and performance is hard to do at times. Also the fact that there is no real standard (at least not that everyone adheres to) for browsers makes consistency really..........fun.
A: You need to have a network access to the server that you are going to have the web application on (if there are going to be multiple users for the application - which is typically the case).
Actually, there are more pros than cons - if you can give some details about your application, we could help a little more...
A: It completely depends on the requirements of your project. For the most part, there isn't much web applications cannot do these days. Admittedly, certain applications do belong on the desktop as browsers (while currently advancing, and rapidly), still are not quite there yet. From the advent of applications such as Google Docs, Gmail
There isn't much you -cannot- do on the web. If you're creating a World of Warcraft competitor however, the web is most certainly not the optimal solution. Again, unfortunately we'd need more insight on the application you're building for the camp. The best part about the web is that anyone with a browser can use your application.
A: Web applications delegate processing to a remote machine. Depending on the amount of processing, this can be a con. Consider a photo editor that's a web app.
Web applications also can't deal with a whole lot of data going back and forth to and from a client. You can watch video online.. when it's compressed. It will be awhile before we see any web-based video editing software.
Browser compatibility is also a hassle. You can't control the look-and-feel of the application 100%.
Vaibhav has a good point. What's your application?
A: A major one is down time for migrations... users will not expect the application to be down, ever, but realistically it will have to be down for major upgrades. When doing this with a desktop application, the user (or end-user systems admin) is in control of when upgrades happen; with an online app, they're not.
For applications which have large data, performance can be a major problem as you're storing a large number of users' data centrally, which means the IO performance will not be as good as it would be if you gave them all a laptop.
In general scalability gives problems for a server-based app. Desktop applications scale really well.
A: You can do an awful lot with a web-based app, but it is a lot easier to do certain things with a thick client:
*
*Performance: You get simple access to the full power of the client's CPU.
*Responsiveness: Interactivity is fast and easy.
*Graphics: You can easily use graphics libraries such as DirectX and OpenGL to create fast impressive graphics.
*Work with local files
*Peer-to-peer
A: Deciding whether a web application is a good approach depends on what you are trying to achieve. However here are some more general cons of web applications:
*
*Real integration with desktop apps (e.g. Outlook) is impossible
*Drag and drop between your app and the desktop / other running apps
A: With a web application, there are more privacy concerns, when you are storing user data on your servers. You have to make sure that you don't loose/disclose it and your users have to be comfortable with the idea of storing that data on your servers.
Apart from that, there are many security problems, like Man-in-the-middle attacks, XSS or SQL injections.
You also need to make sure that you have enough computing power and bandwidth at hand.
A: "Ex. The back button can cause you some trouble."
You'll have to be specific on this. A lot of people make fundamental mistakes in their web applications and introduce bugs in how they handle transactions. If you do not use "Redirect after Post" (also known as Post-Redirect-Get, PRG design), then you've created a bug which appears as a problem with the back button.
A blanket statement that the back button in trouble is unlikely to be true. A specific example would clarify your specific question on this.
A: The back button really is not that much of an issue if you design your application correctly. You can use AJAX to manipulate parts of the current page, without adding items into the browser history (since the page itself wont change).
The biggest issue with designing web applications has to do with state, and the challenges that need to be programmed around. With a desktop application, state is easy to handle, you can leave a database connection opened, lock the record and wait for the user to make the changes and commit. With a web application, you could lock the record...but then what if the user closes the browser? These things must be overcome in the design of your application.
When designing a web application, make sure that each trip to the server "stands alone" and provides a complete answer. Always re-initialize your variables before performing any work and never assume anything. One of the challenges I ran into once was pulling "pages" of grid data back to the user. In a real busy system, with record additions/modifications happening in real time, the user navigation from page to page would vary greatly, sometimes even resulting in viewing the same set of a few records as new additions were added in-front of the query.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/111985",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: C# class separation into a header and a .cs file Is there a way to separate a C# class into a header that contains the class definition and then an actual .cs file that contains the implementation? I suppose one can do this by creating an interface, but that doesn't seem right. I just want a file where I can just see the class design, and not all the detail. It's easy enough to do in C++, but I haven't seen it done with C#.
Thanks in advance.
A: That's a wrong approach. C# isn't C++. Forget about header files.
If you want the class summary, just open the Object Browser in Visual Studio. It will give you the signature of all the methods within your classes.
A: No there is no way (or real reason) to want to do this in C#. You can get VS.NET to summarise a class for you (collapse all in the view menu) or if you really want to as you say you can use an interface. What is the reason behind you asking?
A: You could use partial classes and partial methods. I'm not sure why you'd do this though...
Partial Classes and Methods - MSDN
A: In the same file, you can use Visual Studio outline function to collapse the class so that you only see the names of methods and properties.
You can also use Visual Studio to see the Class View which gives you the names of various methods and properties of a class.
There is almost no reason in dotnet to need to define a class in a separate place from its implementation.
A: I don't think you can do header files like you can in C++.
Check out the partial keyword for both classes and methods. I just learned about them yesterday, so I haven't really used them, but they might help you accomplish what you're trying to do.
A: You can use an interface to achieve the same intention.
IFoo.cs:
public interface IFoo
{
int DoFoo();
}
Foo.cs:
public class Foo : IFoo
{
public int DoFoo()
{
return 1;
}
}
A: Extracting the interfaces isn't a great plan if you're interested in the private methods.
Using abstract classes means materially altering the design of the application (and I think, increasing complexity needlessly) to support the "view" requirement. Partial classes don't show you the complete public and private signature in one place, so that's not ideal either.
So if you don't have the IDE, or don't want to use it, I would use the default disassemble action in Reflector (free, and a great toy to have anyway):
http://www.red-gate.com/products/reflector/index.htm
eg. System.Web.Caching.Cache
public sealed class Cache : IEnumerable
{
// Fields
private CacheInternal _cacheInternal;
public static readonly DateTime NoAbsoluteExpiration;
public static readonly TimeSpan NoSlidingExpiration;
// Methods
static Cache();
[SecurityPermission(SecurityAction.Demand, Unrestricted=true)]
public Cache();
internal Cache(int dummy);
public object Add(string key, object value, CacheDependency dependencies, DateTime absoluteExpiration, TimeSpan slidingExpiration, CacheItemPriority priority, CacheItemRemovedCallback onRemoveCallback);
public object Get(string key);
internal object Get(string key, CacheGetOptions getOptions);
public IDictionaryEnumerator GetEnumerator();
public void Insert(string key, object value);
public void Insert(string key, object value, CacheDependency dependencies);
public void Insert(string key, object value, CacheDependency dependencies, DateTime absoluteExpiration, TimeSpan slidingExpiration);
public void Insert(string key, object value, CacheDependency dependencies, DateTime absoluteExpiration, TimeSpan slidingExpiration, CacheItemPriority priority, CacheItemRemovedCallback onRemoveCallback);
public object Remove(string key);
internal void SetCacheInternal(CacheInternal cacheInternal);
IEnumerator IEnumerable.GetEnumerator();
// Properties
public int Count { get; }
public long EffectivePercentagePhysicalMemoryLimit { get; }
public long EffectivePrivateBytesLimit { get; }
public object this[string key] { get; set; }
}
A: This was only a feature of C++ because ancient compilers needed a forward-declaration of the function signatures to work properly.
If this is something that you find handy to have though, and you want more than once, you could try writing a small utility that used reflection to extract the public interface from any component, and format it out to a text file in whatever layout you wanted.
Another alternative would be to use the /// syntax to create XML documentation for the class.
A: Isn't this what the IDE is for?
EDIT: Otherwise inferfaces and abstract classes is the way to go.
A: Try the Class View. When you click on each class you will get the members listed.
A: The IDE will show you exactly that inline when you have an instance followed by the "." like
myBadlyNamedObject.
(or "ClassName."), and the beauty is that you have it at your fingertips when working with the object and not when you decide to open up the object definition to see what it might be
A: As far as I know that's not possible. You can however make things a little bit better by using partial classes where you put different parts of a class in different files. You can for example put all public methods in one file and all private in one to make it easier to get an overview of which methods are available for use from other objects.
A: If you really, really need to do this, then the closest option would be
Refactor --> Extract interface.
A: To all you people saying "USE THE IDE~!~~", you're missing the point. Code isn't always read in the IDE. Maybe he wants it to be printed out? Or emailed? That's the problem with not implementing language features because you can get the IDE to do it: Code isn't always read (or even written) in an IDE.
That said, you can use partial classes and methods to do it; I don't think you'll be able to have instance variables in both files, however.
A: WinCV is a .net 1.0 framework sdk utility that gives you a c++ like header view for .net assemblies. Search google for wincv.exe on how to configure it for .net 2.0.
A: you can always use a partial class
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/111995",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: How to enable inno-db support on MySql 5 installed above MySql 4? How to enable inno-db support on installed instance of MySql?
I have installed mysql-5.0.67-win32.
'InnoDB' is 'DISABLED' when executing 'show engines'.
According to documentation MySql is compiled with support of inno-db
(From doc: A value of DISABLED occurs either because the server was started with an option that disables the engine, or because not all options required to enable it were given.)
In my.ini I commented line with 'skip-innodb'. This didn't help.
All other inno-db related variables remain unchanged.
I have performed some unusual action before I experienced described situation.
I have mysql-4.0.17-win installed. I uninstall it and after this installed mysql-5.0.67-win32.
In installation wizard I chose MyISAM support only (as far as I understand I disabled inno-db support in such way. When I tried to reinstall with support of inno-db I had problems of using my previous database 'mysql' with account information).
MySQL documentation says that I should use mysqldump to export data and after this to import exported data in process of upgrade. I tried to do so, but when importing data I obtained message about syntax error (I think that it is connected with some incompatibilities of 4-th and 5-th version of mysql)
A: Should be enabled by default. There are some situations where wrong permissions on the MySQL lib folder cause InnoDB to bark. Check your MySQL error log for permission errors.
A: I do have the following innodb options in my.ini. It is a very minimal configuration, so dont' use this values if you would like mysql to have a good performance. Please restart mysql after a change of my.ini.
#*** INNODB Specific options ***
innodb_data_home_dir="C:/mysqldata/"
#skip-innodb
innodb_additional_mem_pool_size=120M
innodb_flush_log_at_trx_commit=1
innodb_log_buffer_size=16M
innodb_buffer_pool_size=10M
innodb_log_file_size=2M
innodb_thread_concurrency=8
A: Maybe you have inno-db disabled in the global configuration file. On Linux this would be something like /etc/mysql/my.cnf - maybe Windows has a similar global conf-file.
A: Make sure you are changing the correct my.ini file. On Windows this is read from many locations. The order is:
*
*WINDIR\my.ini, WINDIR\my.cnf
*C:\my.ini, C:\my.cnf
*INSTALLDIR\my.ini, INSTALLDIR\my.cnf
*defaults-extra-file
Type mysql --help in the command prompt to see the actual order on your computer e.g.:
Default options are read from the
following files in the given order:
C:\my.ini C:\my.cnf C:\WINDOWS\my.ini
C:\WINDOWS\my.cnf C:\Program
Files\MySQL\M ySQL Server 5.0\my.ini
C:\Program Files\MySQL\MySQL Server
5.0\my.cnf
A: have you checked the startup parameters? maybe the shell script or batch file that you use to start up the server disable the engine on the command line.. IIRC command line flags trumps the .ini settings.
A: I have resolved the problem.
In short:
I was not able to dump databases on MySql4 and restore it on MySql5 due to some strange syntactic errors when importing data.
I tried after installation to override MySql5 databases with old ones, including database 'mysql'. It works ok but I was not able to enable inno-db support. (In such way I even was able to use function PASSWORD for old passwords (instead of OLD_PASSWORD))
Since database structure of 'mysql' is changed in 5 version I tried to install MySql5 again and copied my old databases except 'mysql' one. After this I updated 'mysql' database with corrected version of exported data from 'mysql'. In such a way I obtained mysql 5 working.
After all I also executed mysqlcheck --all-databases --auto-repair
to upgrade my tables.
P.S. Thank to authors of all answers which hint me to the correct way of resolving problem.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/112010",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Creating a column of RadioButtons in Adobe Flex I'm using the AdvancedDataGrid widget and I want two columns to be radio buttons, where each column is it's own RadioButtonGroup. I thought I had all the necessary mxxml, but I'm running into a strange behavior issue. When I scroll up and down, the button change values! The selected button becomes deselected, and unselected ones become selected. Anyone have a clue about this bug? Should I being going about this a different way. -- Here's a stripped down example of what I trying to do.
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
<mx:RadioButtonGroup id="leftAxisGrp" />
<mx:RadioButtonGroup id="rightAxisGrp">
<mx:change>
<![CDATA[
trace (rightAxisGrp.selection);
trace (rightAxisGrp.selection.data.name);
]]>
</mx:change>
</mx:RadioButtonGroup>
<mx:AdvancedDataGrid
id="readingsGrid"
designViewDataType="flat"
height="150" width="400"
sortExpertMode="true"
selectable="false">
<mx:columns>
<mx:AdvancedDataGridColumn
headerText="L" width="25" paddingLeft="6"
dataField="left" sortable="false">
<mx:itemRenderer>
<mx:Component>
<mx:RadioButton groupName="leftAxisGrp" />
</mx:Component>
</mx:itemRenderer>
</mx:AdvancedDataGridColumn>
<mx:AdvancedDataGridColumn
headerText="R" width="25" paddingLeft="6"
dataField="right" sortable="false">
<mx:itemRenderer>
<mx:Component>
<mx:RadioButton groupName="rightAxisGrp" />
</mx:Component>
</mx:itemRenderer>
</mx:AdvancedDataGridColumn>
<mx:AdvancedDataGridColumn headerText="" dataField="name" />
</mx:columns>
<mx:dataProvider>
<mx:Array>
<mx:Object left="false" right="false" name="Reddish-gray Mouse Lemur" />
<mx:Object left="false" right="false" name="Golden-brown Mouse Lemur" />
<mx:Object left="false" right="false" name="Northern Rufous Mouse Lemur" />
<mx:Object left="false" right="false" name="Sambirano Mouse Lemur" />
<mx:Object left="false" right="false" name="Simmons' Mouse Lemur" />
<mx:Object left="false" right="false" name="Pygmy Mouse Lemur" />
<mx:Object left="false" right="false" name="Brown Mouse Lemur" />
<mx:Object left="false" right="false" name="Madame Berthe's Mouse Lemur" />
<mx:Object left="false" right="false" name="Goodman's Mouse Lemur" />
<mx:Object left="false" right="false" name="Jolly's Mouse Lemur" />
<mx:Object left="false" right="false" name="Mittermeier's Mouse Lemur" />
<mx:Object left="false" right="false" name="Claire's Mouse Lemur" />
<mx:Object left="false" right="false" name="Danfoss' Mouse Lemur" />
<mx:Object left="false" right="false" name="Lokobe Mouse Lemur" />
<mx:Object left="true" right="true" name="Bongolava Mouse Lemur" />
</mx:Array>
</mx:dataProvider>
</mx:AdvancedDataGrid>
</mx:WindowedApplication>
UPDATED (thanks bill!)
Alright! Go it working. I just had to make a couple of changes from bill's suggestion. Mainly using ArrayCollection with ObjectProxy so it was both bindable and dynamic. One weird thing - I couldn't select a button in the first row if I filled in the array at construction time; I had to delay that until the creationComplete event was fired (which is fine, since I'm going to populate the grid from a db anyway).
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
<mx:Script>
<![CDATA[
import mx.utils.ObjectProxy;
import mx.collections.ArrayCollection;
[Bindable]
private var myData:ArrayCollection = new ArrayCollection ();
private function selectItem (selObject:Object, property:String) : void
{
for each (var obj:ObjectProxy in myData) {
obj[property] = (obj.name === selObject.name);
}
readingsGrid.invalidateDisplayList ();
}
]]>
</mx:Script>
<mx:RadioButtonGroup id="leftAxisGrp">
<mx:change>
<![CDATA[
selectItem (leftAxisGrp.selectedValue, 'left');
]]>
</mx:change>
</mx:RadioButtonGroup>
<mx:RadioButtonGroup id="rightAxisGrp">
<mx:change>
<![CDATA[
selectItem (rightAxisGrp.selectedValue, 'right');
]]>
</mx:change>
</mx:RadioButtonGroup>
<mx:AdvancedDataGrid
id="readingsGrid"
designViewDataType="flat"
dataProvider="{myData}"
sortExpertMode="true"
height="150" width="400"
selectable="false">
<mx:columns>
<mx:AdvancedDataGridColumn id="leftCol"
headerText="L" width="25" paddingLeft="6" sortable="false">
<mx:itemRenderer>
<mx:Component>
<mx:RadioButton groupName="leftAxisGrp"
buttonMode="true" value="{data}" selected="{data.left}" />
</mx:Component>
</mx:itemRenderer>
</mx:AdvancedDataGridColumn>
<mx:AdvancedDataGridColumn id="rightCol"
headerText="R" width="25" paddingLeft="6" sortable="false">
<mx:itemRenderer>
<mx:Component>
<mx:RadioButton groupName="rightAxisGrp"
buttonMode="true" value="{data}" selected="{data.right}" />
</mx:Component>
</mx:itemRenderer>
</mx:AdvancedDataGridColumn>
<mx:AdvancedDataGridColumn headerText="" dataField="name" />
</mx:columns>
<mx:creationComplete>
<![CDATA[
myData.addItem(new ObjectProxy ({ left:true, right:true, name:"Golden-brown Mouse Lemur" }));
myData.addItem(new ObjectProxy ({ left:false, right:false, name:"Reddish-gray Mouse Lemur" }));
myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Northern Rufous Mouse Lemur" }));
myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Sambirano Mouse Lemur" }));
myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Simmons' Mouse Lemur" }));
myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Pygmy Mouse Lemur" }));
myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Brown Mouse Lemur" }));
myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Madame Berthe's Mouse Lemur" }));
myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Goodman's Mouse Lemur" }));
myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Jolly's Mouse Lemur" }));
myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Mittermeier's Mouse Lemur" }));
myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Claire's Mouse Lemur" }));
myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Danfoss' Mouse Lemur" }));
myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Lokobe Mouse Lemur" }));
myData.addItem( new ObjectProxy ({ left:false, right:false, name:"Bongolava Mouse Lemur" }));
]]>
</mx:creationComplete>
</mx:AdvancedDataGrid>
</mx:WindowedApplication>
A: What's happening here is that Flex only creates itemRenderer instances for the visible columns. When you scroll around, those instances get recycled. So if you scroll down, the RadioButton object that was drawing the first column of the first row may now have changed to instead be drawing the first column of the seventh row. Flex resets the "data" property of the itemRenderer whenever this happens.
So while there are 15 rows of data, there are only ever 12 RadioButtons (6 for the "left", and 6 for the "right" for the 6 visible rows), not 30 RadioButtons, as you might expect. This isn't a big problem if you're only displaying the selection, but it becomes more of a problem when you allow updates.
To fix the display issue, instead of setting the "dataField" on the column, you can bind the RadioButton's "selected" property to the itemRenderer's data.left (or right) value. You'll then need to make the items in your dataProvider "Bindable".
To fix the update issue, since you'd be binding directly to the dataProvider item values, you need to be sure to update them. Since there's isn't one RadioButton per-item, you'll need another scheme for that. In this case I put in a handler that goes and sets the left/right property of each item to "false", except for the "selected" one, which gets set to "true".
I updated your example code based on these thoughts. Try something like this:
<?xml version="1.0" encoding="utf-8"?>
<mx:Application layout="absolute"
xmlns:my="*"
xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:RadioButtonGroup id="leftAxisGrp"
change="selectItem(leftAxisGrp.selectedValue, 'left');"/>
<mx:RadioButtonGroup id="rightAxisGrp"
change="selectItem(rightAxisGrp.selectedValue, 'right');">
</mx:RadioButtonGroup>
<mx:AdvancedDataGrid
id="readingsGrid"
designViewDataType="flat"
height="150" width="400"
sortExpertMode="true"
selectable="false"
dataProvider="{adgData.object}">
<mx:columns>
<mx:AdvancedDataGridColumn
headerText="L" width="25" paddingLeft="6"
sortable="false">
<mx:itemRenderer>
<mx:Component>
<mx:RadioButton groupName="leftAxisGrp"
value="{data}" selected="{data.left}"/>
</mx:Component>
</mx:itemRenderer>
</mx:AdvancedDataGridColumn>
<mx:AdvancedDataGridColumn
headerText="R" width="25" paddingLeft="6"
sortable="false">
<mx:itemRenderer>
<mx:Component>
<mx:RadioButton groupName="rightAxisGrp"
value="{data}" selected="{data.right}"/>
</mx:Component>
</mx:itemRenderer>
</mx:AdvancedDataGridColumn>
<mx:AdvancedDataGridColumn headerText="" dataField="name" />
</mx:columns>
</mx:AdvancedDataGrid>
<mx:Model id="adgData">
<root>
<object left="false" right="false" name="Reddish-gray Mouse Lemur" />
<object left="false" right="false" name="Golden-brown Mouse Lemur" />
<object left="false" right="false" name="Northern Rufous Mouse Lemur" />
<object left="false" right="false" name="Sambirano Mouse Lemur" />
<object left="false" right="false" name="Simmons' Mouse Lemur" />
<object left="false" right="false" name="Pygmy Mouse Lemur" />
<object left="false" right="false" name="Brown Mouse Lemur" />
<object left="false" right="false" name="Madame Berthe's Mouse Lemur" />
<object left="false" right="false" name="Goodman's Mouse Lemur" />
<object left="false" right="false" name="Jolly's Mouse Lemur" />
<object left="false" right="false" name="Mittermeier's Mouse Lemur" />
<object left="false" right="false" name="Claire's Mouse Lemur" />
<object left="false" right="false" name="Danfoss' Mouse Lemur" />
<object left="false" right="false" name="Lokobe Mouse Lemur" />
<object left="true" right="true" name="Bongolava Mouse Lemur" />
</root>
</mx:Model>
<mx:Script>
<![CDATA[
private function selectItem(selObject:Object, property:String) : void {
for each(var obj:Object in adgData.object) {
obj[property] = (obj === selObject);
}
readingsGrid.invalidateDisplayList();
}
]]>
</mx:Script>
</mx:Application>
A: Reproduced this. Likely to be a ADG bug, we've run into a few here. (Didn't find this one on bugs.adobe.com, but their search sucks).
You could try Flex 3.0.3, or a nightly build here (warning, may be pretty broken), and see if they've fixed it, or you could try implementing a custom renderer, but that is a pain to get right.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/112036",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to deal with pair programming issues? Some members of the team are having problems programming together.
Different gender, different culture, different age. How to deal with those problems?
- Do not pair them together, or
- Pair them together and let them come to a "golden middle"
A: How about rotating the pairs every week or every sprint so that if there are issues between a couple of pairs they don't feel like it has to be that way forever. I think if there is a specific time frame that you have to work with someone you do not get along with it makes it easier to "suck it up" and hopefully you won't lose any great people that way.
If after a few rotations you notice a specific individual that nobody is enjoying it may be appropriate to focus on adjusting the way that individual interacts with the team or if it continues perpetually removing them from the team all together.
A: Reassess your hiring practices and make sure that you select for team oriented employees.
Failing that, breath mints.
-Adam
A: What exactly are they having problems with? Do they not get along, not understand each other? Are they at different levels of programming experience?
It may help if you have a team member that can act as a "mediator" of sorts. Somebody who's successfully done pair-programming in the past and can help the two through their first few times together.
A: Pair programming is based on the idea that the interaction of two programmers adds value. If this is not true, change the pairs... let them choose. Programming should be fun!
A: The first step to resolving conflicts is to recognize that people are different. Even the most mild mannered programmer's patience can be tried in pair programming, it can be very stressful. Some people withdraw when they are confronted by conflict, others get aggressive.
The best way of approaching pair programming, in my experience, is to have a detailed discussion of what it is you want to accomplish for the session, before you lay hands on code. This will put both of your minds on the same track. When you disagree on something, stop coding, discuss it away from the computer, try to find common ground and most importantly don't dismiss any ideas your partner may have. Take breaks; don't work for 2 hours straight, try to stand up or go for a break every 45 minutes or so.
A: Talk about pairing troubles as a group, and make sure the group is aware of different pairings that aren't working. That way, the group can help ensure that your pairs aren't avoiding each other. If you keep a disfunctional pair separate, they will always be disfunctional.
Get the pair to open lines of communication; try to get both sides to do new things. Assuming both people are genuinely good developers, they both have much to learn from one another. Try to alter their attitude from teacher to student.
A: I'd second muloh's question - what kinds of thing are they having problems with?
In my experience these problems are often (but not always) a sign of underlying problems with the team structure / skills / relationships that need to be addressed if you want to get the best out of everybody involved.
Is Mary not getting along with Fred because Fred doesn't know enough about how sane folk work with databases? Is Fred not getting along with Jo because Jo doesn't bathe quite as regularly as they ought? Is Jo not getting along with Mary because Mary is a rude SOB? If so you can almost guarantee that Fred, Jo & Mary are also annoying the rest of the team in similar ways.
Just coz one or two folk push the issue enough to avoid pairing doesn't mean the problems goes away. It may well be annoying other folk too - they may have alternate ways of coping. Like looking for alternate employment for example :-)
If the team doesn't work well together it isn't a team.
Out of curiosity - how long are your pairing sessions and how often do you switch pairs? I find that it's sometimes easier to deal with this sort of thing if folk are switching pairs on a regular basis - once or twice a day. That way everybody gets to share the relative pros and cons of everybody on the team - which can help everybody focus on solving some of the cons.
A: Another approach is to continually switch your pairs within the scrum. Have a timer which might be set for 1/2/3 hours. When the bell goes off, rotate your pairs. This has a few effects:
*
*Two people don't get stuck pairing together for a long time
*Your developers will get to rotate through your current stories, getting familiar with each one and different areas of the code
*If one of your dev's smells, you will only have to get through a short period of stink!
A: Pairing is a critical practice for an agile team. To begin with, it is best to identify developers that are willing and able to work effectively in pairs. One company I am aware of does extreme interviewing. That is, they will interview candidates in pairs giving them a problem to solve. They are interested if the developers are ability to solve the problem but are interested in their collaboration skills. Only those that can work well with others are considered.
It is not a requirement that all pair like each other. What is important is that they are effective. Given that pairs rotate frequently (for each card or more frequently), personality is less of an issue. If someone is not across pairs, and after being coached is still a problem, he or she should be asked to leave the team.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/112046",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
}
|
Q: What does %~d0 mean in a Windows batch file? I'm looking at a batch file which defines the following variables:
set _SCRIPT_DRIVE=%~d0
set _SCRIPT_PATH=%~p0
*
*What do %~d0 or %~p0 actually mean?
*Is there a set of well-known values for things like current directory, drive, parameters to a script?
*Are there any other similar shortcuts I could use?
A: Some gotchas to watch out for:
If you double-click the batch file %0 will be surrounded by quotes. For example, if you save this file as c:\test.bat:
@echo %0
@pause
Double-clicking it will open a new command prompt with output:
"C:\test.bat"
But if you first open a command prompt and call it directly from that command prompt, %0 will refer to whatever you've typed. If you type test.batEnter, the output of %0 will have no quotes because you typed no quotes:
c:\>test.bat
test.bat
If you type testEnter, the output of %0 will have no extension too, because you typed no extension:
c:\>test
test
Same for tEsTEnter:
c:\>tEsT
tEsT
If you type "test"Enter, the output of %0 will have quotes (since you typed them) but no extension:
c:\>"test"
"test"
Lastly, if you type "C:\test.bat", the output would be exactly as though you've double clicked it:
c:\>"C:\test.bat"
"C:\test.bat"
Note that these are not all the possible values %0 can be because you can call the script from other folders:
c:\some_folder>/../teST.bAt
/../teST.bAt
All the examples shown above will also affect %~0, because the output of %~0 is simply the output of %0 minus quotes (if any).
A: %~d0 gives you the drive letter of argument 0 (the script name), %~p0 the path.
A: The magic variables %n contains the arguments used to invoke the file: %0 is the path to the bat-file itself, %1 is the first argument after, %2 is the second and so on.
Since the arguments are often file paths, there is some additional syntax to extract parts of the path. ~d is drive, ~p is the path (without drive), ~n is the file name. They can be combined so ~dp is drive+path.
%~dp0 is therefore pretty useful in a bat: it is the folder in which the executing bat file resides.
You can also get other kinds of meta info about the file: ~t is the timestamp, ~z is the size.
Look here for a reference for all command line commands. The tilde-magic codes are described under for.
A: Yes, There are other shortcuts that you can use which are given below.
In your command, ~d0 would mean the drive letter of the 0th argument.
~ expands the given variable
d gets the drive letter only
0 is the argument you are referencing
As the 0th argument is the script path, it gets the drive letter of the path for you. You can use the following shortcuts too.
%~1 - expands %1 removing any surrounding quotes (")
%~f1 - expands %1 to a fully qualified path name
%~d1 - expands %1 to a drive letter only
%~p1 - expands %1 to a path only
%~n1 - expands %1 to a file name only
%~x1 - expands %1 to a file extension only
%~s1 - expanded path contains short names only
%~a1 - expands %1 to file attributes
%~t1 - expands %1 to date/time of file
%~z1 - expands %1 to size of file
%~$PATH:1 - searches the directories listed in the PATH
environment variable and expands %1 to the fully
qualified name of the first one found. If the
environment variable name is not defined or the
file is not found by the search, then this
modifier expands to the empty string
%~dp1 - expands %1 to a drive letter and path only
%~nx1 - expands %1 to a file name and extension only
%~dp$PATH:1 - searches the directories listed in the PATH
environment variable for %1 and expands to the
drive letter and path of the first one found.
%~ftza1 - expands %1 to a DIR like output line
This can be also found directly in command prompt when you run CALL /? or FOR /?
A: This code explains the use of the ~tilde character, which was the most confusing thing to me. Once I understood this, it makes things much easier to understand:
@ECHO off
SET "PATH=%~dp0;%PATH%"
ECHO %PATH%
ECHO.
CALL :testargs "these are days" "when the brave endure"
GOTO :pauseit
:testargs
SET ARGS=%~1;%~2;%1;%2
ECHO %ARGS%
ECHO.
exit /B 0
:pauseit
pause
A: They are enhanced variable substitutions. They modify the %N variables used in batch files. Quite useful if you're into batch programming in Windows.
%~I - expands %I removing any surrounding quotes ("")
%~fI - expands %I to a fully qualified path name
%~dI - expands %I to a drive letter only
%~pI - expands %I to a path only
%~nI - expands %I to a file name only
%~xI - expands %I to a file extension only
%~sI - expanded path contains short names only
%~aI - expands %I to file attributes of file
%~tI - expands %I to date/time of file
%~zI - expands %I to size of file
%~$PATH:I - searches the directories listed in the PATH
environment variable and expands %I to the
fully qualified name of the first one found.
If the environment variable name is not
defined or the file is not found by the
search, then this modifier expands to the
empty string
You can find the above by running FOR /?.
A: From Filename parsing in batch file and more idioms - Real's How-to:
The path (without drive) where the script is : ~p0
The drive where the script is : ~d0
A: Another tip that would help a lot is that to set the current directory to a different drive one would have to use %~d0 first, then cd %~dp0. This will change the directory to the batch file's drive, then change to its folder.
For #oneLinerLovers, cd /d %~dp0 will change both the drive and directory :)
Hope this helps someone.
A: It displays the current location of the file or directory that you are currently in. for example; if your batch file was in the desktop directory, then "%~dp0" would display the desktop directory. if you wanted it to display the current directory with the current file name you could type "%~dp0%~n0%~x0".
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/112055",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "403"
}
|
Q: What is an invariant? The word seems to get used in a number of contexts. The best I can figure is that they mean a variable that can't change. Isn't that what constants/finals (darn you Java!) are for?
A: It is a condition you know to always be true at a particular place in your logic and can check for when debugging to work out what has gone wrong.
A: Something that doesn't change within a block of code
A: All the answers here are great, but i felt that i can shed more light on the matter:
Invariant from a language point of view means something that never changes. The concept though comes actually from math, it's one of the popular proof techniques when combined with induction.
Here is how a proof goes, If you can find an invariant that is in the initial state, And that this invariant persists regardless of any [legal] transformation applied to the state, then you can prove that If a certain state does not have this invariant then it can never occur, no matter what sequence of transformations are applied to the initial state.
Now the previous way of thinking (again combined with induction) makes it possible to predicate the logic of computer software. Especially important when the execution goes in loops, in which an invariant can be used to prove that a certain loop will yield a certain result or that it will never change the state of a program in a certain way.
When invariant is used to predicate a loop logic its called loop invariant. It can be used outside loops, but for loops it is really important, because you often have a lot of possibilities, or an infinite number of possibilities.
Notice that i use the word "predicate" the logic of a computer software, and not prove. And that's because while in math invariant can be used as a proof, it can never prove that the computer software when executed will yield what is expected, due to the fact that the software is executed on top of many abstractions, that can never be proved that they will yield what is expected (think of the hardware abstraction for example).
Finally while theoretically and rigorously predicting software logic is only important for high critical applications like Medical, and Military ones. Invariant can still be used to aid the typical programmer when debugging. It can be used to know where at a certain location The program failed because it has failed to maintain a certain invariant - many of us use it anyway without giving a thought about it.
A: Class Invariant
Class Invariant is a condition which should be always true before and after calling relevant function
For example balanced tree has an Invariant which is called isBalanced. When you modify your tree through some methods (e.g. addNode, removeNode...) - isBalanced should be always true before and after modifying the tree
A: An invariant is more "conceptual" than a variable. In general, it's a property of the program state that is always true. A function or method that ensures that the invariant holds is said to maintain the invariant.
For instance, a binary search tree might have the invariant that for every node, the key of the node's left child is less than the node's own key. A correctly written insertion function for this tree will maintain that invariant.
As you can tell, that's not the sort of thing you can store in a variable: it's more a statement about the program. By figuring out what sort of invariants your program should maintain, then reviewing your code to make sure that it actually maintains those invariants, you can avoid logical errors in your code.
A: The magic of wikipedia: Invariant (computer science)
In computer science, a predicate that,
if true, will remain true throughout a
specific sequence of operations, is
called (an) invariant to that
sequence.
A: Following on from what it is, invariants are quite useful in writing clean code, since knowing conceptually what invariants should be present in your code allows you to easily decide how to organize your code to reach those aims. As mentioned ealier, they're also useful in debugging, as checking to see if the invariant's being maintained is often a good way of seeing if whatever manipulation you're attempting to perform is actually doing what you want it to.
A: It's typically a quantity that does not change under certain mathematical operations.
An example is a scalar, which does not change under rotations. In magnetic resonance imaging, for example, it is useful to characterize a tissue property by a rotational invariant, because then its estimation ideally does not depend on the orientation of the body in the scanner.
A: This answer is for my 5 year old kid. Do not think of an invariant as a constant or fixed numerical value. But it can be. However, it is more than that.
Rather, an invariant is something like of a fixed relationship between varying entities. For example, your age will always be less than that compared to your biological parents. Both your age, and your parent's age changes in the passage of time, but the relationship that i mentioned above is an invariant.
An invariant can also be a numerical constant. For example, the value of pi is an invariant ratio between the circle's circumference over its diameter. No matter how big or small the circle is, that ratio will always be pi.
A: I usually view them more in terms of algorithms or structures.
For example, you could have a loop invariant that could be asserted--always true at the beginning or end of each iteration. That is, if your loop was supposed to process a collection of objects from one stack to another, you could say that |stack1|+|stack2|=c, at the top or bottom of the loop.
If the invariant check failed, it would indicate something went wrong. In this example, it could mean that you forgot to push the processed element onto the final stack, etc.
A: As this line states:
In computer science, a predicate that, if true, will remain true throughout a specific sequence of operations, is called (an) invariant to that sequence.
To better understand this hope this example in C++ helps.
Consider a scenario where you have to get some values and get the total count of them in a variable called as count and add them in a variable called as sum
The invariant (again it's more like a concept):
// invariant:
// we have read count grades so far, and
// sum is the sum of the first count grades
The code for the above would be something like this,
int count=0;
double sum=0,x=0;
while (cin >> x) {
++count;
sum+=x;
}
What the above code does?
1) Reads the input from cin and puts them in x
2) After one successful read, increment count and sum = sum + x
3) Repeat 1-2 until read stops ( i.e ctrl+D)
Loop invariant:
The invariant must be True ALWAYS. So initially you start out your code with just this
while(cin>>x){
}
This loop reads data from standard input and stores in x. Well and good. But the invariant becomes false because the first part of our invariant wasn't followed (or kept true).
// we have read count grades so far, and
How to keep the invariant true?
Simple! increment count.
So ++count; would do good!. Now our code becomes something like this,
while(cin>>x){
++count;
}
But
Even now our invariant (a concept which must be TRUE) is False because now we didn't satisfy the second part of our invariant.
// sum is the sum of the first count grades
So what to do now?
Add x to sum and store it in sum ( sum+=x) and the next time
cin>>x will read a new value into x.
Now our code becomes something like this,
while(cin>>x){
++count;
sum+=x;
}
Let's check
Whether code matches our invariant
// invariant:
// we have read count grades so far, and
// sum is the sum of the first count grades
code:
while(cin>>x){
++count;
sum+=x;
}
Ah!. Now the loop invariant is True always and code works fine.
The above example was taken and modified from the book Accelerated C++ by Andrew-koening and Barbara-E
A: The ADT invariant specifes relationships
among the data fields (instance variables)
that must always be true before and after
the execution of any instance method.
A: There is an excellent example of an invariant and why it matters in the book Java Concurrency in Practice.
Although Java-centric, the example describes some code that is responsible for calculating the factors of a provided integer. The example code attempts to cache the last number provided, and the factors that were calculated to improve performance. In this scenario there is an invariant that was not accounted for in the example code which has left the code susceptible to race conditions in a concurrent scenario.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/112064",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "189"
}
|
Q: Is this C++ structure initialization trick safe? Instead of having to remember to initialize a simple 'C' structure, I might derive from it and zero it in the constructor like this:
struct MY_STRUCT
{
int n1;
int n2;
};
class CMyStruct : public MY_STRUCT
{
public:
CMyStruct()
{
memset(this, 0, sizeof(MY_STRUCT));
}
};
This trick is often used to initialize Win32 structures and can sometimes set the ubiquitous cbSize member.
Now, as long as there isn't a virtual function table for the memset call to destroy, is this a safe practice?
A: This would make me feel much safer as it should work even if there is a vtable (or the compiler will scream).
memset(static_cast<MY_STRUCT*>(this), 0, sizeof(MY_STRUCT));
I'm sure your solution will work, but I doubt there are any guarantees to be made when mixing memset and classes.
A: You can simply value-initialize the base, and all its members will be zero'ed out. This is guaranteed
struct MY_STRUCT
{
int n1;
int n2;
};
class CMyStruct : public MY_STRUCT
{
public:
CMyStruct():MY_STRUCT() { }
};
For this to work, there should be no user declared constructor in the base class, like in your example.
No nasty memset for that. It's not guaranteed that memset works in your code, even though it should work in practice.
A: This is a perfect example of porting a C idiom to C++ (and why it might not always work...)
The problem you will have with using memset is that in C++, a struct and a class are exactly the same thing except that by default, a struct has public visibility and a class has private visibility.
Thus, what if later on, some well meaning programmer changes MY_STRUCT like so:
struct MY_STRUCT
{
int n1;
int n2;
// Provide a default implementation...
virtual int add() {return n1 + n2;}
};
By adding that single function, your memset might now cause havoc.
There is a detailed discussion in comp.lang.c+
A: The examples have "unspecified behaviour".
For a non-POD, the order by which the compiler lays out an object (all bases classes and members) is unspecified (ISO C++ 10/3). Consider the following:
struct A {
int i;
};
class B : public A { // 'B' is not a POD
public:
B ();
private:
int j;
};
This can be laid out as:
[ int i ][ int j ]
Or as:
[ int j ][ int i ]
Therefore, using memset directly on the address of 'this' is very much unspecified behaviour. One of the answers above, at first glance looks to be safer:
memset(static_cast<MY_STRUCT*>(this), 0, sizeof(MY_STRUCT));
I believe, however, that strictly speaking this too results in unspecified behaviour. I cannot find the normative text, however the note in 10/5 says: "A base class subobject may have a layout (3.7) different from the layout of a most derived object of the same type".
As a result, I compiler could perform space optimizations with the different members:
struct A {
char c1;
};
struct B {
char c2;
char c3;
char c4;
int i;
};
class C : public A, public B
{
public:
C ()
: c1 (10);
{
memset(static_cast<B*>(this), 0, sizeof(B));
}
};
Can be laid out as:
[ char c1 ] [ char c2, char c3, char c4, int i ]
On a 32 bit system, due to alighments etc. for 'B', sizeof(B) will most likely be 8 bytes. However, sizeof(C) can also be '8' bytes if the compiler packs the data members. Therefore the call to memset might overwrite the value given to 'c1'.
A: Precise layout of a class or structure is not guaranteed in C++, which is why you should not make assumptions about the size of it from the outside (that means if you're not a compiler).
Probably it works, until you find a compiler on which it doesn't, or you throw some vtable into the mix.
A: PREAMBLE:
While my answer is still Ok, I find litb's answer quite superior to mine because:
*
*It teaches me a trick that I did not know (litb's answers usually have this effect, but this is the first time I write it down)
*It answers exactly the question (that is, initializing the original struct's part to zero)
So please, consider litb's answer before mine. In fact, I suggest the question's author to consider litb's answer as the right one.
Original answer
Putting a true object (i.e. std::string) etc. inside will break, because the true object will be initialized before the memset, and then, overwritten by zeroes.
Using the initialization list doesn't work for g++ (I'm surprised...). Initialize it instead in the CMyStruct constructor body. It will be C++ friendly:
class CMyStruct : public MY_STRUCT
{
public:
CMyStruct() { n1 = 0 ; n2 = 0 ; }
};
P.S.: I assumed you did have no control over MY_STRUCT, of course. With control, you would have added the constructor directly inside MY_STRUCT and forgotten about inheritance. Note that you can add non-virtual methods to a C-like struct, and still have it behave as a struct.
EDIT: Added missing parenthesis, after Lou Franco's comment. Thanks!
EDIT 2 : I tried the code on g++, and for some reason, using the initialization list does not work. I corrected the code using the body constructor. The solution is still valid, though.
Please reevaluate my post, as the original code was changed (see changelog for more info).
EDIT 3 : After reading Rob's comment, I guess he has a point worthy of discussion: "Agreed, but this could be an enormous Win32 structure which may change with a new SDK, so a memset is future proof."
I disagree: Knowing Microsoft, it won't change because of their need for perfect backward compatibility. They will create instead an extended MY_STRUCTEx struct with the same initial layout as MY_STRUCT, with additionnal members at the end, and recognizable through a "size" member variable like the struct used for a RegisterWindow, IIRC.
So the only valid point remaining from Rob's comment is the "enormous" struct. In this case, perhaps a memset is more convenient, but you will have to make MY_STRUCT a variable member of CMyStruct instead of inheriting from it.
I see another hack, but I guess this would break because of possible struct alignment problem.
EDIT 4: Please take a look at Frank Krueger's solution. I can't promise it's portable (I guess it is), but it is still interesting from a technical viewpoint because it shows one case where, in C++, the "this" pointer "address" moves from its base class to its inherited class.
A: Much better than a memset, you can use this little trick instead:
MY_STRUCT foo = { 0 };
This will initialize all members to 0 (or their default value iirc), no need to specifiy a value for each.
A: If you already have a constructor, why not just initialize it there with n1=0; n2=0; -- that's certainly the more normal way.
Edit: Actually, as paercebal has shown, ctor initialization is even better.
A: My opinion is no. I'm not sure what it gains either.
As your definition of CMyStruct changes and you add/delete members, this can lead to bugs. Easily.
Create a constructor for CMyStruct that takes a MyStruct has a parameter.
CMyStruct::CMyStruct(MyStruct &)
Or something of that sought. You can then initialize a public or private 'MyStruct' member.
A: From an ISO C++ viewpoint, there are two issues:
(1) Is the object a POD? The acronym stands for Plain Old Data, and the standard enumerates what you can't have in a POD (Wikipedia has a good summary). If it's not a POD, you can't memset it.
(2) Are there members for which all-bits-zero is invalid ? On Windows and Unix, the NULL pointer is all bits zero; it need not be. Floating point 0 has all bits zero in IEEE754, which is quite common, and on x86.
Frank Kruegers tip addresses your concerns by restricting the memset to the POD base of the non-POD class.
A: Try this - overload new.
EDIT: I should add - This is safe because the memory is zeroed before any constructors are called. Big flaw - only works if object is dynamically allocated.
struct MY_STRUCT
{
int n1;
int n2;
};
class CMyStruct : public MY_STRUCT
{
public:
CMyStruct()
{
// whatever
}
void* new(size_t size)
{
// dangerous
return memset(malloc(size),0,size);
// better
if (void *p = malloc(size))
{
return (memset(p, 0, size));
}
else
{
throw bad_alloc();
}
}
void delete(void *p, size_t size)
{
free(p);
}
};
A: If MY_STRUCT is your code, and you are happy using a C++ compiler, you can put the constructor there without wrapping in a class:
struct MY_STRUCT
{
int n1;
int n2;
MY_STRUCT(): n1(0), n2(0) {}
};
I'm not sure about efficiency, but I hate doing tricks when you haven't proved efficiency is needed.
A: Comment on litb's answer (seems I'm not yet allowed to comment directly):
Even with this nice C++-style solution you have to be very careful that you don't apply this naively to a struct containing a non-POD member.
Some compilers then don't initialize correctly anymore.
See this answer to a similar question.
I personally had the bad experience on VC2008 with an additional std::string.
A: It's a bit of code, but it's reusable; include it once and it should work for any POD. You can pass an instance of this class to any function expecting a MY_STRUCT, or use the GetPointer function to pass it into a function that will modify the structure.
template <typename STR>
class CStructWrapper
{
private:
STR MyStruct;
public:
CStructWrapper() { STR temp = {}; MyStruct = temp;}
CStructWrapper(const STR &myStruct) : MyStruct(myStruct) {}
operator STR &() { return MyStruct; }
operator const STR &() const { return MyStruct; }
STR *GetPointer() { return &MyStruct; }
};
CStructWrapper<MY_STRUCT> myStruct;
CStructWrapper<ANOTHER_STRUCT> anotherStruct;
This way, you don't have to worry about whether NULLs are all 0, or floating point representations. As long as STR is a simple aggregate type, things will work. When STR is not a simple aggregate type, you'll get a compile-time error, so you won't have to worry about accidentally misusing this. Also, if the type contains something more complex, as long as it has a default constructor, you're ok:
struct MY_STRUCT2
{
int n1;
std::string s1;
};
CStructWrapper<MY_STRUCT2> myStruct2; // n1 is set to 0, s1 is set to "";
On the downside, it's slower since you're making an extra temporary copy, and the compiler will assign each member to 0 individually, instead of one memset.
A: What I do is use aggregate initialization, but only specifying initializers for members I care about, e.g:
STARTUPINFO si = {
sizeof si, /*cb*/
0, /*lpReserved*/
0, /*lpDesktop*/
"my window" /*lpTitle*/
};
The remaining members will be initialized to zeros of the appropriate type (as in Drealmer's post). Here, you are trusting Microsoft not to gratuitously break compatibility by adding new structure members in the middle (a reasonable assumption). This solution strikes me as optimal - one statement, no classes, no memset, no assumptions about the internal representation of floating point zero or null pointers.
I think the hacks involving inheritance are horrible style. Public inheritance means IS-A to most readers. Note also that you're inheriting from a class which isn't designed to be a base. As there's no virtual destructor, clients who delete a derived class instance through a pointer to base will invoke undefined behaviour.
A: I assume the structure is provided to you and cannot be modified. If you can change the structure, then the obvious solution is adding a constructor.
Don't over engineer your code with C++ wrappers when all you want is a simple macro to initialise your structure.
#include <stdio.h>
#define MY_STRUCT(x) MY_STRUCT x = {0}
struct MY_STRUCT
{
int n1;
int n2;
};
int main(int argc, char *argv[])
{
MY_STRUCT(s);
printf("n1(%d),n2(%d)\n", s.n1, s.n2);
return 0;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/112085",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "31"
}
|
Q: Background color stretches accross entire width of ul I have a simple list I am using for a horizontal menu:
<ul>
<h1>Menu</h1>
<li>
<a href="/" class="selected">Home</a>
</li>
<li>
<a href="/Home">Forum</a>
</li>
</ul>
When I add a background color to the selected class, only the text gets the color, I want it to stretch the entire distance of the section.
Hope this makes sense.
A: Everyone is correct that your problem is that anchors are inline elements, but I thought it is also worth mentioning that you have an H1 inside of your list as well. The H1 isn't allowed there and should be pulled out of the UL or placed into an LI tag.
A: Would something like this work?
.selected {
display: block;
width: 100%;
background: #BEBEBE;
}
A: The a element is an inline element, meaning it only applies to the text it encloses. If you want the background color to stretch across horizontally, apply the selected class to a block level element. Applying the class to the li element should work fine.
Alternatively, you could add this to the selected class' CSS:
display: block;
Which will make the a element display like a block element.
A: Put the selected class on the <li> and not the <a>
A: <a> elements are inline by default. This means that they don't establish their own block, they are just part of the text. You want them to establish their own block, so you should use a { display: block; } with an appropriate context. This also enables you to add padding to the <a> elements rather than the <li> elements, making their clickable area larger, and thus easier to use.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/112093",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Secure Gmail login on web browser from external Java program Is there a secure way of logging into a Gmail account on a web browser, from an external Java program? I know the following works, but is there a safer alternative?
Desktop.getDesktop().browse(new URI(
"https://www.google.com/accounts/ServiceLoginAuth?continue=http://mail.google.com/gmail" +
"&service=mail&Email=LOGIN&Passwd=PASSWORD&null=Sign+in"));
Clarification: The external Java program is GmailAssistant, a Gmail notifier that already uses the IMAP capabilities of JavaMail. I just need a way of allowing the user to access the account directly in a web browser.
A: Depending of how much you want to integrate, you can check Google single sign-on (SSO) api. I'm studing how to use it and the best way to integrate it
http://code.google.com/apis/apps/sso/saml_reference_implementation.html
Victor
UPDATED:
As a better option, you should check this link as well http://esoeproject.org/
A: If you're really wanting to control a browser from Java, you'll have to use a web-connector such as Selenium or WebDriver. Both of these let you control a browser directly from within Java and simulate a user typing text, clicking on links and submitting forms. One thing to keep in mind when doing this with Selenium is that it interacts with a complete new profile which is usually independent of your standard Firefox probile.
A: If you are afraid that the link is visible in the Page, create a javascript document that sends a POST request to the server.
A: If you want to programmatically access the content of a GMail account, I would strongly suggest to use the IMAP access provided by Google.
Looking at the question the other way around, you can setup an OpenID authentication scheme based on your Google account.
A: I used google's IMAP access with the JavaMail API, and it was very simple.
A: If you're worried about the URL being sent for the login, understand that:
*
*https:// starts with www.google.com and will encrypt the session before
*sending the login details (or even the page it's going to
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/112102",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Javascript interpreter to replace Python In terms of quick dynamically typed languages, I'm really starting to like Javascript, as I use it a lot for web projects, especially because it uses the same syntax as Actionscript (flash).
It would be an ideal language for shell scripting, making it easier to move code from the front and back end of a site, and less of the strange syntax of python.
Is there a good, javascript interpreter that is easy to install (I know there's one based on java, but that would mean installing all the java stuff to use),
A: Of course, in Windows, the JavaScript interpreter is shipped with the OS.
Just run cscript or wscript against any .js file.
A: There are four big javascript interpreters currently. V8, Squirrelfish, Spidermonkey and Rhino. I think more important than performance is how well it integrates into existing infrastructure, and I guess Rhino with its bridge to Java wins here.
A: Try jslibs, a scripting-focused standalone JS runtime and set of libraries that uses SpiderMonkey (the Gecko JS engine).
A: On the 'easy to translate' theme, there's also Lua.
It's somewhat similar to Javascript, but more 'orthogonal' (closer to functional roots).
The heavy orientation to 'pure' programming theory has made it really small and fast. It's the fastest scripting language around, and the JIT runs circles around the new JavaScript JITs that are starting to appear.
Also, since it was originally thought as an extension language, it has a very nice and clean interface to C, making it very easy to create bindings to any C library you might want to access.
A: I personally use SpiderMonkey, but here's an extensive list of ECMAScript shells
Example spidermonkey install and use on Ubuntu:
$ sudo apt-get install spidermonkey
$ js myfile.js
output
$ js
js> var f = function(){};
js> f();
A: Google's V8 can be used as a standalone interpreter. Configuring with scons sample=shell will build an executable named shell, that can be called like so: ./shell file.js.
A: You'll need some server-side JavaScript interpreter. Check out the following blog post. Something such as Rhino might be useful for you.
A: You might try toying around with SquirrelFish or v8, both should be runnable on the command line.
A: FYI, there is a built-in one already on modern windows platforms. You need to use JScript, but it's close enough. Same environment also allows for VBScript. To run a program you can execute something like:
cscript foo.js
The windows system API is a bit weird and frustrating if you expect the same flexibility as with basic JS objects, but they do have thorough documentation if you can handle digging through the MSDN pages and seeing all the examples in VBScript.
Not sure what's available for Linux/Mac in terms of js shell.
A: Well, for safety reasons, javascript had not been provided with file access right by design. So as a scripting language, it's a bit limited.
But still, if you really want to, spider monkey is your best option. Here is a tuto :
http://developer.mozilla.org/en/Introduction_to_the_JavaScript_shell
A: Node.JS. It's great. Has many modules. you can do all your file scripting with Node.
A: In my years I've found most Javascript developers find it quite easy to transfer over to PHP and vice versa - it isn't a direct answer to your question, although if you're working in ActionScript and JavaScript then you're best to stick with something like PHP (if you're not willing to move to Java, and stick with the ECMA base)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/112112",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "21"
}
|
Q: Should I prefix my method with "get" or "load" when communicating with a web service? I'm writing a desktop application that communicates with a web service. Would you name all web-service functions that that fetch data LoadXXXX, since they take a while to execute. Or would you use GetXXXX, for instance when getting just a single object.
A: I would use Load if you expect it to take "file-time" and Get if you expect it to take "simple DB" time.
That is, if the call is expensive, use "Load".
A: Get. And then provide a way of calling them asynchronously to emphasize that they may be out to lunch for a while...
A: Use MyObject.GetXXXX() when the method returns XXXX.
Use MyObject.LoadXXXX() when XXXX will be loaded into MyObject, in other words, when MyObject keeps control of XXXX.
The same applies to webservices, I guess.
A: Do what the verb implies. GetXXX implies that something is being returned to the caller, while LoadXXX doesn't necessarily return something as it may be just loading something into memory.
For an API, use GetXXX to be clear to the caller that something will be returned.
A: Always use Get, except perhaps when actually loading something (eg, loading a file into memory).
A: When I read LoadXXX, I'm already thinking that the data comes from some storage media. Since the web service is up in the cloud, GetXXX feels more natural.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/112121",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How long does it really take to do something? I mean name off a programming project you did and how long it took, please. The boss has never complained but I sometimes feel like things take too long. But this could be because I am impatient as well. Let me know your experiences for comparison.
I've also noticed that things always seem to take longer, sometimes much longer, than originally planned. I don't know why we don't start planning for it but then I think that maybe it's for motivational purposes.
Ryan
A: It is best to simply time yourself, record your estimates and determine the average percent you're off. Given that, as long as you are consistent, you can appropriately estimate actual times based on when you believed you'd get it done. It's not simply to determine how bad you are at estimating, but rather to take into account the regularity of inevitable distractions (both personal and boss/client-based).
This is based on Joel Spolsky's Evidence Based Scheduling, essential reading, as he explains that the primary other important aspect is breaking your tasks down into bite-sized (16-hour max) tasks, estimating and adding those together to arrive at your final project total.
A: Gut-based estimates come with experience but you really need to detail out the tasks involved to get something reasonable.
If you have a spec or at least some constraints, you can start creating tasks (design users page, design tags page, implement users page, implement tags page, write tags query, ...).
Once you do this, add it up and double it. If you are going to have to coordinate with others, triple it.
Record your actual time in detail as you go so you can evaluate how accurate you were when the project is complete and hone your estimating skills.
A: I completely agree with the previous posters... don't forget your team's workload also. Just because you estimated a project would take 3 months, it doesn't mean it'll be done anywhere near that.
I work on a smaller team (5 devs, 1 lead), many of us work on several projects at a time - some big, some small. Depending on the priority of the project, the whims of management and the availability of other teams (if needed), work on a project gets interspersed amongst the others.
So, yes, 3 months worth of work may be dead on, but it might be 3 months worth of work over a 6 month period.
A: I've done projects between 1 - 6 months on my own, and I always tend to double or quadrouple my original estimates.
A: It's effectively impossible to compare two programming projects, as there are too many factors that mean that the metrics from only aren't applicable to another (e.g., specific technologies used, prior experience of the developers, shifting requirements). Unless you are stamping out another system that is almost identical to one you've built previously, your estimates are going to have a low probability of being accurate.
A caveat is when you're building the next revision of an existing system with the same team; the specific experience gained does improve the ability to estimate the next batch of work.
I've seen too many attempts at estimation methodology, and none have worked. They may have a pseudo-scientific allure, but they just don't work in practice.
The only meaningful answer is the relatively short iteration, as advocated by agile advocates: choose a scope of work that can be executed within a short timeframe, deliver it, and then go for the next round. Budgets are then allocated on a short-term basis, with the stakeholders able to evaluate whether their money is being effectively spent. If it's taking too long to get anywhere, they can ditch the project.
A: Hofstadter's Law:
'It always takes longer than you expect, even when you take Hofstadter's Law into account.'
I believe this is because:
*
*Work expands to fill the time available to do it. No matter how ruthless you are cutting unnecessary features, you would have been more brutal if the deadlines were even tighter.
*Unexpected problems occur during the project.
In any case, it's really misleading to compare anecdotes, partly because people have selective memories. If I tell you it once took me two hours to write a fully-optimised quicksort, then maybe I'm forgetting the fact that I knew I'd have that task a week in advance, and had been thinking over ideas. Maybe I'm forgetting that there was a bug in it that I spent another two hours fixing a week later.
I'm almost certainly leaving out all the non-programming work that goes on: meetings, architecture design, consulting others who are stuck on something I happen to know about, admin. So it's unfair on yourself to think of a rate of work that seems plausible in terms of "sitting there coding", and expect that to be sustained all the time. This is the source of a lot of feelings after the fact that you "should have been quicker".
A: I do projects from 2 weeks to 1 year. Generally my estimates are quite good, a posteriori. At the beginning of the project, though, I generally get bashed because my estimates are considered too large.
This is because I consider a lot of things that people forget:
*
*Time for bug fixing
*Time for deployments
*Time for management/meetings/interaction
*Time to allow requirement owners to change their mind
*etc
The trick is to use evidence based scheduling (see Joel on Software).
Thing is, if you plan for a little extra time, you will use it to improve the code base if no problems arise. If problems arise, you are still within the estimates.
A: I believe Joel has wrote an article on this: What you can do, is ask each developer on team to lay out his task in detail (what are all the steps that need to be done) and ask them to estimate time needed for each step. Later, when project is done, compare the real time to estimated time, and you'll get the bias for each developer. When a new project is started, ask them to evaluate the time again, and multiply that with bias of each developer to get the values close to what's really expects.
After a few projects, you should have very good estimates.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/112131",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Searching for regex patterns on a 30GB XML dataset. Making use of 16gb of memory I currently have a Java SAX parser that is extracting some info from a 30GB XML file.
Presently it is:
*
*reading each XML node
*storing it into a string object,
*running some regexex on the string
*storing the results to the database
For several million elements. I'm running this on a computer with 16GB of memory, but the memory is not being fully utilized.
Is there a simple way to dynamically 'buffer' about 10gb worth of data from the input file?
I suspect I could manually take a 'producer' 'consumer' multithreaded version of this (loading the objects on one side, using them and discarding on the other), but damnit, XML is ancient now, are there no efficient libraries to crunch em?
A: *
*Just to cover the bases, is Java able to use your 16GB? You (obviously) need to be on a 64-bit OS, and you need to run Java with -d64 -XMx10g (or however much memory you want to allocate to it).
*It is highly unlikely memory is a limiting factor for what you're doing, so you really shouldn't see it fully utilized. You should be either IO or CPU bound. Most likely, it'll be IO. If it is, IO, make sure you're buffering your streams, and then you're pretty much done; the only thing you can do is buy a faster harddrive.
*If you really are CPU-bound, it's possible that you're bottlenecking at regex rather than XML parsing.
See this (which references this)
*If your bottleneck is at SAX, you can try other implementations. Off the top of my head, I can think of the following alternatives:
*
*StAX (there are multiple implementations; Woodstox is one of the fastest)
*Javolution
*Roll your own using JFlex
*Roll your own ad hoc, e.g. using regex
For the last two, the more constrained is your XML subset, the more efficient you can make it.
*It's very hard to say, but as others mentioned, an XML-native database might be a good alternative for you. I have limited experience with those, but I know that at least Berkeley DB XML supports XPath-based indices.
A: No Java experience, sorry, but maybe you should change the parser? SAX should work sequentially and there should be no need to buffer most of the file ...
A: SAX is, essentially, "event driven", so the only state you should be holding on to from element to element is state that relevant to that element, rather than the document as a whole. What other state are you maintaining, and why? As each "complete" node (or set of nodes) comes by, you should be discarding them.
A: First, try to find out what's slowing you down.
*
*How much faster is the parser when you parse from memory?
*Does using a BufferedInputStream with a large size help?
Is it easy to split up the XML file? In general, shuffling through 30 GiB of any kind of data will take some time, since you have to load it from the hard drive first, so you are always limited by the speed of this. Can you distribute the load to several machines, maybe by using something like Hadoop?
A: I don't really understand what you're trying to do with this huge amount of XML, but I get the impression that
*
*using XML was wrong for the data stored
*you are buffering way beyond what you should do (and you are giving up all advantages of SAX parsing by doing so)
Apart from that: XML is not ancient and in massive and active use. What do you think all those interactive web sites are using for their interactive elements?
A: Are you being slowed down by multiple small commits to your db? Sounds like you would be writing to the db almost all the time from your program and making sure you don't commit too often could improve performance. Possibly also preparing your statements and other standard bulk processing tricks could help
Other than this early comment, we need more info - do you have a profiler handy that can scrape out what makes things run slowly
A: You can use the Jibx library, and bind your XML "nodes" to objects that represent them. You can even overload an ArrayList, then when x number of objects are added, perform the regexes all at once (presumably using the method on your object that performs this logic) and then save them to the database, before allowing the "add" method to finish once again.
Jibx is hosted on SourceForge: Jibx
To elaborate: you can bind your XML as a "collection" of these specialized String holders. Because you define this as a collection, you must choose what collection type to use. You can then specify your own ArrayList implementation.
Override the add method as follows (forgot the return type, assumed void for example):
public void add(Object o) {
super.add(o);
if(size() > YOUR_DEFINED_THRESHOLD) {
flushObjects();
}
}
YOUR_DEFINED_THRESHOLD
is how many objects you want to store in the arraylist until it has to be flushed out to the database. flushObjects(); is simply the method that will perform this logic. The method will block the addition of objects from the XML file until this process is complete. However, this is ok, the overhead of the database will probably be much greater than file reading and parsing anyways.
A: I would suggest to first import your massive XML file into a native XML database (such as eXist if you are looking for open source stuff, never tested it myself), and then perform iterative paged queries to process your data small chunks at a time.
A: You may want to try Stax instead of SAX, I hear it's better for that sort of thing (I haven't used it myself).
A: If the data in the XML is order independent, can you multi-thread the process to split the file up or run multiple processes starting in different locations in the file? If you're not I/O bound that should help speed it along.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/112154",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: is the + operator less performant than StringBuffer.append() On my team, we usually do string concatentation like this:
var url = // some dynamically generated URL
var sb = new StringBuffer();
sb.append("<a href='").append(url).append("'>click here</a>");
Obviously the following is much more readable:
var url = // some dynamically generated URL
var sb = "<a href='" + url + "'>click here</a>";
But the JS experts claim that the + operator is less performant than StringBuffer.append(). Is this really true?
A: JavaScript doesn't have a native StringBuffer object, so I'm assuming this is from a library you are using, or a feature of an unusual host environment (i.e. not a browser).
I doubt a library (written in JS) would produce anything faster, although a native StringBuffer object might. The definitive answer can be found with a profiler (if you are running in a browser then Firebug will provide you with a profiler for the JS engine found in Firefox).
A: Like already some users have noted: This is irrelevant for small strings.
And new JavaScript engines in Firefox, Safari or Google Chrome optimize so
"<a href='" + url + "'>click here</a>";
is as fast as
["<a href='", url, "'>click here</a>"].join("");
A: In the words of Knuth, "premature optimization is the root of all evil!" The small defference either way will most likely not have much of an effect in the end; I'd choose the more readable one.
A: Internet Explorer is the only browser which really suffers from this in today's world. (Versions 5, 6, and 7 were dog slow. 8 does not show the same degradation.) What's more, IE gets slower and slower the longer your string is.
If you have long strings to concatenate then definitely use an array.join technique. (Or some StringBuffer wrapper around this, for readability.) But if your strings are short don't bother.
A: The easier to read method saves humans perceptible amounts of time when looking at the code, whereas the "faster" method only wastes imperceptible and likely negligible amounts of time when people are browsing the page.
I know this post is lame, but I accidentally posted something entirely different thinking this was a different thread and I don't know how to delete posts. My bad...
A: Yes it's true but you shouldn't care. Go with the one that's easier to read. If you have to benchmark your app, then focus on the bottlenecks.
I would guess that string concatenation isn't going to be your bottleneck.
A: Agreed with Michael Haren.
Also consider the use of arrays and join if performance is indeed an issue.
var buffer = ["<a href='", url, "'>click here</a>"];
buffer.push("More stuff");
alert(buffer.join(""));
A: It is pretty easy to set up a quick benchmark and check out Javascript performance variations using jspref.com. Which probably wasn't around when this question was asked. But for people stumbling on this question they should take alook at the site.
I did a quick test of various methods of concatenation at http://jsperf.com/string-concat-methods-test.
A: I like to use functional style, such as:
function href(url,txt) {
return "<a href='" +url+ "'>" +txt+ "</a>"
}
function li(txt) {
return "<li>" +txt+ "</li>"
}
function ul(arr) {
return "<ul>" + arr.map(li).join("") + "</ul>"
}
document.write(
ul(
[
href("http://url1","link1"),
href("http://url2","link2"),
href("http://url3","link3")
]
)
)
This style looks readable and transparent. It leads to the creation of utilities which reduces repetition in code.
This also tends to use intermediate strings automatically.
A: Try this:
var s = ["<a href='", url, "'>click here</a>"].join("");
A: Your example is not a good one in that it is very unlikely that the performance will be signficantly different. In your example readability should trump performance because the performance gain of one vs the other is negligable. The benefits of an array (StringBuffer) are only apparent when you are doing many concatentations. Even then your mileage can very depending on your browser.
Here is a detailed performance analysis that shows performance using all the different JavaScript concatenation methods across many different browsers; String Performance an Analysis
More:
Ajaxian >> String Performance in IE: Array.join vs += continued
A: As far I know, every concatenation implies a memory reallocation. So the problem is not the operator used to do it, the solution is to reduce the number of concatenations. For example do the concatenations outside of the iteration structures when you can.
A: Yes, according to the usual benchmarks. E.G : http://mckoss.com/jscript/SpeedTrial.htm.
But for the small strings, this is irrelevant. You will only care about performances on very large strings. What's more, in most JS script, the bottle neck is rarely on the string manipulations since there is not enough of it.
You'd better watch the DOM manipulation.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/112158",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "91"
}
|
Q: How do you maintain your program vocabulary? In a not-so-small program, when you have not-so-few entities, in order to maintain code readability, common terms, and otherwise improve mutual understanding between team members, one have to define and maintain program vocabulary.
How do you (or your company) deal with this task, what discipline do you have, what arrangements do you introduce?
A: Most projects of reasonable size should have a programming/coding standards document that dictates common conventions and naming guidelines that should be followed.
Another way to help with this is through code reviews. Obviously some coordination among reviewers is required (the document helps with that, too). Code reviews help keep the greener devs and senior devs alike on track and act as an avenue to enforce the coding standards.
A: @Ilya Ryzhenkov,
I'm afraid most companies don't have such practice :) I've worked in the not-so-small company with multimillion LOC code base and they don't have any documentation at all (beside common coding guideline)
On one of my projects we maintained thesaurus of common terms used in our application domain and used it during code review. I analyzed .NET XML documentation diff from time to time to decide which entities\terms should be added to the thesaurus. Only means to enforce compliance with thesaurus was coding guideline.
Wiki approach proved to be non-applicable because nobody cares to update it regularly :)
I'm wondering what methods do you use at JetBrains ? I've inspected ReSharper's code in Reflector and was amazed with number and names of entities :)
A: Divide your packages/modules into logical groups and use descriptive and concise names. Avoid generic names except if they are really counters etc. Create conventions for groups of functions or functionality and stick to them.
A: Domain Driven Design is interesting here, since it encourages programmers to embrace the domain vocabulary. On top of that, there is some design conventions, which allow you to refer parts of your application using well known terms, like services, repositories, factories, etc.
Combining domain vocabulary and using technical conventions above it could be a good solution.
A: My team keeps this kind of information (conventions/vocabulary etc.) on a wiki. This makes it easy to keep up to date and share.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/112161",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: How do I get my Twitter feed to integrate with a blog (with individual comment threads)? I would like to create a blog where my Twitter updates essentially create blog posts, with a comment thread. If there isn't blog software that does this right now (I did some searching but couldn't find the commenting aspect) what would be the simplest approach and starting blog software to do this?
Potentially an alternate approach to this would be a blog interface that could auto-update my Twitter feed with the title text.
Whatever the solution, I'd like it to be fully automated so that it is roughly no more work than currently updating my Twitter feed using the Twitter web interface. Note: I'm also interested in 'normal' blog posting via the default blog web admin interface.
A: You could use something like Tumblr or Sweetcron with Disqus comments. You can auto-import your Twitter/Flickr/any RSS feed. You can also post text/audio/video from the site admin. You'll have to manually add Disqus comments, but then each post or Twitter message will have its own threaded comments.
A: If you would like to use Wordpress, you can use the Twitter Tools plugin.
"Pull your tweets into your blog and create new tweets on blog posts and from within WordPress."
Each tweet/blog post would automatically have comments enabled.
Good luck man,
Brian Gianforcaro
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/112162",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Google Chrome broke ShellExecute()? For years I've been using ShellExecute() API to launch the default web browser from within my applications. Like this:
ShellExecute( hwnd, _T("open"),
_T("http://www.winability.com/home/"),
NULL, NULL, SW_NORMAL );
It's been working fine until a couple of weeks ago, when Google released its Chrome browser. Now, if Chrome is installed on the computer, the ShellExecute API no longer opens a web page.
Has anyone figured out yet how to solve this problem? (Short of detecting Chrome and displaying a message telling the user it's Chrome's fault?)
EDIT: the code provided by Sergey seems to work, so I've accepted it as "the" answer. Except that I don't like the call to WinExec: MSDN reads that WinExec is provided only for compatibility with 16-bit applications. IOW, it may stop working with any Service Pack. I did not try it, but I would not be surprised if it has already stopped working with Windows x64, since it does not support 16-bit applications at all. So, instead of WinExec, I'm going to use ShellExecute, with the path taken from the registry like Sergey's code does, and the URL as the argument. Thanks!
A: Here is the code that works across all browsers. The trick is to call WinExec if ShellExecute fails.
HINSTANCE GotoURL(LPCTSTR url, int showcmd)
{
TCHAR key[MAX_PATH + MAX_PATH];
// First try ShellExecute()
HINSTANCE result = 0;
CString strURL = url;
if ( strURL.Find(".htm") <0 && strURL.Find("http") <0 )
result = ShellExecute(NULL, _T("open"), url, NULL, NULL, showcmd);
// If it failed, get the .htm regkey and lookup the program
if ((UINT)result <= HINSTANCE_ERROR) {
if (GetRegKey(HKEY_CLASSES_ROOT, _T(".htm"), key) == ERROR_SUCCESS) {
lstrcat(key, _T("\\shell\\open\\command"));
if (GetRegKey(HKEY_CLASSES_ROOT,key,key) == ERROR_SUCCESS) {
TCHAR *pos;
pos = _tcsstr(key, _T("\"%1\""));
if (pos == NULL) { // No quotes found
pos = strstr(key, _T("%1")); // Check for %1, without quotes
if (pos == NULL) // No parameter at all...
pos = key+lstrlen(key)-1;
else
*pos = '\0'; // Remove the parameter
}
else
*pos = '\0'; // Remove the parameter
lstrcat(pos, _T(" \""));
lstrcat(pos, url);
lstrcat(pos, _T("\""));
result = (HINSTANCE) WinExec(key,showcmd);
}
}
}
return result;
}
A: After hearing reports of ShellExecute failing on a minority of systems, I implemented a function similar to the example given by Sergey Kornilov. This was about a year ago. Same premise - Do a direct HKCR lookup of the .HTM file handler.
However, it turns out that some users have editors (e.g. UltraEdit) that register themselves to 'open' .htm files (instead of 'edit' them). Thus, if ShellExecute fails, this secondary method will also fail in those cases. It opens the editor, as the shell association errantly instructs.
Thus, the user should use the HTTP handler instead, or at least in preference of the HTML handler.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/112169",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: php.ini & SMTP= - how do you pass username & password My ISP account requires that I send a username & password for outbound SMTP mail.
How do I get PHP to use this when executing php.mail()? The php.ini file only contains entries for the server (SMTP= ) and From: (sendmail_from= ).
A: I prefer the PHPMailer tool as it doesn't require PEAR. But either way, you have a misunderstanding: you don't want a PHP-server-wide setting for the SMTP user and password. This should be a per-app (or per-page) setting. If you want to use the same account across different PHP pages, add it to some kind of settings.php file.
A: After working all day on this, I finally found a solution. Here's how I send from Windows XP with WAMP.
*
*Use Google's SMTP server. You probably need an account.
*Download and install Fake Sendmail. I just downloaded it, unzipped it and put it in the WAMP folder.
*Create a test PHP file. See below.
<?php
$message = "test message body";
$result = mail('recipient@some-domain.com', 'message subject', $message);
echo "result: $result";
?>
*Update your php.ini file and your sendmail.ini file (sendmail.ini is in the sendmail folder).
*Check the error.log file in the sendmail folder that you just created if it doesn't work.
Reference:
*
*http://www.geekzone.co.nz/tonyhughes/599
*http://www.joshstauffer.com/send-test-emails-with-wampserver/
A: PHP mail() command does not support authentication. Your options:
*
*PHPMailer- Tutorial
*PEAR - Tutorial
*Custom functions - See various solutions in the notes section: http://php.net/manual/en/ref.mail.php
A: I apply following details on php.ini file. its works fine.
SMTP = smtp.example.com
smtp_port = 25
username = info@example.com
password = yourmailpassord
sendmail_from = info@example.com
These details are same as on outlook settings.
A: Use Fake sendmail for Windows to send mail.
*
*Create a folder named sendmail in C:\wamp\.
*Extract these 4 files in sendmail folder: sendmail.exe, libeay32.dll, ssleay32.dll and sendmail.ini.
*Then configure C:\wamp\sendmail\sendmail.ini:
smtp_server=smtp.gmail.com
smtp_port=465
auth_username=user@gmail.com
auth_password=your_password
*The above will work against a Gmail account. And then configure php.ini:
sendmail_path = "C:\wamp\sendmail\sendmail.exe -t"
*Now, restart Apache, and that is basically all you need to do.
A: These answers are outdated and deprecated.
The actual best practice would be:
composer require phpmailer/phpmailer
As the next step, your sendmail.php file just requires the following:
# use namespace
use PHPMailer\PHPMailer\PHPMailer;
# require php mailer
require_once "../vendor/autoload.php";
//PHPMailer Object
$mail = new PHPMailer;
//From email address and name
$mail->From = "from@yourdomain.com";
$mail->FromName = "Full Name";
//To address and name
$mail->addAddress("recepient1@example.com", "Recepient Name");
$mail->addAddress("recepient1@example.com"); //Recipient name is optional
//Address to which recipient will reply
$mail->addReplyTo("reply@yourdomain.com", "Reply");
//CC and BCC
$mail->addCC("cc@example.com");
$mail->addBCC("bcc@example.com");
//Send HTML or Plain Text email
$mail->isHTML(true);
$mail->Subject = "Subject Text";
$mail->Body = "<i>Mail body in HTML</i>";
$mail->AltBody = "This is the plain text version of the email content";
if(!$mail->send())
{
echo "Mailer Error: " . $mail->ErrorInfo;
}
else
{
echo "Message has been sent successfully";
}
This can be configured however you like.
A: PHP does have authentication on the mail-command!
The following is working for me on WAMPSERVER (windows, php 5.2.17)
php.ini
[mail function]
; For Win32 only.
SMTP = mail.yourserver.com
smtp_port = 25
auth_username = smtp-username
auth_password = smtp-password
sendmail_from = you@yourserver.com
A: *
*Install Postfix (Sendmail-compatible).
*Edit /etc/postfix/main.cf to read:
#Relay config
relayhost = smtp.server.net
smtp_use_tls=yes
smtp_sasl_auth_enable=yes
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
smtp_tls_CAfile = /etc/postfix/cacert.pem
smtp_sasl_security_options = noanonymous
*Create /etc/postfix/sasl_passwd, enter:
smtp.server.net username:password
*Type # /usr/sbin/postmap sasl_passwd
*Then run: service postfix reload
Now PHP will run mail as usual with the sendmail -t -i command and Postfix will intercept it and relay it to your SMTP server that you provided.
A: Use Mail::factory in the Mail PEAR package. Example.
A: *
*Install the latest hMailServer. "Run hMailServer Administrator" in the last step.
*Connect to "localhost".
*"Add domain..."
*Set "127.0.0.1." as the "Domain", click "Save".
*"Settings" > "Protocols" > "SMTP" > "Delivery of e-mail"
*Set "localhost" as the "Local host name", provide your data in the "SMTP Relayer" section, click "Save".
*"Settings" > "Advanced" > "IP Ranges" > "My Computer"
*Disable the "External to external e-mail addresses" checkbox in the "Require SMTP authentication" group.
*If you have modified php.ini, rewrite these 3 values:
"SMTP = localhost",
"smtp_port = 25",
"; sendmail_path = ".
Credit: How to configure WAMP (localhost) to send email using Gmail?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/112190",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "70"
}
|
Q: What is the best way to return multiple tags from a Rails Helper? I want to create a hidden field and create a link in one helper and then output both to my erb.
<%= my_cool_helper "something", form %>
Should out put the results of
link_to "something", a_path
form.hidden_field "something".tableize, :value => "something"
What would the definition of the helper look like? The details of what link_to and the form.hidden_field don't really matter. What matters is, how do I return the output from two different calls.
A: Using safe_join.
I typically prefer just concatenating with +, as shown in Orion Edwards's Answer, but here's another option I recently discovered.
safe_join( [
link_to( "something", something_path ),
form.hidden_field( "something".tableize, value: "something" )
] )
It has the advantage of explicitly listing all of the elements and the joining of those elements.
I find that with long elements, the + symbol can get lost at the end of the line. Additionally, if you're concatenating more than a few elements, I find listing them in an Array like this to be more obvious to the next reader.
A: There are several ways to do this.
Remember that the existing rails helpers like link_to, etc, just output strings. You can concatenate the strings together and return that (which is what I do most of the time, if things are simple).
EG:
link_to( "something", something_path ) + #NOTE THE PLUS FOR STRING CONCAT
form.hidden_field('something'.tableize, :value=>'something')
If you're doing things which are more complicated, you could just put that code in a partial, and have your helper call render :partial.
If you're doing more complicated stuff than even that, then you may want to look at errtheblog's block_to_partial helper, which is pretty cool
A: If you want to buffer other output which apart from string then you can use concat instead of +.
see this - http://thepugautomatic.com/2013/06/helpers/
A: So far the best I have come up with is:
def my_cool_helper(name, form)
out = capture { link_to name, a_path }
out << capture { form.hidden_field name.tableize, value => 'something' }
end
Is there a better way?
A: def output_siblings
div1 = tag.div 'some content'
div2 = tag.div 'other content'
div1 + div2
end
just simplifying some other answers in here.
A: This worked for me.
def format_paragraphs(text)
text.split(/\r?\n/).sum do |paragraph|
tag.p(paragraph)
end
end
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/112197",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "28"
}
|
Q: Click through transparency for Visual C# Window Forms? I made a panel and set it to fill the screen, now I can see the windows under it but I want it to be click through, meaning they could click a file or see a tool tip of another object through the transparency.
RE: This may be too obvious, but have you tried sending the panel to the back by right clicking and choosing "Send to Back"?
I mean like the desktop or firefox, not something within my project.
A: Creating a top level form that is transparent is very easy. Just make it fill the screen, or required area, and define it to have a TransparenyKey color and BackColor of the same value.
Getting it to ignore the mouse is simple enough, you just need to override the WndProc and tell the WM_HITTEST that all mouse positions are to be treated as transparent. Thus causing the mouse to interact with whatever happens to be underneath the window. Something like this...
protected override void WndProc(ref Message m)
{
if (m.Msg == (int)WM_NCHITTEST)
m.Result = (IntPtr)HTTRANSPARENT;
else
base.WndProc(ref m);
}
A: A much simpler method that might work.
step 1.) click on the panel in (design)
step 2.) look in properties
step 3.) set Enabled to False
this allowed me to click past my panel to the one behind it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/112224",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
}
|
Q: Consistently retrieve "From" email addresses across Outlook versions I am working a standalone c# desktop application that sends out documents and then imports them from Outlook when they are sent back. The application picks up the emails from a specified folder processes them and then saves the senders name plus other stuff to a database.
This works well for Outlook 2003 and 2007 which has the SenderEmailAddress property. However Outlook 2000 and XP does not have this property and will not consistently return name@domain.com. I am providing support for these versions.
I have found that a library called Outlook Redemption will solve this but I am developing in .net and really want to avoid writing to customer registries. I also found MAPI33 a .Net wrapper around MAPI but it is unclear from the forums whether it is still being supported.
Would appreciate any pointers as to a .Net alternative to the Redemption dll or an approach to being able to consistently retrieve an email address across Outlook versions.
Many thanks
AbsFabs
Epilogue:
I ended up using a solution from this article http://support.microsoft.com/kb/324530. It comprised creating a reply and then extracting the reply to address of the created mailitem. It worked well for emails sent over the internet and is currently going through Exchange Server testing.
Also found this on my travels http://anoriginalidea.wordpress.com/2008/01/11/getting-the-smtp-email-address-of-an-exchange-sender-of-a-mailitem-from-outlook-in-vbnet-vsto/ it appears to be a touch involved. This might comprise my plan B if my existing implementation does not survive testing.
Thanks for your feedback
AbsFabs
I ultimately wound up using Redemption. Excellent tool for the job. My issue was with having to register the dll when my app was installed. Since my app is written in dotnet it does not need to register anything. I was able to work around the dll registration issue using registry-free COM.
Many thanks for your inspiration.
A: I'm using the Outlook Redemption solution in a C# production code. It works beautifully.
With it, you can get the SenderID of a mail message (IRDOMail), and from there, you can use the GetAddressEntryFromID() method of the IRDOSession object.
A: While having a similar problem at work, we decided to go the netMAPI route, which has caused some problems.
The main problem with it is that MAPI managed its own memory, as does .NET meaning that occasionally (we have around 300 people using our in house software) it would cause our application to crash, generating the windows 'report error' dialog rather than our own bug tracking dialog. This was caused by the two overwriting each others memory heaps.
As we have to use an exchange server, we did some research, and discovered that if you wrote the MAPI code in a VB6 app, it would have its own memory space, and thus not overwrite the .NET heap.
It is a rather long winded way of doing things, but thus far we have had no problems, and hundreds (if not thousands) of emails are sent by our staff everyday.
A: Good news is that ou are on the right track with tracking down the right interfaces. The bad news is that 2000 and XP are very poorly supported in .NET because they came before .NET and only with 2003 was their a real effort to get the COM working in .NET.
You solution for these version 2000 and XP is going to consist of you tracking down the right COM interfaces and wrapping them your self. I have had to do this many times for these version of Outlook and it is never pretty. So good luck.
A: I've never actually used these, but you could try the Outlook Collaboration Data Objects (CDO). They used to be an add-on that you could install with outlook, but now they are being provided separately.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/112227",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Sorting matched arrays in Java Let's say that I have two arrays (in Java),
int[] numbers; and int[] colors;
Each ith element of numbers corresponds to its ith element in colors.
Ex, numbers = {4,2,1}
colors = {0x11, 0x24, 0x01}; Means that number 4 is color 0x11, number 2 is 0x24, etc.
I want to sort the numbers array, but then still have it so each element matches up with its pair in colors.
Ex. numbers = {1,2,4};
colors = {0x01,0x24,0x11};
What's the cleanest, simplest way to do this? The arrays have a few thousand items, so being in place would be best, but not required. Would it make sense to do an Arrays.sort() and a custom comparator? Using library functions as much as possible is preferable.
Note: I know the "best" solution is to make a class for the two elements and use a custom comparator. This question is meant to ask people for the quickest way to code this. Imagine being at a programming competition, you wouldn't want to be making all these extra classes, anonymous classes for the comparator, etc. Better yet, forget Java; how would you code it in C?
A: It seems like the cleanest thing to do would be to create a custom property class that implements Comparable. For example:
class Color implements Comparable {
private int number;
private int color;
// (snip ctor, setters, etc.)
public int getNumber() {
return number;
}
public int getColor() {
return color;
}
public int compareTo(Color other) {
if (this.getNumber() == other.getNumber) {
return 0;
} else if (this.getNumber() > other.getNumber) {
return 1;
} else {
return -1;
}
}
}
Then you can separate your sorting algorithm from the ordering logic (you could use Collections.sort if you use a List instead of an array), and most importantly, you won't have to worry about somehow getting two arrays out of sync.
A: If you'd be willing to allocate some extra space, you could generate another array, call it extra, with elements like this:
extra = [0,1,...,numbers.length-1]
Then you could sort this extra array using Arrays.sort() with custom comparator (that, while comparing elements i and j really compares numbers[extra[i]] and numbers[extra[j]]). This way after sorting the extra array, extra[0] would contain the index of the smallest number and, as numbers and colours didn't move, the corresponding colour.
This isn't very nice, but it gets the job done, and I can't really think of an easier way to do it.
As a side note, in the competition I usually find the C++ templated pairs and nice maps indispensable ;)
A: Why not introduce an object to represent a number and a color and implement a comparator function for that?
Also, do you really need an array, why not use something derived from Collection?
A: I like @tovare's solution. Make a pointer array:
int ptr[] = { 1, 2, 3 };
and then when you sort on numbers, swap the values in ptr instead of in numbers. Then access through the ptr array, like
for (int i = 0; i < ptr.length; i++)
{
printf("%d %d\n", numbers[ptr[i]], colors[ptr[i]]);
}
Update: ok, it appears others have beaten me to this. No XP for me.
A: An example illustrating using a third index array. Not sure if this is the best implementation.
import java.util.*;
public class Sort {
private static void printTable(String caption, Integer[] numbers,
Integer[] colors, Integer[] sortOrder){
System.out.println(caption+
"\nNo Num Color"+
"\n----------------");
for(int i=0;i<sortOrder.length;i++){
System.out.printf("%x %d %d\n",
i,numbers[sortOrder[i]],colors[sortOrder[i]]);
}
}
public static void main(String[] args) {
final Integer[] numbers = {1,4,3,4,2,6};
final Integer[] colors = {0x50,0x34,0x00,0xfe,0xff,0xff};
Integer[] sortOrder = new Integer[numbers.length];
// Create index array.
for(int i=0; i<sortOrder.length; i++){
sortOrder[i] = i;
}
printTable("\nNot sorted",numbers, colors, sortOrder);
Arrays.sort(sortOrder,new Comparator<Integer>() {
public int compare(Integer a, Integer b){
return numbers[b]-numbers[a];
}});
printTable("\nSorted by numbers",numbers, colors, sortOrder);
Arrays.sort(sortOrder,new Comparator<Integer>() {
public int compare(Integer a, Integer b){
return colors[b]-colors[a];
}});
printTable("\nSorted by colors",numbers, colors, sortOrder);
}
}
The output should look like this:
Not sorted
No Num Color
----------------
0 1 80
1 4 52
2 3 0
3 4 254
4 2 255
5 6 255
Sorted by numbers
No Num Color
----------------
0 6 255
1 4 52
2 4 254
3 3 0
4 2 255
5 1 80
Sorted by colors
No Num Color
----------------
0 6 255
1 2 255
2 4 254
3 1 80
4 4 52
5 3 0
A: You could use sort() with a custom comparator if you kept a third array with the index, and sorted on that, leaving the data intact.
Java code example:
Integer[] idx = new Integer[numbers.length];
for( int i = 0 ; i < idx.length; i++ ) idx[i] = i;
Arrays.sort(idx, new Comparator<Integer>() {
public int compare(Integer i1, Integer i2) {
return Double.compare(numbers[i1], numbers[i2]);
}
});
// numbers[idx[i]] is the sorted number at index i
// colors[idx[i]] is the sorted color at index i
Note that you have to use Integer instead of int or you can't use a custom comparator.
A: One quick hack would be to combine the two arrays with bit shifts. Make an array of longs such that the most significant 32 bits is the number and the least significant 32 is the color. Use a sorting method and then unpack.
A: Would it suffice to code your own sort method? A simple bubblesort would probably be quick to code (and get right). No need for extra classes or comparators.
A: Credit to @tovare for the original best answer.
My answer below removes the (now) unnecessary autoboxing via Maven dependency {net.mintern : primitive : 1.2.2} from this answer: https://stackoverflow.com/a/27095994/257299
int[] idx = new int[numbers.length];
for( int i = 0 ; i < idx.length; i++ ) idx[i] = i;
final boolean isStableSort = false;
Primitive.sort(idx,
(i1, i2) -> Double.compare(numbers[i1], numbers[i2]),
isStableSort);
// numbers[idx[i]] is the sorted number at index i
// colors[idx[i]] is the sorted color at index i
A: I guess you want performance optimization while trying to avoid using array of objects (which can cause a painful GC event).
Unfortunately there's no general solution, thought.
But, for your specific case, in which numbers are different from each others, there might be two arrays to be created only.
/**
* work only for array of different numbers
*/
private void sortPairArray(int[] numbers, int[] colors) {
int[] tmpNumbers = Arrays.copyOf(numbers, numbers.length);
int[] tmpColors = Arrays.copyOf(colors, colors.length);
Arrays.sort(numbers);
for (int i = 0; i < tmpNumbers.length; i++) {
int number = tmpNumbers[i];
int index = Arrays.binarySearch(numbers, number); // surely this will be found
colors[index] = tmpColors[i];
}
}
Two sorted arrays can be replace by Int2IntOpenHashMap, which performs faster run, but memory usage could be double.
A: You need to sort the colors array by its relative item in the numbers array. Specify a comparator that compares numbers and use that as the comparison for the colors array.
A: The simplest way to do this in C, would be bubblesort + dual pointers. Ofcourse the fastest would be quicksort + two pointers. Ofcourse the 2nd pointer maintains the correlation between the two arrays.
I would rather define values that are stored in two arrays as a struct, and use the struct in a single array. Then use quicksort on it. you can write a generic version of sort, by calling a compare function, which can then be written for each struct, but then you already know that :)
A: Use a TreeMap
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/112234",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "25"
}
|
Q: Where can I get a list of what Crystal Reports features conflict? There are certain Crystal Reports features that cannot be combined in the same report, for example SQL command objects and server side grouping. However, as far as I can find, the built-in help doesn't seem to clearly document these conflicts. For example, checking the help page for either of those features doesn't mention that it doesn't work with the other. I want to be able to find out about these conflicts when I decide to use a new feature, not later when I go to use some other feature and the option is greyed out. Is there any place that documents these conflicts?
I am specifically working with Crystal Reports XI. Bonus points if the list of conflicts documents what range of versions each feature is available and conflicting in.
I have now also checked the release notes (release.pdf on install CD), and it does not have any answers to this question.
A: I have not found these anywhere, my suggestion is to create a test/dummy report, make something painfully simple that runs what your trying together.
This is of course no guarantee that is will work once you get all your real data in there. But I've upvoted your question, cause I'd like to see those doc's myself.
A:
For installation notes and details
regarding known issues with this
release, please refer to release.pdf
on the Crystal Reports CD.
How about the Known Issues list? Did you find anything there?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/112235",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Building a web search engine I've always been interested in developing a web search engine. What's a good place to start? I've heard of Lucene, but I'm not a big Java guy. Any other good resources or open source projects?
I understand it's a huge under-taking, but that's part of the appeal. I'm not looking to create the next Google, just something I can use to search a sub-set of sites that I might be interested in.
A: Xapian is another option for you. I've heard it scales better than some implementations of Lucene.
A: Check out nutch, it's written by the same guy that created Lucene (Doug Cutting).
A: There are several parts to a search engine. Broadly speaking, in a hopelessly general manner (folks, feel free to edit if you feel you can add better descriptions, links, etc):
*
*The crawler. This is the part that goes through the web, grabs the pages, and stores information about them into some central data store. In addition to the text itself, you will want things like the time you accessed it, etc. The crawler needs to be smart enough to know how often to hit certain domains, to obey the robots.txt convention, etc.
*The parser. This reads the data fetched by the crawler, parses it, saves whatever metadata it needs to, throws away junk, and possibly makes suggestions to the crawler on what to fetch next time around.
*The indexer. Reads the stuff the parser parsed, and creates inverted indexes into the terms found on the webpages. It can be as smart as you want it to be -- apply NLP techniques to make indexes of concepts, cross-link things, throw in synonyms, etc.
*The ranking engine. Given a few thousand URLs matching "apple", how do you decide which result is the best? Jut the index doesn't give you that information. You need to analyze the text, the linking structure, and whatever other pieces you want to look at, and create some scores. This may be done completely on the fly (that's really hard), or based on some pre-computed notions of "experts" (see PageRank, etc).
*The front end. Something needs to receive user queries, hit the central engine, and respond; this something needs to be smart about caching results, possibly mixing in results from other sources, etc. It has its own set of problems.
My advice -- choose which of these interests you the most, download Lucene or Xapian or any other open source project out there, pull out the bit that does one of the above tasks, and try to replace it. Hopefully, with something better :-).
Some links that may prove useful:
"Agile web-crawler", a paper from Estonia (in English)
Sphinx Search engine, an indexing and search api. Designed for large DBs, but modular and open-ended.
"Information Retrieval, a textbook about IR from Manning et al. Good overview of how the indexes are built, various issues that come up, as well as some discussion of crawling, etc. Free online version (for now)!
A: It seems to me that the biggest part is the indexing of sites. Making bots to scour the internet and parse their contents.
A friend and I were talking about how amazing Google and other search engines have to be under the hood. Millions of results in under half a second? Crazy. I think that they might have preset search results for commonly searched items.
edit:
This site looks rather interesting.
A: I would start with an existing project, such as the open source search engine from Wikia.
[My understanding is that the Wikia Search project has ended. However I think getting involved with an existing open-source project is a good way to ease into an undertaking of this size.]
http://re.search.wikia.com/about/get_involved.html
A: If you're interested in learning about the theory behind information retrieval and some of the technical details behind implementing search engines, I can recommend the book Managing Gigabytes by Ian Witten, Alistair Moffat and Tim C. Bell. (Disclosure: Alistair Moffat was my university supervisor.) Although it's a bit dated now (the first edition came out in 1994 and the second in 1999 -- what's so hard about managing gigabytes now?), the underlying theory is still sound and it's a great introduction to both indexing and the use of compression in indexing and retrieval systems.
A: I'm interested in Search Engine too. I recommended both Apache Hadoop MapReduce and Apache Lucene. Getting faster by Hadoop Cluster is the best way.
A: There are ports of Lucene. Zend have one freely available. Have a look at this quick tutorial: http://devzone.zend.com/node/view/id/91
A: Here's a slightly different approach, if you are not so much interested in the programming of it but more interested in the results: consider building it using Google Custom Search Engine API.
Advantages:
*
*Google does all the heavy lifting for you
*Familiar UI and behavior for your users
*Can have something up and running in minutes
*Lots of customization capabilities
Disadvantages:
*
*You're not writing code, so no learning opportunity there
*Everything you want to search must be public & in the Google index already
*Your result is tied to Google
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/112248",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "39"
}
|
Q: Update VERY LARGE PostgreSQL database table efficiently I have a very large database table in PostgresQL and a column like "copied". Every new row starts uncopied and will later be replicated to another thing by a background programm. There is an partial index on that table "btree(ID) WHERE replicated=0". The background programm does a select for at most 2000 entries (LIMIT 2000), works on them and then commits the changes in one transaction using 2000 prepared sql-commands.
Now the problem ist that I want to give the user an option to reset this replicated-value, make it all zero again.
An update table set replicated=0;
is not possible:
*
*It takes very much time
*It duplicates the size of the tabel because of MVCC
*It is done in one transaction: It either fails or goes through.
I actually don't need transaction-features for this case: If the system goes down, it shall process only parts of it.
Several other problems:
Doing an
update set replicated=0 where id >10000 and id<20000
is also bad: It does a sequential scan all over the whole table which is too slow.
If it weren't doing that, it would still be slow because it would be too many seeks.
What I really need is a way of going through all rows, changing them and not being bound to a giant transaction.
Strangely, an
UPDATE table
SET replicated=0
WHERE ID in (SELECT id from table WHERE replicated= LIMIT 10000)
is also slow, although it should be a good thing: Go through the table in DISK-order...
(Note that in that case there was also an index that covered this)
(An update LIMIT like Mysql is unavailable for PostgresQL)
BTW: The real problem is more complicated and we're talking about an embedded system here that is already deployed, so remote schema changes are difficult, but possible
It's PostgresQL 7.4 unfortunately.
The amount of rows I'm talking about is e.g. 90000000. The size of the databse can be several dozend gigabytes.
The database itself only contains 5 tables, one is a very large one.
But that is not bad design, because these embedded boxes only operate with one kind of entity, it's not an ERP-system or something like that!
Any ideas?
A: How about adding a new table to store this replicated value (and a primary key to link each record to the main table). Then you simply add a record for every replicated item, and delete records to remove the replicated flag. (Or maybe the other way around - a record for every non-replicated record, depending on which is the common case).
That would also simplify the case when you want to set them all back to 0, as you can just truncate the table (which zeroes the table size on disk, you don't even have to vacuum to free up the space)
A: If you are trying to reset the whole table, not just a few rows, it is usually faster (on extremely large datasets -- not on regular tables) to simply CREATE TABLE bar AS SELECT everything, but, copied, 0 FROM foo, and then swap the tables and drop the old one. Obviously you would need to ensure nothing gets inserted into the original table while you are doing that. You'll need to recreate that index, too.
Edit: A simple improvement in order to avoid locking the table while you copy 14 Gigabytes:
lock ;
create a new table, bar;
swap tables so that all writes go to bar;
unlock;
create table baz as select from foo;
drop foo;
create the index on baz;
lock;
insert into baz from bar;
swap tables;
unlock;
drop bar;
(let writes happen while you are doing the copy, and insert them post-factum).
A: While you cannot likely fix the problem of space usage (it is temporary, just until a vacuum) you can probably really speed up the process in terms of clock time. The fact that PostgreSQL uses MVCC means that you should be able to do this without any issues related to newly inserted rows. The create table as select will get around some of the performance issues, but will not allow for continued use of the table, and takes just as much space. Just ditch the index, and rebuild it, then do a vacuum.
drop index replication_flag;
update big_table set replicated=0;
create index replication_flag on big_table btree(ID) WHERE replicated=0;
vacuum full analyze big_table;
A: This is pseudocode. You'll need 400MB (for ints) or 800MB (for bigints) temporary file (you can compress it with zlib if it is a problem). It will need about 100 scans of a table for vacuums. But it will not bloat a table more than 1% (at most 1000000 dead rows at any time). You can also trade less scans for more table bloat.
// write all ids to temporary file in disk order
// no where clause will ensure disk order
$file = tmpfile();
for $id, $replicated in query("select id, replicated from table") {
if ( $replicated<>0 ) {
write($file,&$id,sizeof($id));
}
}
// prepare an update query
query("prepare set_replicated_0(bigint) as
update table set replicated=0 where id=?");
// reread this file, launch prepared query and every 1000000 updates commit
// and vacuum a table
rewind($file);
$counter = 0;
query("start transaction");
while read($file,&$id,sizeof($id)) {
query("execute set_replicated_0($id)");
$counter++;
if ( $counter % 1000000 == 0 ) {
query("commit");
query("vacuum table");
query("start transaction");
}
}
query("commit");
query("vacuum table");
close($file);
A: I think it's better to change your postgres to version 8.X. probably the cause is the low version of Postgres. Also try this query below. I hope this can help.
UPDATE table1 SET name = table2.value
FROM table2
WHERE table1.id = table2.id;
A: I guess what you need to do is
a. copy the 2000 records PK value into a temporary table with the same standard limit, etc.
b. select the same 2000 records and perform the necessary operations in the cursor as it is.
c. If successful, run a single update query against the records in the temp table. Clear the temp table and run step a again.
d. If unsuccessful, clear the temp table without running the update query.
Simple, efficient and reliable.
Regards,
KT
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/112249",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
}
|
Q: How to auto-focus RTE editor inside firefox? We have a RTE editor based on htmlarea which consists of content with editmode enabled inside an iframe. The question is how to automatically bring the focus into the editor?
A: Where the id of the IFRAME is myRTE:
var iframe = document.getElementById("myRTE");
if ( iframe && iframe.contentWindow )
iframe.contentWindow.focus();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/112261",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do I overlap widgets with the Tkinter pack geometry manager? I want to put a Canvas with an image in my window, and then I want to pack widgets on top of it, so the Canvas acts as a background.
Is it possible to have two states for the pack manager: one for one set of widgets and another for another set?
A: The answer to your specific question is no. You can't have two states or otherwise use pack two different ways in the same parent.
However, what I think you want to accomplish is simple. Use the built-in features of the canvas to create an image item that is part of the canvas, then pack things into the canvas as if it were a frame.
You can accomplish a similar thing by creating a label widget with an image, then pack your other widgets into the label.
One advantage to using a canvas is you can easily tile an image to fill the whole canvas with a repeating background image so as the window grows the image will continue to fill the window (of course you can just use a sufficiently large original image...)
A: I believe that Bryan's answer is probably the best general solution. However, you may also want to look at the place geometry manager. The place geometry manager lets you specify the exact size and position of the widget... which can get tedious quickly, but will get the job done.
A:
... turned out to be unworkable because I wanted to add labels and more canvases to it, but I can't find any way to make their backgrounds transparent
If it is acceptable to load an additional extension, take a look at Tkzinc. From the web site,
Tkzinc (historically called Zinc) widget is very similar to the Tk Canvas in that they both support structured graphics. Like the Canvas, Tkzinc implements items used to display graphical entities. Those items can be manipulated and bindings can be associated with them to implement interaction behaviors. But unlike the Canvas, Tkzinc can structure the items in a hierarchy, has support for scaling and rotation, clipping can be set for sub-trees of the item hierarchy, supports muti-contour curves. It also provides advanced rendering with the help of OpenGL, such as color gradient, antialiasing, transparencies and a triangles item.
I'm currently using it on a tcl project and am quite pleased with the results. Extensions for tcl, perl, and python are available.
A: Not without swapping widget trees in and out, which I don't think can be done cleanly with Tk. Other toolkits can do this a little more elegantly.
*
*COM/VB/MFC can do this with an ActiveX control - you can hide/show multiple ActiveX controls in the same region. Any of the containers will let you do this by changing the child around. If you're doing a windows-specific program you may be able to accomplish it this way.
*QT will also let you do this in a similar manner.
*GTK is slightly harder.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/112263",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Directory Modification Monitoring I'm building a C# application that will monitor a specified directory for changes and additions and storing the information in a database.
I would like to avoid checking each individual file for modifications, but I'm not sure if I can completely trust the file access time.
What would be the best method to use for getting recently modified files in a directory?
It would check for modifications only when the user asks it to, it will not be a constantly running service.
A: Use the FileSystemWatcher object. Here is some code to do what you are looking for.
// Declares the FileSystemWatcher object
FileSystemWatcher watcher = new FileSystemWatcher();
// We have to specify the path which has to monitor
watcher.Path = @"\\somefilepath";
// This property specifies which are the events to be monitored
watcher.NotifyFilter = NotifyFilters.LastAccess |
NotifyFilters.LastWrite | NotifyFilters.FileName | notifyFilters.DirectoryName;
watcher.Filter = "*.*"; // Only watch text files.
// Add event handlers for specific change events...
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.Created += new FileSystemEventHandler(OnChanged);
watcher.Deleted += new FileSystemEventHandler(OnChanged);
watcher.Renamed += new RenamedEventHandler(OnRenamed);
// Begin watching.
watcher.EnableRaisingEvents = true;
// Define the event handlers.
private static void OnChanged(object source, FileSystemEventArgs e)
{
// Specify what is done when a file is changed, created, or deleted.
}
private static void OnRenamed(object source, RenamedEventArgs e)
{
// Specify what is done when a file is renamed.
}
A: I think what you want is provided by the FileSystemWatcher class.
This tutorial describes how to use it to monitor a directory for changes in a simple windows service; How to implement a simple filewatcher Windows service in C#
A: Hmm... interesting question. Initially I'd point you at the FileSystemWatcher class. If you are going to have it work, however, on user request, then it would seem you might need to store off the directory info initially and then compare each time the user requests. I'd probably go with a FileSystemWatcher and just store off your results anyhow.
A: If you only need it to check when the user asks rather then all the time, don't use the FileSystemWatcher. Especially if it's a shared resource - the last thing you want is 50 client machines watching the same shared directory.
It's probably just a typo, but you shouldn't be looking at the file access time, you want to look at the file modification time to pick up changes. Even that's not reliable.
What I would do is implement some sort of checksum function on the file date and byte size, or other file system properties. That way I wouldn't be looking for changes in the complete file - only the properties of it and I can do it on request, rather than trying to hold a connection to a remote resource to monitor it.
A heavier solution would be to do it the other way around, and install a service on the machine hosting the shared drive which could monitor the files and make note of the changes. Then you could query the service rather than touching the files at all - but it's probably overkill.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/112276",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Best introduction to C++ template metaprogramming? Static metaprogramming (aka "template metaprogramming") is a great C++ technique that allows the execution of programs at compile-time. A light bulb went off in my head as soon as I read this canonical metaprogramming example:
#include <iostream>
using namespace std;
template< int n >
struct factorial { enum { ret = factorial< n - 1 >::ret * n }; };
template<>
struct factorial< 0 > { enum { ret = 1 }; };
int main() {
cout << "7! = " << factorial< 7 >::ret << endl; // 5040
return 0;
}
If one wants to learn more about C++ static metaprogramming, what are the best sources (books, websites, on-line courseware, whatever)?
A: Two good books that spring to mind are:
*
*Modern C++ Design / Andrei Alexandrescu (It's actually 7 years old despite the name!)
*C++ Templates: The Complete Guide / Vandevoorde & Josuttis
It's quite an in-depth field, so a good book like one of these is definitely recommended over websites. Some of the more advanced techniques will have you studying the code for some time to figure out how they work!
A: Modern C++ is one of the best introductions I've read. It covers actual useful examples of template metaprogramming. Also take a look at the companion library Loki.
A: There won't be a large list of books, as the list of people with a lot of experience is limited. Template metaprogramming started for real around the first C++ Template Programming Workshop in 2000, and many of the authors named so far attended. (IIRC, Andrei didn't.) These pioneers greatly influenced the field, and basically what should be written is now written. Personally, I'd advice Vandevoorde & Josuttis. Alexandrescu's is a tough book if you're new to the field.
A: google Alexandrescu, Modern C++ Design: Generic Programming and Design Patterns Applied
A: Veldhuizen's original papers were good. If you up for a whole book, then there's Vandevoorde's book "C++ Templates Complete Guide". And when you're ready for the master's course, try Alexandrescu's Modern C++ Design.
A: Andrei Alexandrescu's Modern C++ Design book covers a lot of this and other tricks for speedy and efficient modern C++ code and is the basis for the Loki library.
Also worth mentioning is the Boost libraries, which heavily use these techniques and are usually of very high quality to learn from (although some are quite dense).
A: Modern C++ Design, a brilliant book and design pattern framework by Alexandrescu. Word of warning, after reading this book I stopped doing C++ and thought "What the heck, I can just pick a better language and get it for free".
A: [Answering my own question]
The best introductions I've found so far are chapter 10, "Static Metaprogramming in C++" from Generative Programming, Methods, Tools, and Applications by Krzysztof Czarnecki and Ulrich W. Eisenecker, ISBN-13: 9780201309775; and chapter 17, "Metaprograms" of C++ Templates: The Complete Guide by David Vandevoorder and Nicolai M. Josuttis, ISBN-13: 9780201734843.
Todd Veldhuizen has an excellent tutorial here.
A good resource for C++ programming in general is Modern C++ Design by Andrei Alexandrescu, ISBN-13: 9780201704310. This book mixes a bit of metaprogramming with other template techniques. For metaprogramming in particular, see sections 2.1 "Compile-Time Assertions", 2.4 "Mapping Integral Constants to Types", 2.6 "Type Selection", 2.7 "Detecting Convertibility and Inheritance at Compile Time", 2.9 "NullType and EmptyType" and 2.10 "Type Traits".
The best intermediate/advanced resource I've found is C++ Template Metaprogramming by David Abrahams and Aleksey Gurtovoy, ISBN-13: 9780321227256
If you'd prefer just one book, get C++ Templates: The Complete Guide since it is also the definitive reference for templates in general.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/112277",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "121"
}
|
Q: SharePoint 2007 performance issues I don't expect a straightforward silver bullet answer to this, but what are the best practices for ensuring good performance for SharePoint 2007 sites?
We've a few sites for our intranet, and it generally is thought to run slow. There's plenty of memory and processor power in the servers, but the pages just don't 'snap' like you'd expect from a web site running on powerful servers.
We've done what we can to tweak setup, but is there anything we could be missing?
A: There is a known issue with initial requests once an IIS application pool has unloaded the SharePoint resources or recycled itself where the spin-up on a new request is very slow.
Details about why that happens and how to fix it can be found here; SharePoint 2007 Quirks - Solving painfully slow spin-up times
A: Andrew Connell's latest book (Professional SharePoint 2007 Web Content Management Development) has an entire chapter dedicated to imporving performance of SharePoint sites.
Key topics it covers are Caching, Limiting page load (particularly how to remove CORE.js if it's not needed), working with Disposable objects and how to work with SharePoint querying.
2 really good tricks I've got are to use the CSS Freindly Control Adapters to generate smaller HTML for the common components (menus, etc) and setting up a server "wake up", so when IIS sleeps the app-pool due to inactivity you can reawaken it before someone hits your site.
A: Microsoft has released a white paper on this very issue.
How Microsoft IT Increases
Availability and Decreases Rendering
Time of SharePoint Sites Technical
White Paper Published: September 2008
Download it from here.
A: SharePoint has a lot of limitations that contribute to low performance problems we may call them performance bottlenecks. The SharePoint performance problems occur primarily due to the following reasons:
*
*BLOBs overwhelm SQL Server
*Too many database trips for lists
You can dramatically improve SharePoint performance if you use a few of intelligent techniques which are:
*
*Externalize Documents (BLOBs)
*Cache Lists and BLOBs
Microsoft Office SharePoint Server (MOSS) is an extremely popular product that improves effectiveness of organizations through content management and enterprise search, shared business processes, and information-sharing across boundaries for better business insight. And StorageEdge is an extremely fine product that enhance/improve SharePoint performance.
By using StorageEdge SharePoint's performance can easily be enhanced.
A: Just a few ideas...
Is displaying your pages as slow when doing it from the Server or from a Client? If slower from client, do check your network.
Are your pages very "heavy"? (means, many elements, web parts and so on?) Than maybe it's normal.
Have you noticed they load slowlier since you've add one specific web part? Maybe there's some issues with that specific web part (for example, it's accessing to a document library that has many -thousands of- documents). If that's the case, try to deactivate that specific web part and see if the performance works better.
A: I noticed that Sharepoint loves to add a ton of JavaScript. If you run a Browser with slow JavaScript (say, Internet Explorer), i notice that it sometimes does not "feel" fast.
Also, if you are running custom code on it: Make sure to dispose your SPWebs after use, that can up a lot!
A: Are you running on virtual or physical servers? We found that it is significantly faster on physical servers. Also, check the disk performance - if you are running the servers from a SAN it might be a sign that your SAN is over utilised.
A: To investigate SharePoint performance issues, I would try these things first, in that order:
*
*Run SQL profiler for those non-performing pages. SharePoint API excels at hiding what's going on behind the scenes in respect to database roundtrips. There are single API calls that, without the knowledge of the developer, generate many roundtrips, which hurt performance.
*Profile w3wp.exe process serving your SharePoint site. That's going to tell you relative API usage. Focus on ticks, no time, and do a top-down inclusive time analysis to see which calls are taking up most of the time. See here for instructions.
*Run Fiddler or Microsoft NetMon to spot potential excessive client roundtrips (i.e. between browser and web front end server) and redirections (301's).
A: The three main major components of SharePoint setup is SharePoint Server (the one which runs WSS/SPS services), SQL Server DB and IIS.
You said you have decent power for your SharePoint services and I assume IIS would definitely be on a good machine.
Usually SQL Server setup that hosts the SP related DBs that would slow down the page loads. I would want you to take a look at your whole SQL Server related performance counters and you might want to tune these DBs too (which includes OS Server/Stored Procedures/Network, etc)
Hope this adds to your checklist of things you want to take a look at.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/112318",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Is static metaprogramming possible in Java? I am a fan of static metaprogramming in C++. I know Java now has generics. Does this mean that static metaprogramming (i.e., compile-time program execution) is possible in Java? If so, can anyone recommend any good resources where one can learn more about it?
A: What do you exactly mean by "static metaprogramming"? Yes, C++ template metaprogramming is impossible in Java, but it offers other methods, much more powerful than those from C++:
*
*reflection
*aspect-oriented programming (@AspectJ)
*bytecode manipulation (Javassist, ObjectWeb ASM, Java agents)
*code generation (Annotation Processing Tool, template engines like Velocity)
*Abstract Syntax Tree manipulations (APIs provided by popular IDEs)
*possibility to run Java compiler and use compiled code even at runtime
There's no best method: each of those methods has its strengths and weaknesses.
Due to flexibility of JVM, all of those methods in Java can be used both at compilation time and runtime.
A: No. Even more, generic types are erased to their upper bound by the compiler, so you cannot create a new instance of a generic type T at runtime.
The best way to do metaprogamming in Java is to circumvent the type erasure and hand in the Class<T> object of your type T. Still, this is only a hack.
A: No, this is not possible. Generics are not as powerful as templates. For instance, a template argument can be a user-defined type, a primitive type, or a value; but a generic template argument can only be Object or a subtype thereof.
Edit: This is an old answer; since 2011 we have Java 7, which has Annotations that can be used for such trickery.
A: If you need powerful compile-time logic for Java, one way to do that is with some kind of code generation. Since, as other posters have pointed out, the Java language doesn't provide any features suitable for doing compile-time logic, this may be your best option (iff you really do have a need for compile-time logic). Once you have exhausted the other possibilities and you are sure you want to do code-generation, you might be interested in my open source project Rjava, available at:
http://www.github.com/blak3mill3r
It is a Java code generation library written in Ruby, which I wrote in order to generate Google Web Toolkit interfaces for Ruby on Rails applications automatically. It has proved quite handy for that.
As a warning, it can be very difficult to debug Rjava code, Rjava doesn't do much checking, it just assumes you know what you're doing. That's pretty much the state of static metaprogramming anyway. I'd say it's significantly easier to debug than anything non-trivial done with C++ TMP, and it is possible to use it for the same kinds of things.
Anyway, if you were considering writing a program which outputs Java source code, stop right now and check out Rjava. It might not do what you want yet, but it's MIT licensed, so feel free to improve it, deep fry it, or sell it to your grandma. I'd be glad to have other devs who are experienced with generic programming to comment on the design.
A: Lombok offers a weak form of compile time metaprogramming. However, the technique they use is completely general.
See Java code transform at compile time for a related discussion
A: You can use a metaprogramming library for Java such as Spoon: https://github.com/INRIA/spoon/
A: Take a look at Clojure. It's a LISP with Macros (meta-programming) that runs on the JVM and is very interoperable with Java.
A: The short answer
This question is nearly more than 10 years old, but I am still missing one answer to this. And this is: yes, but not because of generics and note quite the same as C++.
As of Java 6, we have the pluggable annotation processing api. Static metaprogramming is (as you already stated in your question)
compile-time program execution
If you know about metaprogramming, then you also know that this is not really true, but for the sake of simplicity, we will use this. Please look here if you want to learn more about metaprogramming in general.
The pluggable annotation processing api is called by the compiler, right after the .java files are read but before the compiler writes the byte-code to the .class files. (I had one source for this, but i cannot find it anymore.. maybe someone can help me out here?).
It allows you, to do logic at compile time with pure java-code. However, the world you are coding in is quite different. Not specifically bad or anything, just different. The classes you are analyzing do not yet exist and you are working on meta data of the classes. But the compiler is run in a JVM, which means you can also create classes and program normally. But furthermore, you can analyze generics, because our annotation processor is called before type erasure.
The main gist about static metaprogramming in java is, that you provide meta-data (in form of annotations) and the processor will be able to find all annotated classes to process them. On (more easy) example can be found on Baeldung, where an easy example is formed. In my opinion, this is quite a good source for getting started. If you understand this, try to google yourself. There are multiple good sources out there, to much to list here. Also take a look at Google AutoService, which utilizes an annotation processor, to take away your hassle of creating and maintaining the service files. If you want to create classes, i recommend looking at JavaPoet.
Sadly though, this API does not allow us, to manipulate source code. But if you really want to, you should take a look at Project Lombok. They do it, but it is not supported.
Why is this important (Further reading for the interested ones among you)
TL;DR: It is quite baffling to me, why we don't use static metaprogramming as much as dynamic, because it has many many advantages.
Most developers see "Dynamic and Static" and immediately jump to the conclusion that dynamic is better. Nothing wrong with that, static has a lot of negative connotations for developers. But in this case (and specifically for java) this is the exact other way around.
Dynamic metaprogramming requires reflections, which has some major drawbacks. There are quite a lot of them. In short: Performance, Security, and Design.
Static metaprogramming (i.e. Annotation Processing) allows us to intersect the compiler, which already does most of the things we try to accomplish with reflections. We can also create classes in this process, which are again passed to the annotation processors. You then can (for example) generate classes, which do what normally had to be done using reflections. Further more, we can implement a "fail fast" system, because we can inform the compiler about errors, warnings and such.
To conclude and compare as much as possible: let us imagine Spring. Spring tries to find all Component annotated classes at runtime (which we could simplify by using service files at compile time), then generates certain proxy classes (which we already could have done at compile time) and resolves bean dependencies (which, again, we already could have done at compile time). Jake Whartons talk about Dagger2, in which he explains why they switched to static metaprogramming. I still don't understand why the big players like Spring don't use it.
This post is to short to fully explain those differences and why static would be more powerful. If you want, i am currently working on a presentation for this. If you are interested and speak German (sorry about that), you can have a look at my website. There you find a presentation, which tries to explain the differences in 45 minutes. Only the slides though.
A: No, generics in Java is purely a way to avoid casting of Object.
A: In a very reduced sense, maybe?
http://michid.wordpress.com/2008/08/13/type-safe-builder-pattern-in-java/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/112320",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "40"
}
|
Q: .NET - Can you over interface, and when shouldn't you interface Is it possible to over interface? when designing an system now, I will start from interfaces and progressively write unit tests along with the interfaces until I have a pattern that works well.. I'll move onto writing some concrete classes and set the unit tests up against these..
Now I'm someone who loves interfaces, I will generally end up only ever passing/returning primatives or interfaces around when I control the code.. so far I've found this to be ideal, you can easily adapt and enhance a system generally without impacting the dependent systems.
I obviously don't need to sell the reasons for using interfaces, but im wondering if its overboard to interface everything, ps. I'm not talking about blank interfaces as in something crazy like:
interface IStringCollection : ICollection<string>
{
}
I'm talking more something like:
interface ISomethingProvider
{
ISomething Provide(ISomethingOptions options);
}
Is this really over the top? my reasoning is that any type could gain from interfacing at some point.. and the only real problem I've had is that I've had to learn what I think is a better way to design classes, as you don't have daft interactions and 'hacks' going on.
Would love your feedback about if this is a timebomb, and when you decide to interface vs not..
ps- this isn't really so much about how to write interfaces.
A: Interfaces describe a contract for behavior. If you need to address some set of objects according to a behavioral pattern, interfaces are useful, not so much if you're simply describing the structure of objects. I think you need to have a good reason to use them, such as using a factory that creates behaviorally related objects or establishing a behavioral contract for part of a library. Using interfaces aimlessly can make a library difficult to read / understand / maintain.
A: In short yes it is possible to over interface a project. Take into account when the situation really calls for an Abstract Base Class and an interface, while they both are similar there are distinct advantages to using both See Here. Typically I've noticed that people use Interfaces when they really should be using Abstract Base Classes. From a OO perspective interfaces should be used to list common behavior that may span vastly different classes. For example you may have an IMove interface with a method called Move(). Now imagine you have an Airplane, Car, Person, and Insect class. Airplane and Car may inherit from an abstract Vehicle class but still need to use IMove and so will Insect and Person but they will all implement move differently. I've noticed, my self included, people tend to use Interfaces to "group" classes together when really that should be handled by a base class.
A: As with anything else - use with moderation and where necessary. Ask yourself "Are you gonna need it?".
A: It is possible to over-interface. The rule where I work is that if you have an interface in your application, you need to have at least two classes that implement it (or have a reasonable expectation that you will be adding implementing classes in the near future).
If you need to create mock objects for testing, then having the mock class and the real class implement a common interface is a valid reason to use an interface.
I would not recommend automatically using interfaces for everything in your application, especially because a single class can usually be easily refactored into an interface if necessary.
A: Whenever I see or hear someone say this
Interfaces describe a contract for behavior
I know I've found someone who doesn't understand interfaces.
Interfaces cannot do that. It is impossible. Interfaces do not prescribe, force, or in any way constrain behaviour.
Interfaces describe a contract for an interface, hence the name. They do not have behaviour.
You might hope that the names you give your interface's methods will imply a required behaviour to anyone implementing it, but there is no requirement that they do so. There is no behavioural contract, nor can there ever be one.
If you require a certain type of behaviour then you must use classes to enforce it (eg with the Template pattern) - that's where all the behaviour is.
Interfaces are regularly abused as a design construct, and one of the reasons is because of widespread belief in this fallacy.
A: It can be a real pain to work out the eventual call stack before you step with the debugger if you have interfaces everywhere. I tend to prefer interfaces only when:
*
*you need team members to agree on who should do what before they start coding - an interface then documents the border exactly
*when you actually need an interface to solve the problem, so at least two implementations that don't extend each other
*You expect case 2
A: I find that interfaces complicates the design, especially for other people to cowork on your stuff. Don't get me wrong, interfaces are great for a lot of stuff, but mostly if you want two or more classes to share a common interface.
If you find yourself in the situation where you suddenly need an interface, refactoring with tools like Resharper is a breeze :)
A: This isn't solely a .NET thing, the same problem occurs in Java quite often.
Unless it's a completely obvious requirement, I vote for not using interfaces and simply refactoring when the need becomes clear.
The pragmatic approach says to just do the simplest thing that could possibly work, and don't get caught in architecture astronautics.
A: I tend to not use too many interfaces for testing purposes. I would rather make a private value public and/or unsealing classes and/or temp methods while building and testing until I am at the point where I have built other objects and tests that will eventually exercise what it was that i needed. Sometmes its a pain in the butt to rack your changes that way but your tests will tell you when you forgot to change something.
A: ISwissArmyKnife!
Consult this:
http://thedailywtf.com/Articles/Classic-WTF-Implements-ISwissArmyKnife.aspx
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/112372",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: How do I remove the passphrase for the SSH key without having to create a new key? I set a passphrase when creating a new SSH key on my laptop. But, as I realise now, this is quite painful when you are trying to commit (Git and SVN) to a remote location over SSH many times in an hour.
One way I can think of is, delete my SSH keys and create new. Is there a way to remove the passphrase, while still keeping the same keys?
A: On windows, you can use PuttyGen to load the private key file, remove the passphrase and then overwrite the existing private key file.
A: In windows for me it kept saying
"id_ed25135: No such file or directory" upon entering above commands. So I went to the folder, copied the path within folder explorer and added "\id_ed25135" at the end.
This is what I ended up typing and worked:
ssh-keygen -p -f C:\Users\john\.ssh\id_ed25135
This worked. Because for some reason, in Cmder the default path was something like this C:\Users\capit/.ssh/id_ed25135 (some were backslashes: "\" and some were forward slashes: "/")
A: You might want to add the following to your .bash_profile (or equivalent), which starts ssh-agent on login.
if [ -f ~/.agent.env ] ; then
. ~/.agent.env > /dev/null
if ! kill -0 $SSH_AGENT_PID > /dev/null 2>&1; then
echo "Stale agent file found. Spawning new agent… "
eval `ssh-agent | tee ~/.agent.env`
ssh-add
fi
else
echo "Starting ssh-agent"
eval `ssh-agent | tee ~/.agent.env`
ssh-add
fi
On some Linux distros (Ubuntu, Debian) you can use:
ssh-copy-id -i ~/.ssh/id_dsa.pub username@host
This will copy the generated id to a remote machine and add it to the remote keychain.
You can read more here and here.
A: Short answer:
$ ssh-keygen -p
This will then prompt you to enter the keyfile location, the old passphrase, and the new passphrase (which can be left blank to have no passphrase).
If you would like to do it all on one line without prompts do:
$ ssh-keygen -p [-P old_passphrase] [-N new_passphrase] [-f keyfile]
Important: Beware that when executing commands they will typically be logged in your ~/.bash_history file (or similar) in plain text including all arguments provided (i.e. the passphrases in this case). It is, therefore, is recommended that you use the first option unless you have a specific reason to do otherwise.
Notice though that you can still use -f keyfile without having to specify -P nor -N, and that the keyfile defaults to ~/.ssh/id_rsa, so in many cases, it's not even needed.
You might want to consider using ssh-agent, which can cache the passphrase for a time. The latest versions of gpg-agent also support the protocol that is used by ssh-agent.
A: To change or remove the passphrase, I often find it simplest to pass in only the p and f flags, then let the system prompt me to supply the passphrases:
ssh-keygen -p -f <name-of-private-key>
For instance:
ssh-keygen -p -f id_rsa
Enter an empty password if you want to remove the passphrase.
A sample run to remove or change a password looks something like this:
ssh-keygen -p -f id_rsa
Enter old passphrase:
Key has comment 'bcuser@pl1909'
Enter new passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved with the new passphrase.
When adding a passphrase to a key that has no passphrase, the run looks something like this:
ssh-keygen -p -f id_rsa
Key has comment 'charlie@elf-path'
Enter new passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved with the new passphrase.
A: On the Mac you can store the passphrase for your private ssh key in your Keychain, which makes the use of it transparent. If you're logged in, it is available, when you are logged out your root user cannot use it. Removing the passphrase is a bad idea because anyone with the file can use it.
ssh-keygen -K
Add this to ~/.ssh/config
UseKeychain yes
A: $ ssh-keygen -p worked for me
Opened git bash. Pasted : $ ssh-keygen -p
Hit enter for default location.
Enter old passphrase
Enter new passphrase - BLANK
Confirm new passphrase - BLANK
BOOM the pain of entering passphrase for git push was gone.
Thanks!
A: If you have set a passphrase before and is using mac, use the keychain instead, you'll need to enter your passpharase for the last time and that's it
ssh-add --apple-use-keychain ~/.ssh/id_rsa
Enter passphrase for /Users/{{user_name}}/.ssh/id_rsa:
Identity added: /Users/{{user_name}}/.ssh/id_rsa(/Users/{{user_name}}/.ssh/id_rsa)
A: If you are using Mac
*
*Go to .ssh folder
*update config file by adding "UseKeychain yes"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/112396",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1472"
}
|
Q: How does replication in team foundation server work We have two offices in different states and issues with performance when using integrated source control over the WAN. We were contemplating using replication in TFS to allow both office to have fast and robust connectivity. We need to understand network load, speed of access, how conflicts are managed.
A: TFS has a proxy server which should help to aleviate the performance issues.
EDIT: Although i have never used it personally, the docs state that is exactly what it is for
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/112411",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Using Visual Studio 2008 to Assemble, Link, Debug, and Execute MASM 6.11 Assembly Code I would like to use Visual Studio 2008 to the greatest extent possible while effectively compiling/linking/building/etc code as if all these build processes were being done by the tools provided with MASM 6.11. The exact version of MASM does not matter, so long as it's within the 6.x range, as that is what my college is using to teach 16-bit assembly.
I have done some research on the subject and have come to the conclusion that there are several options:
*
*Reconfigure VS to call the MASM 6.11 executables with the same flags, etc as MASM 6.11 would natively do.
*Create intermediary batch file(s) to be called by VS to then invoke the proper commands for MASM's linker, etc.
*Reconfigure VS's built-in build tools/rules (assembler, linker, etc) to provide an environment identical to the one used by MASM 6.11.
Option (2) was brought up when I realized that the options available in VS's "External Tools" interface may be insufficient to correctly invoke MASM's build tools, thus a batch file to interpret VS's strict method of passing arguments might be helpful, as a lot of my learning about how to get this working involved my manually calling ML.exe, LINK.exe, etc from the command prompt.
Below are several links that may prove useful in answering my question. Please keep in mind that I have read them all and none are the actual solution. I can only hope my specifying MASM 6.11 doesn't prevent anyone from contributing a perhaps more generalized answer.
Similar method used to Option (2), but users on the thread are not contactable:
http://www.codeguru.com/forum/archive/index.php/t-284051.html
(also, I have my doubts about the necessity of an intermediary batch file)
Out of date explanation to my question:
http://www.cs.fiu.edu/~downeyt/cop3402/masmaul.html
Probably the closest thing I've come to a definitive solution, but refers to a suite of tools from something besides MASM, also uses a batch file:
http://www.kipirvine.com/asm/gettingStarted/index.htm#16-bit
I apologize if my terminology for the tools used in each step of the code -> exe process is off, but since I'm trying to reproduce the entirety of steps in between completion of writing the code and generating an executable, I don't think it matters much.
A: There is a MASM rules file located at (32-bit system remove (x86)):
C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\VCProjectDefaults\masm.rules
Copy that file to your project directory, and add it to the Custom Build Rules for your project. Then "Modify Rule File...", select the MASM build rule and "Modify Build Rule...".
Add a property:
*
*User property type: String
*Default value: *.inc
*Description: Add additional MASM file dependencies.
*Display name: Additional Dependencies
*Is read only: False
*Name: AdditionalDependencies
*Property page name: General
*Switch: [value]
Set the Additional Dependencies value to [AdditionalDependencies]. The build should now automatically detect changes to *.inc, and you can edit the properties for an individual asm file to specify others.
A: You can create a makefile project. In Visual Studio, under File / New / Project, choose Visual C++ / Makefile project.
This allows you to run an arbitrary command to build your project. It doesn't have to be C/C++. It doesn't even have to be a traditional NMake makefile. I've used it to compile a driver using a batch file, and using a NAnt script.
It should be fairly easy to get it to run the MASM 6.x toolchain.
A: I would suggest to define Custom Build rules depending on file extension.
(Visual Studio 2008, at least in Professinal Edition, can generate .rules files, which can be distributed). There you can define custom build tools for asm files. By using this approach, you should be able to leave the linker step as is.
Way back, we used MASM32 link text as IDE to help students learn assembly. You could check their batchfiles what they do to assemble and link.
A: instead of batch files, why not use the a custom build step defined on the file?
A: If you are going to use Visual Studio, couldn't you give them a skeleton project in C/C++ with the entry point for a console app calling a function that has en empty inline assembly block, and let them fill their results in it?
A: Why don't you use Irvine's guide? Irvine's library is nice and if you want, you can ignore it and work with Windows procs directly. I've searching for a guide like this, Irvine's was the best solution.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/112412",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Should I use #define, enum or const? In a C++ project I'm working on, I have a flag kind of value which can have four values. Those four flags can be combined. Flags describe the records in database and can be:
*
*new record
*deleted record
*modified record
*existing record
Now, for each record I wish to keep this attribute, so I could use an enum:
enum { xNew, xDeleted, xModified, xExisting }
However, in other places in code, I need to select which records are to be visible to the user, so I'd like to be able to pass that as a single parameter, like:
showRecords(xNew | xDeleted);
So, it seems I have three possible appoaches:
#define X_NEW 0x01
#define X_DELETED 0x02
#define X_MODIFIED 0x04
#define X_EXISTING 0x08
or
typedef enum { xNew = 1, xDeleted, xModified = 4, xExisting = 8 } RecordType;
or
namespace RecordType {
static const uint8 xNew = 1;
static const uint8 xDeleted = 2;
static const uint8 xModified = 4;
static const uint8 xExisting = 8;
}
Space requirements are important (byte vs int) but not crucial. With defines I lose type safety, and with enum I lose some space (integers) and probably have to cast when I want to do a bitwise operation. With const I think I also lose type safety since a random uint8 could get in by mistake.
Is there some other cleaner way?
If not, what would you use and why?
P.S. The rest of the code is rather clean modern C++ without #defines, and I have used namespaces and templates in few spaces, so those aren't out of question either.
A: Combine the strategies to reduce the disadvantages of a single approach. I work in embedded systems so the following solution is based on the fact that integer and bitwise operators are fast, low memory & low in flash usage.
Place the enum in a namespace to prevent the constants from polluting the global namespace.
namespace RecordType {
An enum declares and defines a compile time checked typed. Always use compile time type checking to make sure arguments and variables are given the correct type. There is no need for the typedef in C++.
enum TRecordType { xNew = 1, xDeleted = 2, xModified = 4, xExisting = 8,
Create another member for an invalid state. This can be useful as error code; for example, when you want to return the state but the I/O operation fails. It is also useful for debugging; use it in initialisation lists and destructors to know if the variable's value should be used.
xInvalid = 16 };
Consider that you have two purposes for this type. To track the current state of a record and to create a mask to select records in certain states. Create an inline function to test if the value of the type is valid for your purpose; as a state marker vs a state mask. This will catch bugs as the typedef is just an int and a value such as 0xDEADBEEF may be in your variable through uninitialised or mispointed variables.
inline bool IsValidState( TRecordType v) {
switch(v) { case xNew: case xDeleted: case xModified: case xExisting: return true; }
return false;
}
inline bool IsValidMask( TRecordType v) {
return v >= xNew && v < xInvalid ;
}
Add a using directive if you want to use the type often.
using RecordType ::TRecordType ;
The value checking functions are useful in asserts to trap bad values as soon as they are used. The quicker you catch a bug when running, the less damage it can do.
Here are some examples to put it all together.
void showRecords(TRecordType mask) {
assert(RecordType::IsValidMask(mask));
// do stuff;
}
void wombleRecord(TRecord rec, TRecordType state) {
assert(RecordType::IsValidState(state));
if (RecordType ::xNew) {
// ...
} in runtime
TRecordType updateRecord(TRecord rec, TRecordType newstate) {
assert(RecordType::IsValidState(newstate));
//...
if (! access_was_successful) return RecordType ::xInvalid;
return newstate;
}
The only way to ensure correct value safety is to use a dedicated class with operator overloads and that is left as an exercise for another reader.
A: Here are couple of articles on const vs. macros vs. enums:
Symbolic Constants
Enumeration Constants vs. Constant Objects
I think you should avoid macros especially since you wrote most of your new code is in modern C++.
A: Forget the defines
They will pollute your code.
bitfields?
struct RecordFlag {
unsigned isnew:1, isdeleted:1, ismodified:1, isexisting:1;
};
Don't ever use that. You are more concerned with speed than with economizing 4 ints. Using bit fields is actually slower than access to any other type.
However, bit members in structs have practical drawbacks. First, the ordering of bits in memory varies from compiler to compiler. In addition, many popular compilers generate inefficient code for reading and writing bit members, and there are potentially severe thread safety issues relating to bit fields (especially on multiprocessor systems) due to the fact that most machines cannot manipulate arbitrary sets of bits in memory, but must instead load and store whole words. e.g the following would not be thread-safe, in spite of the use of a mutex
Source: http://en.wikipedia.org/wiki/Bit_field:
And if you need more reasons to not use bitfields, perhaps Raymond Chen will convince you in his The Old New Thing Post: The cost-benefit analysis of bitfields for a collection of booleans at http://blogs.msdn.com/oldnewthing/archive/2008/11/26/9143050.aspx
const int?
namespace RecordType {
static const uint8 xNew = 1;
static const uint8 xDeleted = 2;
static const uint8 xModified = 4;
static const uint8 xExisting = 8;
}
Putting them in a namespace is cool. If they are declared in your CPP or header file, their values will be inlined. You'll be able to use switch on those values, but it will slightly increase coupling.
Ah, yes: remove the static keyword. static is deprecated in C++ when used as you do, and if uint8 is a buildin type, you won't need this to declare this in an header included by multiple sources of the same module. In the end, the code should be:
namespace RecordType {
const uint8 xNew = 1;
const uint8 xDeleted = 2;
const uint8 xModified = 4;
const uint8 xExisting = 8;
}
The problem of this approach is that your code knows the value of your constants, which increases slightly the coupling.
enum
The same as const int, with a somewhat stronger typing.
typedef enum { xNew = 1, xDeleted, xModified = 4, xExisting = 8 } RecordType;
They are still polluting the global namespace, though.
By the way... Remove the typedef. You're working in C++. Those typedefs of enums and structs are polluting the code more than anything else.
The result is kinda:
enum RecordType { xNew = 1, xDeleted, xModified = 4, xExisting = 8 } ;
void doSomething(RecordType p_eMyEnum)
{
if(p_eMyEnum == xNew)
{
// etc.
}
}
As you see, your enum is polluting the global namespace.
If you put this enum in an namespace, you'll have something like:
namespace RecordType {
enum Value { xNew = 1, xDeleted, xModified = 4, xExisting = 8 } ;
}
void doSomething(RecordType::Value p_eMyEnum)
{
if(p_eMyEnum == RecordType::xNew)
{
// etc.
}
}
extern const int ?
If you want to decrease coupling (i.e. being able to hide the values of the constants, and so, modify them as desired without needing a full recompilation), you can declare the ints as extern in the header, and as constant in the CPP file, as in the following example:
// Header.hpp
namespace RecordType {
extern const uint8 xNew ;
extern const uint8 xDeleted ;
extern const uint8 xModified ;
extern const uint8 xExisting ;
}
And:
// Source.hpp
namespace RecordType {
const uint8 xNew = 1;
const uint8 xDeleted = 2;
const uint8 xModified = 4;
const uint8 xExisting = 8;
}
You won't be able to use switch on those constants, though. So in the end, pick your poison...
:-p
A: If possible do NOT use macros. They aren't too much admired when it comes to modern C++.
A:
With defines I lose type safety
Not necessarily...
// signed defines
#define X_NEW 0x01u
#define X_NEW (unsigned(0x01)) // if you find this more readable...
and with enum I lose some space (integers)
Not necessarily - but you do have to be explicit at points of storage...
struct X
{
RecordType recordType : 4; // use exactly 4 bits...
RecordType recordType2 : 4; // use another 4 bits, typically in the same byte
// of course, the overall record size may still be padded...
};
and probably have to cast when I want to do bitwise operation.
You can create operators to take the pain out of that:
RecordType operator|(RecordType lhs, RecordType rhs)
{
return RecordType((unsigned)lhs | (unsigned)rhs);
}
With const I think I also lose type safety since a random uint8 could get in by mistake.
The same can happen with any of these mechanisms: range and value checks are normally orthogonal to type safety (though user-defined-types - i.e. your own classes - can enforce "invariants" about their data). With enums, the compiler's free to pick a larger type to host the values, and an uninitialised, corrupted or just miss-set enum variable could still end up interpretting its bit pattern as a number you wouldn't expect - comparing unequal to any of the enumeration identifiers, any combination of them, and 0.
Is there some other cleaner way? / If not, what would you use and why?
Well, in the end the tried-and-trusted C-style bitwise OR of enumerations works pretty well once you have bit fields and custom operators in the picture. You can further improve your robustness with some custom validation functions and assertions as in mat_geek's answer; techniques often equally applicable to handling string, int, double values etc..
You could argue that this is "cleaner":
enum RecordType { New, Deleted, Modified, Existing };
showRecords([](RecordType r) { return r == New || r == Deleted; });
I'm indifferent: the data bits pack tighter but the code grows significantly... depends how many objects you've got, and the lamdbas - beautiful as they are - are still messier and harder to get right than bitwise ORs.
BTW /- the argument about thread safety's pretty weak IMHO - best remembered as a background consideration rather than becoming a dominant decision-driving force; sharing a mutex across the bitfields is a more likely practice even if unaware of their packing (mutexes are relatively bulky data members - I have to be really concerned about performance to consider having multiple mutexes on members of one object, and I'd look carefully enough to notice they were bit fields). Any sub-word-size type could have the same problem (e.g. a uint8_t). Anyway, you could try atomic compare-and-swap style operations if you're desperate for higher concurrency.
A: Enums would be more appropriate as they provide "meaning to the identifiers" as well as type safety. You can clearly tell "xDeleted" is of "RecordType" and that represent "type of a record" (wow!) even after years. Consts would require comments for that, also they would require going up and down in code.
A: Have you ruled out std::bitset? Sets of flags is what it's for. Do
typedef std::bitset<4> RecordType;
then
static const RecordType xNew(1);
static const RecordType xDeleted(2);
static const RecordType xModified(4);
static const RecordType xExisting(8);
Because there are a bunch of operator overloads for bitset, you can now do
RecordType rt = whatever; // unsigned long or RecordType expression
rt |= xNew; // set
rt &= ~xDeleted; // clear
if ((rt & xModified) != 0) ... // test
Or something very similar to that - I'd appreciate any corrections since I haven't tested this. You can also refer to the bits by index, but it's generally best to define only one set of constants, and RecordType constants are probably more useful.
Assuming you have ruled out bitset, I vote for the enum.
I don't buy that casting the enums is a serious disadvantage - OK so it's a bit noisy, and assigning an out-of-range value to an enum is undefined behaviour so it's theoretically possible to shoot yourself in the foot on some unusual C++ implementations. But if you only do it when necessary (which is when going from int to enum iirc), it's perfectly normal code that people have seen before.
I'm dubious about any space cost of the enum, too. uint8 variables and parameters probably won't use any less stack than ints, so only storage in classes matters. There are some cases where packing multiple bytes in a struct will win (in which case you can cast enums in and out of uint8 storage), but normally padding will kill the benefit anyhow.
So the enum has no disadvantages compared with the others, and as an advantage gives you a bit of type-safety (you can't assign some random integer value without explicitly casting) and clean ways of referring to everything.
For preference I'd also put the "= 2" in the enum, by the way. It's not necessary, but a "principle of least astonishment" suggests that all 4 definitions should look the same.
A: Even if you have to use 4 byte to store an enum (I'm not that familiar with C++ -- I know you can specify the underlying type in C#), it's still worth it -- use enums.
In this day and age of servers with GBs of memory, things like 4 bytes vs. 1 byte of memory at the application level in general don't matter. Of course, if in your particular situation, memory usage is that important (and you can't get C++ to use a byte to back the enum), then you can consider the 'static const' route.
At the end of the day, you have to ask yourself, is it worth the maintenance hit of using 'static const' for the 3 bytes of memory savings for your data structure?
Something else to keep in mind -- IIRC, on x86, data structures are 4-byte aligned, so unless you have a number of byte-width elements in your 'record' structure, it might not actually matter. Test and make sure it does before you make a tradeoff in maintainability for performance/space.
A: If you want the type safety of classes, with the convenience of enumeration syntax and bit checking, consider Safe Labels in C++. I've worked with the author, and he's pretty smart.
Beware, though. In the end, this package uses templates and macros!
A: Do you actually need to pass around the flag values as a conceptual whole, or are you going to have a lot of per-flag code? Either way, I think having this as class or struct of 1-bit bitfields might actually be clearer:
struct RecordFlag {
unsigned isnew:1, isdeleted:1, ismodified:1, isexisting:1;
};
Then your record class could have a struct RecordFlag member variable, functions can take arguments of type struct RecordFlag, etc. The compiler should pack the bitfields together, saving space.
A: I probably wouldn't use an enum for this kind of a thing where the values can be combined together, more typically enums are mutually exclusive states.
But whichever method you use, to make it more clear that these are values which are bits which can be combined together, use this syntax for the actual values instead:
#define X_NEW (1 << 0)
#define X_DELETED (1 << 1)
#define X_MODIFIED (1 << 2)
#define X_EXISTING (1 << 3)
Using a left-shift there helps to indicate that each value is intended to be a single bit, it is less likely that later on someone would do something wrong like add a new value and assign it something a value of 9.
A: Based on KISS, high cohesion and low coupling, ask these questions -
*
*Who needs to know? my class, my library, other classes, other libraries, 3rd parties
*What level of abstraction do I need to provide? Does the consumer understand bit operations.
*Will I have have to interface from VB/C# etc?
There is a great book "Large-Scale C++ Software Design", this promotes base types externally, if you can avoid another header file/interface dependancy you should try to.
A: If you are using Qt you should have a look for QFlags.
The QFlags class provides a type-safe way of storing OR-combinations of enum values.
A: I would rather go with
typedef enum { xNew = 1, xDeleted, xModified = 4, xExisting = 8 } RecordType;
Simply because:
*
*It is cleaner and it makes the code readable and maintainable.
*It logically groups the constants.
*Programmer's time is more important, unless your job is to save those 3 bytes.
A: Not that I like to over-engineer everything but sometimes in these cases it may be worth creating a (small) class to encapsulate this information.
If you create a class RecordType then it might have functions like:
void setDeleted();
void clearDeleted();
bool isDeleted();
etc... (or whatever convention suits)
It could validate combinations (in the case where not all combinations are legal, eg if 'new' and 'deleted' could not both be set at the same time). If you just used bit masks etc then the code that sets the state needs to validate, a class can encapsulate that logic too.
The class may also give you the ability to attach meaningful logging info to each state, you could add a function to return a string representation of the current state etc (or use the streaming operators '<<').
For all that if you are worried about storage you could still have the class only have a 'char' data member, so only take a small amount of storage (assuming it is non virtual). Of course depending on the hardware etc you may have alignment issues.
You could have the actual bit values not visible to the rest of the 'world' if they are in an anonymous namespace inside the cpp file rather than in the header file.
If you find that the code using the enum/#define/ bitmask etc has a lot of 'support' code to deal with invalid combinations, logging etc then encapsulation in a class may be worth considering. Of course most times simple problems are better off with simple solutions...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/112433",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "129"
}
|
Q: CPU Emulation and locking to a specific clock speed If you had read my other question, you'll know I've spent this weekend putting together a 6502 CPU emulator as a programming exercise.
The CPU emulator is mostly complete, and seems to be fairly accurate from my limited testing, however it is running incredibly fast, and I want to throttle it down to the actual clock speed of the machine.
My current test loop is this:
// Just loop infinitely.
while (1 == 1)
{
CPU.ClockCyclesBeforeNext--;
if (CPU.ClockCyclesBeforeNext <= 0)
{
// Find out how many clock cycles this instruction will take
CPU.ClockCyclesBeforeNext = CPU.OpcodeMapper.Map[CPU.Memory[CPU.PC]].CpuCycles;
// Run the instruction
CPU.ExecuteInstruction(CPU.Memory[CPU.PC]);
// Debugging Info
CPU.DumpDebug();
Console.WriteLine(CPU.OpcodeMapper.Map[CPU.Memory[CPU.PC]].ArgumentLength);
// Move to next instruction
CPU.PC += 1 + CPU.OpcodeMapper.Map[CPU.Memory[CPU.PC]].ArgumentLength;
}
}
As you can tell, each opcode takes a specific amount of time to complete, so I do not run the next instruction until I count down the CPU Cycle clock. This provides proper timing between opcodes, its just that the entire thing runs way to fast.
The targeted CPU speed is 1.79mhz, however I'd like whatever solution to the clock issue to keep the speed at 1.79mhz even as I add complexity, so I don't have to adjust it up.
Any ideas?
A: Take a look at the original quicktime documentation for inspiration.
It was written a long time ago, when displaying video meant just swapping still frames at high enough speed, but the Apple guys decided they needed a full time-management framework. The design at first looks overengineered, but it let them deal with widely different speed requirements and keep them tightly synchronized.
you're fortunate that 6502 has deterministic time behaviour, the exact time each instruction takes is well documented; but it's not constant. some instructions take 2 cycles, other 3. Just like frames in QuickTime, a video doesn't have a 'frames per second' parameter, each frame tells how long it wants to be in screen.
Since modern CPU's are so non-deterministic, and multitasking OS's can even freeze for a few miliseconds (virtual memory!), you should keep a tab if you're behind schedule, or if you can take a few microseconds nap.
A: As jfk says, the most common way to do this is tie the cpu speed to the vertical refresh of the (emulated) video output.
Pick a number of cycles to run per video frame. This will often be machine-specific but you can calculate it by something like :
cycles = clock speed in Hz / required frames-per-second
Then you also get to do a sleep until the video update is hit, at which point you start the next n cycles of CPU emulation.
If you're emulating something in particular then you just need to look up the fps rate and processor speed to get this approximately right.
EDIT: If you don't have any external timing requirements then it is normal for an emulator to just run as fast as it possibly can. Sometimes this is a desired effect and sometimes not :)
A: I would use the clock cycles to calculate time and them sleep the difference in time. Of course, to do this, you need a high-resolution clock. They way you are doing it is going to spike the CPU in spinning loops.
A: Yes, as said before most of the time you don't need a CPU emulator to emulate instructions at the same speed of the real thing. What user perceive is the output of the computation (i.e. audio and video outputs) so you only need to be in sync with such outputs which doesn't mean you must have necessarily an exact CPU emulation speed.
In other words, if the frame rate of the video input is, let's say, 50Hz, then let the CPU emulator run as fast as it can to draw the screen but be sure to output the screen frames at the correct rate (50Hz). From an external point of view your emulator is emulating at the correct speed.
Trying to be cycle exact even in the execution time is a non-sense on a multi-tasking OS like Windows or Linux because the emulator instruction time (tipically 1uS for vintage 80s CPUs) and the scheduling time slot of the modern OS are comparable.
Trying to output something at a 50Hz rate is a much simpler task you can do very good on any modern machine
A: I wrote a Z80 emulator many years ago, and to do cycle accurate execution, I divided the clock rate into a number of small blocks and had the core execute that many clock cycles. In my case, I tied it to the frame rate of the game system I was emulating. Each opcode knew how many cycles it took to execute and the core would keep running opcodes until the specified number of cycles had been executed. I had an outer run loop that would run the cpu core, and run other parts of the emulated system and then sleep until the start time of the next iteration.
EDIT: Adding example of run loop.
int execute_run_loop( int cycles )
{
int n = 0;
while( n < cycles )
{
/* Returns number of cycles executed */
n += execute_next_opcode();
}
return n;
}
Hope this helps.
A: Another option is available if audio emulation is implemented, and if audio output is tied to the system/CPU clock. In particular I know that this is the case with the 8-bit Apple ][ computers.
Usually sound is generated in buffers of a fixed size (which is a fixed time), so operation (generation of data etc) of these buffers can be tied to CPU throughput via synchronization primitives.
A: I am in the process of making something a little more general use case based, such as the ability to convert time to an estimated amount of instructions and vice versa.
The project homepage is @ http://net7mma.codeplex.com
The code starts like this: (I think)
#region Copyright
/*
This file came from Managed Media Aggregation, You can always find the latest version @ https://net7mma.codeplex.com/
Julius.Friedman@gmail.com / (SR. Software Engineer ASTI Transportation Inc. http://www.asti-trans.com)
Permission is hereby granted, free of charge,
* to any person obtaining a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction,
* including without limitation the rights to :
* use,
* copy,
* modify,
* merge,
* publish,
* distribute,
* sublicense,
* and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
*
* JuliusFriedman@gmail.com should be contacted for further details.
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
*
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE,
* ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* v//
*/
#endregion
namespace Media.Concepts.Classes
{
//Windows.Media.Clock has a fairly complex but complete API
/// <summary>
/// Provides a clock with a given offset and calendar.
/// </summary>
public class Clock : Media.Common.BaseDisposable
{
static bool GC = false;
#region Fields
/// <summary>
/// Indicates when the clock was created
/// </summary>
public readonly System.DateTimeOffset Created;
/// <summary>
/// The calendar system of the clock
/// </summary>
public readonly System.Globalization.Calendar Calendar;
/// <summary>
/// The amount of ticks which occur per update of the <see cref="System.Environment.TickCount"/> member.
/// </summary>
public readonly long TicksPerUpdate;
/// <summary>
/// The amount of instructions which occured when synchronizing with the system clock.
/// </summary>
public readonly long InstructionsPerClockUpdate;
#endregion
#region Properties
/// <summary>
/// The TimeZone offset of the clock from UTC
/// </summary>
public System.TimeSpan Offset { get { return Created.Offset; } }
/// <summary>
/// The average amount of operations per tick.
/// </summary>
public long AverageOperationsPerTick { get { return InstructionsPerClockUpdate / TicksPerUpdate; } }
/// <summary>
/// The <see cref="System.TimeSpan"/> which represents <see cref="TicksPerUpdate"/> as an amount of time.
/// </summary>
public System.TimeSpan SystemClockResolution { get { return System.TimeSpan.FromTicks(TicksPerUpdate); } }
/// <summary>
/// Return the current system time in the TimeZone offset of this clock
/// </summary>
public System.DateTimeOffset Now { get { return System.DateTimeOffset.Now.ToOffset(Offset).Add(new System.TimeSpan((long)(AverageOperationsPerTick / System.TimeSpan.TicksPerMillisecond))); } }
/// <summary>
/// Return the current system time in the TimeZone offset of this clock converter to UniversalTime.
/// </summary>
public System.DateTimeOffset UtcNow { get { return Now.ToUniversalTime(); } }
//public bool IsUtc { get { return Offset == System.TimeSpan.Zero; } }
//public bool IsDaylightSavingTime { get { return Created.LocalDateTime.IsDaylightSavingTime(); } }
#endregion
#region Constructor
/// <summary>
/// Creates a clock using the system's current timezone and calendar.
/// The system clock is profiled to determine it's accuracy
/// <see cref="System.DateTimeOffset.Now.Offset"/>
/// <see cref="System.Globalization.CultureInfo.CurrentCulture.Calendar"/>
/// </summary>
public Clock(bool shouldDispose = true)
: this(System.DateTimeOffset.Now.Offset, System.Globalization.CultureInfo.CurrentCulture.Calendar, shouldDispose)
{
try { if (false == GC && System.Runtime.GCSettings.LatencyMode != System.Runtime.GCLatencyMode.NoGCRegion) GC = System.GC.TryStartNoGCRegion(0); }
catch { }
finally
{
System.Threading.Thread.BeginCriticalRegion();
//Sample the TickCount
long ticksStart = System.Environment.TickCount,
ticksEnd;
//Continually sample the TickCount. while the value has not changed increment InstructionsPerClockUpdate
while ((ticksEnd = System.Environment.TickCount) == ticksStart) ++InstructionsPerClockUpdate; //+= 4; Read,Assign,Compare,Increment
//How many ticks occur per update of TickCount
TicksPerUpdate = ticksEnd - ticksStart;
System.Threading.Thread.EndCriticalRegion();
}
}
/// <summary>
/// Constructs a new clock using the given TimeZone offset and Calendar system
/// </summary>
/// <param name="timeZoneOffset"></param>
/// <param name="calendar"></param>
/// <param name="shouldDispose">Indicates if the instace should be diposed when Dispose is called.</param>
public Clock(System.TimeSpan timeZoneOffset, System.Globalization.Calendar calendar, bool shouldDispose = true)
{
//Allow disposal
ShouldDispose = shouldDispose;
Calendar = System.Globalization.CultureInfo.CurrentCulture.Calendar;
Created = new System.DateTimeOffset(System.DateTime.Now, timeZoneOffset);
}
#endregion
#region Overrides
public override void Dispose()
{
if (false == ShouldDispose) return;
base.Dispose();
try
{
if (System.Runtime.GCSettings.LatencyMode == System.Runtime.GCLatencyMode.NoGCRegion)
{
System.GC.EndNoGCRegion();
GC = false;
}
}
catch { }
}
#endregion
//Methods or statics for OperationCountToTimeSpan? (Estimate)
public void NanoSleep(int nanos)
{
Clock.NanoSleep((long)nanos);
}
public static void NanoSleep(long nanos)
{
System.Threading.Thread.BeginCriticalRegion();
NanoSleep(ref nanos);
System.Threading.Thread.EndCriticalRegion();
}
static void NanoSleep(ref long nanos)
{
try
{
unchecked
{
while (Common.Binary.Clamp(--nanos, 0, 1) >= 2)
{
/* if(--nanos % 2 == 0) */
NanoSleep(long.MinValue); //nanos -= 1 + (ops / (ulong)AverageOperationsPerTick);// *10;
}
}
}
catch
{
return;
}
}
}
}
Once you have some type of layman clock implementation you advance to something like a Timer
/// <summary>
/// Provides a Timer implementation which can be used across all platforms and does not rely on the existing Timer implementation.
/// </summary>
public class Timer : Common.BaseDisposable
{
readonly System.Threading.Thread m_Counter; // m_Consumer, m_Producer
internal System.TimeSpan m_Frequency;
internal ulong m_Ops = 0, m_Ticks = 0;
bool m_Enabled;
internal System.DateTimeOffset m_Started;
public delegate void TickEvent(ref long ticks);
public event TickEvent Tick;
public bool Enabled { get { return m_Enabled; } set { m_Enabled = value; } }
public System.TimeSpan Frequency { get { return m_Frequency; } }
internal ulong m_Bias;
//
//Could just use a single int, 32 bits is more than enough.
//uint m_Flags;
//
readonly internal Clock m_Clock = new Clock();
readonly internal System.Collections.Generic.Queue<long> Producer;
void Count()
{
System.Threading.Thread Event = new System.Threading.Thread(new System.Threading.ThreadStart(() =>
{
System.Threading.Thread.BeginCriticalRegion();
long sample;
AfterSample:
try
{
Top:
System.Threading.Thread.CurrentThread.Priority = System.Threading.ThreadPriority.Highest;
while (m_Enabled && Producer.Count >= 1)
{
sample = Producer.Dequeue();
Tick(ref sample);
}
System.Threading.Thread.CurrentThread.Priority = System.Threading.ThreadPriority.Lowest;
if (false == m_Enabled) return;
while (m_Enabled && Producer.Count == 0) if(m_Counter.IsAlive) m_Counter.Join(0); //++m_Ops;
goto Top;
}
catch { if (false == m_Enabled) return; goto AfterSample; }
finally { System.Threading.Thread.EndCriticalRegion(); }
}))
{
IsBackground = false,
Priority = System.Threading.ThreadPriority.AboveNormal
};
Event.TrySetApartmentState(System.Threading.ApartmentState.MTA);
Event.Start();
Approximate:
ulong approximate = (ulong)Common.Binary.Clamp((m_Clock.AverageOperationsPerTick / (Frequency.Ticks + 1)), 1, ulong.MaxValue);
try
{
m_Started = m_Clock.Now;
System.Threading.Thread.BeginCriticalRegion();
unchecked
{
Start:
if (IsDisposed) return;
switch (++m_Ops)
{
default:
{
if (m_Bias + ++m_Ops >= approximate)
{
System.Threading.Thread.CurrentThread.Priority = System.Threading.ThreadPriority.Highest;
Producer.Enqueue((long)m_Ticks++);
ulong x = ++m_Ops / approximate;
while (1 > --x /*&& Producer.Count <= m_Frequency.Ticks*/) Producer.Enqueue((long)++m_Ticks);
m_Ops = (++m_Ops * m_Ticks) - (m_Bias = ++m_Ops / approximate);
System.Threading.Thread.CurrentThread.Priority = System.Threading.ThreadPriority.Lowest;
}
if(Event != null) Event.Join(m_Frequency);
goto Start;
}
}
}
}
catch (System.Threading.ThreadAbortException) { if (m_Enabled) goto Approximate; System.Threading.Thread.ResetAbort(); }
catch (System.OutOfMemoryException) { if ((ulong)Producer.Count > approximate) Producer.Clear(); if (m_Enabled) goto Approximate; }
catch { if (m_Enabled) goto Approximate; }
finally
{
Event = null;
System.Threading.Thread.EndCriticalRegion();
}
}
public Timer(System.TimeSpan frequency)
{
Producer = new System.Collections.Generic.Queue<long>((int)(m_Frequency = frequency).Ticks * 10);
m_Counter = new System.Threading.Thread(new System.Threading.ThreadStart(Count))
{
IsBackground = false,
Priority = System.Threading.ThreadPriority.AboveNormal
};
m_Counter.TrySetApartmentState(System.Threading.ApartmentState.MTA);
Tick = delegate { m_Ops += 1 + m_Bias; };
}
public void Start()
{
if (m_Enabled) return;
m_Enabled = true;
m_Counter.Start();
var p = System.Threading.Thread.CurrentThread.Priority;
System.Threading.Thread.CurrentThread.Priority = System.Threading.ThreadPriority.Lowest;
while (m_Ops == 0) m_Counter.Join(0); //m_Clock.NanoSleep(0);
System.Threading.Thread.CurrentThread.Priority = p;
}
public void Stop()
{
m_Enabled = false;
}
void Change(System.TimeSpan interval, System.TimeSpan dueTime)
{
m_Enabled = false;
m_Frequency = interval;
m_Enabled = true;
}
delegate void ElapsedEvent(object sender, object args);
public override void Dispose()
{
if (IsDisposed) return;
base.Dispose();
Stop();
try { m_Counter.Abort(m_Frequency); }
catch (System.Threading.ThreadAbortException) { System.Threading.Thread.ResetAbort(); }
catch { }
Tick = null;
//Producer.Clear();
}
}
Then you can really replicate some logic using something like
/// <summary>
/// Provides a completely managed implementation of <see cref="System.Diagnostics.Stopwatch"/> which expresses time in the same units as <see cref="System.TimeSpan"/>.
/// </summary>
public class Stopwatch : Common.BaseDisposable
{
internal Timer Timer;
long Units;
public bool Enabled { get { return Timer != null && Timer.Enabled; } }
public double ElapsedMicroseconds { get { return Units * Media.Common.Extensions.TimeSpan.TimeSpanExtensions.TotalMicroseconds(Timer.Frequency); } }
public double ElapsedMilliseconds { get { return Units * Timer.Frequency.TotalMilliseconds; } }
public double ElapsedSeconds { get { return Units * Timer.Frequency.TotalSeconds; } }
//public System.TimeSpan Elapsed { get { return System.TimeSpan.FromMilliseconds(ElapsedMilliseconds / System.TimeSpan.TicksPerMillisecond); } }
public System.TimeSpan Elapsed
{
get
{
switch (Units)
{
case 0: return System.TimeSpan.Zero;
default:
{
System.TimeSpan taken = System.DateTime.UtcNow - Timer.m_Started;
return taken.Add(new System.TimeSpan(Units * Timer.Frequency.Ticks));
//System.TimeSpan additional = new System.TimeSpan(Media.Common.Extensions.Math.MathExtensions.Clamp(Units, 0, Timer.Frequency.Ticks));
//return taken.Add(additional);
}
}
//////The maximum amount of times the timer can elapse in the given frequency
////double maxCount = (taken.TotalMilliseconds / Timer.Frequency.TotalMilliseconds) / ElapsedMilliseconds;
////if (Units > maxCount)
////{
//// //How many more times the event was fired than needed
//// double overage = (maxCount - Units);
//// additional = new System.TimeSpan(System.Convert.ToInt64(Media.Common.Extensions.Math.MathExtensions.Clamp(Units, overage, maxCount)));
//// //return taken.Add(new System.TimeSpan((long)Media.Common.Extensions.Math.MathExtensions.Clamp(Units, overage, maxCount)));
////}
//////return taken.Add(new System.TimeSpan(Units));
}
}
public void Start()
{
if (Enabled) return;
Units = 0;
//Create a Timer that will elapse every OneTick //`OneMicrosecond`
Timer = new Timer(Media.Common.Extensions.TimeSpan.TimeSpanExtensions.OneTick);
//Handle the event by incrementing count
Timer.Tick += Count;
Timer.Start();
}
public void Stop()
{
if (false == Enabled) return;
Timer.Stop();
Timer.Dispose();
}
void Count(ref long count) { ++Units; }
}
Finally, create something semi useful e.g. a Bus and then perhaps a virtual screen to emit data to the bus...
public abstract class Bus : Common.CommonDisposable
{
public readonly Timer Clock = new Timer(Common.Extensions.TimeSpan.TimeSpanExtensions.OneTick);
public Bus() : base(false) { Clock.Start(); }
}
public class ClockedBus : Bus
{
long FrequencyHz, Maximum, End;
readonly Queue<byte[]> Input = new Queue<byte[]>(), Output = new Queue<byte[]>();
readonly double m_Bias;
public ClockedBus(long frequencyHz, double bias = 1.5)
{
m_Bias = bias;
cache = Clock.m_Clock.InstructionsPerClockUpdate / 1000;
SetFrequency(frequencyHz);
Clock.Tick += Clock_Tick;
Clock.Start();
}
public void SetFrequency(long frequencyHz)
{
FrequencyHz = frequencyHz;
//Clock.m_Frequency = new TimeSpan(Clock.m_Clock.InstructionsPerClockUpdate / 1000);
//Maximum = System.TimeSpan.TicksPerSecond / Clock.m_Clock.InstructionsPerClockUpdate;
//Maximum = Clock.m_Clock.InstructionsPerClockUpdate / System.TimeSpan.TicksPerSecond;
Maximum = cache / (cache / FrequencyHz);
Maximum *= System.TimeSpan.TicksPerSecond;
Maximum = (cache / FrequencyHz);
End = Maximum * 2;
Clock.m_Frequency = new TimeSpan(Maximum);
if (cache < frequencyHz * m_Bias) throw new Exception("Cannot obtain stable clock");
Clock.Producer.Clear();
}
public override void Dispose()
{
ShouldDispose = true;
Clock.Tick -= Clock_Tick;
Clock.Stop();
Clock.Dispose();
base.Dispose();
}
~ClockedBus() { Dispose(); }
long sample = 0, steps = 0, count = 0, avg = 0, cache = 1;
void Clock_Tick(ref long ticks)
{
if (ShouldDispose == false && false == IsDisposed)
{
//Console.WriteLine("@ops=>" + Clock.m_Ops + " @ticks=>" + Clock.m_Ticks + " @Lticks=>" + ticks + "@=>" + Clock.m_Clock.Now.TimeOfDay + "@=>" + (Clock.m_Clock.Now - Clock.m_Clock.Created));
steps = sample;
sample = ticks;
++count;
System.ConsoleColor f = System.Console.ForegroundColor;
if (count <= Maximum)
{
System.Console.BackgroundColor = ConsoleColor.Yellow;
System.Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("count=> " + count + "@=>" + Clock.m_Clock.Now.TimeOfDay + "@=>" + (Clock.m_Clock.Now - Clock.m_Clock.Created) + " - " + DateTime.UtcNow.ToString("MM/dd/yyyy hh:mm:ss.ffffff tt"));
avg = Maximum / count;
if (Clock.m_Clock.InstructionsPerClockUpdate / count > Maximum)
{
System.Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("---- Over InstructionsPerClockUpdate ----" + FrequencyHz);
}
}
else if (count >= End)
{
System.Console.BackgroundColor = ConsoleColor.Black;
System.Console.ForegroundColor = ConsoleColor.Blue;
avg = Maximum / count;
Console.WriteLine("avg=> " + avg + "@=>" + FrequencyHz);
count = 0;
}
}
}
//Read, Write at Frequency
}
public class VirtualScreen
{
TimeSpan RefreshRate;
bool VerticalSync;
int Width, Height;
Common.MemorySegment DisplayMemory, BackBuffer, DisplayBuffer;
}
Here is how I tested the StopWatch
internal class StopWatchTests
{
public void TestForOneMicrosecond()
{
System.Collections.Generic.List<System.Tuple<bool, System.TimeSpan, System.TimeSpan>> l = new System.Collections.Generic.List<System.Tuple<bool, System.TimeSpan, System.TimeSpan>>();
//Create a Timer that will elapse every `OneMicrosecond`
for (int i = 0; i <= 250; ++i) using (Media.Concepts.Classes.Stopwatch sw = new Media.Concepts.Classes.Stopwatch())
{
var started = System.DateTime.UtcNow;
System.Console.WriteLine("Started: " + started.ToString("MM/dd/yyyy hh:mm:ss.ffffff tt"));
//Define some amount of time
System.TimeSpan sleepTime = Media.Common.Extensions.TimeSpan.TimeSpanExtensions.OneMicrosecond;
System.Diagnostics.Stopwatch testSw = new System.Diagnostics.Stopwatch();
//Start
testSw.Start();
//Start
sw.Start();
while (testSw.Elapsed.Ticks < sleepTime.Ticks - (Common.Extensions.TimeSpan.TimeSpanExtensions.OneTick + Common.Extensions.TimeSpan.TimeSpanExtensions.OneTick).Ticks)
sw.Timer.m_Clock.NanoSleep(0); //System.Threading.Thread.SpinWait(0);
//Sleep the desired amount
//System.Threading.Thread.Sleep(sleepTime);
//Stop
testSw.Stop();
//Stop
sw.Stop();
var finished = System.DateTime.UtcNow;
var taken = finished - started;
var cc = System.Console.ForegroundColor;
System.Console.WriteLine("Finished: " + finished.ToString("MM/dd/yyyy hh:mm:ss.ffffff tt"));
System.Console.WriteLine("Sleep Time: " + sleepTime.ToString());
System.Console.WriteLine("Real Taken Total: " + taken.ToString());
if (taken > sleepTime)
{
System.Console.ForegroundColor = System.ConsoleColor.Red;
System.Console.WriteLine("Missed by: " + (taken - sleepTime));
}
else
{
System.Console.ForegroundColor = System.ConsoleColor.Green;
System.Console.WriteLine("Still have: " + (sleepTime - taken));
}
System.Console.ForegroundColor = cc;
System.Console.WriteLine("Real Taken msec Total: " + taken.TotalMilliseconds.ToString());
System.Console.WriteLine("Real Taken sec Total: " + taken.TotalSeconds.ToString());
System.Console.WriteLine("Real Taken μs Total: " + Media.Common.Extensions.TimeSpan.TimeSpanExtensions.TotalMicroseconds(taken).ToString());
System.Console.WriteLine("Managed Taken Total: " + sw.Elapsed.ToString());
System.Console.WriteLine("Diagnostic Taken Total: " + testSw.Elapsed.ToString());
System.Console.WriteLine("Diagnostic Elapsed Seconds Total: " + ((testSw.ElapsedTicks / (double)System.Diagnostics.Stopwatch.Frequency)));
//Write the rough amount of time taken in micro seconds
System.Console.WriteLine("Managed Time Estimated Taken: " + sw.ElapsedMicroseconds + "μs");
//Write the rough amount of time taken in micro seconds
System.Console.WriteLine("Diagnostic Time Estimated Taken: " + Media.Common.Extensions.TimeSpan.TimeSpanExtensions.TotalMicroseconds(testSw.Elapsed) + "μs");
System.Console.WriteLine("Managed Time Estimated Taken: " + sw.ElapsedMilliseconds);
System.Console.WriteLine("Diagnostic Time Estimated Taken: " + testSw.ElapsedMilliseconds);
System.Console.WriteLine("Managed Time Estimated Taken: " + sw.ElapsedSeconds);
System.Console.WriteLine("Diagnostic Time Estimated Taken: " + testSw.Elapsed.TotalSeconds);
if (sw.Elapsed < testSw.Elapsed)
{
System.Console.WriteLine("Faster than Diagnostic StopWatch");
l.Add(new System.Tuple<bool, System.TimeSpan, System.TimeSpan>(true, sw.Elapsed, testSw.Elapsed));
}
else if (sw.Elapsed > testSw.Elapsed)
{
System.Console.WriteLine("Slower than Diagnostic StopWatch");
l.Add(new System.Tuple<bool, System.TimeSpan, System.TimeSpan>(false, sw.Elapsed, testSw.Elapsed));
}
else
{
System.Console.WriteLine("Equal to Diagnostic StopWatch");
l.Add(new System.Tuple<bool, System.TimeSpan, System.TimeSpan>(true, sw.Elapsed, testSw.Elapsed));
}
}
int w = 0, f = 0;
var cc2 = System.Console.ForegroundColor;
foreach (var t in l)
{
if (t.Item1)
{
System.Console.ForegroundColor = System.ConsoleColor.Green;
++w; System.Console.WriteLine("Faster than Diagnostic StopWatch by: " + (t.Item3 - t.Item2));
}
else
{
System.Console.ForegroundColor = System.ConsoleColor.Red;
++f; System.Console.WriteLine("Slower than Diagnostic StopWatch by: " + (t.Item2 - t.Item3));
}
}
System.Console.ForegroundColor = System.ConsoleColor.Green;
System.Console.WriteLine("Wins = " + w);
System.Console.ForegroundColor = System.ConsoleColor.Red;
System.Console.WriteLine("Loss = " + f);
System.Console.ForegroundColor = cc2;
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/112439",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "27"
}
|
Q: Javascript error I'm getting a JS error on displaying a page: Nothing concrete is specified but the line where it seems to be thrown. When looking into the source code of the page, I see the error is thrown inside the following script, but I can't understand why! It's only about loading images!
<SCRIPT language=JavaScript>
<!--
function newImage(arg) {
var rslt = new Image();
rslt.src = arg;
return rslt;
}
function changeImages(a, b) {
a.src = b;
}
newImage("\/_layouts\/images\/icon1.gif");
newImage("\/_layouts\/images\/icon2.gif");
// -->
</SCRIPT>
The error I am getting is when clicking on a drop down context menu on a page, for this line:
newImage("\/_layouts\/images\/icon1.gif");
The object doesn't accept this property or method
Code: 0
I really don't see what could happen... Any tips on what may be happening here?
A: Have you tried loading your scripts into a JS debugger such as Aptana or Firefox plugin like Firebug?
A: Why are you escaping the forward slashes. That's not necessary. The two lines should be:
newImage("/_layouts/images/icon1.gif");
newImage("/_layouts/images/icon2.gif");
A: It is hard to answer your question with the limited information provided:
*
*You are not showing the complete script
*You never said what the exact error message is, or even what browser is giving the error.
*Which line number is the error supposedly coming from?
I'd recommend using Firebug in firefox for debugging javascript if you aren't already. IE tends to give bogus line numbers.
And as others have already said, the language attribute for script tags is deprecated.
A: Write proper xml with the " around attributes.
<script type="text/javascript">
function newImage(arg) {
var rslt = new Image();
rslt.src = arg;
return rslt;
}
function changeImages(a, b) {
a.src = b;
}
newImage("/_layouts/images/icon1.gif");
newImage("/_layouts/images/icon2.gif");
</script>
A: should your script block not be:
<script type="text/javascript">
?
A: For starters, start your script block with
<script type="text/javascript">
Not
<script language=JavaScript>
That's probably not the root of your problem, but since we can't see your script, that's about all we can offer.
A: You probably need to enlist the help of a Javascript debugger. I've never figured out how to make the various debuggers for IE work, so I can't help you if you're using IE.
If you're using Firefox or you CAN use Firefox, make sure you have a Tools / Javascript Debugger command. (If you don't, reinstall it and be sure to enable that option.) Next, open up the debugger, rerun the problem page, and see what comes up.
A: How are you calling changeImages? It looks as though you are not saving a reference to the images returned by newImage. You probably want to save the results of newImage and pass that to the changeImages routine. Then changeImages should look like this:
function changeImages(a, b) {
a.src = b.src;
}
You also may want to ensure that the images have finished loading before calling changeImages.
You've posted the routine that throws the error, without posting the error or showing us how you are calling it. If none of the answers posted fix your problem then please post some detail about how you are calling the method, which specific line the error is on, and what the error message is.
A: You firebug to debug.
http://www.mozilla.com/en-US/products/download.html?product=firefox-3.0.10&os=win&lang=en-US
https://addons.mozilla.org/en-US/firefox/addon/1843
JSLint is also a nice resource.
http://www.jslint.com/
Using CDATA instead of the <!-- // -->
http://www.w3schools.com/XML/xml_cdata.asp
<script type="text/javascript">
<![CDATA[
]]>
</script>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/112440",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is it possible to have one appBase served by multiple context paths in Tomcat? Is it possible to have one appBase served up by multiple context paths in Tomcat?
I have an application base that recently replaced a second application base. My problem is a number of users still access the old context. I would like to serve the, now common, application from a single appBase yet accessed via either context. I took a swing at the low lying fruit and used a symbolic link in the 'webapps' directory... pointing the old context path at the new context path; it works, but feels "cheezy." And I don't like that a database connection pool is created for both contexts ( I would like to minimize the resources for connecting to the database ).
Anyway, if anyone knows of the "proper" way to do this I will greatly appreciate it. I'm using Tomcat 6.0.16 - no apache front end ( I suppose URL rewrite would be nice ).
A: I'm not sure if the answer above will prevent your webapp from loading twice (as you'd have to deploy it to both new and old context paths), but I could be mistaken. Another option would be to have an extremely simple webapp left in the old context, that does nothing except have one custom servlet filter declared in the web.xml that re-writes all requests to the new path (essentially simulating apache's rewrite rule behaviour). You'd have to write the filter class yourself but it would be quite trivial.
A: Yes, go into the Tomcat Web Application Manager and scroll down to "Deploy directory or WAR file located on server". For "Context Path (optional):" put in the new context. For "WAR or Directory URL:" put in the same path as your existing app.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/112480",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: What is the difference between "lang" and "type" attributes in a script tag? For <script> HTML tags, what is the technical difference between lang=Javascript and type=text/javascript?
I usually use both, because I've always assumed that older browsers need one or the other.
A: Per the HTML 4.01 Spec:
type:
This attribute specifies the scripting language of the element's contents and overrides the default scripting language. The scripting language is specified as a content type (e.g., "text/javascript"). Authors must supply a value for this attribute. There is no default value for this attribute.
language: Deprecated. This attribute specifies the scripting language of the contents of this element. Its value is an identifier for the language, but since these identifiers are not standard, this attribute has been deprecated in favor of type.
A: <script language=""> can be used for serving VBScript and different versions of Javascript.
Unless you need a specific version of Javascript, don't use the language attribute, your code will still work as normal without it.
Even if you do need a specific Javascript version for some part of the code, try to test if the feature exists instead, with a (typeof window.blah.feature != "undefined") check.
Here is an example of the language attribute's usage:
http://bclary.com/2004/08/27/javascript-version-incompatibilities
The language attribute is deprecated because of this loosely defined or uncertain behaviour.
The type attribute is different entirely. It tells the browser what mime type the script is, and should always be specified in a script tag.
A: The OP specifically said "lang" not "language". The much older "language" tag would have been Javascript or VBScript.
But the current and seemingly valid "lang" tag is actually which written language like English, Spanish, Japanese. Microsoft's Visual Studio provides a dropdown list for the values for "lang" and they are all like en-us, fr, ja, etc.. for English US, French, Japanese, etc...
I'm thinking there could be valid reasons for using this tag if you have a complex multilingual setup - maybe there's a content mgmt system that could support this and then deliver the proper javascript file - like jQuery control resources?
A: language is the old attribute, type is the new one. You'd have to use a transitional (not positive on that, but fairly sure) doctype to legally use both attributes.
A: Type is more general and refers to the mime encoding of the script block. As far as I know you only need one and usually the block will work without either type or lag attributes.
I tend to use type.
A: lang is the language of the script, and type is the MIME type of the content of the script tag.
A: Basically, neither attribute is necessary. The only reason to use them is validation, and this has become void in HTML5.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/112482",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
}
|
Q: Does anyone know of a widget for a desktop toolkit(GTK, Qt, WX) for displaying a map of US states? I'm specifically looking for one that lets me display a map of US states with each one as it's own "object" in the sense that I can control the color, on click, and on mouseover of each one individually. GTK is my personal preference, but at this point I'd settle for just about anything. The application itself will be written in Python, FWIW.
A: You can use QGraphicsView in PyQt. Each state is a new QGraphicsItem, which is either a bitmap or a path object. You just need to provide the outlines (or bitmaps) and the positions of the states.
If you have SVGs of the states, you can use them, too.
There is no generally accepted canvas class for GTK+.
A: If you consider Qt, consider also throwing in kdelibs dependency, then you'll have marble widget, which handles maps in neat way.
If you stick only to Qt, then QGraphicsView is a framework to go.
(note: kdelibs != running whole kde desktop)
A: You can use Quantum GIS. QGIS is a Open Source Geographic Information System using the Qt Framework.
QGIS can also be used with Python. You can either extend it with plugins written in Python or use the PyGIS Python bindings to write your own application.
They have a Wiki with some good informations for developers.
Maybe QGIS is to heavy for your purpose, but I add it here for completition anyway.
A:
If you consider Qt, consider also throwing in kdelibs dependency,
then you'll have marble widget, which handles maps in neat way.
Thanks for advertizing Marble. But you are incorrect:
The Marble Widget doesn't depend on kdelibs at all. It just depends on Qt (>=4.3).
Additionally Marble also has just received Python bindings.
I think that the given problem can be solved using Marble. Would just take a few days of work at max. If you have questions about Marble, feel free to ask us on our mailing list or IRC.
A: Quick tip, if you color each state differently you can identify which one to pick from the color under mouse cursor rather than doing a complex point in polygon routine.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/112483",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How do I remove objects from an array in Java? Given an array of n Objects, let's say it is an array of strings, and it has the following values:
foo[0] = "a";
foo[1] = "cc";
foo[2] = "a";
foo[3] = "dd";
What do I have to do to delete/remove all the strings/objects equal to "a" in the array?
A: You can use external library:
org.apache.commons.lang.ArrayUtils.remove(java.lang.Object[] array, int index)
It is in project Apache Commons Lang http://commons.apache.org/lang/
A: See code below
ArrayList<String> a = new ArrayList<>(Arrays.asList(strings));
a.remove(i);
strings = new String[a.size()];
a.toArray(strings);
A: If you need to remove multiple elements from array without converting it to List nor creating additional array, you may do it in O(n) not dependent on count of items to remove.
Here, a is initial array, int... r are distinct ordered indices (positions) of elements to remove:
public int removeItems(Object[] a, int... r) {
int shift = 0;
for (int i = 0; i < a.length; i++) {
if (shift < r.length && i == r[shift]) // i-th item needs to be removed
shift++; // increment `shift`
else
a[i - shift] = a[i]; // move i-th item `shift` positions left
}
for (int i = a.length - shift; i < a.length; i++)
a[i] = null; // replace remaining items by nulls
return a.length - shift; // return new "length"
}
Small testing:
String[] a = {"0", "1", "2", "3", "4"};
removeItems(a, 0, 3, 4); // remove 0-th, 3-rd and 4-th items
System.out.println(Arrays.asList(a)); // [1, 2, null, null, null]
In your task, you can first scan array to collect positions of "a", then call removeItems().
A: There are a lot of answers here--the problem as I see it is that you didn't say WHY you are using an array instead of a collection, so let me suggest a couple reasons and which solutions would apply (Most of the solutions have already been answered in other questions here, so I won't go into too much detail):
reason: You didn't know the collection package existed or didn't trust it
solution: Use a collection.
If you plan on adding/deleting from the middle, use a LinkedList. If you are really worried about size or often index right into the middle of the collection use an ArrayList. Both of these should have delete operations.
reason: You are concerned about size or want control over memory allocation
solution: Use an ArrayList with a specific initial size.
An ArrayList is simply an array that can expand itself, but it doesn't always need to do so. It will be very smart about adding/removing items, but again if you are inserting/removing a LOT from the middle, use a LinkedList.
reason: You have an array coming in and an array going out--so you want to operate on an array
solution: Convert it to an ArrayList, delete the item and convert it back
reason: You think you can write better code if you do it yourself
solution: you can't, use an Array or Linked list.
reason: this is a class assignment and you are not allowed or you do not have access to the collection apis for some reason
assumption: You need the new array to be the correct "size"
solution:
Scan the array for matching items and count them. Create a new array of the correct size (original size - number of matches). use System.arraycopy repeatedly to copy each group of items you wish to retain into your new Array. If this is a class assignment and you can't use System.arraycopy, just copy them one at a time by hand in a loop but don't ever do this in production code because it's much slower. (These solutions are both detailed in other answers)
reason: you need to run bare metal
assumption: you MUST not allocate space unnecessarily or take too long
assumption: You are tracking the size used in the array (length) separately because otherwise you'd have to reallocate your array for deletes/inserts.
An example of why you might want to do this: a single array of primitives (Let's say int values) is taking a significant chunk of your ram--like 50%! An ArrayList would force these into a list of pointers to Integer objects which would use a few times that amount of memory.
solution: Iterate over your array and whenever you find an element to remove (let's call it element n), use System.arraycopy to copy the tail of the array over the "deleted" element (Source and Destination are same array)--it is smart enough to do the copy in the correct direction so the memory doesn't overwrite itself:
System.arraycopy(ary, n+1, ary, n, length-n)
length--;
You'll probably want to be smarter than this if you are deleting more than one element at a time. You would only move the area between one "match" and the next rather than the entire tail and as always, avoid moving any chunk twice.
In this last case, you absolutely must do the work yourself, and using System.arraycopy is really the only way to do it since it's going to choose the best possibly way to move memory for your computer architecture--it should be many times faster than any code you could reasonably write yourself.
A: An alternative in Java 8:
String[] filteredArray = Arrays.stream(array)
.filter(e -> !e.equals(foo)).toArray(String[]::new);
A: Something about the make a list of it then remove then back to an array strikes me as wrong. Haven't tested, but I think the following will perform better. Yes I'm probably unduly pre-optimizing.
boolean [] deleteItem = new boolean[arr.length];
int size=0;
for(int i=0;i<arr.length;i==){
if(arr[i].equals("a")){
deleteItem[i]=true;
}
else{
deleteItem[i]=false;
size++;
}
}
String[] newArr=new String[size];
int index=0;
for(int i=0;i<arr.length;i++){
if(!deleteItem[i]){
newArr[index++]=arr[i];
}
}
A: I realise this is a very old post, but some of the answers here helped me out, so here's my tuppence' ha'penny's worth!
I struggled getting this to work for quite a while before before twigging that the array that I'm writing back into needed to be resized, unless the changes made to the ArrayList leave the list size unchanged.
If the ArrayList that you're modifying ends up with greater or fewer elements than it started with, the line List.toArray() will cause an exception, so you need something like List.toArray(new String[] {}) or List.toArray(new String[0]) in order to create an array with the new (correct) size.
Sounds obvious now that I know it. Not so obvious to an Android/Java newbie who's getting to grips with new and unfamiliar code constructs and not obvious from some of the earlier posts here, so just wanted to make this point really clear for anybody else scratching their heads for hours like I was!
A: Make a List out of the array with Arrays.asList(), and call remove() on all the appropriate elements. Then call toArray() on the 'List' to make back into an array again.
Not terribly performant, but if you encapsulate it properly, you can always do something quicker later on.
A: Initial array
int[] array = {5,6,51,4,3,2};
if you want remove 51 that is index 2, use following
for(int i = 2; i < array.length -1; i++){
array[i] = array[i + 1];
}
A: You can always do:
int i, j;
for (i = j = 0; j < foo.length; ++j)
if (!"a".equals(foo[j])) foo[i++] = foo[j];
foo = Arrays.copyOf(foo, i);
A: [If you want some ready-to-use code, please scroll to my "Edit3" (after the cut). The rest is here for posterity.]
To flesh out Dustman's idea:
List<String> list = new ArrayList<String>(Arrays.asList(array));
list.removeAll(Arrays.asList("a"));
array = list.toArray(array);
Edit: I'm now using Arrays.asList instead of Collections.singleton: singleton is limited to one entry, whereas the asList approach allows you to add other strings to filter out later: Arrays.asList("a", "b", "c").
Edit2: The above approach retains the same array (so the array is still the same length); the element after the last is set to null. If you want a new array sized exactly as required, use this instead:
array = list.toArray(new String[0]);
Edit3: If you use this code on a frequent basis in the same class, you may wish to consider adding this to your class:
private static final String[] EMPTY_STRING_ARRAY = new String[0];
Then the function becomes:
List<String> list = new ArrayList<>();
Collections.addAll(list, array);
list.removeAll(Arrays.asList("a"));
array = list.toArray(EMPTY_STRING_ARRAY);
This will then stop littering your heap with useless empty string arrays that would otherwise be newed each time your function is called.
cynicalman's suggestion (see comments) will also help with the heap littering, and for fairness I should mention it:
array = list.toArray(new String[list.size()]);
I prefer my approach, because it may be easier to get the explicit size wrong (e.g., calling size() on the wrong list).
A: EDIT:
The point with the nulls in the array has been cleared. Sorry for my comments.
Original:
Ehm... the line
array = list.toArray(array);
replaces all gaps in the array where the removed element has been with null. This might be dangerous, because the elements are removed, but the length of the array remains the same!
If you want to avoid this, use a new Array as parameter for toArray(). If you don`t want to use removeAll, a Set would be an alternative:
String[] array = new String[] { "a", "bc" ,"dc" ,"a", "ef" };
System.out.println(Arrays.toString(array));
Set<String> asSet = new HashSet<String>(Arrays.asList(array));
asSet.remove("a");
array = asSet.toArray(new String[] {});
System.out.println(Arrays.toString(array));
Gives:
[a, bc, dc, a, ef]
[dc, ef, bc]
Where as the current accepted answer from Chris Yester Young outputs:
[a, bc, dc, a, ef]
[bc, dc, ef, null, ef]
with the code
String[] array = new String[] { "a", "bc" ,"dc" ,"a", "ef" };
System.out.println(Arrays.toString(array));
List<String> list = new ArrayList<String>(Arrays.asList(array));
list.removeAll(Arrays.asList("a"));
array = list.toArray(array);
System.out.println(Arrays.toString(array));
without any null values left behind.
A: My little contribution to this problem.
public class DeleteElementFromArray {
public static String foo[] = {"a","cc","a","dd"};
public static String search = "a";
public static void main(String[] args) {
long stop = 0;
long time = 0;
long start = 0;
System.out.println("Searched value in Array is: "+search);
System.out.println("foo length before is: "+foo.length);
for(int i=0;i<foo.length;i++){ System.out.println("foo["+i+"] = "+foo[i]);}
System.out.println("==============================================================");
start = System.nanoTime();
foo = removeElementfromArray(search, foo);
stop = System.nanoTime();
time = stop - start;
System.out.println("Equal search took in nano seconds = "+time);
System.out.println("==========================================================");
for(int i=0;i<foo.length;i++){ System.out.println("foo["+i+"] = "+foo[i]);}
}
public static String[] removeElementfromArray( String toSearchfor, String arr[] ){
int i = 0;
int t = 0;
String tmp1[] = new String[arr.length];
for(;i<arr.length;i++){
if(arr[i] == toSearchfor){
i++;
}
tmp1[t] = arr[i];
t++;
}
String tmp2[] = new String[arr.length-t];
System.arraycopy(tmp1, 0, tmp2, 0, tmp2.length);
arr = tmp2; tmp1 = null; tmp2 = null;
return arr;
}
}
A: Arrgh, I can't get the code to show up correctly. Sorry, I got it working. Sorry again, I don't think I read the question properly.
String foo[] = {"a","cc","a","dd"},
remove = "a";
boolean gaps[] = new boolean[foo.length];
int newlength = 0;
for (int c = 0; c<foo.length; c++)
{
if (foo[c].equals(remove))
{
gaps[c] = true;
newlength++;
}
else
gaps[c] = false;
System.out.println(foo[c]);
}
String newString[] = new String[newlength];
System.out.println("");
for (int c1=0, c2=0; c1<foo.length; c1++)
{
if (!gaps[c1])
{
newString[c2] = foo[c1];
System.out.println(newString[c2]);
c2++;
}
}
A: It depends on what you mean by "remove"? An array is a fixed size construct - you can't change the number of elements in it. So you can either a) create a new, shorter, array without the elements you don't want or b) assign the entries you don't want to something that indicates their 'empty' status; usually null if you are not working with primitives.
In the first case create a List from the array, remove the elements, and create a new array from the list. If performance is important iterate over the array assigning any elements that shouldn't be removed to a list, and then create a new array from the list. In the second case simply go through and assign null to the array entries.
A: Will copy all elements except the one with index i:
if(i == 0){
System.arraycopy(edges, 1, copyEdge, 0, edges.length -1 );
}else{
System.arraycopy(edges, 0, copyEdge, 0, i );
System.arraycopy(edges, i+1, copyEdge, i, edges.length - (i+1) );
}
A: If it doesn't matter the order of the elements. you can swap between the elements foo[x] and foo[0], then call foo.drop(1).
foo.drop(n) removes (n) first elements from the array.
I guess this is the simplest and resource efficient way to do.
PS: indexOf can be implemented in many ways, this is my version.
Integer indexOf(String[] arr, String value){
for(Integer i = 0 ; i < arr.length; i++ )
if(arr[i] == value)
return i; // return the index of the element
return -1 // otherwise -1
}
while (true) {
Integer i;
i = indexOf(foo,"a")
if (i == -1) break;
foo[i] = foo[0]; // preserve foo[0]
foo.drop(1);
}
A: to remove only the first of several equal entries
with a lambda
boolean[] done = {false};
String[] arr = Arrays.stream( foo ).filter( e ->
! (! done[0] && Objects.equals( e, item ) && (done[0] = true) ))
.toArray(String[]::new);
can remove null entries
A: Assign null to the array locations.
A: In an array of Strings like
String name = 'a b c d e a f b d e' // could be like String name = 'aa bb c d e aa f bb d e'
I build the following class
class clearname{
def parts
def tv
public def str = ''
String name
clearname(String name){
this.name = name
this.parts = this.name.split(" ")
this.tv = this.parts.size()
}
public String cleared(){
int i
int k
int j=0
for(i=0;i<tv;i++){
for(k=0;k<tv;k++){
if(this.parts[k] == this.parts[i] && k!=i){
this.parts[k] = '';
j++
}
}
}
def str = ''
for(i=0;i<tv;i++){
if(this.parts[i]!='')
this.str += this.parts[i].trim()+' '
}
return this.str
}}
return new clearname(name).cleared()
getting this result
a b c d e f
hope this code help anyone
Regards
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/112503",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "90"
}
|
Q: Can't attach to w3wp under Vista with UAC turned on I run Vista (business x32) on my work machine, in which I do ASP.NET development. Because I use IIS to server the sites I build (I do a lot of CMS integrations so I need to use IIS not the inbuilt web development server) I always need to attach to w3wp for debugging.
The problem is that w3wp requires elevated permissions for me to connect to the processes from VS 2008. But when I try and restart VS to "run as administrator" I get the error:
"This program has been blocked"
"Your administrator has set a policy to block this program"
I only get this problem when I'm logged into my machine with my domain account (which is in the local admin group), if I use the local admin I have no problems.
I'm the only person on the domain who has this problem, everyone else using Vista can open VS as an administrator no dramas.
To get around this I have to turn off UAC, but it always turns itself back on (after each restart), so this is highly frustrating.
I've not been able to find out how to add a program to the "safe" list either.
A: Have you asked the Domain Admins if they have a Group Policy which is re-enabling UAC?
It may be that Vista by default has only a few places that can run unrestricted and if you have Visual Studio installed outside those areas, it may be preventing it from running with elevated permissions.
Check where it is installed, and add its location as an "unrestricted" area within the Softwware Restrictions / Additional Rules area.
To do this follow these steps:
*
*Open the secpol.msc editor.
*Browse to Local Policies / Software Restriction Policies / Additional Rules.
*Then right click the right window and choose New Path Rule...
*Browse to the path where VS is installed and set the Security Level to Unrestricted.
See if that doesn't do the trick.
Good Luck!
A: You could write a script that disables UAC and then run that script every time you restart your computer, or maybe just before you launch VS.
Modify registry:
*
*How to Disable or Enable Vista User Access Control in Command Prompt
More options for disable/enable UAC:
*
*How to Disable and Turn Off UAC in Windows 7
I can open VS with "Run as administrator" under my domain account (which is in the local admin group) on my work computer, so I suspect something is wrong on your computer. And by now, you may have had you PC re-imaged, so perhaps the problem went away for you.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/112508",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to build interface for such enum I have the following enum:
public enum Status implements StringEnum{
ONLINE("on"),OFFLINE("off");
private String status = null;
private Status(String status) {
this.status = status;
}
public String toString() {
return this.status;
}
public static Status find(String value) {
for(Status status : Status.values()) {
if(status.toString().equals(value)) {
return status;
}
}
throw new IllegalArgumentException("Unknown value: " + value );
}
}
Is it possible to build StringEnum interface to make sure every enum has find(), toString() and a constructor?
Thanks.
A: It's not possible to specify either constructors or static methods in an interface. For a good, concise explanation, check out this article: No static methods in interfaces
A: Enums already have a valueOf() (your find method) method. And "toString()" is a java.lang.Object method, so, every class will have that, in other words, you can't force it! I can't see the value of enforcing a constructor since different enums could have different initializations.
Kind Regards
A: *
*static methods cannot be defined in interfaces
*constructors cannot be defined in interfaces
*toString is defined in java.lang.Object, requiring it in an interface will never result in a compile error if the method isn't defined.
Why do you want to enforce the constructor anyway? You cannot create new instances of enums at runtime anyway (unless maybe via some reflection mechanism).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/112517",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Calculate text diffs in PHP Are there any libraries (3rd party or built-in) in PHP to calculate text diffs?
A: it depends exactly what you mean and what you want to do but there is
PEAR Text_Diff - Engine for performing and rendering text diffs
A: What sort of diffs? File diffs? There is array_diff() which acts on arrays. Then there is also xdiff, which "enables you to create and apply patch files containing differences between different revisions of files.". The latter acts on files or strings.
Edit: I should add xdiff doesn't appear to be out in a release yet. You have to build from source to use it.
A: There is a nice and tiny Simplediff project on Github which creates text and HTML diffs.
A: The output of this is in GNU diff format. It might be what you're looking for.
A: MediaWiki's diff engine is open source (just like the rest of it). If you like the way Wikipedia handles text diffs, it may be a solution for you.
A: It really depends on what outcome you want. If all you want to do is to get the diff files for two sets of text, you may find it simpler to just use an external diff command (which of course totally depends on the environment you're developing for).
$diff = `diff $file1 $file2`;
From there if you want to use the diff information at all you would need to parse and this solution might not be what you're after. In that case I'd suggest looking at the PEAR library mentioned above or searching for a similar text parsing library.
A: I really like this JavaScript based one for web projects.
jsdifflib
A: Not build in, but I like it because it has such a nice interface to test everything out on the website, and because it seems to be somewhat faster than Text_Diff at high granularity levels.
http://www.raymondhill.net/finediff/viewdiff-ex.php
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/112523",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
}
|
Q: List all words in a dictionary that start with How would a go about making a program where the user enters a string, and the program generates a list of words beginning with that string?
Ex:
User: "abd"
Program:abdicate, abdomen, abduct...
Thanks!
Edit: I'm using python, but I assume that this is a fairly language-independent problem.
A: One of the best ways to do this is to use a directed graph to store your dictionary. It takes a little bit of setting up, but once done it is fairly easy to then do the type of searches you are talking about.
The nodes in the graph correspond to a letter in your word, so each node will have one incoming link and up to 26 (in English) outgoing links.
You could also use a hybrid approach where you maintain a sorted list containing your dictionary and use the directed graph as an index into your dictionary. Then you just look up your prefix in your directed graph and then go to that point in your dictionary and spit out all words matching your search criteria.
A: If you on a debian[-like] machine,
#!/bin/bash
echo -n "Enter a word: "
read input
grep "^$input" /usr/share/dict/words
Takes all of 0.040s on my P200.
A: egrep `read input && echo ^$input` /usr/share/dict/words
oh I didn't see the Python edit, here is the same thing in python
my_input = raw_input("Enter beginning of word: ")
my_words = open("/usr/share/dict/words").readlines()
my_found_words = [x for x in my_words if x[0:len(my_input)] == my_input]
A: If you really want speed, use a trie/automaton. However, something that will be faster than simply scanning the whole list, given that the list of words is sorted:
from itertools import takewhile, islice
import bisect
def prefixes(words, pfx):
return list(
takewhile(lambda x: x.startswith(pfx),
islice(words,
bisect.bisect_right(words, pfx),
len(words)))
Note that an automaton is O(1) with regard to the size of your dictionary, while this algorithm is O(log(m)) and then O(n) with regard to the number of strings that actually start with the prefix, while the full scan is O(m), with n << m.
A: def main(script, name):
for word in open("/usr/share/dict/words"):
if word.startswith(name):
print word,
if __name__ == "__main__":
import sys
main(*sys.argv)
A: If you really want to be efficient - use suffix trees or suffix arrays - wikipedia article.
Your problem is what suffix trees were designed to handle.
There is even implementation for Python - here
A: You can use str.startswith(). Reference from the official docs:
str.startswith(prefix[, start[, end]])
Return True if string starts with the prefix, otherwise return False. prefix can also be a tuple of prefixes to look for. With optional start, test string beginning at that position. With optional end, stop comparing string at that position.
try code below:
dictionary = ['apple', 'abdicate', 'orange', 'abdomen', 'abduct', 'banana']
user_input = input('Enter something: ')
for word in dictionary:
if word.startswith(user_input):
print(word)
Output:
Enter something: abd
abdicate
abdomen
abduct
A: Use a trie.
Add your list of words to a trie. Each path from the root to a leaf is a valid word. A path from a root to an intermediate node represents a prefix, and the children of the intermediate node are valid completions for the prefix.
A: var words = from word in dictionary
where word.key.StartsWith("bla-bla-bla");
select word;
A: Try using regex to search through your list of words, e.g. /^word/ and report all matches.
A: If you need to be really fast, use a tree:
build an array and split the words in 26 sets based on the first letter, then split each item in 26 based on the second letter, then again.
So if your user types "abd" you would look for Array[0][1][3] and get a list of all the words starting like that. At that point your list should be small enough to pass over to the client and use javascript to filter.
A: Most Pythonic solution
# set your list of words, whatever the source
words_list = ('cat', 'dog', 'banana')
# get the word from the user inpuit
user_word = raw_input("Enter a word:\n")
# create an generator, so your output is flexible and store almost nothing in memory
word_generator = (word for word in words_list if word.startswith(user_word))
# now you in, you can make anything you want with it
# here we just list it :
for word in word_generator :
print word
Remember generators can be only used once, so turn it to a list (using list(word_generator)) or use the itertools.tee function if you expect using it more than once.
Best way to do it :
Store it into a database and use SQL to look for the word you need. If there is a lot of words in your dictionary, it will be much faster and efficient.
Python got thousand of DB API to help you do the job ;-)
A: If your dictionary is really big, i'd suggest indexing with a python text index (PyLucene - note that i've never used the python extension for lucene) The search would be efficient and you could even return a search 'score'.
Also, if your dictionary is relatively static you won't even have the overhead of re-indexing very often.
A: Don't use a bazooka to kill a fly. Use something simple just like SQLite. There are all the tools you need for every modern languages and you can just do :
"SELECT word FROM dict WHERE word LIKE "user_entry%"
It's lightning fast and a baby could do it. What's more it's portable, persistent and so easy to maintain.
Python tuto :
http://www.initd.org/pub/software/pysqlite/doc/usage-guide.html
A: A linear scan is slow, but a prefix tree is probably overkill. Keeping the words sorted and using a binary search is a fast and simple compromise.
import bisect
words = sorted(map(str.strip, open('/usr/share/dict/words')))
def lookup(prefix):
return words[bisect.bisect_left(words, prefix):bisect.bisect_right(words, prefix+'~')]
>>> lookup('abdicat')
['abdicate', 'abdication', 'abdicative', 'abdicator']
A: If you store the words in a .csv file, you can use pandas to solve this rather neatly, and after you have read it once you can reuse the already loaded data frame if the user should be able to perform more than one search per session.
df = pd.read_csv('dictionary.csv')
matching_words = df[0].loc[df[0].str.startswith(user_entry)]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/112532",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: SQL Server Priority Ordering I have a table that contains tasks and I want to give these an explicit ordering based on the priority of the task. The only way I can think to do this is via an unique int column that indexes where the task is in term of the priority (i.e. 1 is top 1000 is low).
The problem is that say I wanted to update task and set its priority to a lower value , I would have to update all the other rows between its current value and its new value.
Can anyone suggest a better way of implementing this?
A: Use a real number value as the priority. You can always slide in a value between two existing values with something like newPri = task1Pri + (task2Pri - task1Pri)/2 where Task1 has the lower priority numeric value (which is probably the higher piority).
Corin points out that min and max priorities would have to be calculated for tasks inserted at the top or bottom of the priority list.
And joelhardi reminds us that a reorder process is a good idea to clean up the table from time to time.
A: Instead of creating an numbered column like you said, create a field called something like parent. Each row contains the pk of its parent item. When you want to move one item down just change its parent pk to the new one and the item(s) which reference it in their parent pk. Think singly linked lists.
A: I like Kevin's answer best, but if you want a quick-and-dirty solution, just do it the way you've already described, but instead of incrementing by 1, increment by 10 or 100... that way if you need to re-prioritize, you have some wiggle room between tasks.
A: I would assign only a small number of values (1..10) and then ORDER BY Priority DESC, DateCreated ASC.
If you need to have different priorities for each task you need to UPDATE WHERE Priority > xxx like you said.
A: if no two tasks can have the same priority then I think that is what you have to do. But you could have a priority and a datemodified column and just sort by both to get the right order based on priority and last update if you allow priority to be duplicated.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/112551",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: How do I use genshi.builder to programmatically build an HTML document? I recently discovered the genshi.builder module. It reminds me of Divmod Nevow's Stan module. How would one use genshi.builder.tag to build an HTML document with a particular doctype? Or is this even a good thing to do? If not, what is the right way?
A: It's not possible to build an entire page using just genshi.builder.tag -- you would need to perform some surgery on the resulting stream to insert the doctype. Besides, the resulting code would look horrific. The recommended way to use Genshi is to use a separate template file, generate a stream from it, and then render that stream to the output type you want.
genshi.builder.tag is mostly useful for when you need to generate simple markup from within Python, such as when you're building a form or doing some sort of logic-heavy modification of the output.
See documentation for:
*
*Creating and using templates
*The XML-based template language
*genshi.builder API docs
If you really want to generate a full document using only builder.tag, this (completely untested) code could be a good starting point:
from itertools import chain
from genshi.core import DOCTYPE, Stream
from genshi.output import DocType
from genshi.builder import tag as t
# Build the page using `genshi.builder.tag`
page = t.html (t.head (t.title ("Hello world!")), t.body (t.div ("Body text")))
# Convert the page element into a stream
stream = page.generate ()
# Chain the page stream with a stream containing only an HTML4 doctype declaration
stream = Stream (chain ([(DOCTYPE, DocType.get ('html4'), None)], stream))
# Convert the stream to text using the "html" renderer (could also be xml, xhtml, text, etc)
text = stream.render ('html')
The resulting page will have no whitespace in it -- it'll look normal, but you'll have a hard time reading the source code because it will be entirely on one line. Implementing appropriate filters to add whitespace is left as an exercise to the reader.
A: Genshi.builder is for "programmatically generating markup streams"[1]. I believe the purpose of it is as a backend for the templating language. You're probably looking for the templating language for generating a whole page.
You can, however do the following:
>>> import genshi.output
>>> genshi.output.DocType('html')
('html', '-//W3C//DTD HTML 4.01//EN', 'http://www.w3.org/TR/html4/strict.dtd')
See other Doctypes here: http://genshi.edgewall.org/wiki/ApiDocs/genshi.output#genshi.output:DocType
[1] genshi.builder.__doc__
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/112564",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: C101: the best way to fill an array from user input? I'm having a hard time understanding and therefore managing arrays and indexes manually in C. These are my two classic approaches but they doesn't seem to work as they keep looping when the condition is reached:
#include<stdio.h>
#define MAX 255
int main(){
int arr[MAX]={0};
int idx=0;
/* Approach #1 */
printf("Enter elements, -1 to finish:\n");
scanf("%d", &arr[idx]);
while(arr[idx-1] != -1 && idx < MAX){
printf("Enter elements, -1 to finish:\n");
scanf("%d", &arr[idx]);
idx++;
}
/* Approach #2 */
do{
printf("Enter elements, -1 to finish:\n");
scanf("%d", &arr[idx]);
idx++;
}while(arr[idx-1] != -1 && idx < MAX);
// Main func continues here.
}
Any advice would be much appreciated!
Update:
Now it works! thanks MUCH all of you guys for such instant responses. This is definitely a great community, it's helping me a lot.
A: arr[idx] <= MAX
should be
idx <= MAX
A: while(arr[idx] != -1 && idx <= MAX){ // Fixed by sklivvz
printf("Enter elements, -1 to finish:\n");
scanf("%d", &arr[idx]);
idx++;
}
First of all, you should check if the index variabel idx is smaller than MAX (not smaller than or equal to). You would go out of bounds if your index equals MAX. An array with MAX = 10 has index values 0 to and including 9, but not 10.
Secondly, you add the first element to arr[0], you increment your index from 0 to 1, then you jump back to the while-condition and check if arr[1] == -1, which it is not. So check instead that arr[idx-1] != -1. Note however that the first time you get to the while-loop, you will actually check arr[-1] != -1, which is also out of bounds. ;) So you need to figure out how to solve this one.
A: to Roman M:
First of all, the guy asking the question has just started a programming course, and has probably not yet learned about pointers. Secondly, you now deal with both a counter and a pointer. I'm not sure I see the benefit of doing that versus using an index like this:
for(idx=0; idx < MAX; ++idx) {
scanf("%d", &arr[idx]);
if(arr[idx] == -1)
break;
}
A: Using a for loop you can eliminate the need for the messy idx-1 checking code:
/* Approach #3*/
int i;
int value;
for (i = 0; i < MAX; ++i)
{
printf("Enter elements, -1 to finish:\n");
scanf("%d", &value);
if (value == -1) break;
arr[i] = value;
}
A: C arrays begin counting from 0.
If you allocate an array of size MAX, accessing the element at MAX would be an error.
Change the loop to;
int arr[MAX];
for ( .... && idx < MAX )
A: arr[idx] <= MAX
should be
idx < MAX
unless you are checking the item instead of the index.
You are also always checking the "next" element for -1 (arr[idx] != -1) because you are incrementing idx prior to checking your added value.
so if you had
arr[idx-1] != -1
you would be fine.
A: In your first while loop, the
arr[idx] <= MAX
line should read
idx <= MAX
In your second loop, you're incrementing idx before the test - it should end with
} while ((arr[idx-1] != -1) && (idx-1 <= MAX));
I also tend to parenthesize all internal conditions just to be absolutely certain that the precedence is correct (hence the extra brackets above).
A: I'd go with somthing like this.
You don't have to worry about array bounds and other confusing conditions.
int cnt = MAX; // how many elements in the array, in this case MAX
int * p = &arr[0]; // p is a pointer to an integer and is initialize to the address of the first
// element of the array. So now *p is the same as arr[0] and p is same as &arr[0]
// iterate over all elements. stop when cnt == 0
while (cnt) {
// do somthing
scanf("%d", *p); // remember that *p is same as arr[some index]
if (*p == -1) // inspect element to see what user entered
break;
cnt --; // loop counter
p++; // incrementing p to point to next element in the array
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/112582",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Select Element in a Namespace with XPath I want to select the topmost element in a document that has a given namespace (prefix).
More specifically: I have XML documents that either start with /html/body (in the XHTML namespace) or with one of several elements in a particular namespace. I effectively want to strip out /html/body and just return the body contents OR the entire root namespaced element.
A: The XPath expression that I want is:
/html:html/html:body/node()|/foo:*
Where the "html" prefix is mapped to the XHTML namespace, and the "foo" prefix is mapped to my target namespace.
A: In XPath 2.0 and XQuery 1.0 you can test against the namespace prefix using the in-scope-prefixes() function in a predicate.
e.g.
//*[in-scope-prefixes(.)='html']
If you cant use v2, in XPath 1.0 you can use the namespace-uri() function to test against the namespace itself.
e.g.
//*[namespace-uri()='http://www.w3c.org/1999/xhtml']
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/112601",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
}
|
Q: What is 'JNI Global reference' I am using jProfiler to find memory leaks in a Java swing application. I have identified instances of a JFrame which keeps growing in count.
This frame is opened, and then closed.
Using jProfiler, and viewing the Paths to GC Root there is only one reference, 'JNI Global reference'.
What does this mean? Why is it hanging on to each instance of the frame?
A: A JNI global reference is a reference from "native" code to a Java object managed by the Java garbage collector. Its purpose is to prevent collection of an object that is still in use by native code, but doesn't appear to have any live references in the Java code.
A JFrame is a java.awt.Window, and is associated with a "native" Window object. When you are completely finished with a particular JFrame instance, you should invoke its dispose() method to clean up.
I am not sure if any native code is creating a global reference to the JFrame, but it seems likely. If it does, this will prevent the JFrame from being garbage collected. If you are creating many Windows (or subclasses) and seeing that they are never collected, make sure that they are disposed.
A: Wikipedia has a good overview of Java Native Interface, essentially it allows communication between Java and native operating system libraries writen in other languages.
JNI global references are prone to memory leaks, as they are not automatically garbage collected, and the programmer must explicitly free them. If you are not writing any JNI code yourself, it is possible that the library you are using has a memory leak.
edit here is a bit more info on local vs. global references, and why global references are used (and how they should be freed)
A: I had this exact problem when fixing memory leaks in a JavaFX application. In the end the problem turned out to be that i was running the application in debug mode and had several breakpoints in the code. This seems to have caused objects to be 'JNI Global reference' and being kept in memory without apparent reason. When i turned off the debug mode everything worked as it should!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/112603",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "34"
}
|
Q: Are C++ non-type parameters to (function) templates ordered? I am hosting SpiderMonkey in a current project and would like to have template functions generate some of the simple property get/set methods, eg:
template <typename TClassImpl, int32 TClassImpl::*mem>
JSBool JS_DLL_CALLBACK WriteProp(JSContext* cx, JSObject* obj, jsval id, jsval* vp)
{
if (TClassImpl* pImpl = (TClassImpl*)::JS_GetInstancePrivate(cx, obj, &TClassImpl::s_JsClass, NULL))
return ::JS_ValueToInt32(cx, *vp, &(pImpl->*mem));
return JS_FALSE;
}
Used:
::JSPropertySpec Vec2::s_JsProps[] = {
{"x", 1, JSPROP_PERMANENT, &JsWrap::ReadProp<Vec2, &Vec2::x>, &JsWrap::WriteProp<Vec2, &Vec2::x>},
{"y", 2, JSPROP_PERMANENT, &JsWrap::ReadProp<Vec2, &Vec2::y>, &JsWrap::WriteProp<Vec2, &Vec2::y>},
{0}
};
This works fine, however, if I add another member type:
template <typename TClassImpl, JSObject* TClassImpl::*mem>
JSBool JS_DLL_CALLBACK WriteProp(JSContext* cx, JSObject* obj, jsval id, jsval* vp)
{
if (TClassImpl* pImpl = (TClassImpl*)::JS_GetInstancePrivate(cx, obj, &TClassImpl::s_JsClass, NULL))
return ::JS_ValueToObject(cx, *vp, &(pImpl->*mem));
return JS_FALSE;
}
Then Visual C++ 9 attempts to use the JSObject* wrapper for int32 members!
1>d:\projects\testing\jswnd\src\main.cpp(93) : error C2440: 'specialization' : cannot convert from 'int32 JsGlobal::Vec2::* ' to 'JSObject *JsGlobal::Vec2::* const '
1> Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast
1>d:\projects\testing\jswnd\src\main.cpp(93) : error C2973: 'JsWrap::ReadProp' : invalid template argument 'int32 JsGlobal::Vec2::* '
1> d:\projects\testing\jswnd\src\wrap_js.h(64) : see declaration of 'JsWrap::ReadProp'
1>d:\projects\testing\jswnd\src\main.cpp(93) : error C2440: 'initializing' : cannot convert from 'overloaded-function' to 'JSPropertyOp'
1> None of the functions with this name in scope match the target type
Surprisingly, parening JSObject* incurs a parse error! (unexpected '('). This is probably a VC++ error (can anyone test that "template void foo() {}" compiles in GCC?). Same error with "typedef JSObject* PObject; ..., PObject TClassImpl::mem>", void, struct Undefined*, and double. Since the function usage is fully instantiated: "&ReadProp", there should be no normal function overload semantics coming into play, it is a defined function at that point and gets priority over template functions. It seems the template ordering is failing here.
Vec2 is just:
class Vec2
{
public:
int32 x, y;
Vec2(JSContext* cx, JSObject* obj, uintN argc, jsval* argv);
static ::JSClass s_JsClass;
static ::JSPropertySpec s_JsProps[];
};
JSPropertySpec is described in JSAPI link in OP, taken from header:
typedef JSBool
(* JS_DLL_CALLBACK JSPropertyOp)(JSContext *cx, JSObject *obj, jsval id,
jsval *vp);
...
struct JSPropertySpec {
const char *name;
int8 tinyid;
uint8 flags;
JSPropertyOp getter;
JSPropertyOp setter;
};
A: Pretty sure VC++ has "issues" here. Comeau and g++ 4.2 are both happy with the following program:
struct X
{
int i;
void* p;
};
template<int X::*P>
void foo(X* t)
{
t->*P = 0;
}
template<void* X::*P>
void foo(X* t)
{
t->*P = 0;
}
int main()
{
X x;
foo<&X::i>(&x);
foo<&X::p>(&x);
}
VC++ 2008SP1, however, is having none of it.
I haven't the time to read through my standard to find out exactly what's what... but I think VC++ is in the wrong here.
A: Try changing the JSObject * to another pointer type to see if that reproduces the error. Is JSObject defined at the point of use? Also, maybe JSObject* needs to be in parens.
A: I am certainly no template guru, but does this boil down to a subtle case of trying to differentiate overloads based purely on the return type?
Since C++ doesn't allow overloading of functions based on return type, perhaps the same thing applies to template parameters.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/112612",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: git instaweb gives 403 Forbidden - No projects found running git instaweb in my repository opens a page that says "403 Forbidden - No projects found". What am I missing?
A: looks like the debian install of git sets $projectroot globally in a way that confuses instaweb. I removed the $projectroot line from /etc/gitweb.conf and the error went away.
A: I don't know Git about Git, but you're probably missing the ability to execute on the directory in question, chmod +X it.
A: check the git-web cgi (the perl), see the directory of the projectroot is same as your currect setting. there are some settings that not in gitweb.conf
A: Two years later ..
I fixed this problem by stating the projectroot in gitweb.cgi (it's the only value that seems to matter)
A: And another year later ...
I fixed this problem (F12, git 1.7.2.3) by:
vi .git/gitweb/gitweb.cgi # set DocumentRoot to <root>/.git/gitweb.cgi
GITWEB_CONFIG=.git/gitweb lighttpd -f .git/gitweb/httpd.conf
I didn't dig further to figure out why I needed to do this ...
A: two year later ...
I fixed this problem by adding this line
Options All ExecCGI FollowSymLinks Includes Indexes
to my httpd.conf file
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/112613",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: == vs. Object.Equals(object) in .NET So, when I was a comparative novice to the novice I am right now, I used to think that these two things were syntactic sugar for each other, i.e. that using one over the other was simply a personal preference. Over time, I'm come to find that these two are not the same thing, even in a default implementation (see this and this). To further confuse the matter, each can be overridden/overloaded separately to have completely different meanings.
Is this a good thing, what are the differences, and when/why should you use one over the other?
A: Microsoft says that class implementers should make == behave as similarly as possible to Equals:
DO ensure that Object.Equals and the equality operators have exactly the same semantics
from http://msdn.microsoft.com/en-us/library/vstudio/7h9bszxx(v=vs.110).aspx
If you want to be certain you are getting IDENTITY comparison (when comparing references), then use ReferenceEquals instead.
If a class implementor does not override ==, then static method is looked for, at compile time, in base classes. If this search reaches Object, then Object.== is used. For classes, this is same as ReferenceEquals.
If class documentation is uncertain as to whether a given class (from a vendor other than Microsoft presumably) implements == as Equals or ReferenceEquals (or it could in theory be different than both of those),
I sometimes avoid ==. Instead, I use the less readable Equals(a, b) or ReferenceEquals(a, b), depending on which meaning I want.
OTOH, ps2goat makes a good point that using == avoids exception if first operand is null (because == is a static operator). This is an argument in favor of using ==.
Removed controversial commentary regarding ==
UPDATE A recent Microsoft doc quote, from .Net 4.7.2 retrieved Feb. 2019, shows they still intend the two to behave similarly:
Object.Equals Method
Some languages such as C# and Visual Basic support operator overloading. When a type overloads the equality operator, it must also override the Equals(Object) method to provide the same functionality. This is typically accomplished by writing the Equals(Object) method in terms of the overloaded equality operator, as in the following example.
NOTE: See other answers for the consequences of == being a static method vs Equals being an instance method. I'm not claiming behavior is identical; I'm observing that Microsoft recommends making the two as similar as possible.
A: I was going to post this as a comment on the accepted answer, but I think this deserves to be considered when determining which route to take.
dotnetfiddle: https://dotnetfiddle.net/gESLzO
Fiddle code:
Object a = null;
Object b = new Object();
// Ex 1
Console.WriteLine(a == b);
// Ex 2
Console.WriteLine(b == a);
// Ex 3
Console.WriteLine(b.Equals(a));
// Ex 4
Console.WriteLine(a.Equals(b));
The first 3 WriteLine examples will work, but the fourth throws an exception. 1 and 2 use ==, which is a static method that does not require either object to be instantiated.
Example 3 works because b is instantiated.
Example 4 fails because a is null, and thus a method can not be called on a null object.
Because I try to code as lazily as possible, I use ==, especially when working with scenarios where either object (or both) can be null. If I didn't, I'd have to do a null check, first, before being able to call .Equals().
A: string x = "hello";
string y = String.Copy(x);
string z = "hello";
To test if x points to the same object as y:
(object)x == (object)y // false
x.ReferenceEquals(y) // false
x.ReferenceEquals(z) // true (because x and z are both constants they
// will point to the same location in memory)
To test if x has the same string value as y:
x == y // true
x == z // true
x.Equals(y) // true
y == "hello" // true
Note that this is different to Java.
In Java the == operator is not overloaded so a common mistake in Java is:
y == "hello" // false (y is not the same object as "hello")
For string comparison in Java you need to always use .equals()
y.equals("hello") // true
A: MSDN has clear and solid descriptions of both things.
object.Equals method
operator ==
Overloadable Operators
Guidelines for Overriding Equals() and Operator ==
Is this a good thing, what are the
differences, and when/why should you
use one over the other?
How can it be "good" or "bad" thing? One - method, another - operator. If reference equality is not sufficient, overload them, otherwise leave them as is. For primitive types they just work out of box.
A: My understanding of the uses of both was this: use == for conceptual equality (in context, do these two arguments mean the same thing?), and .Equals for concrete equality (are these two arguments in actual fact the exact same object?).
Edit: Kevin Sheffield's linked article does a better job of explaining value vs. reference equality…
A: To answer this, we must describe the four kinds of object equivalence:
*
*Reference Equality, object.ReferenceEquals(a, b): The two variables point to the same exact object in RAM. (If this were C, both variables would have the same exact pointer.)
*Interchangeability, a == b: The two variables refer to objects that are completely interchangeable. Thus, when a == b, Func(a,b) and Func(b,a) do the same thing.
*Semantic Equality, object.Equals(a, b): At this exact moment in time, the two objects mean the same thing.
*Entity equality, a.Id == b.Id: The two objects refer to the same entity, such as a database row, but don’t have to have the same contents.
As a programmer, when working with an object of a known type, you need to understand the kind of equivalence that’s appropriate for your business logic at the specific moment of code that you’re in.
The simplest example about this is the string versus StringBuilder types. String overrides ==, StringBuilder does not:
var aaa1 = "aaa";
var aaa2 = $"{'a'}{'a'}{'a'}";
var bbb = "bbb";
// False because aaa1 and aaa2 are completely different objects with different locations in RAM
Console.WriteLine($"Object.ReferenceEquals(aaa1, aaa2): {Object.ReferenceEquals(aaa1, aaa2)}");
// True because aaa1 and aaa2 are completely interchangable
Console.WriteLine($"aaa1 == aaa2: {aaa1 == aaa2}"); // True
Console.WriteLine($"aaa1.Equals(aaa2): {aaa1.Equals(aaa2)}"); // True
Console.WriteLine($"aaa1 == bbb: {aaa1 == bbb}"); // False
Console.WriteLine($"aaa1.Equals(bbb): {aaa1.Equals(bbb)}"); // False
// Won't compile
// This is why string can override ==, you can not modify a string object once it is allocated
//aaa1[0] = 'd';
// aaaUpdated and aaa1 point to the same exact object in RAM
var aaaUpdated = aaa1;
Console.WriteLine($"Object.ReferenceEquals(aaa1, aaaUpdated): {Object.ReferenceEquals(aaa1, aaaUpdated)}"); // True
// aaaUpdated is a new string, aaa1 is unmodified
aaaUpdated += 'c';
Console.WriteLine($"Object.ReferenceEquals(aaa1, aaaUpdated): {Object.ReferenceEquals(aaa1, aaaUpdated)}"); // False
var aaaBuilder1 = new StringBuilder("aaa");
var aaaBuilder2 = new StringBuilder("aaa");
// False, because both string builders are different objects
Console.WriteLine($"Object.ReferenceEquals(aaaBuider1, aaaBuider2): {Object.ReferenceEquals(aaa1, aaa2)}");
// Even though both string builders have the same contents, they are not interchangable
// Thus, == is false
Console.WriteLine($"aaaBuider1 == aaaBuilder2: {aaaBuilder1 == aaaBuilder2}");
// But, because they both have "aaa" at this exact moment in time, Equals returns true
Console.WriteLine($"aaaBuider1.Equals(aaaBuilder2): {aaaBuilder1.Equals(aaaBuilder2)}");
// Modifying the contents of the string builders changes the strings, and thus
// Equals returns false
aaaBuilder1.Append('e');
aaaBuilder2.Append('f');
Console.WriteLine($"aaaBuider1.Equals(aaaBuilder2): {aaaBuilder1.Equals(aaaBuilder2)}");
To get into more details, we can work backwards, starting with entity equality. In the case of entity equality, properties of the entity may change over time, but the entity’s primary key never changes. This can be demonstrated with pseudocode:
// Hold the current user object in a variable
var originalUser = database.GetUser(123);
// Update the user’s name
database.UpdateUserName(123, user.Name + "son");
var updatedUser = database.GetUser(123);
Console.WriteLine(originalUser.Id == updatedUser.Id); // True, both objects refer to the same entity
Console.WriteLine(Object.Equals(originalUser, updatedUser); // False, the name property is different
Moving to semantic equality, the example changes slightly:
var originalUser = new User() { Name = "George" };
var updatedUser = new User() { Name = "George" };
Console.WriteLine(Object.Equals(originalUser, updatedUser); // True, the objects have the same contents
Console.WriteLine(originalUser == updatedUser); // User doesn’t define ==, False
updatedUser.Name = "Paul";
Console.WriteLine(Object.Equals(originalUser, updatedUser); // False, the name property is different
What about interchangeability? (overriding ==) That’s more complicated. Let’s build on the above example a bit:
var originalUser = new User() { Name = "George" };
var updatedUser = new User() { Name = "George" };
Console.WriteLine(Object.Equals(originalUser, updatedUser); // True, the objects have the same contents
// Does this change updatedUser? We don’t know
DoSomethingWith(updatedUser);
// Are the following equivalent?
// SomeMethod(originalUser, updatedUser);
// SomeMethod(updatedUser, originalUser);
In the above example, DoSomethingWithUser(updatedUser) might change updatedUser. Thus we can no longer guarantee that the originalUser and updatedUser objects are "Equals." This is why User does not override ==.
A good example for when to override == is with immutable objects. An immutable object is an object who’s publicly-visible state (properties) never change. The entire visible state must be set in the object’s constructor. (Thus, all properties are read-only.)
var originalImmutableUser = new ImmutableUser(name: "George");
var secondImmutableUser = new ImmutableUser(name: "George");
Console.WriteLine(Object.Equals(originalImmutableUser, secondImmutableUser); // True, the objects have the same contents
Console.WriteLine(originalImmutableUser == secondImmutableUser); // ImmutableUser defines ==, True
// Won’t compile because ImmutableUser has no setters
secondImmutableUser.Name = "Paul";
// But this does compile
var updatedImmutableUser = secondImmutableUser.SetName("Paul"); // Returns a copy of secondImmutableUser with Name changed to Paul.
Console.WriteLine(object.ReferenceEquals(updatedImmutableUser, secondImmutableUser)); // False, because updatedImmutableUser is a different object in a different location in RAM
// These two calls are equivalent because the internal state of an ImmutableUser can never change
DoSomethingWith(originalImmutableUser, secondImmutableUser);
DoSomethingWith(secondImmutableUser, originalImmutableUser);
Should you override == with a mutable object? (That is, an object who’s internal state can change?) Probably not. You would need to build a rather complicated event system to maintain interchangeability.
In general, I work with a lot of code that uses immutable objects, so I override == because it’s more readable than object.Equals. When I work with mutable objects, I don’t override == and rely on object.Equals. Its the programmer’s responsibility to know if the objects they are working with are mutable or not, because knowing if something’s state can change should influence how you design your code.
The default implementation of == is object.ReferenceEquals because, with mutable objects, interchangeability is only guaranteed when the variables point to the same exact object in RAM. Even if the objects have the same contents at a given point in time, (Equals returns true,) there is no guarantee that the objects will continue to be equal; thus the objects are not interchangeable. Thus, when working with a mutable object that does not override ==, the default implementation of == works, because if a == b, they are the same object, and SomeFunc(a, b) and SomeFunc(b, a) are exactly the same.
Furthermore, if a class does not define equivalence, (For example, think of a database connection, and open file handle, ect,) then the default implementation of == and Equals fall back to reference equality, because two variables of type database connection, open file handle, ect, are only equal if they are the exact instance of the database connection, open file handle, ect. Entity equality might make sense in business logic that needs to know that two different database connections refer to the same database, or that two different file handles refer to the same file on disk.
Now, for my soapbox moment. In my opinion, C# handles this topic in a confusing way. == should be for semantic equality, instead of the Equals method. There should be a different operator, like ===, for interchangeability, and potentially another operator, ====, for referential equality. This way, someone who's a novice, and / or writing CRUD applications, only needs to understand ==, and not the more nuanced details of interchangeability and referential equality.
A: You may want to use .Equals as someone may come along at a later time and overload them for you class.
A: Two of the most often used types, String and Int32, implement both operator==() and Equals() as value equality (instead of reference equality). I think one can consider these two defining examples, so my conclusion is that both have identical meanings. If Microsoft states otherwise, I think they are intentionally causing confusion.
A: Operator == and Equals() both are same while we are comparing values instead of references. Output of both are same see below example.
Example
static void Main()
{
string x = " hello";
string y = " hello";
string z = string.Copy(x);
if (x == y)
{
Console.WriteLine("== Operator");
}
if(x.Equals(y))
{
Console.WriteLine("Equals() Function Call");
}
if (x == z)
{
Console.WriteLine("== Operator while coping a string to another.");
}
if (x.Equals(y))
{
Console.WriteLine("Equals() Function Call while coping a string to another.");
}
}
Output:
== Operator
Equals() Function Call
== Operator while coping a string to another.
Equals() Function Call while coping a string to another.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/112625",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "52"
}
|
Q: How can I dynamically create a selector at runtime with Objective-C? I know how to create a SEL at compile time using @selector(MyMethodName:) but what I want to do is create a selector dynamically from an NSString. Is this even possible?
What I can do:
SEL selector = @selector(doWork:);
[myobj respondsToSelector:selector];
What I want to do: (pseudo code, this obviously doesn't work)
SEL selector = selectorFromString(@"doWork");
[myobj respondsToSelector:selector];
I've been searching the Apple API docs, but haven't found a way that doesn't rely on the compile-time @selector(myTarget:) syntax.
A: I know this has been answered for long ago, but still I wanna share. This can be done using sel_registerName too.
The example code in the question can be rewritten like this:
SEL selector = sel_registerName("doWork:");
[myobj respondsToSelector:selector];
A: According to the XCode documentation, your psuedocode basically gets it right.
It’s most efficient to assign values to SEL variables at compile time with the @selector() directive. However, in some cases, a program may need to convert a character string to a selector at runtime. This can be done with the NSSelectorFromString function:
setWidthHeight = NSSelectorFromString(aBuffer);
Edit: Bummer, too slow. :P
A: I'm not an Objective-C programmer, merely a sympathizer, but maybe NSSelectorFromString is what you need. It's mentioned explicity in the Runtime Reference that you can use it to convert a string to a selector.
A: I'd have to say that it's a little more complicated than the previous respondents' answers might suggest... if you indeed really want to create a selector... not just "call one" that you "have laying around"...
You need to create a function pointer that will be called by your "new" method.. so for a method like [self theMethod:(id)methodArg];, you'd write...
void (^impBlock)(id,id) = ^(id _self, id methodArg) {
[_self doSomethingWith:methodArg];
};
and then you need to generate the IMP block dynamically, this time, passing, "self", the SEL, and any arguments...
void(*impFunct)(id, SEL, id) = (void*) imp_implementationWithBlock(impBlock);
and add it to your class, along with an accurate method signature for the whole sucker (in this case "v@:@", void return, object caller, object argument)
class_addMethod(self.class, @selector(theMethod:), (IMP)impFunct, "v@:@");
You can see some good examples of this kind of runtime shenanigans, in one of my repos, here.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/112643",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "94"
}
|
Q: Comparison of embedded operating systems? I've been involved in embedded operating systems of one flavor or another, and have generally had to work with whatever the legacy system had. Now I have the chance to start from scratch on a new embedded project.
The primary constraints on the system are:
*
*It needs a web-based interface.
*Inputs are required to be processed in real-time (so a true RTOS is needed).
*The memory available is 32MB of RAM and FLASH.
The operating systems that the team has used previously are VxWorks, ThreadX, uCos, pSOS, and Windows CE.
Does anyone have a comparison or trade study regarding operating system choice?
Are there any other operating systems that we should consider? (We've had eCos and RT-Linux suggested).
Edit - Thanks for all the responses to date. A pity I can't flag all as "accepted".
A: I think it would be wise to evaluate carefully what you mean by "RTOS". I have worked for years at a large company that builds high-performance embedded systems, and they refer to them as "real-time", although that's not what they really are. They are low-latency and have deterministic schedulers, and 9 times out of 10, that's what people are really after when they say RTOS.
True real-time requires hardware support and is likely not what you really mean. If all you want is low latency and deterministic scheduling (again, I think this is what people mean 90% of the time when they say "real-time"), then any Linux distribution would work just fine for you. You could probably even get by with Windows (I'm not sure how you control the Windows scheduler though...).
Again, just be careful what you mean by "Real-time".
A: I worked with QNX many years ago, and have nothing but great things to say about it. Even back then, QNX 4 (which is positively chunky compared to the Neutrino microkernel) was perfectly suited for low memory situations (though 32MB is oodles compared to the 1-2MB that we had to play with), and while I didn't explicitly play with any web-based stuff, I know Apache was available.
A: It all depends on how much time was allocated for your team has to learn a "new" RTOS.
Are there any reasons you don't want to use something that people already have experience with?
I have plenty of experience with vxWorks and I like it, but disregard my opinion as I work for WindRiver.
uC/OS II has the advantage of being fully documented (as in the source code is actually explained) in Labrosse's Book. Don't know about Web Support though.
I know pSos is no longer available.
You can also take a look at this list of RTOSes
A: I purchased some development hardware from netburner
It has been very easy to work with and very well documented. It is an RTOS running uCLinux. The company is great to work with.
A: It might be a wise decision to select an OS that your team is experienced with. However I would like to promote two good open source options:
*
*eCos (has you mentioned)
*RTEMS
Both have a lot of features and drivers for a wide variety of architectures. You haven't mentioned what architecture you will be using. They provide POSIX layers which is nice if you want to stay as portable as possible.
Also the license for both eCos and RTEMS is GPL but with an exception so that the executable that is produced by linking against the kernel is not covered by GPL.
The communities are very active and there are companies which provide commercial support and development.
A: We've been very happy with the Keil RTX system....light and fast and meets all of our tight real time constraints. It also has some nice debugging features built in to monitor stack overflow, etc.
A: I have been pretty happy with Windows CE, although it is 'heavier'.
A: Posting to agree with Ben Collins -- your really need to determine if you have a soft real-time requirement (primarily for human interaction) or hard real-time requirement (for interfacing with timing-sensitive devices).
A: Soft can also mean that you can tolerate some hiccups every once in a while.
What is the reliability requirements? My experience with more general-purpose operating systems like Linux in embedded is that they tend to experience random hiccups due to their smart average-case optimizations that try to avoid starvation and similar for individual tasks.
A: VxWorks is good:
*
*good documentation;
*friendly developing tool;
*low latency;
*deterministic scheduling.
However, I doubt that WindRiver would convert their major attention to Linux and WindRiver Linux would break into the market of WindRiver VxWorks.
Less market, less requirement of engineers.
A: Here is the latest study. The last one was done more than 8 years ago so this is most relevant. The tables can be used to add additional RTOS choices. You'll note that this comparison is focused on lighter machines but is equally applicable to heavier machines provided virtual memory is not required.
http://www.embedded.com/design/operating-systems/4425751/Comparing-microcontroller-real-time-operating-systems
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/112663",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: Connect to SQL Server from cygwin window times out, from DOS prompt works I can connect to my SQL Server database via sqlcmd from a DOS command window, but not from a Cygwin window. From DOS:
F:\Cygnus>sqlcmd -Q "select 'a test'" -S .\SQLEXPRESS
a test
(1 rows affected)
F:\Cygnus>
====================================================
From Cygwin:
$ sqlcmd -Q "select 'a test'" -S .\SQLEXPRESS
HResult 0x35, Level 16, State 1 Named Pipes Provider: Could not
open a connection to SQL Server [53]. Sqlcmd: Error: Microsoft SQL
Native Client : An error has occurred while establishing a connection
to the server. When connecting to SQL Server 2005, this failure may be
caused by the fact that under the default settings SQL Server does not
allow remote connections.. Sqlcmd: Error: Microsoft SQL Native Client
: Login timeout expired.
A: The backslash is being eaten by cygwin's bash shell. Try doubling it:
sqlcmd -Q "select 'a test'" -S .\\SQLEXPRESS
A: You may have to allow remote connections for this, and give the full server name i.e SERVER\SQLEXPRESS
A: You can also pass query/instruction to db and receive output in shell if you use "-Q" switch:
sqlcmd -Q "select * from nice.dbo.TableName ac ORDER BY 1 DESC" -S server_name\\db_name
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/112664",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Restore a SQL Server database from single instance to cluster I need to transfer a database from a SQL Server instance test server to a production environment that is clustered. But SQL Server doesn't allow you to use backup/restore to do it from single instance to cluster. I'm talking about a Microsoft CRM complex database here.
Your help is greatly appreciated.
A: Have a look at the Microsoft SQL Server Database Publishing Wizard:
SQL Server Database Publishing Wizard
enables the deployment of SQL Server
databases into a hosted environment on
either a SQL Server 2000 or 2005
server. It generates a single SQL
script file which can be used to
recreate a database (both schema and
data) in a shared hosting environment
where the only connectivity to a
server is through a web-based control
panel with a script execution window.
If supported by the hosting service
provider, the Database Publishing
Wizard can also directly upload
databases to servers located at the
shared hosting provider.
Optionally, SQL Server Database
Publishing Wizard can integrate
directly into Visual Studio 2005
and/or Visual Web Developer 2005
allowing easy publishing of databases
from within the development
environment.
You don't have to use the server-side piece; the client-side 'create a script' piece is generally enough.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/112676",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Friendly url scheme? One of the many things that's been lacking from my scraper service that I set up last week are pretty URLs. Right now the user parameter is being passed into the script with ?u=, which is a symptom of a lazy hack (which the script admittedly is). However, I've been thinking about redoing it and I'd like to get some feedback on the options available. Right now there are two pages, update and chart, that provide information to the user. Here are the two possibilities that I came up with. "1234" is the user ID number. For technical reasons the user name unfortunately cannot be used:
*
*http://< tld >/update/1234
*http://< tld >/chart/1234
or
*
*http://< tld >/1234/update
*http://< tld >/1234/chart
Option #1, conceptually, is calling update with the user ID. Option #2 is providing a verb to operate on a user ID.
From a consistency standpoint, which makes more sense?
Another option mentioned is
*
*http://< tld >/user/1234/update
*http://< tld >/user/1234/chart
This provides room for pages not relating to a specific user. i.e.
*
*http://< tld >/stats
A: If you go with this scheme it becomes simple to stop (well-behaved) robots from spidering your site:
http://< tld >/update/1234
http://< tld >/chart/1234
This is because you could setup a /robots.txt file to contain:
Disallow /update/
Disallow /chart/
To me that is a nice bonus which is often overlooked.
A: Option #1 matches the common ASP.NET MVC examples. Some of the examples at Model View Controller model have the form {controller}/{action}/{id}. The .NET 3.5 quickstart on routing has a table showing some valid route patterns:
Route definition
-- Example of matching URL
{controller}/{action}/{id}
-- /Products/show/beverages
{table}/Details.aspx
-- /Products/Details.aspx
blog/{action}/{entry}
-- /blog/show/123
{reporttype}/{year}/{month}/{day}
-- /sales/2008/1/5
{locale}/{action}
-- /en-US/show
{language}-{country}/{action}
-- /en-US/show
A: I'd be gently inclined toward leading with the userid -- option #2 -- since (what exists of) the directory structure is two different functions over a user's data. It's the user's chart, and the user's update.
It's a pretty minor point, though, without knowing if there's plans for significant expansion of the functionality of this thing.
*
*Is everything going forward going to be additional functions foo and bar and baz for individual users? If so, option #2 gets more attractive for the above reason -- the userid is the core data, it kind of makes sense to start with it semantically.
*Are you going to add non-user-driven functionality? Leading with a header directory might make sense then -- /user/1234/update, /user/1234/chart, /question/45678/activity, /question/45678/stats, etc.
A: I personally like this style, because it keeps the user the same, but gives you specific insight in to them.
*
*http://< tld >/1234/update
*http://< tld >/1234/chart
If you went the other way I would expect to be able to see everything under /update or /chart and then narrow in by user.
A: Go with the latter; URLs are meant to be hierarchical (or, at least, users read them that way by analogy to local directory paths). The focus here is on different views of a specific user, so "user" is the more general concept and should appear first.
A: I just replied to the question "How do you structure your URL routes?" with my opinions about making URLs RESTful, hackable and user friendly. I think it would be better to link than to write something similar in this question, hence the link.
A: I agree from a context standpoint, the application followed by the parameters make much more sense to me than the surrogate key for an item followed by the context of what the item is. Ultimately I'd suggest which ever is more natural for you to program.
A: Convention says object/verb/ID, so it should be:
http://< tld >/user/update/1234
(I just noticed that matches your updated question :)
So yes, #3 is the best choice.
This supports non-user operations as you mention (stats/), as well as multi-user operations:
http://< tld >/user/list/
A: If there's a way of listing users I'd introduce a users segment:
http://< tld >/users/ <--- user list
http://< tld >/users/1234/ <--- user profile, use overloaded POST on this to update.
http://< tld >/users/1234/chart/ <--- user chart
If you can only see your own details, ie users are invisible to each other, you don't need the user id since you can infer it from the session, in which case:
http://< tld >/user/ <--- user profile, use overloaded POST on this to update.
http://< tld >/user/chart/ <--- user chart
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/112695",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: py2exe - generate single executable file I thought I heard that py2exe was able to do this, but I never figured it out. Has anyone successfully done this? Can I see your setup.py file, and what command line options you used?
Basically I'm thinking of it giving me a single executable file that does something like unzips itself to maybe /temp and runs.
A: I've been able to create a single exe file with all resources embeded into the exe.
I'm building on windows. so that will explain some of the os.system calls i'm using.
First I tried converting all my images into bitmats and then all my data files into text strings.
but this caused the final exe to be very very large.
After googleing for a week i figured out how to alter py2exe script to meet my needs.
here is the patch link on sourceforge i submitted, please post comments so we can get it included in
the next distribution.
http://sourceforge.net/tracker/index.php?func=detail&aid=3334760&group_id=15583&atid=315583
this explanes all the changes made, i've simply added a new option to the setup line.
here is my setup.py.
i'll try to comment it as best I can.
Please know that my setup.py is complex do to the fact that i'm access the images by filename.
so I must store a list to keep track of them.
this is from a want-to-b screen saver I was trying to make.
I use exec to generate my setup at run time, its easyer to cut and paste like that.
exec "setup(console=[{'script': 'launcher.py', 'icon_resources': [(0, 'ICON.ico')],\
'file_resources': [%s], 'other_resources': [(u'INDEX', 1, resource_string[:-1])]}],\
options={'py2exe': py2exe_options},\
zipfile = None )" % (bitmap_string[:-1])
breakdown
script = py script i want to turn to an exe
icon_resources = the icon for the exe
file_resources = files I want to embed into the exe
other_resources = a string to embed into the exe, in this case a file list.
options = py2exe options for creating everything into one exe file
bitmap_strings = a list of files to include
Please note that file_resources is not a valid option untill you edit your py2exe.py file as described in the link above.
first time i've tried to post code on this site, if I get it wrong don't flame me.
from distutils.core import setup
import py2exe #@UnusedImport
import os
#delete the old build drive
os.system("rmdir /s /q dist")
#setup my option for single file output
py2exe_options = dict( ascii=True, # Exclude encodings
excludes=['_ssl', # Exclude _ssl
'pyreadline', 'difflib', 'doctest', 'locale',
'optparse', 'pickle', 'calendar', 'pbd', 'unittest', 'inspect'], # Exclude standard library
dll_excludes=['msvcr71.dll', 'w9xpopen.exe',
'API-MS-Win-Core-LocalRegistry-L1-1-0.dll',
'API-MS-Win-Core-ProcessThreads-L1-1-0.dll',
'API-MS-Win-Security-Base-L1-1-0.dll',
'KERNELBASE.dll',
'POWRPROF.dll',
],
#compressed=None, # Compress library.zip
bundle_files = 1,
optimize = 2
)
#storage for the images
bitmap_string = ''
resource_string = ''
index = 0
print "compile image list"
for image_name in os.listdir('images/'):
if image_name.endswith('.jpg'):
bitmap_string += "( " + str(index+1) + "," + "'" + 'images/' + image_name + "'),"
resource_string += image_name + " "
index += 1
print "Starting build\n"
exec "setup(console=[{'script': 'launcher.py', 'icon_resources': [(0, 'ICON.ico')],\
'file_resources': [%s], 'other_resources': [(u'INDEX', 1, resource_string[:-1])]}],\
options={'py2exe': py2exe_options},\
zipfile = None )" % (bitmap_string[:-1])
print "Removing Trash"
os.system("rmdir /s /q build")
os.system("del /q *.pyc")
print "Build Complete"
ok, thats it for the setup.py
now the magic needed access the images.
I developed this app without py2exe in mind then added it later.
so you'll see access for both situations. if the image folder can't be found
it tries to pull the images from the exe resources. the code will explain it.
this is part of my sprite class and it uses a directx. but you can use any api you want or just access the raw data.
doesn't matter.
def init(self):
frame = self.env.frame
use_resource_builtin = True
if os.path.isdir(SPRITES_FOLDER):
use_resource_builtin = False
else:
image_list = LoadResource(0, u'INDEX', 1).split(' ')
for (model, file) in SPRITES.items():
texture = POINTER(IDirect3DTexture9)()
if use_resource_builtin:
data = LoadResource(0, win32con.RT_RCDATA, image_list.index(file)+1) #windll.kernel32.FindResourceW(hmod,typersc,idrsc)
d3dxdll.D3DXCreateTextureFromFileInMemory(frame.device, #Pointer to an IDirect3DDevice9 interface
data, #Pointer to the file in memory
len(data), #Size of the file in memory
byref(texture)) #ppTexture
else:
d3dxdll.D3DXCreateTextureFromFileA(frame.device, #@UndefinedVariable
SPRITES_FOLDER + file,
byref(texture))
self.model_sprites[model] = texture
#else:
# raise Exception("'sprites' folder is not present!")
Any questions fell free to ask.
A: You should create an installer, as mentioned before. Even though it is also possible to let py2exe bundle everything into a single executable, by setting bundle_files option to 1 and the zipfile keyword argument to None, I don't recommend this for PyGTK applications.
That's because of GTK+ tries to load its data files (locals, themes, etc.) from the directory it was loaded from. So you have to make sure that the directory of your executable contains also the libraries used by GTK+ and the directories lib, share and etc from your installation of GTK+. Otherwise you will get problems running your application on a machine where GTK+ is not installed system-wide.
For more details read my guide to py2exe for PyGTK applications. It also explains how to bundle everything, but GTK+.
A: The way to do this using py2exe is to use the bundle_files option in your setup.py file. For a single file you will want to set bundle_files to 1, compressed to True, and set the zipfile option to None. That way it creates one compressed file for easy distribution.
Here is a more complete description of the bundle_file option quoted directly from the py2exe site*
Using "bundle_files" and "zipfile"
An easier (and better) way to create
single-file executables is to set
bundle_files to 1 or 2, and to set
zipfile to None. This approach does
not require extracting files to a
temporary location, which provides
much faster program startup.
Valid values for bundle_files are:
*
*3 (default) don't bundle
*2 bundle everything but the Python interpreter
*1 bundle everything, including the Python interpreter
If zipfile is set to None, the files will be bundle
within the executable instead of library.zip.
Here is a sample setup.py:
from distutils.core import setup
import py2exe, sys, os
sys.argv.append('py2exe')
setup(
options = {'py2exe': {'bundle_files': 1, 'compressed': True}},
windows = [{'script': "single.py"}],
zipfile = None,
)
A: As the other poster mention, py2exe, will generate an executable + some libraries to load. You can also have some data to add to your program.
Next step is to use an installer, to package all this into one easy-to-use installable/unistallable program.
I have used InnoSetup with delight for several years and for commercial programs, so I heartily recommend it.
A: PyInstaller will create a single .exe file with no dependencies; use the --onefile option. It does this by packing all the needed shared libs into the executable, and unpacking them before it runs, just as you describe (EDIT: py2exe also has this feature, see minty's answer)
I use the version of PyInstaller from svn, since the latest release (1.3) is somewhat outdated. It's been working really well for an app which depends on PyQt, PyQwt, numpy, scipy and a few more.
A: I'm told bbfreeze will create a single file .EXE, and is newer than py2exe.
A: I recently used py2exe to create an executable for post-review for sending reviews to ReviewBoard.
This was the setup.py I used
from distutils.core import setup
import py2exe
setup(console=['post-review'])
It created a directory containing the exe file and the libraries needed. I don't think it is possible to use py2exe to get just a single .exe file. If you need that you will need to first use py2exe and then use some form of installer to make the final executable.
One thing to take care of is that any egg files you use in your application need to be unzipped, otherwise py2exe can't include them. This is covered in the py2exe docs.
A: try
c_x freeze
it can create a good standalone
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/112698",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "152"
}
|
Q: What are the advantages of using Objective-C over C++ I have heard mention of Objective-C but I have never used it myself. I was curious what everyones opinion of it was in general and also in relation to C++. Are there any types of projects where it would be more useful or less useful?
A: Objective C's OO features use dynamic typing instead of static (compile-time) typing. That's the major difference in the approaches of the two languages - whether it's an advantage or not depends on your opinion about static vs. dynamic typing.
A: My opinion is that the syntax of Objective-C is a little "weird" at first, particularly if you are coming from a C/C++ background (as I did). If you plan to write apps for the Mac or iPhone, Cocoa development is the way to go. I had an opportunity to do some development on the Mac for about a month this Spring and opted to write it in C++ using the Qt libraries since I was quite familiar with those and time was of the essence.
If you have a Mac, give it a shot! There is a LOT of info out there on it and there are some good tools for development.
A: Part of what makes Objective-C so great isn't the language (although that is a big part ot it), it's the Cocoa (or CocoaTouch) framework that goes along with it (at least for 99% of objc users ;-)
In practical terms, I used to be a C++ programmer back in the old "classic" Mac days. Switching to Objective-C, Cocoa and Mac OS X i found I became much more productive. Hard to say exactly how much more productive, but 50% to 100% feels right.
A: If you're running Linux you can install GNUStep which provides pretty good compatibility with Cocoa. This can get you started on Objective-C/Cocoa development without owning a Mac. The best resources for learning Objective-C [in my opinion] are with Apple.
http://developer.apple.com/referencelibrary/Cocoa/index.html
A: Well, If you are coding for the some platforms like the IPhone, Objective-C is required. Objective-C also uses dynamic(run-time) typing, which many people prefer over static(compile-time).
A: Like many others I've just started looking at Obj-C due to iPhone. I've done a lot of C++ and C# and from what I can see Obj-C has a basically different approach to OO in that it adds Smalltalk-like messaging to C. Like C++ it's basically still C-compatible but the OO extensions let you send any message to any object. In that sense it's not statically typed like C++ and C# where the things an object can do are tied to the class it is. In Obj-C you can send a message to an object even if it doesn't support it. The object can then forward it if it doesn't know what to do with it.
The really cool thing is that you can add interfaces (protocols) at runtime and you can add your own handlers that intercept and hide message handlers for existing classes.
All in all there's a lot more flexibility when it comes to message handling, more like what you would do in Ruby or Smalltalk. Whether it's a good idea to have this type of OO grafted onto C or not I can't tell yet, in some ways the C++ approach meshes better with the original idea of C but on the other hand the Obj-C OO approach is more what OO purists like.
A: It is more dynamic than C++ and heavily influenced from Smalltalk. I don't find it "better" than C++ - on the contrary, but some people do.
A: WebKit was originally a C++ project (khtml from KDE) that was later adapted by Apple to be more compatible with the Cocoa-environment and thereby got its Objective-C layer.
A: From "Some nice features of the Objective-C language":
*
*Classes are objects
*Dynamic typing and optional static typing
*Categories
*Message sending
*Expressive message syntax
*Introspection
*Dynamic run-time
*Automatic garbage collection
*C inside
*C++ fluent
*Simplicity
*Access to Apple technologies
A: I find objective-c's syntax a little cleaner than c++'s although I know I'm in the minority here
A: For Mac and iPhone development, it is definitely better. The latest version has a GC, so if you like that, you'll probably like it better than C++.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/112702",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "23"
}
|
Q: How do I enable multimode emacs to program PHP without messing up my indents? Whenever I indent HTML in PHP mode, emacs (22.1.1, basic install on Redaht Linux over Putty-SSH) pops up a frame and tells me to get MUMODE or somesuch extra add-on. I installed PHP Mode without a big hassle, but I don't know how to get this multi-mode rolling.
I'd like to know 2 things
How to install and configure multi-mode
How to disable pop-ups in Emacs
A: If you're running emacs 22, you should just be able to run:
M-x nxhtml-mumamo
when editing an html document. You might want to add it to your auto-mode-alist to get it to automatically load for html docs. See here for more info:
http://www.emacswiki.org/cgi-bin/wiki/MuMaMo
http://www.emacswiki.org/cgi-bin/wiki/PhpMode
A: web-mode.el is available on http://web-mode.org
This major mode is designed to edit html php templates (with JS and CSS)
Add those two lines in your .emacs
(require 'web-mode)
(add-to-list 'auto-mode-alist '("\\.phtml$" . web-mode))
A: multi-mode and html-php-mode can be found here : http://www.loveshack.ukfsn.org/emacs/
It can be initialized with:
(require 'html-php)
(add-to-list 'auto-mode-alist '("\\.php\\'" . html-php-mode))
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/112707",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Combining Scriptaculous and jQuery in a Rails application I've got the following situation
*
*A rails application that makes use of rjs / Scriptaculous to offer AJAX functionality
*Lot of nice javascript written using jQuery (for a separate application)
I want to combine the two and use my jQuery based functionality in my Rails application, but I'm worried about jQuery and Scriptaculous clashing (they both define the $() function, etc).
What is my easiest option to bring the two together? Thanks!
A: I believe it's jQuery.noConflict().
You can call it standalone like this:
jQuery.noConflict();
jQuery('div').hide();
Or you can assign it to another variable of your choosing:
var $j = jQuery.noConflict();
$j('div').hide();
Or you can keep using jQuery's $ function inside a block like this:
jQuery.noConflict();
// Put all your code in your document ready area
jQuery(document).ready(function($){
// Do jQuery stuff using $
$("div").hide();
});
// Use Prototype with $(...), etc.
$('someid').hide();
For more information, see Using jQuery with Other Libraries in the jQuery documentation.
A: jQuery.noConflict();
Then use jQuery instead of $ to refer to jQuery. e.g.,
jQuery('div.foo').doSomething()
If you need to adapt jQuery code that uses $, you can surround it with this:
(function($) {
...your code here...
})(jQuery);
A: jRails is a drop-in replacement for scriptaculous/prototype in Rails using the jQuery library, it does exactly what you're looking for.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/112721",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: How to avoid the dangers of optimisation when designing for the unknown? A two parter:
1) Say you're designing a new type of application and you're in the process of coming up with new algorithms to express the concepts and content -- does it make sense to attempt to actively not consider optimisation techniques at that stage, even if in the back of your mind you fear it might end up as O(N!) over millions of elements?
2) If so, say to avoid limiting cool functionality which you might be able to optimise once the proof-of-concept is running -- how do you stop yourself from this programmers habit of a lifetime? I've been trying mental exercises, paper notes, but I grew up essentially counting clock cycles in assembler and I continually find myself vetoing potential solutions for being too wasteful before fully considering the functional value.
Edit: This is about designing something which hasn't been done before (the unknown), when you're not even sure if it can be done in theory, never mind with unlimited computing power at hand. So answers along the line of "of course you have to optimise before you have a prototype because it's an established computing principle," aren't particularly useful.
A: I say all the following not because I think you don't already know it, but to provide moral support while you suppress your inner critic :-)
The key is to retain sanity.
If you find yourself writing a Theta(N!) algorithm which is expected to scale, then you're crazy. You'll have to throw it away, so you might as well start now finding a better algorithm that you might actually use.
If you find yourself worrying about whether a bit of Pentium code, that executes precisely once per user keypress, will take 10 cycles or 10K cycles, then you're crazy. The CPU is 95% idle. Give it ten thousand measly cycles. Raise an enhancement ticket if you must, but step slowly away from the assembler.
Once thing to decide is whether the project is "write a research prototype and then evolve it into a real product", or "write a research prototype". With obviously an expectation that if the research succeeds, there will be another related project down the line.
In the latter case (which from comments sounds like what you have), you can afford to write something that only works for N<=7 and even then causes brownouts from here to Cincinnati. That's still something you weren't sure you could do. Once you have a feel for the problem, then you'll have a better idea what the performance issues are.
What you're doing, is striking a balance between wasting time now (on considerations that your research proves irrelevant) with wasting time later (because you didn't consider something now that turns out to be important). The more risky your research is, the more you should be happy just to do something, and worry about what you've done later.
A: My big answer is Test Driven Development. By writing all your tests up front then you force yourself to only write enough code to implement the behavior you are looking for. If timing and clock cycles becomes a requirement then you can write tests to cover that scenario and then refactor your code to meet those requirements.
A: Optimization isn't exactly a danger; its good to think about speed to some extent when writing code, because it stops you from implementing slow and messy solutions when something simpler and faster would do. It also gives you a check in your mind on whether something is going to be practical or not.
The worst thing that can happen is you design a large program explicitly ignoring optimization, only to go back and find that your entire design is completely useless because it cannot be optimized without completely rewriting it. This never happens if you consider everything when writing it--and part of that "everything" is potential performance issues.
"Premature optimization is the root of all evil" is the root of all evil. I've seen projects crippled by overuse of this concept. At my company we have a software program that broadcasts transport streams from disk on the network. It was originally created for testing purposes (so we would just need a few streams at once), but it was always in the program's spec requirements that it work for larger numbers of streams so it could later be used for video on demand.
Because it was written completely ignoring speed, it was a mess; it had tons of memcpys despite the fact that they should never be necessary, its TS processing code was absurdly slow (it actually parsed every single TS packet multiple times), and so forth. It handled a mere 40 streams at a time instead of the thousands it was supposed to, and when it actually came time to use it for VOD, we had to go back and spend a huge amount of time cleaning it up and rewriting large parts of it.
A: Like security and usability, performance is something that has to be considered from the beginning of the project. As such, you should definitely be designing with good performance in mind.
A: The old Knuth line is "We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil." O(N!) to O(poly(N)) is not a "small efficiency"!
The best way to handle type 1 is to start with the simplest thing that could possibly work (O(N!) cannot possibly work unless you're not scaling past a couple dozen elements!) and encapsulate it from the rest of the application so you could rewrite it to a better approach assuming that there is going to be a performance issue.
A: "First, make it run. Then make it run fast."
or
"To finish first, first you have to finish."
Slow existing app is usually better than ultra-fast non-existing app.
A: First of all peopleclaim that finishign is only thing that matters (or almost).
But if you finish a product that has O(N!) complexity on its main algorithm, as a rule of thumb you did not finished it! You have an incomplete and unacceptable product for 99% of the cases.
A reasonable performance is part of a working product. A perfect performance might not be. If you finish a text editor that needs 6 GB of memory to write a short note, then you have not finished a product at all, you have only a waste of time at your hands.. You must remember always that is not only delivering code that makes a product complete, is making it achieve capability of supplying the costumer/users needs. If you fail at that it matters nothing that you have finished the code writing in the schedule.
So all optimizations that avoid a resulting useless product are due to be considered and applied as soon as they do not compromise the rest of design and implementation proccess.
A: "actively not consider optimisation" sounds really weird to me. Usually 80/20 rule works quite good. If you spend 80% of your time to optimize program for less than 20% of use cases, it might be better to not waste time unless those 20% of use-cases really matter.
As for perfectionism, there is nothing wrong with it unless it starts to slow you down and makes you miss time-frames. Art of computer programming is an act of balancing between beauty and functionality of your applications. To help yourself consider learning time-management. When you learn how to split and measure your work, it would be easy to decide whether to optimize it right now, or create working version.
A: I think it is quite reasonable to forget about O(N!) worst case for an algorithm. First you need to determine that a given process is possible at all. Keep in mind that Moore's law is still in effect, so even bad algorithms will take less time in 10 or 20 years!
First optimize for Design -- e.g. get it to work first :-) Then optimize for performance. This is the kind of tradeoff python programmers do inherently. By programming in a language that is typically slower at run-time, but is higher level (e.g. compared to C/C++) and thus faster to develop, python programmers are able to accomplish quite a bit. Then they focus on optimization.
One caveat, if the time it takes to finish is so long that you can't determine if your algorithm is right, then it is a very good time to worry about optimization earlier up stream. I've encountered this scenario only a few times -- but good to be aware of it.
A: Following on from onebyone's answer there's a big difference between optimising the code and optimising the algorithm.
Yes, at this stage optimising the code is going to be of questionable benefit. You don't know where the real bottlenecks are, you don't know if there is going to be a speed problem in the first place.
But being mindful of scaling issues even at this stage of the development of your algorithm/data structures etc. is not only reasonable but I suspect essential. After all there's not going to be a lot of point continuing if your back-of-the-envelope analysis says that you won't be able to run your shiny new application once to completion before the heat death of the universe happens. ;-)
A: I like this question, so I'm giving an answer, even though others have already answered it.
When I was in grad school, in the MIT AI Lab, we faced this situation all the time, where we were trying to write programs to gain understanding into language, vision, learning, reasoning, etc.
My impression was that those who made progress were more interested in writing programs that would do something interesting than do something fast. In fact, time spent worrying about performance was basically subtracted from time spent conceiving interesting behavior.
Now I work on more prosaic stuff, but the same principle applies. If I get something working I can always make it work faster.
I would caution however that the way software engineering is now taught strongly encourages making mountains out of molehills. Rather than just getting it done, folks are taught to create a class hierarchy, with as many layers of abstraction as they can make, with services, interface specifications, plugins, and everything under the sun. They are not taught to use these things as sparingly as possible.
The result is monstrously overcomplicated software that is much harder to optimize because it is much more complicated to change.
I think the only way to avoid this is to get a lot of experience doing performance tuning and in that way come to recognize the design approaches that lead to this overcomplication. (Such as: an over-emphasis on classes and data structure.)
Here is an example of tuning an application that has been written in the way that is generally taught.
A: If I'm concerned about the codes ability to handle data growth, before I get too far along I try to set up sample data sets in large chunk increments to test it with like:
1000 records
10000 records
100000 records
1000000 records
and see where it breaks or becomes un-usable. Then you can decide based on real data if you need to optimize or re-design the core algorithms.
A: I will give a little story about something that happened to me, but not really an answer.
I am developing a project for a client where one part of it is processing very large scans (images) on the server. When i wrote it i was looking for functionality, but i thought of several ways to optimize the code so it was faster and used less memory.
Now an issue has arisen. During Demos to potential clients for this software and beta testing, on the demo unit (self contained laptop) it fails due to too much memory being used. It also fails on the dev server with really large files.
So was it an optimization, or was it a known future bug. Do i fix it or oprtimize it now? well, that is to be determined as their are other priorities as well.
It just makes me wish I did spend the time to reoptimize the code earlier on.
A: Think about the operational scenarios. ( use cases)
Say that we're making a pizza-shop finder gizmo.
The user turns on the machine. It has to show him the nearest Pizza shop in meaningful time. It Turns out our users want to know fast: in under 15 seconds.
So now, any idea you have, you think: is this going to ever, realistically run in some time less than 15 seconds, less all other time spend doing important stuff..
Or you're a trading system: accurate sums. Less than a millisecond per trade if you can, please. (They'd probably accept 10ms), so , agian: you look at every idea from the relevant scenarios point of view.
Say it's a phone app: has to start in under (how many seconds)
Demonstrations to customers fomr laptops are ALWAYS a scenario. We've got to sell the product.
Maintenance, where some person upgrades the thing are ALWAYS a scenario.
So now, as an example: all the hard, AI heavy, lisp-customized approaches are not suitable.
Or for different strokes, the XML server configuration file is not user friendly enough.
See how that helps.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/112727",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How do I join two tables in a third n..n (hasAndBelongsToMany) relationship in CakePHP? I have a n...n structure for two tables, makes and models. So far no problem.
In a third table (products) like:
id
make_id
model_id
...
My problem is creating a view for products of one specifi make inside my ProductsController containing just that's make models:
I thought this could work:
var $uses = array('Make', 'Model');
$this->Make->id = 5; // My Make
$this->Make->find(); // Returns only the make I want with it's Models (HABTM)
$this->Model->find('list'); // Returns ALL models
$this->Make->Model->find('list'); // Returns ALL models
So, If I want to use the list to pass to my view to create radio buttons I will have to do a foreach() in my make array to find all models titles and create a new array and send to the view via $this->set().
$makeArray = $this->Make->find();
foreach ($makeArray['Model'] as $model) {
$modelList[] = $model['title'];
}
$this->set('models', $models)
Is there any easier way to get that list without stressing the make Array. It will be a commom task to develops such scenarios in my application(s).
Thanks in advance for any hint!
A: Here's my hint: Try getting your query written in regular SQL before trying to reconstruct using the Cake library. In essence you're doing a lot of extra work that the DB can do for you.
Your approach (just for show - not good SQL):
SELECT * FROM makes, models, products WHERE make_id = 5
You're not taking into consideration the relationships (unless Cake auto-magically understands the relationships of the tables)
You're probably looking for something that joins these things together:
SELECT models.title FROM models
INNER JOIN products
ON products.model_id = models.model_id
AND products.make_id = 5
Hopefully this is a nudge in the right direction?
A: Judging from your comment, what you're asking for is how to get results from a certain model, where the condition is in a HABTM related model. I.e. something you'd usually do with a JOIN statement in raw SQL.
Currently that's one of the few weak points of Cake. There are different strategies to deal with that.
*
*Have the related model B return all ids of possible candidates for Model A, then do a second query on Model A. I.e.:
$this->ModelB->find('first', array('conditions' => array('field' => $condition)));
array(
['ModelB'] => array( ... ),
['ModelA'] => array(
[0] => array(
'id' => 1
)
)
Now you have an array of all ids of ModelA that belong to ModelB that matches your conditions, which you can easily extract using Set::extract(). Basically the equivalent of SELECT model_a.id FROM model_b JOIN model_a WHERE model_b.field = xxx. Next you look for ModelA:
$this->ModelA->find('all', array('conditions' => array('id' => $model_a_ids)));
That will produce SELECT model_a.* FROM model_a WHERE id IN (1, 2, 3), which is a roundabout way of doing the JOIN statement. If you need conditions on more than one related model, repeat until you have all the ids for ModelA, SQL will use the intersection of all ids (WHERE id IN (1, 2, 3) AND id IN (3, 4, 5)).
*If you only need one condition on ModelB but want to retrieve ModelA, just search for ModelB. Cake will automatically retrieve related ModelAs for you (see above). You might need to Set::extract() them again, but that might already be sufficient.
*You can use the above method and combine it with the Containable behaviour to get more control over the results.
*If all else fails or the above methods simply produce too much overhead, you can still write your own raw SQL with $this->Model->query(). If you stick to the Cake SQL standards (naming tables correctly with FROM model_as AS ModelA) Cake will still post-process your results correctly.
Hope this sends you in the right direction.
A: All your different Make->find() and Model->find() calls are completely independent of each other. Even Make->Model->find() is the same as Model->find(), Cake does not in any way remember or take into account what you have already found in other models. What you're looking for is something like:
$this->Product->find('all', array('conditions' => array('make_id' => 5)));
A: Check out the Set::extract() method for getting a list of model titles from the results of $this->Make->find()
A: The solution can be achieved with the use of the with operation in habtm array on the model.
Using with you can define the "middle" table like:
$habtm = " ...
'with' => 'MakeModel',
... ";
And internally, in the Model or Controller, you can issue conditions to the find method.
See: http://www.cricava.com/blogs/index.php?blog=6&title=modelizing_habtm_join_tables_in_cakephp_&more=1&c=1&tb=1&pb=1
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/112730",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How does boost bind work behind the scenes in general? Without spending a long time reviewing the boost source code, could someone give me a quick rundown of how boost bind is implemented?
A: I like this piece of the bind source:
template<class R, class F, class L> class bind_t
{
public:
typedef bind_t this_type;
bind_t(F f, L const & l): f_(f), l_(l) {}
#define BOOST_BIND_RETURN return
#include <boost/bind/bind_template.hpp>
#undef BOOST_BIND_RETURN
};
Tells you almost all you need to know, really.
The bind_template header expands to a list of inline operator() definitions. For example, the simplest:
result_type operator()()
{
list0 a;
BOOST_BIND_RETURN l_(type<result_type>(), f_, a, 0);
}
We can see the BOOST_BIND_RETURN macro expands to return at this point so the line is more like return l_(type...).
The one parameter version is here:
template<class A1> result_type operator()(A1 & a1)
{
list1<A1 &> a(a1);
BOOST_BIND_RETURN l_(type<result_type>(), f_, a, 0);
}
It's pretty similar.
The listN classes are wrappers for the parameter lists. There is a lot of deep magic going on here that I don't really understand too much though. They have also overloaded operator() that calls the mysterious unwrap function. Ignoring some compiler specific overloads, it doesn't do a lot:
// unwrap
template<class F> inline F & unwrap(F * f, long)
{
return *f;
}
template<class F> inline F & unwrap(reference_wrapper<F> * f, int)
{
return f->get();
}
template<class F> inline F & unwrap(reference_wrapper<F> const * f, int)
{
return f->get();
}
The naming convention seems to be: F is the type of the function parameter to bind. R is the return type. L tends to be a list of parameter types. There are also a lot of complications because there are no less than nine overloads for different numbers of parameters. Best not to dwell on that too much.
A: By the way, if bind_t is collapsed and simplified by including boost/bind/bind_template.hpp , it becomes easier to understand like the following :
template<class R, class F, class L>
class bind_t
{
public:
typedef bind_t this_type;
bind_t(F f, L const & l): f_(f), l_(l) {}
typedef typename result_traits<R, F>::type result_type;
...
template<class A1>
result_type operator()(A1 & a1)
{
list1<A1 &> a(a1);
return l_(type<result_type>(), f_, a, 0);
}
private:
F f_;
L l_;
};
A: I think it's a template class that declares a member variable for the arguments you want to bind and overloads () for the rest of the arguments.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/112738",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "33"
}
|
Q: Shortest Root to Leaf Path What is the easiest way, preferably using recursion, to find the shortest root-to-leaf path in a BST (Binary Search Tree). Java prefered, pseudocode okay.
Thanks!
A: This is in C++, but it is so simple you can convert it easily. Just change min to max to get the maximum tree depth.
int TreeDepth(Node* p)
{
return (p == NULL) ? 0 : min(TreeDepth(p->LeftChild), TreeDepth(p->RightChild)) + 1;
}
Just to explain what this is doing, it is counting from the leaf node (it returns 0 when it finds a leaf) and counts up back to the root. Doing this for the left and right hand sides of the tree and taking the minimum will give you the shortest path.
A: General description:
Use a Breadth-first search (BFS) as opposed to a Depth-first search (DFS). Find the first node with no children.
Using a DFS you might get lucky on some input trees (but there is no way to know you got lucky so you still need to search the whole tree), but using the BFS method is much faster and you can find a solution without touching all nodes.
To find the root to leaf path, you could follow the first found childless node all the way back up to the root using the parent reference. If you have no parent reference stored in each node, you can keep track of the parent nodes as you recurse down. If you have your list in reverse order you could push it all on a stack and then pop it off.
Pseudo-code:
The problem is very simple; here is pseudo code to find the smallest length:
*
*Put the root node on the queue.
Repeat while the queue is not empty, and no result was found:
*Pull a node from the beginning of the queue and check if it has no children. If it has no children you
are done you found the shortest path.
*Otherwise push all the children (left, right) onto the queue.
Finding all shortest paths:
To find all shortest paths you can store the depth of the node along with node inside the queue. Then you would continue the algorithm for all nodes in the queue with the same depth.
Alternative:
If instead you decided to use a DFS, you would have to search the entire tree to find the shortest path. But this could be optimized by keeping a value for the shortest so far, and only checking the depth of future nodes up until you find a new shortest, or until you reach the shortest so far. The BFS is a much better solution though.
A: Breadth first search is exactly optimal in terms of the number of vertices visited. You have to visit every one of the vertices you'd visit in a breadth first search just in order to prove you have the closest leaf!
However, if you have a mandate to use recursion, Mike Thompson's approach is almost the right one to use -- and is slightly simpler.
TD(p) is
0 if p is NULL (empty tree special case)
1 if p is a leaf (p->left == NULL and p->right == NULL)
min(TD(p->left), TD(p->right)) if p is not a leaf
A: static int findCheapestPathSimple(TreeNode root){
if(root==null){
return 0;
}
return root.data+Math.min(findCheapestPathSimple(root.left), findCheapestPathSimple(root.right));
}
A: shortestPath(X)
if X == NIL
return 0
else if X.left == NIL and X.right == NIL //X is a leaf
return 1
else
if X.left == NIL
return 1 + shortestPath(X.right)
else if X.right == NIL
return 1 + shortestPath(X.left)
else
return 1 + min(shortestPath(X.left), shortestPath(X.right))
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/112739",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
}
|
Q: How to map geo location based on one or all of these services I'm looking for a solution to map one or all of the following Flickr, twitter, vimeo, by exif, keywords or whatever to google maps. I'm trying to show a map of my location from updating social sites.
A: If each of the services you want supports GeoRSS, then you can actually build such a map with zero coding whatsoever! This is because Google Maps supports mapping a GeoRSS feed directly. All you have to do is type the URL of the RSS feed with the GeoRSS data within, into the box on Google maps. Here's an example of the feed from my What's The Harm? website mapped in Google Maps.
Now you mention several services there, each of which whould presumably have its own GeoRSS feed. What you would need to do is merge the feeds together before handing the resulting feed to Google Maps. There are a variety of ways to do this, one quick point-and-click way is via Yahoo Pipes. Search for "merge feed" or "merge RSS" on there and you can find many examples that you can copy and modify.
Yahoo Pipes also has functionality to add GeoRSS coding to feeds that don't have it already. You could use that to bring in data like blog posts and son on that might not be GeoRSS. Look under "Operators" for the "Location Extractor" widget.
As for the websites you mentioned:
*
*Flickr: Yes. Make sure you map your photos, and use the feed marked "geoFeed".
*twitter: There's a service called GeoTwitter that can add this for you.
*vimeo: It doesn't appear they support it out of the box.
A: There's a nice greasemonkey script to ease geotagging on Flickr.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/112759",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How would one log into a phpBB3 forum through a Python script using urllib, urllib2 and ClientCookie? (ClientCookie is a module for (automatic) cookie-handling: http://wwwsearch.sourceforge.net/ClientCookie)
# I encode the data I'll be sending:
data = urllib.urlencode({'username': 'mandark', 'password': 'deedee'})
# And I send it and read the page:
page = ClientCookie.urlopen('http://www.forum.com/ucp.php?mode=login', data)
output = page.read()
The script doesn't log in, but rather seems to get redirected back to the same login page asking it for a username and password. What am I doing wrong?
Any help would be greatly appreciated! Thanks!
A: Have you tried fetching the login page first?
I would suggest using Tamper Data to have a peek at exactly what's being sent when you request the login page and then log in normally using a web browser from a fresh start, with no initial cookies in place, so that your script can replicate it exactly.
That's the approach I used when writing the following, extracted from a script which needs to login to an Invision Power Board forum, using cookielib and urllib2 - you may find it useful as a reference.
import cookielib
import logging
import sys
import urllib
import urllib2
cookies = cookielib.LWPCookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookies))
urllib2.install_opener(opener)
headers = {
'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 5.0; en-GB; rv:1.8.1.12) Gecko/20080201 Firefox/2.0.0.12',
'Accept': 'text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5',
'Accept-Language': 'en-gb,en;q=0.5',
'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
}
# Fetch the login page to set initial cookies
urllib2.urlopen(urllib2.Request('http://www.rllmukforum.com/index.php?act=Login&CODE=00', None, headers))
# Login so we can access the Off Topic forum
login_headers = headers.copy()
login_headers.update({
'Referer': 'http://www.rllmukforum.com/index.php?act=Login&CODE=00',
'Content-Type': 'application/x-www-form-urlencoded',
})
html = urllib2.urlopen(urllib2.Request('http://www.rllmukforum.com/index.php?act=Login&CODE=01',
urllib.urlencode({
'referer': 'http://www.rllmukforum.com/index.php?',
'UserName': RLLMUK_USERNAME,
'PassWord': RLLMUK_PASSWORD,
}),
login_headers)).read()
if 'The following errors were found' in html:
logging.error('RLLMUK login failed')
logging.info(html)
sys.exit(1)
A: I'd recommend taking a look at the mechanize library; it's designed for precisely this type of task. It's also far easier than doing it by hand.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/112768",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How do you re-attach a subversion local copy to a different remote? Our subversion repository has been moved to a new host, and we have old applications that connect to that host. We CANNOT add an alias for the new server with the old name, how can we re-connect our checked out clients to the new repository?
A: Look up the svn switch command. In particular, the --relocate option is what you want.
A: Example:
svn switch --relocate \
http://svn.example.com/path/to/repository/path/within/repository \
http://svnnew.example.com/new/repository/path/within/repository
One thing which is to remember, lets assume you checked out the project "path/within/repository" then you have to go to the root of your working copy, and execute the above command. it is NOT enough just to use the repository root (as in svn switch --relocate http://svn.example.com/path/to/repository/ http://svnnew.example.com/new/repository/), because that wouldn't work.
A: SVN command line - see svn switch
TortoiseSVN - see relocate dialog
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/112770",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "17"
}
|
Q: Possible to use multiple/nested MySQLi statements? Is it possible to have a MySQLi prepared statement within the fetch() call of a previous statement? If not, what's the best way around it?
Example code:
if($stmt = $link->prepare("SELECT item FROM data WHERE id = ?")) {
$stmt->bind_param("i", $id);
$stmt->execute();
$stmt->bind_result($item);
while( $stmt->fetch() ) {
/* Other code here */
$itemSummary = $item + $magic;
if($stmt2 = $link->prepare("INSERT INTO summaries (itemID, summary) VALUES (?, ?)")) {
$stmt2->bind_param("is", $itemID, $itemSummary);
$stmt2->execute();
$stmt2->close();
}
}
}
A: You should be able to do that, although you make have to start a second connection.
A: Or use store_result.
A: This is the single connection way:
if($stmt = $link->prepare("SELECT item FROM data WHERE id = ?")) {
$stmt->bind_param("i", $id);
$stmt->execute();
$stmt->store_result(); // <-- this
$stmt->bind_result($item);
while( $stmt->fetch() ) {
/* Other code here */
$itemSummary = $item + $magic;
if($stmt2 = $link->prepare("INSERT INTO summaries (itemID, summary) VALUES (?, ?)")) {
$stmt2->bind_param("is", $itemID, $itemSummary);
$stmt2->execute();
$stmt2->store_result(); // <-- this
/*DO WHATEVER WITH STMT2*/
$stmt2->close();
}
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/112775",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
}
|
Q: Conflicting desires in Database Design, with fields of two similar functions Okay, so I'm making a table right now for "Box Items".
Now, a Box Item, depending on what it's being used for/the status of the item, may end up being related to a "Shipping" box or a "Returns" box.
A Box Item may be defective:if it is, a flag will be set in the Box Item's row (IsDefective), and the Box Item will be put in a "Returns" box (with other items to be returned to that vendor). Otherwise, the Box Item will eventually be put into a "Shipping" box (with other items to be shipped). (Note that Shipping and Returns boxes have their own tables: there's not one common table for all boxes... though maybe I should consider doing that if possible as a third possibility?)
Maybe I'm just not thinking clearly today, but I started questioning what should be done in this situation.
My gut tells me that I should have a separate field for each possible relation, even if only one of the relations can happen at any given time, which would make the schema for Box Items look like:
BoxItemID
Description
IsDefective
ShippingBoxID
ReturnBoxID
etc...
This would make the relations clear, but it seems wasteful (since only one of the relations will be used at any time). So then I thought I could have just one field for the BoxID, and determine which BoxID it's referring to (a Shipping or a Returns Box ID) based on the IsDefective field:
BoxItemID
Description
IsDefective
BoxID
etc...
This seems less wasteful, but doesn't sit right with me. The relation isn't obvious.
So, I put it to you, database gurus of Stackoverflow. What would you do in this situation?
EDIT: Thank you everyone for your input! It's given me a lot to think about. For one, I'm going to use an ORM next time I start a project like this. =) For two, since I'm not right now, I'll bite the four bytes and use two fields.
Thanks everyone again!
A: I'm with Psychotic Venom and mattlant.
Going the polymorphic route (having to figure out which table your foreign key points to based on the contents of another field) is going to be a pain. Coding the constraints for that maybe tough (I'm not sure most databases would support that natively, I think you'd have to use a trigger).
Do items ever move between the tables? Sticking with two tables with identical definitions where one is for returns and one is for shipping may be the easiest route. If you want to stick with the definition you first proposed (with the two separate fields) is perfectly reasonable.
"Premature optimization is the root of all evil" and all that. While it seems wasteful, remember what you're storing. Since they are IDs they are probably just integers, maybe 4 bytes. Wasting four bytes per record is basically nothing. In fact, due to padding to put things on even addresses or other such things it may be "free" to put that extra field in there. It all depends on the DB design.
Unless you have a very good reason to go the polymorphic route (like you're on an embedded system with little memory or you have to replicate across some really slow 9600bps link) it probably won't be worth the headaches you can end up with. Having to write all those special cases into your queries can get annoying.
Quick example: doing a join between two tables where if you want to join is based on if the isDefective flag is set is going to be a pain. Being able to just use one of the two columns alone is probably enough of a hassle you may save, at least for me.
A: What you're talking about is polymorphic relations. A single ID that can reference multiple other tables. There are several frameworks that support this, however, it is (potentially) bad for database integrity (that could be a whole other discussion whether or not your database or your application should maintain referential integrity).
What about this?
BoxItem:
BoxItemID, Description, IsDefective
Box:
BoxID, Description
BoxItemMap:
BoxID, BoxItemID, BoxItemType
Then you can have BoxItemType be an enumeration, or an integer where you define constants in your application as "Return" or "Shipping" as the type of box.
A: I would consider making a single table for the boxes and the box type be a column of the box table. This would simplify the relationships and make it easy to still query for box type. So the box item only has one foreign key to the boxId.
A: I'd use what Hibernate calls Table-per-subclass, so my DB would wind up with 3 tables for Boxes: Box, ShippingBox, and ReturnBox. The FK in BoxItem would point to Box.
A: Agree about the polymorphic discussion above, although it has potential to be used poorly, it is still a viable solution.
Basically you have a base table called box. Then you have two other tables, shipping box and return box. Those two add any extra fields that are special to them. they are related to box with a 1:1 fk.Boz base table has the common fields of all box types.
You relate BoxItem with the box table. The way you you get the proper box type is by doing a query that joins the child box with the root box based on the key. The record that has in both the base box and the child box is of that type.
You just have to be careful like mentioned that when you create a box type that it is done correctly. BUt thats what testing is for. The code to add them only needs ot written once. Or use an ORM.
Almost all ORM's support this strategy.
A: I'd probably go with:
BoxTable:
box_id, box_descrip, box_status_id ...
1, Lovely Box, 1
2, Borked box, 2
3, Ugly Box, 3
4, Flammable Box, 4
BoxStatus:
box_status_id, box_status_name, box_type_id, ....
1,Shippable, 1
2,Return, 2
3,Ugly, 2
4,Dangerous,3
BoxType:
box_type_id, box_type_name, ...
1, Shipping box, ...
2, Return box, ....
3, Hazmat box, ...
That way the Box Status defines the box type, and it's flexible if you need to expand into a few more status levels or box types later on.
A: I'd go with just a single BoxItems table with IsDefective, ShippingBoxID, the shipping-box-related fields, ReturnBoxID and the return-box-related fields. Some fields will always be NULL for each record.
This is a very simple and self-evident design that the next developer is unlikely to be confused by. In theory this design is inefficient because of the guaranteed empty fields for each row. In practice, databases tend to have a minimum required storage size for each row anyway, so (unless the number of fields is huge) this design is as efficient as possible anyway, and much easier to code to.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/112780",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: PHP performance considerations? I'm building a PHP site, but for now the only PHP I'm using is a half-dozen or so includes on certain pages. (I will probably use some database queries eventually.)
Are simple include() statements a concern for speed or scaling, as opposed to static HTML? What kinds of things tend to cause a site to bog down?
A: Certainly include() is slower than static pages. However, with modern systems you're not likely to see this as a bottleneck for a long time - if ever. The benefits of using includes to keep common parts of your site up to date outweigh the tiny performance hit, in my opinion (having different navigation on one page because you forgot to update it leads to a bad user experience, and thus bad feelings about your site/company/whatever).
Using caching will really not help either - caching code is going to be slower than just an include(). The only time caching will benefit you is if you're doing computationally-intensive calculations (very rare, on web pages), or grabbing data from a database.
A: Sounds like you are participating in a bit of premature optimization. If the application is not built, while performance concerns are good to be aware of, your primary concern should be getting the app written.
Includes are a fact of life. Don't worry about number, worry about keeping your code well organized (PEAR folder structure is a lovely thing, if you don't know what I'm talking about look at the structure of the Zend Framework class files).
Focus on getting the application written with a reasonable amount of abstraction. Group all of your DB calls into a class (or classes) so that you minimize code duplication (KISS principles and all) and when it comes time to refactor and optimize your queries they are centrally located. Also get started on some unit testing to prevent regression.
Once the application is up and running, don't ask us what is faster or better since it depends on each application what your bottleneck will be. It may turn out that even though you have lots of includes, your loops are eating up your time, or whatever. Use XDebug and profile your code once its up and running. Look for the segments of code that are eating up a disproportionate amount of time then refactor. If you focus too much now on the performance hit between include and include_once you'll end up chasing a ghost when those curl requests running in sync are eating your breakfast.
Though in the mean time, the best suggestions are look through the php.net manual and make sure if there's a built in function doing something you are trying to do, use it! PHP's C-based extensions will always be faster than any PHP code that you could write, and you'll be surprised how much of what you are trying to do is done already.
But again, I cannot stress this enough, premature optimization is BAD!!! Just get your application up off the ground with good levels of abstraction, profile it, then fix what actually is eating up your time rather than fixing what you think might eat up your time.
A: Strictly speaking, straight HTML will always serve faster than a server-side approach since the server doesn't have to do any interpretation of the code.
To answer the bigger question, there are a number of things that will cause your site to bog down; there's just no specific threshold for when your code is causing the problem vs. PHP. (keep in mind that many of Yahoo's sites are PHP-driven, so don't think that PHP can't scale).
One thing I've noticed is that the PHP-driven sites that are the slowest are the ones that include more than is necessary to display a specific page. OSCommerce (oscommerce.com) is one of the most popular PHP-driven shopping carts. It has a bad habit, however, of including all of their core functionality (just in case it's needed) on every single page. So even if you don't need to display an 'info box', the function is loaded.
On the other hand, there are many PHP frameworks out there (such as CakePHP, Symfony, and CodeIgniter) that take a 'load it as you need it' approach.
I would advise the following:
*
*Don't include more functionality than you need for a specific page
*Keep base functions separate (use an MVC approach when possible)
*Use require_once instead of include if you think you'll have nested includes (e.g. page A includes file B which includes file C). This will avoid including the same file more than once. It will also stop the process if a file can't be found; thus helping your troubleshooting process ;)
*Cache static pages as HTML if possible - to avoid having to reparse when things don't change
A: Nah includes are fine, nothing to worry about there.
You might want to think about tweaking your caching headers a bit at some point, but unless you're getting significant hits it should be no problem. Assuming this is all static data, you could even consider converting the whole site to static HTML (easiest way: write a script that grabs every page via the webserver and dumps it out in a matching dir structure)
Most web applications are limited by the speed of their database (or whatever their external storage is, but 9/10 times that'll be a database), the application code is rarely cause for concern, and it doesn't sound like you're doing anything you need to worry about yet.
A: Before you make any long-lasting decisions about how to structure the code for your site, I would recommend that you do some reading on the Model-View-Controller design pattern. While there are others this one appears to be gaining a great deal of ground in web development circles and certainly will be around for a while. You might want to take a look at some of the other design patterns suggested by Martin Fowler in his Patterns of Enterprise Application Architecture before making any final decisions about what sort of design will best fit your needs.
Depending on the size and scope of your project, you may want to go with a ready-made framework for PHP like Zend Framework or PHP On Trax or you may decide to build your own solution.
Specifically regarding the rendering of HTML content I would strongly recommend that you use some form of templating in order to keep your business logic separate from your display logic. I've found that this one simple rule in my development has saved me hours of work when one or the other needed to be changed. I've used http://www.smarty.net/">Smarty and I know that most of the frameworks out there either have a template system of their own or provide a plug-in architecture that allows you to use your own preferred method. As you look at possible solutions, I would recommend that you look for one that is capable of creating cached versions.
Lastly, if you're concerned about speed on the back-end then I would highly recommend that you look at ways to minimize your calls your back-end data store (whether it be a database or just system files). Try to avoid loading and rendering too much content (say a large report stored in a table that contains hundreds of records) all at once. If possible look for ways to make the user interface load smaller bits of data at a time.
And if you're specifically concerned about the actual load time of your html content and its CSS, Javascript or other dependencies I would recommend that you review these suggestions from the guys at Yahoo!.
A: To add on what JayTee mentioned - loading functionality when you need it. If you're not using any of the frameworks that do this automatically, you might want to look into the __autoload() functionality that was introduced in PHP5 - basically, your own logic can be invoked when you instantiate a particular class if it's not already loaded. This gives you a chance to include() a file that defines that class on-demand.
A: The biggest thing you can do to speed up your application is to use an Opcode cache, like APC. There's an excellent list and description available on Wikipedia.
As far as simple includes are concerned, be careful not to include too many files on each request as the disk I/O can cause your application not to scale well. A few dozen includes should be fine, but it's generally a good idea to package your most commonly included files into a single script so you only have one include. The cost in memory of having a few classes here and there you don't need loaded will be better than the cost of disk I/O for including hundreds of smaller files.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/112786",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to view contents of NSDictionary variable in Xcode debugger? Is there a way to view the key/value pairs of a NSDictionary variable through the Xcode debugger? Here's the extent of information when it is fully expanded in the variable window:
Variable Value Summary
jsonDict 0x45c540 4 key/value pairs
NSObject {...}
isa 0xa06e0720
I was expecting it to show me each element of the dictionary (similar to an array variable).
A: You can use CFShow()
NSMutableDictionary* dict = [[NSMutableDictionary alloc] init];
[dict setObject:@"foo" forKey:@"bar"];
[dict setObject:@"fiz" forKey:@"buz"];
CFShow(dict);
In output you will see
{
bar = foo;
buz = fiz;
}
A: You can right-click any object (ObjC or Core Foundation) variable and select “Print Description to Console” (also in Run->Variables View). This prints the result the obejct’s -debugDescription method, which by default calls -description. Unfortunately, NSDictionary overrides this to produce a bunch of internal data the you generally don’t care about, so in this specific case craigb’s solution is better.
The displayed keys and values also use -description, so if you want useful information about your objects in collections and elsewhere, overriding -description is a must. I generally implement it along these lines, to match the format of the default NSObject implementation:
-(NSString *) description
{
return [NSString stringWithFormat:@"<%@ %p>{foo: %@}", [self class], self, [self foo]];
}
A: XCode 4.6 has added the following functionality which may be helpful to you
The elements of NSArray and NSDictionary objects can now be inspected in the Xcode debugger
Now you can inspect these object types without having to print the entire object in the console. Enjoy!
Source: http://developer.apple.com/library/mac/#documentation/DeveloperTools/Conceptual/WhatsNewXcode/Articles/xcode_4_6.html
A: In the gdb window you can use po to inspect the object.
given:
NSMutableDictionary* dict = [[NSMutableDictionary alloc] init];
[dict setObject:@"foo" forKey:@"bar"];
[dict setObject:@"fiz" forKey:@"buz"];
setting a breakpoint after the objects are added you can inspect what is in the dictionary
(gdb) po dict
{
bar = foo;
buz = fiz;
}
Of course these are NSString objects that print nicely. YMMV with other complex objects.
A: Click on your dict, then click on the little "i" icon, it should do the job :-)
A: If you would like to print these in a breakpoint action in modern XCode (yes, I am 10 years after the original post!) use the following breakpoint expression in a "Log Message" action:
@myDictionary.description@
Below is a screenshot of my breakpoint action where the variable event is an NSString and the variable contextData is the NSDictionary that I am logging the contents of:
:
A: You can also use NSLog.
Also you can go in Debug area or xcode, then find out All Variables, Registers, Globals and Statics then select your variable. Right click on it. Then select Print description of "...."
Hope it helps!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/112796",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "85"
}
|
Q: MD5 routines that are GLib friendly? Does anyone know of an MD5/SHA1/etc routine that is easily used with GLib (i.e. you can give it a GIOChannel, etc)?
A: Unless you have a very good reason, use glib's built-in MD5, SHA1, and SHA256 implementations with GChecksum. It doesn't have a built-in function to construct a checksum from an IO stream, but you can write a simple one in 10 lines, and you'd need to write a complex one yourself anyway.
A: You normally have to do library glue stuff yourself...
void get_channel_md5( GIOChannel* channel, unsigned char output[16] )
{
md5_context ctx;
gint64 fileSize = <get file size somehow?>;
gint64 filePos = 0ll;
gsize bufferSize = g_io_channel_get_buffer_size( channel );
void* buffer = malloc( bufferSize );
md5_starts( &ctx );
// hash buffer at a time:
while ( filePos < fileSize )
{
gint64 size = fileSize - filePos;
if ( size > bufferSize )
size = bufferSize;
g_io_channel_read( channel, buffer );
md5_update( &ctx, buffer, (int)size );
filePos += bufferSize;
}
free( buffer );
md5_finish( &ctx, output );
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/112802",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Accessing URL parameters in Oracle Forms / OC4J How do I access parameters passed into an Oracle Form via a URL.
Eg given the url:
http://example.com/forms90/f90servlet?config=cust&form='a_form'&p1=something&p2=else
This will launch the 'a_form' form, using the 'cust' configuration, but I can't work how (or even if it's possible) to access p1 (with value of 'something') p2 (with value of 'else')
Does anyone know how I can do this? (Or even if it is/isn't possible?
Thanks
A: Within Forms you can refer to the parameters p1 an p2 as follows:
*
*:PARAMETER.p1
*:PARAMETER.p2
e.g.
if :PARAMETER.p1 = 'something' then
do_something;
end if;
A: Thanks Tony
That was one part of the problem.
The other needed part I eventually found on oracle.com was the url structure. After all the forms90 parameters (config etc), you need to supply an "otherparams" parameter supplying your parameters as a parameter to that. (parameters seperated by '+': eg
http://server.com/forms90/f90servlet?config=test&otherparams=param1=something+param2=else
Thanks
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/112812",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Displaying the current authenticated Sharepoint user from an asp.net Page Viewer Web Part I am creating a standalone asp.net page that needs to be embedded into a sharepoint site using the Page Viewer Web Part. The asp.net page is published to the same server on a different port, giving me the URL to embed.
The requirement is that after a user is authenticated using Sharepoint authentication, they navigate to a page containing the asp.net web part for more options.
What I need to do from this asp.net page is query Sharepoint for the currently authenticated username, then display this on the page from the asp.net code.
This all works fine when I debug the application from VS, but when published and displayed though Sharepoint, I always get NULL as the user.
Any suggestions on the best way to get this to work would be much appreciated.
A: If you want to retrieve the currently authenticated user from the SharePoint context, you need to remain within the SharePoint context. This means hosting your custom web application within SharePoint (see http://msdn.microsoft.com/en-us/library/cc297200.aspx). Then from your custom application reference Microsoft.SharePoint and use the SPContext object to retrieve the user name. For example:
SPContext.Current.Web.CurrentUser.LoginName
You can still use the Page Viewer Web Part to reference the URL of the site, now located within the SharePoint context.
A: Thanks heaps for the answers!
Turns out that as long as the asp.net page is using the same URL and port as the Sharepoint site, authentication works across both sites.
The solution is to use a Virtual Directory inside of the sharepoint site and install the asp.net page there.
A: When it works in debug, is that being used in SharePoint?
Your page and the Sharepoint site might as well be on different servers as far as authentication is concerned -- in order to get the information over you might need to pass it via the QueryString from the webpart if you can -- or you might need to make your own webpart to do this (just put an IFRAME in the part with the src set to your page with the QueryString passing the username).
It does seem that this would be a security issue if you use the name for anything though -- if you are just displaying it, then it's probably fine.
If you actually need to be authenticated, you might need to add authentication into the web.config of the site hosting your standalone page.
edit: I think you'd have better luck putting your page on the same port and server as SharePoint.
A: I suspect you will have a hard time specifically querying SharePoint for the currently authenticated username. I can't think of a way to easily access the SharePoint context from a separate web application like you are describing.
I don't know what kind of authentication scheme you are using, but you may want to consider using Kerberos, as I've found that it can make these kinds of scenarios a little easier by allowing for delegation and passing credentials from application to application or server to server.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/112818",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: How to get a stack trace when C++ program crashes? (using msvc8/2005) Sometimes my c++ program crashes in debug mode, and what I got is a message box saying that an assertion failed in some of the internal memory management routines (accessing unallocated memory etc.). But I don't know where that was called from, because I didn't get any stack trace. How do I get a stack trace or at least see where it fails in my code (instead of library/ built-in routines)?
A: If you have a crash, you can get information about where the crash happened whether you have a debug or a release build. And you can see the call stack even if you are on a computer that does not have the source code.
To do this you need to use the PDB file that was built with your EXE. Put the PDB file inside the same directory as the EXE that crashed. Note: Even if you have the same source code, building twice and using the first EXE and the second PDB won't work. You need to use the exact PDB that was built with your EXE.
Then attach a debugger to the process that crashed. Example: windbg or VS.
Then simply checkout your call stack, while also having your threads window open. You will have to select the thread that crashed and check on the callstack for that thread. Each thread has a different call stack.
If you already have your VS debugger attached, it will automatically go to the source code that is causing the crash for you.
If the crash is happening inside a library you are using that you don't have the PDB for. There is nothing you can do.
A: If you run the debug version on a machine with VS, it should offer to bring it up and let you see the stack trace.
The problem is that the real problem is not on the call stack any more. If you free a pointer twice, that can result in this problem somewhere else unrelated to the program (the next time anything accesses the heap datastructures)
I wrote this blog on some tips for getting the problem to show up in the call stack so you can figure out what is going on.
http://www.atalasoft.com/cs/blogs/loufranco/archive/2007/02/06/6-_2200_Pointers_2200_-on-Debugging-Unmanaged-Code.aspx
The best tip is to use the gflags utility to make pointer issues cause immediate problems.
A: You can trigger a mini-dump by setting a handler for uncaught exceptions. Here's an article that explains all about minidumps
Google actually implemented their own open source crash handler called BreakPad, which also mozilla use I think (that's if you want something more serious - a rich and robust crash handler).
A: If I remember correctly that message box should have a button which says 'retry'. This should then break the program (in the debugger) at the point where the assertion happened.
A: CrashFinder can help you locate the place of the exception given the DLL and the address of the exception reported.
You can take this code and integrate it into your application to have a stack trage automatically generated when there is an uncaught exception. This is generally performed using __try{} __except{} or with a call to SetUnhandledExceptionFilter which allows you to specify a callback to all unhandled exceptions.
A: You can also have a post-mortem debugger installed on the client system. This is a decent, general way to get information when you do not have dump creation built into your application (maybe for an older version for which you must still get information).
Dr. Watson on Windows can be installed by running: drwtsn32 -i Running drwtsn32 (without any options) will bring up the configuration dialog. This will allow the creation of crash dump files, which you can later analyze with WinDbg or something similar.
A: You can use Poppy for this. You just sprinkle some macros across your code and it will gather the stack trace, together with the actual parameter values, local variables, loop counters, etc. It is very lightweight so it can be left in the release build to gather this information from crashes on end-user machines
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/112831",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: How to resolve a conflict with git-svn? What is the best way to resolve a conflict when doing a git svn rebase, and the git branch you are on becomes "(no-branch)"?
A: While doing a git svn rebase, if you have merge conflicts here are some things to remember:
1) If anything bad happens while performing a rebase you will end up on a (no-branch) branch.
2) If you run git status, you'll see a .dotest file in your working directory. This is safe to ignore.
3) If you want to abort the rebase use the following command.1
git rebase --abort
4) If you have a merge conflict:
*
*Manually edit the files to resolve the conflicts
*Stage any changes with git add [file]
*Continue the rebase with git rebase --continue2
*
*If git asks: "did you forget to call git add?", then the edits turned the conflict into a no-op change3. Continue with git rebase --skip
You may have to repeat this process until the rebase is complete. At any point you can git rebase --abort to cancel and abandon the rebase.
1: There is no --abort option for git svn rebase.
2: There is no --continue option for git svn rebase.
3: This is very strange, but the files are in a state where git thinks they are the same after that particular patch. The solution is to "skip"
that patch on the rebase.
A: You can use git mergetool to view and edit the conflicts in the usual fashion. Once you are sure the conflicts are resolved do git rebase --continue to continue the rebase, or if you don't want to include that revision do git rebase --skip
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/112839",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "54"
}
|
Q: What does either Java GUI editor offer for rapid development and maintainability (i.e., Eclipse/SWT and Netbeans/Matisse)? Between Eclipse/SWT or Netbeans/Matisse, what does either Java GUI editor give you in terms of rapid development and maintainability?
A: You are really asking two different questions: SWT vs Swing, and Eclipse GUI Editor vs Netbeans GUI Editor (Matisse).
First, the difference between SWT and Swing is that they are two fundamentally different GUI libraries. This akin to asking the difference between Tk and Win32, or Java Swing vs .NET Forms (not to say that SWT is .NET). There are a lot of discussions out there discussing SWT vs Swing--I don't know enough about SWT to summarize the differences.
First, let me say my bias is in favor of Netbeans and I have spent 10 years learning the IDE from its days as Forte.
As far as the GUI editor, Eclipse and Netbeans have functionally similar products, but implement the code in very different ways.
My observation is that Matisse behaves, functions, and produces code that's reminiscent of Visual Studio .NET code. There are clear initialziation sections and custom behaviors for certain objects (such as the JTable). You can "Customize" an object and add your own arbitrary code via the GUI editor very easily for everything from initialization to setting individual properties. For event handling, it defaults to replicating "delegates" in .NET by using anonymous inner classes and invoking a stand-alone method. The GUI editor itself provides detailed access to the form object model and has a rich set of customizations. You also have the freedom to drop non-GUI beans into the form for use by GUI components, such as models (tablemodel, listmodel, etc), JPA-related objects, Workers, etc. What used to take a week to produce with hand-coded SWING takes a day with Matisse (though you have to really learn Matisse to do this). If you've been hand-coding swing for many years, then relearning to use a GUI editor effectively is going to be a long, hard lession.
The code is highly maintainable from within Matisse; it is NOT intended to be edited outside of Matisse, but the code is suitable for editing if you needed to (many folks I know use Netbeans GUI and then copy the source into Eclipse).
The Eclipse GUI editor is a very different creature. The GUI editor(s) are roughly the same in terms of overall capability, but I have found them to be less polished. The layout capabilities are about equal, though errors are a bit less forgiving at times. Some customizations required me to go to the source file and edit the file directly, rather than getting access to code customizations through the GUI. The code produced is very different than Matisse. GUI Components are added and initialized through "getters" and is scattered throughout the file; this good because each component is isolated/grouped into a single function, but troublesome when you need to diagnose bad interactions between component initialization. The same goes with the event handlers--very different than matisse.
Eclipse also did not provide any protections from me editing/breaking/tampering with the produced GUI file where as Netbeans was almost obnoxious with its protections. As far as maintainability, the Eclipse code is probably a little closer to the way a human would produce Java code... personally, I find the code it produces harder to maintain, but I've been looking at Matisse generated code since the first beta so my opinion is hardly objective on this issue.
Netbeans also has the capability of using the same editor for building Swing framework applications, Netbeans RCP, etc... I am unsure if Eclipse does the same.
A: This is definitely subjective -- we use both, Eclipse and Netbeans. I think it comes down to a matter of preference.
A: No one can tell you which is better. This is completely subject to change per developer. Here's a google search for "Eclipse vs Netbeans" and you can look at some pros and cons which others have poured their thoughts into already. Eclipse vs. NetBeans
A: I think you should put more research into whether you want the resulting application to be SWT or Swing-based. Which IDE to use should be the least important factor.
I'm personally an Eclipse user, but I heard very good things about Matisse, so I would probably consider it if I had to build a Swing UI. BTW, if you buy MyEclipse, it integrates Matisse.
A: Some may contend that the end product you want to use actually depends on how easy it is to use - which is hinted at in the question.
This article suggests that the Netbeans/Matisse editor is easier to use - and so you should use it on your projects.
http://cld.blog-city.com/netbeans_matisse_versus_eclipses_visual_editor__no_contest.htm
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/112854",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Qt: meaning of slot return value? According to the documentation the return value from a slot doesn't mean anything.
Yet in the generated moc code I see that if a slot returns a value this value is used for something. Any idea what does it do?
Here's an example of what I'm talking about. this is taken from code generated by moc. 'message' is a slot that doesn't return anything and 'selectPart' is declared as returning int.
case 7: message((*reinterpret_cast< const QString(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2]))); break;
case 8: { int _r = selectPart((*reinterpret_cast< AppObject*(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2])));
if (_a[0]) *reinterpret_cast< int*>(_a[0]) = _r; } break;
A: It is Very useful when you deal with dynamic language such qtscript JavaScript QtPython and so on. With this language/bindings, you can use C++ QObject dinamically using the interface provided by MetaObject. As you probably know, just signals and slots are parsed by moc and generate MetaObject description. So if you are using a C++ QObject from a javascript binding, you will be able to call just slots and you will want the return value. Often Qt bindings for dynamic languages provides some facility to acces to normal method, but the process is definitely more triky.
A: All slots are exposed in QMetaObject, where the object can be accessed via a reflective interface.
For instance, QMetaObject::invokeMethod() takes a QGenericReturnArgument parameter. So I belive this is not for explicit slot usage, but rather for dynamic invocation of methods in general. (There are other ways to expose methods to QMetaObject than making them into slots.)
The invokeMethod function is, for example, used by various dynamic languages such as QML and Javascript to call methods of QObject:s. (There's also a Python-Qt bridge called PythonQt which uses this. Not to be confused with PyQt, which is a full wrapper.)
The return value is used when making syncrhonous calls across threads inside a Qt application (supported via invokeMethod and setting connection type to Qt::BlockingQueuedConnection, which has the following documentation:
Same as QueuedConnection, except the current thread blocks until the
slot returns.
This connection type should only be used where the emitter and receiver
are in
different threads. Note: Violating this rule can cause your application
to deadlock.
A: The return value is only useful if you want to call the slot as a normal member function:
class MyClass : public QObject {
Q_OBJECT
public:
MyClass(QObject* parent);
void Something();
public Q_SLOTS:
int Other();
};
void MyClass::Something() {
int res = this->Other();
...
}
Edit: It seems that's not the only way the return value can be used, the QMetaObject::invokeMethod method can be used to call a slot and get a return value. Although it seems like it's a bit more complicated to do.
A: Looking through the Qt source it seems that when a slot is called from QMetaObject::invokeMethod the return type can be specified and the return value obtained. (Have a look at invokeMethod in the Qt help)
I could not find many examples of this actually being used in the Qt source. One I found was
bool QAbstractItemDelegate::helpEvent
which is a slot with a return type and is called from
QAbstractItemView::viewportEvent
using invokeMethod.
I think that the return value for a slot is only available when the function is called directly (when it is a normal C++ function) or when using invokeMethod. I think this is really meant for internal Qt functions rather than for normal use in programs using Qt.
Edit:
For the sample case:
case 8: { int _r = selectPart((*reinterpret_cast< AppObject*(*)>(_a[1])), *reinterpret_cast< int(*)>(_a[2])));
if (_a[0]) *reinterpret_cast< int*>(_a[0]) = _r; } break;
the vector _a is a list of arguments that is passed to qt_metacall. This is passed by QMetaObject::invokeMethod. So the return value in the moc generated code is saved and passed back to the caller. So for normal signal-slot interactions the return value is not used for anything at all. However, the mechanism exists so that return values from slots can be accessed if the slot is called via invokeMethod.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/112861",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "27"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.