text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: Executing a script file from a Windows Installer Custom Action I need to execute a batch file as part of the un-install process in a Windows installer project (standard OOTB VS 2008 installer project-vdproj). One cannot execute a bat file directly from the Custom Actions in the installer project, so I wrote a quick vbs script to call the required bat file.
vbs code:
Set WshShell = WScript.CreateObject( "WScript.Shell" )
command = "uninstall-windows-serivce.bat"
msgbox command
WshShell.Run ("cmd /C " & """" & command & """")
Set WshShell = Nothing
When this script is run independent of the uninstall, it works perfectly. However, when run as part of the uninstall, it does not execute the bat file (but the message box is shown, so I know the vbs file is called). No errors reported (at least that I can tell). Why doesn't this script work as part of the "Uninstall Custom Action"
A: I've run into this same problem and the issue is that you can't call WScript within the vbs file - you will need to JUST call CreateObject
ie.
Set WshShell = CreateObject( "WScript.Shell" )
command = "uninstall-windows-serivce.bat"
msgbox command
WshShell.Run ("cmd /C " & """" & command & """")
Set WshShell = Nothing
A: The wider you need to distribute your application, the more strongly I would recommend against scripted custom actions. I had written a bunch in the past, but I found that too many computers have problems running VBScript or JavaScript. I ended up rewriting them all in C++ to handle this situation. Here are a couple of posts that give an in-depth explanation on why you should avoid scripted custom actions:
*
*VBScript (and Jscript) MSI CustomActions suck
*VBScript (and Jscript) MSI Custom Actions (don't have to) suck
A: In your installer class, are you overriding the Uninstall method:
Public Overrides Sub Uninstall(ByVal savedState As System.Collections.IDictionary)
MyBase.Uninstall(savedState)
'Shell to batch file here
End Sub
And secondly, have you qualified the full path to the batch file?
A: Have you checked that the batch file is in the current directory as seen by the script? I would add another message showing the directory it is using to ensure it is actually trying to execute the batch file where you think it is located.
A: Windows Installer scripts generally run as System, unless you tell it otherwise. Is it possible that your batch file needs to be run by the interactive user?
A: What worked for me was to specify the full path of the .bat file.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/98778",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Should I inject things into my entities? When using an IoC container, is it considered good design to inject other classes into them? i.e. a persistence class
A: This is the Spreadsheet Conundrum: do you write repository.store(entity) or entity.storeIn(repository)?
Each has its merits. I generally tend to favor repository.store(entity) for the main reason that I keep the methods of my entities domain-focused. It makes sense to write pen.dispenseInkOnto(Surface) because that is what pens do. It makes a little less sense to write pen.storeIn(penRepository).
The downside is you need to provide access to the internals of the entity class to the persistence class. Aside from getters, which introduce the same problem as entity.storeIn(), I'd go with a friend class, package protected access, internal access, or a friend class pattern of some kind to restrict access to internal to only those who need it.
As far general injection of classes, in the pen.dispenseInkOnto(Surface) example, you could very well make Surface an interface and use injection. I see no problem with this as long as you inject other entities, value objects, or services.
A: Generally I advise against it. Entities are just that and should represent some identifiable and important part of your core domain. They should have one responsibility and be very, very good at doing it. If the entity requires additional services in order to complete a task (say persist itself) you're starting to let things like infrastructure creep into your domain. Even the notion of an Invoice being able to calculate it's billing value isn't necessarily the responsibility of the Invoice class. It may require things like sales tax, shipping costs, customer discounts. Once you open those doors and try to start bringing those items into your Invoice entity, it becomes an everything class. Domain services are better suited for co-ordination of entities and providing services to them. Infrastructure services are better suited for things like persistance and external communications. Both of those are fine to inject other services into via IoC (and encouraged so they themselves don't become bloatware).
A: I advise against it too, but would recommend reading the DDD forum as there are many posts about it on there. Its questionable whether you should even inject into domain services, in more complex domains I think not.
As Bil said services are great for cross-aggregate coordination and especially any co-ordination with anything outside the domain.
A: I'd generally recommend against it.
It generally keeps your domain cleaner when your entities are given the things they need to do to perform their duties. When they have to look things up they are often taking shortcuts, shortcuts that can be avoided by doing more analysis into the domain and the relationships between members of the domain.
Application and Domain services are generally a better place to allow injection in my opinion. They can also be responsible for creating/persisting entities.
A: Absolutely. That's how you don't tie the class to some specific persistence implementation. Sometimes I write mock DAO classes that "persist" to memory structures only, and I inject these when unit testing.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/98801",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Something wrong in the datetime format When i compile the application in my laptop it runs fine but when i run the same application in the server something is wrong with the date format. But when i checked the system date time format wit my laptop and server it the same format. Can anyone tell me what is wrong.
A: You also have to check the default culture set in the laptop and the server. Are they running in the same culture? Different culture settings will have different default time formats.
A: Is your application running on the server under a different user account? Regional settings are per-user so date and time formats will depend on the user that the application is running under. You can log in as the application user and check the Regional settings to determine if that's the issue.
This is really common in ASP.NET where the developer builds the app on their workstation and upon deployment to QA or production they find that Regional settings differ because the App Pool is using a service identity.
A: Is the system clock running UTC, and the OS changing it to local time on the server. This is a pretty common configuration, but will break programs that bypass the OS's functions to retrieve the date/time.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/98805",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Assign variables with a regular expression I'm looking for a method to assign variables with patterns in regular expressions with C++ .NET
something like
String^ speed;
String^ size;
"command SPEED=[speed] SIZE=[size]"
Right now I'm using IndexOf() and Substring() but it is quite ugly
A: String^ speed; String^ size;
Match m;
Regex theregex = new Regex (
"SPEED=(?<speed>(.*?)) SIZE=(?<size>(.*?)) ",
RegexOptions::ExplicitCapture);
m = theregex.Match (yourinputstring);
if (m.Success)
{
if (m.Groups["speed"].Success)
speed = m.Groups["speed"].Value;
if (m.Groups["size"].Success)
size = m.Groups["size"].Value;
}
else
throw new FormatException ("Input options not recognized");
Apologies for syntax errors, I don't have a compiler to test with right now.
A: If I understand your question correctly, you are looking for capturing groups. I'm not familiar with the .net api, but in java this would look something like:
Pattern pattern = Pattern.compile("command SPEED=(\d+) SIZE=(\d+)");
Matcher matcher = pattern.matcher(inputStr);
if (matcher.find()) {
speed = matcher.group(1);
size = matcher.group(2);
}
There are two capturing groups in the regex pattern above, designated by the two sets of parentheses. In java these must be referenced by number but in some other languages you are able to reference them by name.
A: If you put all the variables in a class, you can use reflection to iterate over its fields, getting their names and values and plugging them into a string.
Given an instance of some class named InputArgs:
foreach (FieldInfo f in typeof(InputArgs).GetFields()) {
string = Regex.replace("\\[" + f.Name + "\\]",
f.GetValue(InputArgs).ToString());
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/98827",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Can the NetBeans code formatter be made to format javadoc comments? The NetBeans 6.1 editor doesn't seem to like to wrap comments, and the code formatter seems to ignore them. For JavaDoc comments, this behaviour seems inappropriate, as you can end up spending a lot of wasted time manually reflowing paragraphs.
I was wondering if there's some magic setting to get the builtin code formatter, or the editor to wrap/reflow javadoc comments?
A: This issue has been raised to the Netbeans development team and will likely be added in a "future" release of Netbeans. If you want this feature (or any other feature) to be added to the IDE, go to the issue tracking website and vote for this feature.
http://www.netbeans.org/issues/show_bug.cgi?id=11553
Most open-source products use the votes on their issue tracking systems to determine where to allocate resources for the next release.
A: I'm fairly sure that you can't do this. Comments are not code and javadoc comments are not exactly plain text either as they're intended to be HTML outputted.
Maybe write your own plugin for this?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/98856",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Information Hiding and Properties Does Information Hiding mean I should minimize the number of properties my classes have? Is that right? Do you tend to make your classes private fields with methods?
A: Information hiding has to do with how much data in your class (fields, properties) is accessible to outside classes. The more you hide, the easier it is to change your implementation later without affecting dependent classes (i.e. your "public interface"). This ultimately leads to more stable designs.
A: Information Hiding is hiding both logic and data. You should be able to change both radically and not affect users of your class.
It seems that many people understand Information Hiding in principle, but then also think that getters and setters for everything / properties for everything is an example of it.
The incendiary article by Allen Holub called "Why Getters and Setters Are Evil" can be an eye-opener on the topic.
In short, private members with direct getters and setters are little more than dressed-up public members. It is true that getters and setters are needed at layer boundaries (UI, persistence, etc), but their visibility should be restricted to those classes that have a legitimate need to call them.
A: Information hiding means not to expose to consumers of your class what they don't need to know. Hiding properties and replacing them with methods is pointless because properties are actually special type of methods
A: Ever strike up a conversation by asking "How are you?", only to be met with a litany of their troubles and triumphs, pet peeves and uninteresting interests, feelings of insecurity and maybe an in-depth review of the breakfast muffins...
...that's not information hiding. Most of us don't do that. Kids do, at least until they first meet someone who uses all the irrelevant information they're sharing to hurt or humiliate them in some way... then, they learn to be secretive and paranoid, one more step on the road to adulthood.
Most of us also learn to do the same sort of thing with the code we write, exposing just enough to get along with other code, but not so much as to allow it to become dependent on our implementation. This is somewhat more nuanced than simply not exposing internal data - merely placing accessor methods or property getters/setters between internal data and the cold outside world is no more information hiding than launching into a conversation about "this friend of mine" and "his" herpes problem...
You arrive at the heart of the question when you start to differentiate between interface and implementation. When you expose properties because they match the view of the world your client code expects, rather than because they provide a convenient way for them to manipulate your implementation. It's rarely a clean divide, even when developing top-down, and contrived examples can easily do more harm than good: going out of your way to obfuscate an implementation detail that happens to be a perfectly good interface is down-right harmful.
A: Declaring something private in scope does not really "hide" the information.
I believe hiding information refers to isolating your logic from the consumer via an interface, so you can change the logic without affecting the consumer.
A: Private fields that are accessed through Public methods. Although it may seem silly doubling up to do something like:
private int _myInt;
public int MyInt
{
get { return _myInt; }
set { _myInt = value; }
}
Although now you can just do (IIRC, my 3.5 knowledge isn't complete):
public int MyInt { get; set; }
You may ask why are you making accessors that just provided the exact same access that making the original property public. But by having the original property private, if you decide you only want even numbers allowed, you can do this:
public int MyInt
{
get { return _myInt; }
set
{
_myInt = (value % 2 == 0) ? value : _myInt;
}
}
(Note: not the best example as it doesn't let the use know that their operation failed.)
Basically, you never want to expose internal operations to any consumer of your class. And the way you do that is by hiding as much as possible and only exposing what you have to.
A: If the outside world doesn't need to see it, then don't show it. You should try to encapsulate your objects so that they are losely coupled and the outside world knows just enough about them as they need to.
A: The point of information hiding is to limit exposure to consumers of your object to changes that occur in how your object operates internally. The more likely a piece is to change, the more important it is to keep it away from the interface. This is why getters and setters are common ... the value that is emitted by the interface can change in any way except type without affecting the contract with the consumers of the interface. It's also a common general rule that only the object itself may affect its state, so setters provide a way of enforcing a contract about how the object's state can change, also ideally without affecting the interface. I think you're usually better off maintaining state in private variables and providing getters and setters as a public interface to them (when outside objects need to access them) mostly because you'll always have the option to provide some kind of validation or transformation if it becomes necessary down the line without breaking your interface.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/98859",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Where did the concept of Interfaces come from? In c#, we have interfaces. Where did these come from? They didn't exist in c++.
A: Interfaces were also a central part of COM, which was a very successful technology for separating interfaces from implementation.
A: I was under the impression that the first formalized concept of interfaces came from Objective-C (called "protocols"). I can tell you for sure that Java at least got the idea from Objective-C, so it wasn't Java that had interfaces first.
Email from Patrick Naughton
A: They came from java, and they were introduced because java (and C#) do not allow multiple inheritance.
EDIT: I'm receiving some downmods because people using COM interfaces in C++ disagree with the above statement. Regardless, the concept of an interface came from java, C++ COM interfaces were virtual classes, java was the first language to make it a language feature.
END EDIT
For example, in C++, you could have a class named Dog that inherited from Animal and Mammal.
In C#, you would have a base class named Animal, and use an interface (IMammal). The I naming notation is historical from C++ (It was used to indicate an abstract virtual class), and was carried over to java but is more significant in C#, because there is no easy way to tell what is a base class and what is a interface from a C# class declaration:
public class Dog : Animal, IMammal
while in Java it was more obvious:
public class Dog extends Animal implements IMammal
Multiple inheritance is very tricky, so interfaces were derived to simplify it. A C# class can only inherit from one base class, but can implement N amount of interfaces.
In C++, interfaces can be simulated by using pure virtual classes. These require all methods to be overridden polymorphicaly by the inheriting class.
A: Interfaces existed in C++ if you did COM programming, which is where the IPrefix convention originates.
Although C++ itself didn't natively support interfaces, COM/C++ used type libraries generated from Interface Definition Language which has the only purpose of defining interfaces, and used the interface keyword long before Java or C# did.
Aside from allowing a form of multiple inheritence, .NET's motivation for interfaces have to do with its component-oriented origins and its main purpose is to define contracts between components that can interoperate without any knowledge of each other's implementations. Some COM interop is also done with .NET interfaces.
A: Interfaces are pretty old, and have been around for quite a while.
Early (mid to late late 1970's) non-object oriented languages such as Modula and Euclid used constructs called "modules" to specify the interfaces between components. Components would then communicate with each other via explicit importing and exporting modules. Interfaces in C# are object oriented evolutions of that same concept.
Interfaces in C# directly extend from the concept of interfaces in C++ (and Java), where they were used as part of COM for describing object-oriented component interfaces.
EDIT: In doing a small amount of research, the earliest language I could find with an explicit "interface" keyword was Modula-3, a derivitive of Modula created around 1986.
A: C++ allows for multiple inheritance. When Java was developed, single inheritance was decided upon however classes were allowed to implement multiple interfaces. C# carried forward this concept.
A: They existed in C++, but they were known as virtual base classes, which consisted only of pure virtual functions. This is where the "I-" prefix for interfaces came from -- to differentiate between virtual base classes from abstract base classes.
A: i've seen the keyword interface first in java, but they are much older than that.
the same concept exists in c++ but it is not exactly the same. They are called "pure virtual classes"
http://en.wikipedia.org/wiki/Virtual_function
They exists with different syntax but are there to allow polymorphism in OOP.
A: The earliest implementation of interfaces that I know of in computing came from CORBA.
My understanding is that the concept came out of electrical and electronic engineering where a power outlet in a wall for instance can be used (and implemented) by anyone who knows the specification. Interfaces then provide the same flexibility programatically.
Incidentally while they were not created to reduce versioning problems they can certainly help with them.
A: I trink interfaces came from the fact that some programmers got tired of writing the implementation of a method over and over again. How many times can you write:
static string Method(int i)
without thinking there has to be an easier way?
A: Well there wasn't any language integrated mechanism syntax for it, but you can achieve interfaces in C++ with pure virtual classes.
class IFoo
{
public:
void Bar() =0;
void Bar2() =0;
};
class Concrete : public IFoo
{
public:
void Bar() { ... }
void Bar2() { ... }
}
A: In C++ you could have an abstract class with no implementation, and you could inherit multiple classes. Java and C# got rid of multiple inheritance, so in order to have the ability to inherit multiple contracts (not behaviors), they created interfaces. You can only inherit one class in C#, but you can inherit as many interfaces as you want.
An interface is jst a contract. It says which members that an instance must implement. It does this, however, without implementing any default behaviors.
A: Interfaces came from computer science. Or, let's say, from common sense in programming.
Interface is a logical group of methods of a class.
C++ didn't need a separate language concept of "interface", because any class might be used as an interface -- just define a set of methods in it, make no implementation, call it like IExecutable and use:
class IExecutable
{
public:
virtual void Execute() = 0;
};
class MyClass : public IExecutable
{
public:
void Execute() { return; };
};
Some languages, called "dynamically typed", like Python, don't require to define interfaces at all, you just call a method you need, and run-time checks if it is possible ("If it walks like a duck and talks like a duck, it must be a duck").
C# clearly separates a concept of interfaces from classes, because it uses static typing... and multiple inheritance is prohibited in that language, but it is ok for a class to have one base class and another interface, or to implement several interfaces at a time.
public interface IPurring
{
void Purr();
}
public class Cat : Animal, IPurring
{
public Cat(bool _isAlive)
{
isAlive = _isAlive;
}
#region IPurring Members
public void Purr()
{
//implement purring
}
#endregion
}
A: While not called 'interfaces', C data structure pointers with function pointers as elements of the structure implemented the concept of interfaces long before c++ did with virtual base classes IMO.
A: Interfaces were also used in CORBA. Interface Definition Language (IDL) was used to describe interfaces independently of whatever language the object was implemented in. This separated not only interface and implementation, but also interface and language binding.
A: I think the basic idea is "multiple inheritance". So the idea came from C++.
A: It's just another layer of abstraction. Not really sure where it came from.. I still often hear them called contracts rather than interfaces.
A: Java, perhaps?
http://java.sun.com/docs/books/tutorial/java/concepts/interface.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/98867",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: How does one elaborate design using CRC cards? I've always been wondering how people use CRC (class responsiblity collaboration) cards. I've read about them in books, found vague information on the internet, but never grasped it really. I think someone ought to make a youtube video showing a session with CRC cards, since one of my books described it as being very hard to formulate in text, that it should be "taught by someone who already masters it". Sadly, I know noone around here who uses CRC cards and I'd like to learn more.
UPDATE
Any links to videos showing people elaborating with this technique would be appreciated.
A: go to the source - Kent Beck, Ward Cunningham, ever heard of them?
A: I think your statement "I know noone around here who uses CRC cards" pretty much sums up the state of CRC cards in development. CRC cards, in my opinion, were a step on the road from traditional, plan-driven development to agile development. The world has moved on. Instead of focusing on how to use CRC cards, I'd investigate techniques like TDD, which can make use of techniques like UML and CRC cards as intermediate artifacts but which concentrates on code, and more particularly on tests. This is the direction that the inventors of CRC cards have taken and I'd recommend that you take also.
A: Easiest way to use them in my opinion without getting into a mess is to write down little CRC cards in your file headers like this:
///////////////////////
//* CRC CARD
//* Class: UISliderEvent
//* Responsability: Event that holds the value and id of a Slider's movement
//* Collaborators: UISlider, UIEvent
//////////////////////
Then everytime you need to add a feature check your card and be sure you don't break any of the contracts you stated in it. Such as all of the sudden depending on UIMouseEvent for example, that's nowhere on the Card so its a no-no to include it.
A: It's hard to summarize in an SO answer, but I'll try. One of the challenges of designing objects is balancing thinking from an overall perspective with thinking from the perspective of an individual object. You need the overall perspective to get the computation completed, but you need the individual object perspective to effectively subdivide the logic and data.
Maintaining this balance is where CRC cards come in. When they are sitting there on the table, you get to look at the computation as a whole. When you pick up a single card, though, you are physically, kinesthetically encouraged to take the point of view of that one object--I have this little piece of this computation to do with limited resources, how am I going to accomplish it?
Over time, the ability to simultaneously hold both perspectives seems to soak into the brain. Less and less gets written on the cards. Then the cards are blank. After a while people just point to where the card would be if they would bother taking a blank one off the stack. Eventually, people have the benefits of the thinking style without needing cards at all. When talking with someone who hasn't mastered the balance, pulling out reals cards can be a useful communication assist, though.
The biggest weakness I find with the cards is the lack of feedback. You can fool yourself about how the code is going to turn out. I would suggest using cards only until an interesting question comes up, turn to tests/code for confirmation, and then resume designing.
Ward and I made a video 15 or so years ago of a design session, but I don't find it online anywhere and I don't have a copy. I'm not sure it would be useful as a teaching tool in any case. I don't know of other videos, but they could be interesting, especially if you got to compare several different designer's styles.
A: In their book Object Design: roles, responsibilities, and collaborations published in 2003 Rebecca Wirfs-Brock & Alan McKean discuss CRC cards in some detail. They really emphasise the difference it makes to the whole procedure that this should be a very tactile experience and it loosens people's thinking to be passing round a physical object when trying to flesh out a design / requirement.
The sub-title of that chapter suggests that using the cards is a part of the 'exploratory design' phase so it probably comes prior to doing much coding, but I see no reason you wouldn't keep coming back to them in each iteration of an Agile project and reminding yourself where you thought you were going and reviewing that if need-be (as a group of course).
I seem to remember that they even suggest passing a ball around the room so that only the person that has the ball is allowed to speak, so perhaps it's not so much the CRC cards as the getting everyone in a room talking about roles and responsibilites of objects that matters?
If you'd like to read a case-study of CRC cards in action (in addition to Kent and Ward's original paper of course) then have a look at The CRC card book.
A: I'll try to give an answer.
So CRC cards are generally used for modelling in a Object-Oriented environment to get a better understanding of the system that has to be developed (but that I think you'll know already).
CRC cards come at the very end, when you arrive just before the actual implementation. The different steps to reach that level could be the following:
*
*The starting point is to do the requirement elicitation. Involving the customer early and continuously is suggested here (take a look at Agile approaches, i.e. Extreme Programming)
*The requirements can then be modeled either with Use Case diagrams (UML) or with User stories (agile extreme programming approach). The key problem here is to find the right involved objects. This depends very much on the domain you're in, of course. If you go the "hard" way, you can apply techniques like "noun extraction". So you parse the specification document and extract all nouns (including composite names and those with adjectives). Analyze all of them and discard the irrelevant ones.
*Once you have the right nouns -> objects you can start creating your CRC cards. So what is done in a CRC session? The main task is to find and assign the responsibilities of your (previously) found objects which are then put down on small index cards (our CRC cards). "Responsibilities" are mainly the core functionalities of a specific object and the "collaboration" part are the needed other objects for fulfilling certain functionalities (these are the dependencies among the different objects in your model). Important points for assigning the responsibilities is that the responsibilities are distributed well on the whole system in some kind of balanced way. Another very important point is to avoid any duplication of responsibilities among the objects (this is where the CRC cards help). A CRC session should start with a brainstorming meeting, having an active discussion among the developers and it should be performed on the actual index cards directly.
I hope I was able to somehow help you.
Regards,
Juri
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/98878",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "29"
}
|
Q: IIS is returning 404 errors for ASPX pages that exist (aka DllRegisterServer entry point was not found) I'm having problems refreshing .Net 2.0 with IIS 6.
I have been able to successfully execute "aspnet_regiis.exe -i", but when I try to register the aspnet_isapi.dll:
regsvr32 “C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll"
I get the error
C:\Windows..\aspnet_isapi.dll was loaded, but the DllRegisterServer entry point was not found.
The file cannot be registered.
Does anyone know how to resolve this? Google hasn't been very helpful.
Edit: My problem is actually that IIS isn't serving my webpages properly - that is, it's returning 404s when I try to request .aspx files that I know exist.
I can access .gif and .js files OK, but I can't access .aspx or other .Net files. I know this is related to .Net being properly configured with IIS, and the above commands are supposed to be the solution, but the second command doesn't work.
@aaronjensen: Your command to register scripts worked successfully, and investigating the logs I find that I'm getting an entry for my failed request with status 404, substatus 2.
Microsoft tells me this because "Lockdown Policy Prevents This Request".
If a request is denied because the
associated ISAPI or CGI has not been
unlocked, a 404.2 error is returned.
Which I assume is due to the isapi DLL in my original query being denied?
A: In the end, I think the problem was caused by a step that is missed by the script when you refresh ASP.Net 2.0 with IIS 6.
I managed to resolve this using the following steps:
*
*Refresh the install using C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis -s /w3svc/1/root
*Enable ASP.Net Web Service Extension in the IIS 6 Management Console - it looks like the extension was not enabled by default in IIS, hence the 404.2 Lockdown Policy Prevents This Request errors that I was seeing. Instructions to enable the ASP.Net webservice extension are on MSDN.
A: You don't need to register that. Try this as well:
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis -s /w3svc/1/root
If IIS is still giving you issues, check your event log and google the error there. You'll get hits.
A: When you get the error, it means either:
1 The DLL does not need to be registered
or
2 The DLL is corrupt
A: *
*Check the credential that IIS server is running under.
*Check for the AppPool user permission.
A: At first try all the following
*
*aspnet_regiis.exe -i
*C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis -s /w3svc/1/root
*regsvr32 “C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll"
If it doesnt fix the problem, check event log in computer management because it could also be another issue.
My case was an impersonation issue, but it only started to show up in event viewer after i did the aspnet_regiis.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/98895",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Windows XP - Create Shortcuts on Desktop and controll their placement In any language really, im looking for a simple (very simple) way to control the position of a shortcut on the users desktop. I already make the assumption that Auto Arrange and Align to Grid are unchecked.
Ex: The program creates the shortcut to the desktop than places it at position (450,302) on the desktop.
I know how to create shortcuts, but i dont know how to control their placement on the desktop.
A: As far as I know, this is controlled by the user and cannot be done programmatically.
A: One can use an automation program such as AutoIt or AutoHotkey to simulate the user clicking and moving the shortcut to another location. These programs can also create the shortcut and place it on the desktop.
A: If you are looking for a simple solution, there is none, except perhaps faking user input.
But there is another way, but it is really hard:
Use the DoDragDrop function to programmatically carry out a drag and drop operation.
The hard parts are to implement the IDataSource interface and to create a IDataObject which the explorer can understand.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/98901",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: What is the point of the Lowered* columns in asp.net membership tables? What is the architectural reason for the column names prefixed with "Lowered" in the SQL schema for ASP.Net membership and friends? Some examples of the columns in question are below:
*
*aspnet_Applications.LoweredApplicationName
*aspnet_users.LoweredUserName
*aspnet_membership.LowerEmail
I see that the lowered columns are indexed, but it seems to me that you could just index the associated non-lowered column and leave out the apparent duplication.
I'm sure there is a good reason for them to exist, but I can't figure it out.
A: There is no purpose for this in a non case sensitive database like SQL Server. This is a reusable database regardless of the type of database in which you are using. E.g. Informix is case-sensitive for all string data which is stored. Using this database on an Informix server would be a good reason to have/use this column instead of lower()'ing the column yourself. I am not saying that you can't do case sensitive searches in SQL Server by any means (varbinary, BINARY_CHECKSUM, runtime/declarative COLLATE, etc.). This would change the functionality of the out of the box database.
The idea of any calculated column is to save cycles on doing those calculations during querying. Most especially during large queries. The other thought is one which you had in indexing those columns. Again, this is done to save cycles.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/98908",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Pros and cons with Jaxer I realize that this question has been asked before, but it has been a month with no decent responses... I'm looking at Aptana's Jaxer and I find the concept to be very exciting.
Here is a quick overview for those who are not familiar with it:
Jaxer is, in their words, "the world's first true AJAX server". It is based on the Mozilla engine so scripts are written with javascript and you have complete access to the DOM on the server-side.
Scripts are placed on your pages with <script> tags and you can specify a runat attribute (ala ASP.NET) to mark scripts for execution on the client, server, both, or as a "server-proxy" which makes the functions available on the client, but they execute on the server via AJAX. This also means that you can use your favorite client-side libraries (jQuery, Prototype) on the server as well as the client.
It also can be used to process documents that are generated in another language (e.g. php, ruby) which I imagine is not practical except to help in transitioning existing applications to use Jaxer.
*
*What are the pros and cons?
*How mature/stable is it the API?
*How good is performance compared to
other server-side html
preprocessors?
*Has anyone used Jaxer with another
technology (php, pearl, ruby, etc.)
and what were your experiences?
EDIT: I've posted another question regarding a drawback I discovered while playing with Jaxer: Defining objects when using Jaxer
A: I didn't use Jaxer for very long, but here's some things I found:
Pros
*
*Write the frontend and backend in the same code. Especially nice for writing validation logic.
*"Seamless" AJAX communication back to the server - it's just like calling a JS function.
*The ability to use JavaScript frameworks like jQuery to manipulate the DOM.
*The ability to generate or manipulate images using the Canvas API.
*You get to write your server JavaScript using whizzy new JavaScript 1.8 features like Array extras and getters/setters.
Cons
*
*I found their API to be unstable (they were transitioning to 1.0 when I was trying it so that kinda made sense) and the documentation was confusing, missing, or didn't match with changed functionality. I also found that it was very hard to debug my Jaxer server-side code, and when I got in trouble the error messages weren't very helpful.
*You don't get real MVC or even MVP (ASP.NET-style) separation between your presentation and your logic.
*I personally couldn't get E4X (xml in JavaScript) working, which was supposed to be a big draw.
*There's not a lot of framework built around it for building a whole application. You're starting from some pretty basic building blocks.
*It's not really providing any help in your view, so forget all the templating or reusable components you might use elsewhere. Not that you can't replicate that, but it's more difficult than having it out of the box.
Overall, I think Jaxer has the most promise as a postprocessor in front of another web framewok. It would be great to use Jaxer to layer all the spiffy AJAX stuff on top of an existing site. It would make it a lot easier to make a dynamic site with validation / page manipulation logic shared between server and client. I don't think I would want to write an application using only Jaxer. Also, it's young (and immature) - I'll be interested to see where it ends up.
A: I did come across this set of performance benchmarks.
It looks as though Jaxer performs better than Rails, but not as well as php...
A: @BRH: Great insight. I would echo all of the "Pros" and "Cons" 2, 4, & 5 and your final overview. I kind of get the sense that they didn't intend to displace any of the market for upstream frameworks ... but if they could do so and keep it as tight and comprehensible as it is, I hope they do! I like the way they think!
P.S. I don't know if it is new, but there is a <jaxer:include tag that injects fragments into the page prior to server-side script execution that might be a help in some code-reuse scenarios. There may be more for me to discover along those lines.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/98915",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: programmatically find number of hosts in a Netmask How do you programmatically find the number of hosts that a netmask supports.
Eg, If you have a /30 , how do you find how many IP's are in it without using a lookup table?
Preferably would be able to work with the "/" notation, rather than 255.xxx.xxx.xxx notation.
A: Here's the formula: 2 ^ (32 - netmask) - 2 where netmask is a bit count as you've shown in the Cisco notation above. So a network with a /30 mask has 2 usable addresses.
The lowest network number always represents the network segment itself and the highest is always the broadcast ... this leads to the -2 at the end of the formula.
For standard notation, convert the aaa.bbb.ccc.ddd netmask into an unsigned 4 byte integer (many networking libraries have this function) and subtract that from 2 ^ 32 - 2.
A: Where n is the number after the '/'
>>> def number_of_hosts(n):
... return 2 ** (32 - n)
...
>>> number_of_hosts(32)
1
>>> number_of_hosts(30)
4
A: Method 1 :
package com.test;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;
public class EasyNet {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
InetAddress localhost = InetAddress.getLocalHost();
System.out.println(" IP Addr: " + localhost.getHostAddress());
// Just in case this host has multiple IP addresses....
InetAddress[] allMyIps = InetAddress.getAllByName(localhost.getCanonicalHostName());
if (allMyIps != null && allMyIps.length > 1) {
System.out.println(" Full list of IP addresses:");
for (int i = 0; i < allMyIps.length; i++) {
System.out.println(" " + allMyIps[i]);
}
}
} catch (UnknownHostException e) {
System.out.println(" (error retrieving server host name)");
}
try {
System.out.println("Full list of Network Interfaces:");
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
System.out.println(" " + intf.getName() + " " + intf.getDisplayName());
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); )
{
System.out.println(" " + enumIpAddr.nextElement().toString());
}
}
} catch (SocketException e) {
System.out.println(" (error retrieving network interface list)");
}
}
}
Method 2:
package com.test;
import java.net.*;
import java.util.*;
public class GetIp {
public static void main(String args[]) throws Exception {
Enumeration<NetworkInterface> nets =
NetworkInterface.getNetworkInterfaces();
for (NetworkInterface netint : Collections.list(nets)) {
System.out.println("\nDisplay name : " + netint.getDisplayName());
Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();
for (InetAddress inetAddress : Collections.list(inetAddresses)) {
System.out.println("InetAddress : " + inetAddress);
}
}
}
}
Method 3
package com.test;
import java.io.IOException;
import java.net.InetAddress;
public class Nethosts {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try{
InetAddress localhost = InetAddress.getLocalHost();
// this code assumes IPv4 is used
byte[] ip = localhost.getAddress();
checkHosts(ip.toString());
}
catch(Exception e){
e.printStackTrace();
}
}
public static void checkHosts(String subnet){
int timeout=1000;
for (int i=1;i<254;i++){
try{
String host=subnet + "." + i;
if (InetAddress.getByName(host).isReachable(timeout)){
System.out.println(host + " is reachable");
}
}
catch(IOException e){e.printStackTrace();}
}
}
}
Method 4 :
package com.test;
import java.awt.List;
import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Enumeration;
public class Netintr {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try
{
System.out.println("Output of Network Interrogation:");
System.out.println("********************************\n");
InetAddress theLocalhost = InetAddress.getLocalHost();
System.out.println(" LOCALHOST INFO");
if(theLocalhost != null)
{
System.out.println(" host: " + theLocalhost.getHostName());
System.out.println(" class: " + theLocalhost.getClass().getSimpleName());
System.out.println(" ip: " + theLocalhost.getHostAddress());
System.out.println(" chost: " + theLocalhost.getCanonicalHostName());
System.out.println(" byteaddr: " + toMACAddrString(theLocalhost.getAddress()));
System.out.println(" sitelocal?: " + theLocalhost.isSiteLocalAddress());
System.out.println("");
}
else
{
System.out.println(" localhost was null");
}
Enumeration<NetworkInterface> theIntfList = NetworkInterface.getNetworkInterfaces();
ArrayList<InterfaceAddress> theAddrList = null;
NetworkInterface theIntf = null;
InetAddress theAddr = null;
while(theIntfList.hasMoreElements())
{
theIntf = theIntfList.nextElement();
System.out.println("--------------------");
System.out.println(" " + theIntf.getDisplayName());
System.out.println(" name: " + theIntf.getName());
System.out.println(" mac: " + toMACAddrString(theIntf.getHardwareAddress()));
System.out.println(" mtu: " + theIntf.getMTU());
System.out.println(" mcast?: " + theIntf.supportsMulticast());
System.out.println(" loopback?: " + theIntf.isLoopback());
System.out.println(" ptp?: " + theIntf.isPointToPoint());
System.out.println(" virtual?: " + theIntf.isVirtual());
System.out.println(" up?: " + theIntf.isUp());
theAddrList = (ArrayList<InterfaceAddress>) theIntf.getInterfaceAddresses();
System.out.println(" int addrs: " + theAddrList.size() + " total.");
int addrindex = 0;
for(InterfaceAddress intAddr : theAddrList)
{
addrindex++;
theAddr = intAddr.getAddress();
System.out.println(" " + addrindex + ").");
System.out.println(" host: " + theAddr.getHostName());
System.out.println(" class: " + theAddr.getClass().getSimpleName());
System.out.println(" ip: " + theAddr.getHostAddress() + "/" + intAddr.getNetworkPrefixLength());
System.out.println(" bcast: " + intAddr.getBroadcast().getHostAddress());
int maskInt = Integer.MIN_VALUE >> (intAddr.getNetworkPrefixLength()-1);
System.out.println(" mask: " + toIPAddrString(maskInt));
System.out.println(" chost: " + theAddr.getCanonicalHostName());
System.out.println(" byteaddr: " + toMACAddrString(theAddr.getAddress()));
System.out.println(" sitelocal?: " + theAddr.isSiteLocalAddress());
System.out.println("");
}
}
}
catch (SocketException e)
{
e.printStackTrace();
}
catch (UnknownHostException e)
{
e.printStackTrace();
}
}
public static String toMACAddrString(byte[] a) { if (a == null) { return "null"; } int iMax = a.length - 1;
if (iMax == -1)
{
return "[]";
}
StringBuilder b = new StringBuilder();
b.append('[');
for (int i = 0;; i++)
{
b.append(String.format("%1$02x", a[i]));
if (i == iMax)
{
return b.append(']').toString();
}
b.append(":");
}
}
public static String toIPAddrString(int ipa)
{
StringBuilder b = new StringBuilder();
b.append(Integer.toString(0x000000ff & (ipa >> 24)));
b.append(".");
b.append(Integer.toString(0x000000ff & (ipa >> 16)));
b.append(".");
b.append(Integer.toString(0x000000ff & (ipa >> 8)));
b.append(".");
b.append(Integer.toString(0x000000ff & (ipa)));
return b.toString();
}
}
Method 5
package com.test;
import java.io.IOException;
import java.net.InetAddress;
public class NetworkPing {
/**
* JavaProgrammingForums.com
*/
public static void main(String[] args) throws IOException {
InetAddress localhost = InetAddress.getLocalHost();
// this code assumes IPv4 is used
byte[] ip = localhost.getAddress();
for (int i = 1; i <= 254; i++)
{
ip[3] = (byte)i;
InetAddress address = InetAddress.getByAddress(ip);
if (address.isReachable(1000))
{
System.out.println(address + " machine is turned on and can be pinged");
}
else if (!address.getHostAddress().equals(address.getHostName()))
{
//hostName is the Machine name and hostaddress is the ip addr
System.out.println(address + " machine is known in a DNS lookup");
}
else
{
System.out.println(address + " the host address and host name are equal, meaning the host name could not be resolved");
}
}
}
}
Method 6
package com.test;
import java.net.*;
import java.util.*;
public class NIC {
public static void main(String args[]) throws Exception {
List<InetAddress> addrList = new ArrayList<InetAddress>();
Enumeration<NetworkInterface> interfaces = null;
try {
interfaces = NetworkInterface.getNetworkInterfaces();
} catch (SocketException e) {
e.printStackTrace();
}
InetAddress localhost = null;
try {
localhost = InetAddress.getByName("127.0.0.1");
} catch (UnknownHostException e) {
e.printStackTrace();
}
while (interfaces.hasMoreElements()) {
NetworkInterface ifc = interfaces.nextElement();
Enumeration<InetAddress> addressesOfAnInterface = ifc.getInetAddresses();
while (addressesOfAnInterface.hasMoreElements()) {
InetAddress address = addressesOfAnInterface.nextElement();
if (!address.equals(localhost) && !address.toString().contains(":")) {
addrList.add(address);
System.out.println("FOUND ADDRESS ON NIC: " + address.getHostAddress());
}
}
}
}
}
A: http://www.unixwiz.net/techtips/netmask-ref.html
That will provide you with all of the logic you need to determine what you need to do.
A: 2^(32-n) - 2, where n is your number, in this case, 30. The number n, gives you the number of bits that are covered in the address range, which gives you 32-n bits left for your network. Therefore, there are 2^(32-n) possible total addresses. You subtract 2 for the network and broadcast addresses to get your answer.
A: with /30 you have only 4 hosts possible.
32-30 = 2
2^2 = 4
with /24 you have 256 hosts possible
32-24 = 8
8^2 = 256
with /23 you have 512 hosts possible
32-23 = 9
9^2 = 512
its is because of the bit representation of the subnet mask
255.255.255.252 translates into
11111111.11111111.11111111.11111100
note that the 2 last bytes are = 0.
this is the same 2 as in 32 - 30 = 2
Also, you lose 2 ip in every subnet, one for the broadcast address and one of the gateway address
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/98916",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Managing the patch level of multiple windows systems In an environment with multiple windows servers what is the best way to ensure patch compliance accross all systems?
Is there a simple tool (some sort of client/server app?) that allows reports to be generated showing the status of all the systems so any that aren't automatically patching themselves can be fixed without having to manually check each systemevery time an audit is needed?
A: WSUS is good for Windows, it's for large distributed enterprises.
A: Microsoft Windows Server Update Services
Microsoft Windows Server Update
Services (WSUS) enables information
technology administrators to deploy
the latest Microsoft product updates
to computers running the Windows
operating system. By using WSUS,
administrators can fully manage the
distribution of updates that are
released through Microsoft Update to
computers in their network.
A WSUS server will download all of the patches you specify, for the products you choose. You then configure your clients to get their updates from the local WSUS server instead of directly from Microsoft. You can group your client machines and approve/disapprove the patches that you want each group to install. The WSUS server will give you lots of reports as to which clients need what patches, etc.
It's pretty easy to setup, if you follow the Microsoft white paper.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/98930",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: wxWidgets: Detecting click event on custom controls How to add a click event listener to my custom control made with wxWidgets? The custom control uses wxWindow as the base. On the event list I see
wxEVT_LEFT_DOWN
wxEVT_LEFT_UP
wxEVT_LEFT_DCLICK
wxEVT_MIDDLE_DOWN
wxEVT_MIDDLE_UP
wxEVT_MIDDLE_DCLICK
wxEVT_RIGHT_DOWN
wxEVT_RIGHT_UP
wxEVT_RIGHT_DCLICK
wxEVT_MOTION
wxEVT_ENTER_WINDOW
wxEVT_LEAVE_WINDOW
wxEVT_MOUSEWHEEL
But there is no wxEVT_LEFT_CLICK or similar.
A: Typically, there is no "click" event (and in the case of wxWidgets - there isn't
). The action of clicking is broken into its two parts: Mouse Down and Mouse Up. Typically what you think of as a "left click" event is actually handled in a "left up" event.
Try it out:
*
*Hover over a button (such as the "Add Comment" button this page)
*Click the left-mouse button down and hold
*Move the mouse off of the button while holding down
*Release the left-mouse button
*Nothing happens!
This time:
*
*Hover over the same button
*Click the
left-mouse button down and hold
*Release the left-mouse button
*The "click" action you expect is triggered by the up event!
A: In the first instance I recommend inheriting from wxControl not wxWindow, wxControl is designed for that exact purpose and you are less likely to find yourself fighting the system. When I look at a control I am building in my own wxWidgets app, I see that my click handler is attached to wxEVT_LEFT_DOWN. Looking in my copy of Cross Platform GUI Programming with wxWidgets I can see a list of all wxMouseEvents, and there is no wxEVT_LEFT_CLICK. I would suggest wxEVT_LEFT_DOWN is the event to use.
Now after posting I've read Burly's answer and I agree with him, wxWidgets offers the lowest level events and that gives you the maximum amount of control of the user interface you construct for your users.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/98941",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to generate a newline in a cpp macro? How do I write a cpp macro which expands to include newlines?
A: It is not possible. It would only be relevant if you were looking at listing files or pre-processor output.
A common technique in writing macros so that they are easier to read is to use the \ character to continue the macro onto a following line.
I (believe I) have seen compilers that include new lines in the expanded macros in listing output - for your benefit. This is only of use to us poor humans reading the expanded macros to try to understand what we really asked the compiler to do. it makes no difference to the compiler.
The C & C++ languages treat all whitespace outside of strings in the same way. Just as a separator.
A: C & C++ compilers ignore unquoted whitespace (except for the > > template issue), so getting a macro to emit newlines doesn't really make sense. You can make a macro span several lines by ending each line of the macro with a backslash, but this doesn't output newlines.
A: The C compiler is aware of white space, but it doesn't distinguish between spaces, tabs or new lines.
If you mean how do I have a new line inside a string in a macro, then:
#define SOME_STRING "Some string\n with a new line."
will work.
A: I am working on a large project that involves a lot of preprocessor macro functions to synthesize any code that cannot be replaced by templates. Believe me, I am familiar with all sorts of template tricks, but as long as there is no standardized, type safe metaprogramming language that can directly create code, we will have to stick with good old preprocessor and its cumbersome macros to solve some problems that would require to write ten times more code without.
Some of the macros span many lines and they are very hard to read in preprocessed code. Therefore, I thought of a solution to that problem and what I came up with is the following:
Let's say we have a C/C++ macro that spans multiple lines, e.g. in a file named MyMacro.hpp
// Content of MyMacro.hpp
#include "MultilineMacroDebugging.hpp"
#define PRINT_VARIABLE(S) \
__NL__ std::cout << #S << ": " << S << std::endl; \
__NL__ /* more lines if necessary */ \
__NL__ /* even more lines */
In every file where I defined such a macro, I include another file MultilineMacroDebugging.hpp that contains the following:
// Content of MultilineMacroDebugging.hpp
#ifndef HAVE_MULTILINE_DEBUGGING
#define __NL__
#endif
This defines an empty macro __NL__, which makes the __NL__ definitions disappear during preprocessing. The macro can then be used somewhere, e.g.
in a file named MyImplementation.cpp.
// Content of MyImplementation.cpp
// Uncomment the following line to enable macro debugging
//#define HAVE_MULTILINE_DEBUGGING
#include "MyMacro.hpp"
int a = 10;
PRINT_VARIABLE(a)
If I need to debug the PRINT_VARIABLE macro, I just uncomment the line that defines the macro HAVE_MULTILINE_DEBUGGING in MyImplementation.cpp. The resulting code does of course not compile, as the __NL__ macro results undefined, which causes it to remain in the compiled code, but it can, however, be preprocessed.
The crucial step is now to replace the __NL__ string in the preprocessor output by newlines using your favorite text editor and, voila, you end up with a readable representation of the result of the replaced macro after preprocessing which resembles exactly what the compiler would see, except for the artificially introduced newlines.
A: I have the same problem. I abuse the preprocessor on non C files, therefore the fact that the C compiler ignores line breaks is irrelevant for me. I am using \\ at the end of lines in the macro definition (which is pretty neat syntax, resembling LaTeX) and pass the result through
sed s/'\\ '/'\n'/g
This does the trick. The preprocessor strips one \ away from the \\ and joins the lines, and the sed splits them again by replacing the remaining \ by a real newline.
A: Use \, like so:
#define my_multiline_macro(a, b, c) \
if (a) { \
b += c; \
}
A: Not quite sure what you're asking here. Do you want a macro on multiple lines?
#define NEWLINE_MACRO(x) line1 \
line2 \
line3
Additionally, if you would like to include a literal in your macro:
#define NEWLINE_MACRO(x) ##x
what you you put in x will be put in place of ##x, so:
NEWLINE_MACRO( line1 ) // is replaced with line1
This can be helpful for making custom global functions then just need part of the function name changed.
Also:
#define NEWLINE_MACRO(x) #x // stringify x
Will put quotes around x
A: Use the \ at the end of the line. I've seen a lot of C macos where they use a do...while(0)
#define foo() do \
{
//code goes here \
\
\
}while(0);
Also, remember to use parenthases in many instances.
Example:
#define foo(x) a+b
//should be
#define foo(x) (a+b)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/98944",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "50"
}
|
Q: Black-box vs White-box Reuse What are the pros/cons of using black-box reuse over white-box reuse?
A: In my experience, White box reuse is normally done through inheritance and black box is done through composition.
White Box Reuse
Pro: You can customize the module to fit the specific situation, this allows reuse in more situations
Con: You now own the customized result, so it adds to your code complexity.
Black Box Reuse
Pro: Simplicity and Cleanliness
Con: Many times it is just not possible
verdict:
I prefer Black Box whenever possible.
A: White-box:
pros:
*
*simple (very natural concept)
*you have more control over things
cons:
*
*requires intrinsic knowledge on
component internals
*can be difficult to implement (OO inheritance constraints)
sometimes it leads to broken\incorrect inheritance chains
Black-box:
pros:
*
*low coupling (gives late binding and other goodies)
cons:
*
*not obvious (code is much harder to understand)
*interfaces are more fragile than classes (i.e. interfaces vs inheritance)
A: I'm not sure what those specific terms mean, so I'll take a stab at defining what they are before I continue:
*
*Black box reuse is using a class/function/code unmodified in a different project
*White box reuse is taking a class/function/code from one project and modifying it to suit the needs of another project.
The pros to black-box reuse are that once the code has been written, debugged, and tested, you can reuse it countless times in different circumstances. The downside is that truly black-box-reusable code is rare and can take time and effort to format the API and calling code and make it consistent with the black box approach (no context leaking).
The pros to white-box reuse are that you can indeed use your code more than once without having to first extricate it from the original project. You simply copy and modify and you're on your way. This type of reuse is much more common, but it also has a few downsides. Mostly, if you discover a bug in one implementation, you need to check to make sure that it's fixed in all the other implementations. This can be difficult if they diverge widely, as often happens.
A: @Kyle,
Black-Box reuse means that you use component without knowing it's internals. All you have is a component interface.
White-box reuse means that you know how component is implemented. Usually White-box reuse means class inheritance.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/98984",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Are there any large-scale commercial projects that use Squeak Smalltalk? I've been learning Squeak Smalltalk & have noticed that it's got a really faithful community and is used in some large academic and open-source projects, but I haven't found any examples of it being used commercially in any significant way. I'm curious about how this environment is doing in the world commercially. Maybe taking over older Smalltalk projects? Does anyone know?
A: http://auctomatic.com/
A: In general, I would agree that Squeak is not widely used commercially.
We have a scheduling app for manufacturing and warehousing called MaxScheduler.com. Its written in Squeak largely because an extensive code base was initially developed in this language. It has its issues though. It provides a 'strange' UI experience to the end user. Also it doesn't play nicely with native platforms like Windows. Recently WXSqueak was created, this really helps by providing a native UI experience.
On the plus side, Squeak has been massively beneficial for us. With our code base we have created complicated applications for customers in short time frames. Few languages give the same level of code re-use.
A: DabbleDB I think is (was?) one. They may have moved off Squeak but I am sure they used it at one point.
A: Qwaq commercializing OpenCroquet - "Qwaq's technology helps employees collaborate in virtual meeting rooms."
A: Squeak has certainly the future, specially because of two happenings:
*
*at least 10 times faster Squeak VM is on the way,
*Pharo fork is cleaning the code with goal to make it viable for professional development.
That's why as otherwise VisualWorker I'm seriously looking at Squeak for Aida/Web based business web applications in the future
A: http://dabbledb.com/ is in fact using Squeak on commodity hardware, and they recently moved from Seaside 2.6 to 2.8 and are looking at 2.9 as it is being released.
A: I'd bet it won't play any "important" role any time soon. The whole programming model with "morhps" is "alien" to anything in the commercial "surrounding". Just try to implement a small example in some Smalltalk like VisualWorks and than the same in Squeak. There are tried to get more "traditonal" GUI toolkit running with Squeak (GTK) but that's in it's infancy and it does not even compiler out of the box. It won't take over other Smalltalk environments, because there's not incentieve for using it instead let's say VisualAge, VisualWorks or Smalltalk/X.
Regards
Friedrich
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/98998",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: WCF netTCPBinding - Is transport encryption enough? I've got a WCF service which handles some sensitive data. I'd like to make sure I keep that data from being exposed and so I'm looking at netTCPBinding... primarily because I can control the network it runs across and performance is a high priority.
I recognize that there are two areas that can be encrypted: transport level and message level. I intend to use certificates to encrypt at the transport level, which I understand uses TLS over TCP.
The calling clients are also mine and so I control the transport level. Since I anticipate no change in the transport layer, do I need to bother with message level encryption? It seems unnecessary unless I want the flexibility of changing the transport.
A: The message-level encryption is needed when you do not control an intermediary. Intermediary services need to be able to modify the soap headers and could peek at your sensitive data for malicious purposes. But if you control everything from initial sender to ultimate receiver, then you do not need encryption at that level.
I work on a project that uses netTCP for internal services, and I can confirm it works well.
A: In general terms, as long as you're dealing with point to point connections, and certificates are being validated on both sides (particularly if you're using mutual authentication), then yes, transport level security might be enough. Checking the certificates is useful to ensure that someone doesn't supplant the server (or no man-in-the-middle gets in the way).
Message-level security becomes more useful when you need to do content signing or you need non-repudiation and particularly when you have intermediaries (routers) between the client and server and want to make sure they can route the message without actually looking at its contents.
A: I think you're spot on. If you don't plan on moving this to another transport mechanism I cant see why you would need both message- and transport encryption. If performance is a key factor skipping message encryption will save you some performance since you don't have to add protection on sending/receiving each messages.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/99001",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: What is the best way to obtain a list of site resources when writing a Maven2 site plugin? When creating a plugin that executes in the default life-cycle, it's easy to obtain a reference to the project and its resources, but I'm getting a null instead of a MavenProject object when creating plugins that execute in the site life-cycle.
Any hints, tips or suggestions?
A: It turns out the problem I was having was related to my declaration of the Project parameter being passed into my Mojo. Since there's only one instance of a MavenProject within a Maven build, you can't specify an expression (and there's really no Java String that can be cast to a MavenProject object) for the parameter and the default value has to be "${project}".
So to access the MavenProject from within a Maven Plugin Mojo, for any phase, use the following parameter declaration:
/**
* Project instance, used to add new source directory to the build.
*
* @parameter expression="export.project" default-value="${project}"
* @required
* @readonly
*/
private MavenProject project;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/99012",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Report design using stored procedures in Report builder (SSRS)? Is it possible to use stored procedures for designing Reports in Report builder?
A: If you're asking if it's possible to use sprocs in SSRS reports that you create, then yes. Just call the sproc in the query for your DataSet like you would normaly.
A: In Report Builder 1.0 (SSRS 2005), the answer is No. (unless you perform special tricks with table functions)
In Report Builder 2.0 (SSRS 2008), the answer is Yes. (stored procedures are readily available in the GUI)
A: If you're using Oracle on the backend, you can query the results of a table function (a stored function that returns a TABLE of TYPE). The query string for your Dataset will look like:
select * from table (f_foo(:p_bar))
...where f_foo is your table function stored in the database and p_bar is a report parameter to f_foo. More info on table functions here:
http://www.databasejournal.com/features/oracle/article.php/2222781
A: Both SSRS 2005/2008 its possible to get data through stored procedure, in ssrs 2005 while creating dataset command type we need to select stored procedure and in ssrs 2008 while creating dataset the query type we need to select stored procedure.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/99013",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How do I have a socket accept connections only from the localhost (in Java)? I have a java app (not running in any application container) which listens on a ServerSocket for connections. I would like it to only accept connections which come from localhost. Currently, after a connection is accepted, it checks the peer IP and rejects it if it is not the loopback address, but I know that peer IP addresses can be spoofed. So, if possible, I'd prefer to bind to a socket that only listens on the loopback interface; is this possible?
I've tried a few different things (such as specifying "127.0.0.1" as the local address when calling bind()) with no luck.
Update:
I'm embarrassed to admit that this was all my mistake. Our application listens on two different ports, and I was binding one to the loopback interface but testing against the other. When I actually try to telnet to the correct port, everything works fine (i.e., binding to "127.0.0.1" does exactly what it's supposed to).
As for spoofing the loopback address, you guys are right. I shouldn't have made it sound like the primary concern. Really, the desired behavior is to only take local connections, and binding to only the local interface is a more direct way of achieving that than accepting all connections and then closing non-local ones.
A: Peer IP addresses cannot be spoofed in this manner, have you nothing to fear from using the technique of inspecting the peer and deciding to drop the connection during establishment.
However: binding to 127.0.0.1 should work, and cause the operating system to tell the connecting host that there is nothing listening if they connect on one of the systems other ip addresses. Can you amend this question with a compilable example? Perhaps you've made a simple error.
A: You could, as you already seem to be doing, accept() the connection anyway then use getInetAddress() to ensure the address is an authorized one. If not, simply close() the socket straight away. 127.0.0.1 is not an address that can be spoofed.
Alternatively, you could install your own security manager which will have its checkAccept() method called with the address and port of the remote site. Thet's a little harder - I've never tried since the first solution has always been adequate for me.
A: If the peer address is spoofed, then there is nothing further that you can do.
However, to spoof 127.0.0.1 is not easy. You would have to have a TCP/IP stack dumb enough to accept such a packet. There would be no way of the spoofer receiving packets back. On a good TCP/IP stack, it should not be able to guess the sequence numbers so it can't keep up with the expected conversation.
A: if (socket.getInetAddress().isLoopbackAddress()){
//Your code goes here
}
A: When you bind your ServerSocket, specifying localhost should make the TCP/IP stack reject the connection. Even if this isn't working on your system, localhost can't (okay, maybe if someone hacked your TCP/IP stack and the default gateway router) be spoofed, since that address isn't routed through the physical interface.
I am curious as to why your binding doesn't succeed, what is your OS, Java version, etc?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/99020",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: Handling browser pop-up windows with Selenium We are running Selenium regression tests against our existing code base, and certain screens in our web app use pop-ups for intermediate steps.
Currently we use the commands in the test:
// force new window to open at this point - so we can select it later
selenium().getEval("this.browserbot.getCurrentWindow().open('', 'enquiryPopup')");
selenium().click("//input[@value='Submit']");
selenium().waitForPopUp("enquiryPopup", getWaitTime());
selenium().selectWindow("enquiryPopup");
...which works most of the time. Occasionally the test will fail on the waitForPopUp() line with
com.thoughtworks.selenium.SeleniumException: Permission denied
Can anyone suggest a better, more reliable method?
Also, we primarily run these tests on IE6 and 7.
A: It works!! Just to make it easier for the folks who prefer selenese.
This worked for me using IE7(normal mode).
What a freaking hassle. Thank the spaghetti monster in the sky for SO or there is no way I would have got this working in IE.
<tr>
<td>getEval</td>
<td>selenium.browserbot.getCurrentWindow().open('', 'windowName');</td>
<td></td>
</tr>
<tr>
<td>click</td>
<td>buttonName</td>
<td></td>
</tr>
<tr>
<td>windowFocus</td>
<td>windowName</td>
<td></td>
</tr>
<tr>
<td>waitForPopUp</td>
<td>windowName</td>
<td>3000</td>
</tr>
<tr>
<td>selectWindow</td>
<td>windowName</td>
<td></td>
</tr>
A: If you are running in *iehta mode then you are going to run into some glitches here and there. We run Selenium at my job and there seem to be lots of issues with IE and AJAX.
However, it sounds like the issue you are running into is one where Selenium is trying to access a component in another window before it completely loads up. I am not sure what your default timeout range is set to, but you may want to try increasing it to 60 (60000ms) seconds or so to get past the issue.
Other than that I would suggest running your tests in Firefox (using *chrome) as it produces much more reliable results, but sometimes it is simply not possible due to business requirements.
A: I just trialled adding another selenium function, windowFocus():
// force new window to open at this point - so we can select it later
selenium().getEval("this.browserbot.getCurrentWindow().open('', 'enquiryPopup')");
selenium().click("//input[@value='Submit']");
selenium().windowFocus("enquiryPopup");
selenium().waitForPopUp("enquiryPopup", getWaitTime());
selenium().selectWindow("enquiryPopup");
The test succeeded when I ran it locally, but only with all those method calls - create/focus/wait/select.
I'm about to let the build server run all the tests, and if that succeeds too, I'll be making a library function out of it...!
A: I needed to select an iframe within a popup window and fill out a form.
I had trouble using the selectWindow cmd where selenium couldn't find my iframe, so I removed the command.
This selenese worked well for me (where the iframe title and id = account_frame) :
<tr>
<td>click</td>
<td>//a[@class='item_add']</td>
<td></td>
</tr>
<tr>
<td>windowFocus</td>
<td>account_frame</td>
<td></td>
</tr>
<tr>
<td>waitForPopUp</td>
<td>account_frame</td>
<td>10000</td>
</tr>
A: Try adding some wait statements around the calls that are causing you issues.
I've had the same errors before and the only way I was able to reliably resolve them was by making calls to System.Threading.Thread.Sleep(5000)..
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/99045",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "21"
}
|
Q: Having trouble achieving 1Gbit UDP throughput For UDP packets with a payload less then 1470, is it possible to achieve 1Gbit throughput? Due to the small packet size, there should be some bottlenecks in achieving such throughput (I/O, OS, network, etc.). I imagine drivers and hardware might have to be tuned to small packet/high throughput. Has anybody attempted successfully achieved 1Gbit throughput with small UDP packets?
A: I've previously done some experimenting with throughput on gigabit links on relatively standard pc hardware, albeit doing just transmits (via tcpreplay), rather than udp.
The biggest bottleneck that I found was in just getting packets to the NIC itself. This can be significantly improved by using a high speed bus to interface to your NIC (eg. a 4x pci-express NIC). But even with this there was a very definate packet/second limit. Obviously increasing the packet size would allow you to utilize more of your bandwidth while reducing processor load.
Along the same lines as the comment by Steve Moyer, there is a theoretical limit for the utilization of any network. In my experiments (which were being done on a completely quiet network) I was seeing a maximum of approximately (and only off the top of my memory) 900Mb/s. This was with cpu loads of 30 to 40%.
It's more likely that the limitation is going to be imposed by your system hardware (ie. PC) than your network infrastructure - any network switch worth its salt should be capable of sustaining full speed network access with small packets - certainly at much higher rates than most PCs can cope with.
A: What type of network connection are you using? If you're using a 1000BaseTx/Fx link, don't expect more than 80% throughput with maximum sized packets. As your packet size decreases, the overhead for spacing, synchronization, Ethernet headers, IP headers and UDP headers increases in relation to the payload and therefore degrades your maximum throughput even more.
A: Check the documentation for the switch you're using. Switches are constrained in the number of packets per second (pps) they can deliver and often can't sustain 1GBps if you're sending packets with significantly smaller than the maximum payload size.
Another thing to check is whether your network card is doing interrupt coalescing, and what is the maximum number of send/receive descriptors it can support. At that level of throughput the interrupt service time and context switching time can become a big overhead on the host system even with a modern CPU and memory system.
Also if you're using gigabit over copper, the smallest ethernet frame the card will emit is 512 bytes, so smaller messages will be padded to that size. This is because of requirements for carrier sense/collision detection.
A: I've found hardware has a significantly lower packet-per-second limit than the networks theoretical capacity. For a Broadcomm BCM5704S I hit this at 69,000 pps compared to 1,488,100pps of gigabit.
Some more numbers I reported here, http://code.google.com/p/openpgm/
A: There's a good tutorial on tweaking your network settings (in Linux) to achieve true gigabit speed here: http://datatag.web.cern.ch/datatag/howto/tcp.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/99054",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: ASP.NET webforms + ASP.NET Ajax versus ASP.NET MVC and Ajax framework freedom If given the choice, which path would you take?
ASP.NET Webforms + ASP.NET AJAX
or
ASP.NET MVC + JavaScript Framework of your Choice
Are there any limitations that ASP.NET Webforms / ASP.NET AJAX has vis-a-vis MVC?
A: I love webforms, but ASP.NET AJAX is a pile of crap.
I prefer to use WebForms + custom HTTPHandlers handling the server side of any AJAX calls.
Heh, downvoted...
ASP.NET AJAX Is a pile of crap because a callback requires the entire page class to be reinstantiated, you aren't calling a single method, you are rebuilding the entire page on the server everytime.
Also, UpdatePanels return the entire page, only the section in the update panel is popped in, its a total waste of bandwidth.
I understand why its done this way, because WebForms controls can't really be easily other ways, but it still is really lousy.
A: I see that the majority of the responses came out prior to MVC 1.0. Since we are now in 2.0 Preview, I thought it might nice to revisit.
I was a ASP.NET developer for about five years before I made the move to MVC last March. I haven't regretted it for a second. I realize now that the stronger I got in ASP.NET WebForms, the more difficult it became to learn other technologies, such as JavaScript and the non-Microsoft implementation of AJAX. Microsoft leveraged their ASP.NET development approach from their WinForms development approach, which helped with the learning curve if you were coming from WebForms development, but it's not a good way to develop web applications if you understand the differences between the two approaches.
The latest project I'm working required me to learn ASP.NET MVC, JavaScript, jQuery, CSS 2, and AJAX (non-Microsoft). After only nine months, I feel much better prepared to approach web development projects than I did after five years of ASP.NET development. The ASP.NET implementation makes things so much more difficult to maintain long-term. MVC makes things so much easier, because you're less dependent on shortcuts. It takes a while to learn the framework, but the more you learn about the framework, the less dependent on the framework you become and the more you start to learn and understand the established standards, like JavaScript and AJAX.
For me, it is a clear-cut choice. I will never go back to ASP.NET. If I can't use ASP.NET MVC, I'll learn Ruby or PHP. I want the progress and advancement of my web development tools to be motivated by the needs of the developer community, not by profit.
A: I've done both lately, I would take MVC nine times out of ten.
*
*I really dislike the implementation of the asp.net ajax controls, I've run into a lot of issues with timing, events, and debugging postback issues. I learned a lot from http://encosia.com/2007/07/11/why-aspnet-ajax-updatepanels-are-dangerous/
*The asp.net project we used the MVP pattern http://www.codeplex.com/aspnetmvp, and the pattern worked great. However we ended up with a lot of code in the view because we were directly interacting with the server side controls (i.e a lot of gridview manipulations). This code is nearly untestable with the unit test frameworks. We should have been more diligent about keeping code out of the view, but in some instances it was just easier and less messy.
The one time I would choose using asp.net forms development would be to use the gridview control. We are using jquery for our javascript framework with MVC and have not yet found a very good gridview like control. We have something that is functional, but the amount of time we have sunk into learning, tweaking, and debugging it vs using asp.net server side controls has been substantial. One looses all of the nice widgets Microsoft provides out of the box doing non asp.net form development. The loss of those widgets is freeing, and scary at the same time when you first start.
At the end of the day I'm happy we are doing MVC development. My team and I have learned a new framework, (we were only asp.net developers before), and have gotten our hands dirty with html and javascript. These are skills we can take onto other projects or other languages if we ever need to.
A: ASP.NET MVC is still in "Preview" form, and as such I wouldn't consider it until it matures. You can roll-your-own MVP pattern pretty easily without much plumbing.
On the Ajax front, I'd say try to find libraries (commercial or otherwise) that do what you're looking for. The basics (Grids, trees, autocomplete textboxes, etc.) have been done to death. Don't Reinvent The Wheel.
A: When I am designing a site one of the big things I prefer is the DRY principle. IMO ASP.NET MVC is much more dry than web forms.
I have recently made the move from webforms to MVC and I hope I never have to go back!
A: If you need update panel, I suggest you to use open source and lite MagicAjax or ComfortASP. If you need framework helps developing custom ajax, I suggest jQuery.
A: Don't let people fool you into thinking that it is a clear cut choice. You can get the best of both worlds. My approach is to create an MVC project, but instead of adding views, add standard asp.net pages, but change the code behind to inherit from MVC.ViewPage like so:
public partial class SamplePage : System.Web.Mvc.ViewPage
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
If you confine yourself to the single form tag (with runat="server") in the code in front, then you have full code behind access to your standard asp.net server controls. This means you get full server side control of the presentation (eg. using databinding and repeaters) without having to do that old ASP-style code weaving.
protected void Page_Load(object sender, EventArgs e)
{
IObjectDefinition instance = (IObjectDefinition)ViewData["definition"];
_objectName.Text = instance.DisplayName;//textbox or label
DataTable itemVals = new DataTable();
itemVals .Columns.Add("itemName");
itemVals .Columns.Add("itemValue");
IDictionary<string, string> items = (IDictionary<string, string>)ViewData["items"];
foreach (KeyValuePair<string, string> datum in items)
{
conditions.Rows.Add(new object[] { datum.Key, datum.Value});
}
_itemList.DataSource = itemVals;//repeater
_itemList.DataBind();
}
The post for any control does not post back to the page, but to the controller. If you remember to use the name property on your server controls then they end up in the FormControls collection for access to your page variables as per standard MVC.
So what do you get?:
*
*full server side control of presentation your code in front is purely HTML and asp.net server control tags
*full separation of concerns - the page does presentation only, and all orchestration and
marshalling is done in the controller (rather than asp.net style in the page)
*full MVC testability
*No html code weaving
*You can tunr view state off and reduce page bloat
What do you lose?
*
*Once again you are confined to one form per page if you want to use only server controls
*You may need to manually specify postback targets for buttons and the form
*You once again have 2 files for your presentation
Oh, and for AJAX - jQuery definitely. Making a request to a controller method that returns a JsonResult really simplifies things.
A: Webforms with ASP.NET Ajax is heaven. The integration between the 2 is just amazing and feels so natural to work with.
Using webforms instead of mvc will give you the ability to utilize the lifecycle to develop very good and re-usable controls.
But I still like to add a little jQuery into the mix for traversing the dom and adding animations, I just like to use asp.net ajax to get the integration with the server side.
A: The concept behind MVC is great, but be prepared to loose virtually all the functionality of all the server controls you've used for so many years. I've only looked at the MVC implementation for about a week now, but the page lifecycle and view state are gone so these controls no longer function properly.
I was also stunned to find a number of examples containing a lot of logic code in the markup. That's right, 'if' and 'foreach' statements in the aspx files -- a horrible step backwards imho. I was very happy to leave classic asp behind but in the current implementation of the asp.net mvc pattern you're back to code in your markup, the need to use helpers everywhere, and the lack of virtually any useable server controls.
If you're starting a new project now I'd recommend sticking with asp.net webforms and make use of a the built in asp.net ajax, the toolkit, and jQuery as needed. The asp.net ajax implementation may not be the absolute best, or most efficient implementation, but unless you're getting a million uniques on day 1 or your server is a commodore vic 20 the performance hit isn't going to be that noticeable.
This of course does depend on your project size. If you're starting a 5 year Enterprise level application that expect millions of page views, UpdatePanel might not cut it, but if you're building an average site, throwing up a prototype, or just need to get moving fast, asp.net ajax works perfectly fine and has an extremely low learning curve.
And to be clear, the entire page is absolutely not returned every time an ajax call is made. /Only/ the content for the panel that needs to be updated is sent across the wire. Any http monitor will prove this point. Yes, the page /lifecycle/ is performed, but knowing that you can can build fairly efficient asp.net ajax applications.
A: My experience has been with programming web apps for apache servers in php and ruby. When I got a job maintaining a web app written in asp.net (webforms), I dove into learning the microsoft way of building web apps. I will have to say I was completely mortified! I was thinking WTF is all this viewstate garbage being sent back in forth? Is this even necessary?
And then I decided to look at doing some simple things with ajax and jquery, which lead me to update panels and clientIDs being generated, and not what I set in the view. What a waste of my time! Why can't I have multiple forms on one page? Why can't I just use regular ajax calls? Why do my views have server logic? These were all questions that im sure that many web programmers face with asp.net webforms. Then, I discovered .NET MVC. My life just got a lot easier.
I was used to using MVC frameworks like Rails and CakePHP to create web apps the way they were meant to be programmed. With technologies actually meant for the web.
My suggestion would be this, Leave WebForms for people that are used to programming winforms type applications because it tries to abstract the fact that you are programming on the web. If you want to have real freedom to develop applications for the web which actually make sense to web programmers, use .NET MVC or something similar that wont get in your way.
Thats my two cents...
A: to compliment @ben's answer, I used ASP.Net webforms for simple databinding, and JQuery for all Ajax transactions. To be honest, I still couldn't let go of databinding because of its simplicity. Viewstate is almost useless so I basically turn it off. You can use MVC though, but be warned, it will take most of your time developing functionality that you take for granted in Forms. Good luck man!
A: I've used asp.net winforms with ajax.net as well as prototype/ext/jquery. I guess something to consider is the goal of the site.. MVC is a popular pattern. I can't say anything against ASP MVC because I haven't had a chance to use it, but I want to make sure you know you are not limited to just ajax.net if you chose webforms.
A: I agree that asp.net ajax UpdatePanels are not an ideal solution.
We have avoided using them and instead have been using the client-side libraries to do any communication with the server. I do like what I saw at PDC about the features coming in asp.net ajax 4.0 with declarative components and client-side templating - very nice! Combining JQuery with the existing libraries provides quite a bit - and I have questioned using JQuery exclusively instead given it's much smaller footprint and it's ability to do a lot of the same things as the asp.net ajax client library.
As far as the server stack - I haven't used MVC yet, but we have had success using a home-rolled MVP approach using webforms.
A: It's been a long time since the original question. Now we have MVC3 and .NET 4
Is MVC now a better solution than before?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/99056",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "21"
}
|
Q: Getting BPL Versions at program startup Is it possible to check what version of BPL (ie Rtl70.BPL, Indy70.bpl etc) are installed on a clients computer when the program starts?
I have had some programs crash because the BPL on there computer is different to the ones on the build machine.
If i have to add each BPL used into the installer on each update, i think it will defeat one of the points on using them.
Delphi 7, if it makes a difference
Just a follow up on the issue i had.
The rtl70.bpl file was only slightly different between the build computer and the clients.
Clients Computer: 7.0.4.453 760 KB (778,240 bytes) Tuesday, 20 August 2002, 4:40:26 PM
Build computer: 7.0.4.453 760 KB (778,240 bytes) Friday, 9 August 2002, 11:30:00 PM
The updater i was using ignored them as being the same (no change in build number), but when i manually deleted and copied the files every thing seemed to work.
A: If your program crashes, it's probably because it can't load the library it's dynamically linked with. (As you where saying, this happens when the system can't find a copy of the needed libaries anywhere in the search path).
The problem is, that this happens at startup of an application, which the Windows OS does via an API called MapAndLoad (also read this). This API is called before your application is even started, so I see no way to intercept this.
One suggestion I could give, would be to use a launcher (which has to be statically linked, to prevent problems for when there are /no/ libraries at all).
This launcher could inspect your actual application, see what imports it needs, checks your environment and display a nice failure/troubleshooting suggestion dialog to the user.
A: Unfortunately, no. If the crash is due to missing imports from the .bpl files required by your application, there is no way (short of rewriting the Delphi RTL and linker themselves) to check for those packages from within the crashing executable itself. PatrickvL's solution is probably the best for your situation.
Neftalí's solution might be an option - of course, at the cost of packaging the RTL, duplicating a lot of files, and losing one of the points of having packages in the first place. However, if you're using private DLLs (i.e., if you copy the DLLs in your private binaries directory) then you should also create an empty file with the same name as your executable but appending the extension .local to it, i.e. for notepad.exe you'd create a notepad.exe.local. See Raymond Chen's article on DLL redirection for more details.
A:
Is it possible to check what version of BPL (ie Rtl70.BPL, Indy70.bpl etc) are installed >on a clients computer when the program starts?
I have had some programs crash because the BPL on there computer is different to the ones >on the build machine.
If i have to add each BPL used into the installer on each update, i think it will defeat >one of the points on using them.
You must install your copy (develop) of BPL's (RTL70.bpl, INDY.BPL,...) into the same directory that you install the application. Your application search first the BPL's at the same directory and after search at directories inside the path.
The negative point is that your system will can have several copies of the same BPL, the positive point is that you will not have problems with differents versions of the same file.
Regards.
P.D: Excuse-me for my bad english.
A: You cannot do that from an executable that uses these bpls, but you could have a small startup-program that checks the bpls and then calls the main executable.
A: Sometimes Delphi adds of automatic form the line:
{$R ' *.res'}
to the files of project or packages.
Comment (//) that line and to compile again.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/99057",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: copying data from production to test server without erasing schema Using sql server 2000, I would like to take my production data and put it in my test database, but I don't want to overwrite the schema of the test database as there are fields in it that I haven't added to production yet. Can this be done? I should add that these databases are on different servers.
A: Use something like OmBelt's exportSQLServer to SQL tool.
(ombelt.com)
The inserts it makes specify fields so you should be okay. If not, mass-edit them.
I find it greatly simplifies SQLServer to have SQL dumps like other databases.
A: If you use a tool to generate scripts that explicitly names columns (such as SSIS), it should work, as long as there aren't columns in your production database that don't exist in dev.
A: Use the INSERT INTO SELECT sentence to bulk from prod tables to your test environment avoiding your test fields that doesn't match in prod.
A: I think the Import/Export Wizard exists in SQL Server 2000. Wizards are generally irritating, but it only takes a few minutes and you probably already have it installed.
The wizard can be used to create a DTS package that can append all of the data from your production database to the end of tables in another database that already exists. If you have any new columns that are not null and don't have defaults I'm not sure how well that will be handled though.
You'll need to provide your production database as the source and the development database as the destination, then make sure to check the "append" option for new data rows.
Edit: I should note, this does work across servers, but I've only tried it from one SQL Server instance to another. In theory it works as long as the destination server supports ODBC, but I can't vouch for that.
A: I use Red-Gate software's SQL Data Compare. It will do diffs of the data in both databases and generate the appropriate transactional update scripts. It will exclude any columns that don't exist in both tables, so you should be fine even if you've added or deleted columns in your test database.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/99059",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Would it be useful to have method return values for null objects? Would it be useful to be able to provide method return value for null objects?
For a List the null return values might be:
get(int) : null
size() : 0
iterator() : empty iterator
That would allow the following code that has less null checks.
List items = null;
if(something) {
items = ...
}
for(int index = 0; index < items.size(); index++) {
Object obj = items.get(index);
}
This would only be used if the class or interface defined it and a null check would still work. Sometimes you don't want to do null checks so it seems like it could be beneficial to have this as an option.
From: http://jamesjava.blogspot.com/2007/05/method-return-values-for-null-objects.html
A: It is nice to not have to check for NULL, and some languages make it easier -- e.g. C#'s non-NULLable types, or Haskell which doesn't have NULLs but can express a missing value with the Maybe type constructor.
A NULL is distinct from an empty list. You can take the point-of-view that someone passing in a NULL where you need a list is making a programming error, and that the right thing to do is throw a NullPointerException.
The typical excuse for accepting NULLs is that often there's a case where you don't need the list, and you shouldn't have to create a new List that's empty, especially when there's some concern about efficiency. You can have many of the benefits without changing the language, but by instead having a static EmptyList that people can pass in, that never needs to be reinitialized.
A: It's a pattern called Null Object
http://en.wikipedia.org/wiki/Null_Object_pattern
A: This is a good idea.
Smalltalk does this.
There is a NULL object. It doesn't descend from Object. (Smalltalk is a singly-rooted class hierarchy like Java)
For the advanced student, you can sub-class it for making proxies!
A: Ruby does this (as well as others). It has nil instead of null and it's an object.
I dp hate when functions that are meant to return lists can return null. It's better to return an empty list and let the user decide if they want to check for null (empty) or not.
A: In C# (among other languages), this is normally not allowed. Without an instance of Foo, .net doesn't know to call Foo's method or Foo's child's method.
However, an C# 3.0 extension method applied to the Foo type would allow this:
Foo x = null;
if (x.Bar() == 0)
{
Console.WriteLine("I win");
}
Bar could be constructed like so:
public static int Bar (this Foo theFoo)
{
return theFoo == null ? 0 : 1;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/99074",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Generate a current datestamp in Java What is the best way to generate a current datestamp in Java?
YYYY-MM-DD:hh-mm-ss
A: Date d = new Date();
String formatted = new SimpleDateFormat ("yyyy-MM-dd:HH-mm-ss").format (d);
System.out.println (formatted);
A: Using the standard JDK, you will want to use java.text.SimpleDateFormat
Date myDate = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd:HH-mm-ss");
String myDateString = sdf.format(myDate);
However, if you have the option to use the Apache Commons Lang package, you can use org.apache.commons.lang.time.FastDateFormat
Date myDate = new Date();
FastDateFormat fdf = FastDateFormat.getInstance("yyyy-MM-dd:HH-mm-ss");
String myDateString = fdf.format(myDate);
FastDateFormat has the benefit of being thread safe, so you can use a single instance throughout your application. It is strictly for formatting dates and does not support parsing like SimpleDateFormat does in the following example:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd:HH-mm-ss");
Date yourDate = sdf.parse("2008-09-18:22-03-15");
A: There's also
long timestamp = System.currentTimeMillis()
which is what new Date() (@John Millikin) uses internally. Once you have that, you can format it however you like.
A: SimpleDateFormatter is what you want.
A: final DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd:hh-mm-ss");
formatter.format(new Date());
The JavaDoc for SimpleDateFormat provides information on date and time pattern strings.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/99098",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
}
|
Q: MIPS - Is it important? My question: Is the MIPS programming language that beneficial to know?
I'm a CS student and am taking an assembly class which focuses on MIPS. I'm very comfortable writing in high level languages, but MIPS has me a little bit down.
Is MIPS something that I should really focus on and try to completely grasp? Will it help me in future?
A: I took on a assembly class doing mips about two years ago. I found myself writing GameBoy Advance games in a mips-like asm language. Can't say I enjoyed it.
Though I think it is good to have an understanding about the inner workings of assembled code (from high level to low level). I feel it made me understand more about how the computer actually works. Also, I couldn't resist making a few virtual machines shortly after, designing my own assembly language :)
A: MIPS is a great language to learn assembly with. You have plenty of general purpose registers to make writing your programs less tedious and it is a RISC architecture so there are less instructions you need to memorize.
Some of the mainstream usage that not a lot of people mention is that the N64, Playstation 1, Playstation 2 and PSP all used MIPS processors.
A: By "mips programming language" I assume you mean MIPS Assembly Language.
Learning an assembly language is beneficial to know, it helps you map the code you write to how it will run on the hardware. This can help expose you to more low level concerns like cache misses, branching, out-of-order execution, and other things you wouldn't think about writing high level code.
Weather learning MIPS assembly is useful to you depends on what career you plan to follow. Personally I think x86/x64 (popular in PCs, directly applicable if you write C++ or C# on PC), PPC (gaining popularity, used in game consoles, and also exposes you to RISC) or ARM (used in a lot of embedded devices such as mobile phones) might be better choices to learn.
A: MIPS specifically is less important than understanding asm in general so you have some idea of what happens when you compile high-level source. Understanding a bit of asm can help you make sense of the symptoms of bugs in high-level code. (e.g. overwriting the wrong data through a bogus pointer, or modifying other locals on the stack when you write outside an array).
Obviously understanding how to make C or C++ run fast is much easier when you know that what actually runs is the compiler-generate asm. It's impossible to design good microbenchmarks to test anything if you don't already mostly know what's going on.
Once you've learned MIPS assembly, it will be pretty easy to learn any other. All other mainstream CPUs are also register machines that work basically the same way:
*
*There are registers and memory
*Everything including pointers are just bits and bytes in memory or registers, i.e. integers.
*Each instruction is independent, and updates the architectural state (register values) according to its simple rules. It only cares about its inputs (usually registers, sometimes also memory). There is no magic.
*Execution continues from one instruction to the next in increasing address in program memory, except for jump / branch instructions.
*Writing programs / functions is a matter of constructing a series of steps for the machine to take that will result in data being moved around and processed the way you want. It's like designing the steps in an algorithm
*ASM is where a debugger really shines: it can show you the full architectural state of the machine (because there are a finite number of registers), and show you which register values changed when you single-step by one instruction.
Every architecture has its own extra wrinkles, but these basics don't change and are what you really learn when you learn your first assembly language. One of MIPS's major wrinkle is the branch-delay slot (which the MARS and SPIM simulators hide / disable by default)
RISC-V is a lot like MIPS, but without quirks like a branch-delay slot. And there is a RARS simulator with a toy system-call environment a lot like MARS provides for MIPS. As a bonus, RISC-V is a lot more commercially-relevant these days, so knowing it specifically has more real-world benefit if it catches your interest. But you can still imagine a classic-RISC pipeline that implements RISC-V, and learn all the same computer-architecture basics.
MIPS is a pretty nice assembly language to learn. It's simple and orthogonal, and leads nicely to discussions of pipelined CPUs because that's what it was designed for. (No microcoded instructions, and very regular machine-code format that's easy to decode.)
Also, there are nice MIPS simulators, MARS and SPIM, which have an editor / assembler / simulator + debugger all in one. And some "system calls" which do high-level things like read an integer from the user's keyboard into a register. Normal OSes have system calls that just let you read/write characters, and you have to call library functions or write your own integer->string functions. This is a blessing and a curse: if you don't realize that MARS system calls are basically library functions with a special calling convention, you might not realize that you can write your own code that does some of those things, or that it's not "normal" for system calls to work this way.
You could learn all this on x86, though, especially if you want to do performance experiments on your desktop / laptop.
A: At one point (in the 90s) MIPS-derived processors were the best selling processors in the world, dwarfing sales of Intel x86 processors. This was because of their huge presence in the embedded market. I think now ARM-based processors may have taken over that title, but there are still tons of embedded systems out there using MIPS.
Even if you never program a MIPS chip in assembler in your career, assembly language can be useful to learn. It can help you write more efficient high level code if you have some idea of what the compiler is going to emit. Other areas where it is still used include compilers (writing your own), device drivers, and multimedia programming (where code requiring MMX or SSE is usually still written by hand in assembler).
Each CPU type has a different instruction set but there's enough commonality that once you learn one dialect of assembly (MIPS in your case) the others should be easy to pick up.
A: Assembly language is always worth learning. You probably aren't being taught or seeing how the compiler turns high-level language code to assembly code, but I'd say that knowledge is the most important benefit of knowing assembly language. It's sobering how inefficient many compilers are even on the highest optimization level. (Most compilers will dump assembly code for you on request, instead of going on to machine code and linking.)
That said, MIPS asm is probably useless, because almost nobody uses MIPS now. (SGI used to, but now their machines are all on x86/IA-64 chips.) If you find assembly language appealing and want to work in assembly further, learn the ARM instruction set. ARM is only a little more complex than MIPS, and virtually all mobile phones, smart phones, and PDAs now use ARM chips (made by dozens of manufacturers). The iPod uses ARM, as does (I think) the Zune.
A: Mips appear to be coming back in embedded systems. @[sk] has given a better summary than me, but I have a recent example :
Broadcom appear to make Wifi cards these days with either MIPS or ARM chips on them ( I'm not sure which tho, documentation says one, firmware says the other ). However, on thier newer chips we're still awaiting on working linux support with all features enabled, so for that reason, I'm glad you're learning. ( Now get and write me some drivers :P )
A: In your case, I think MIPS is used as a tutoring aid. This is a computer science class and rather than give you code monkey tools, they are trying to teach you broad concepts that are easier exemplified on a simpler architecture like MIPS rather than on x86.
Do not expect it to enter your "programmer's toolbox". For the practical purpose of writing low level code, you'd better learn x86 assembly language afterwards.
A: Here are 3 good reasons for you to learn assembly.
*
*Certain small pieces of programs are better written in assembly than in a high level language.
*Old assembly programs may need to be debugged or enhanced.
*Learning to program in assembly will help you to develop precise models for what a processor does and what a compiler does.
The third reason is by far the most important. Knowing how your hardware works will greatly deepen your understanding of computer science and in turn help you to become a better developer.
A: It is helpful to understand the very low levels of the computer. For example there are developers who will say the CPU executes some sort of "new object" instruction. There is of course no such instruction, management of objects happens several layers of abstraction higher. It is good to understand the distinction, so you can understand why object creation might be expensive (or not) or why protected addresses spaces can make the system more robust.
When I was in school, the assembly course was taught on the IBM mainframe using the System/360 instruction set. I have never, at any point in my career, come anywhere near working on such a machine, but the knowledge of what the CPU looks like has been valuable.
Nowadays I work on embedded systems using MIPS processors. I actually spend a reasonable amount of time poring over MIPS assembly listings, and write some MIPS assembly for the boot vectors and synchronization primitives. Yet even if you never actually write anything in assembly, understanding CPU operation is still valuable.
A: I have studied MIPS last year. MIPS is an important language, but unfortunately, you will probably never use MIPS. You will learn some basics, but don't waste time trying to learn more than you need, because there are not to many jobs in MIPS, compared to other languages.
A: MIPS Assembly Language is definitely a nice language to learn compared to other assembly languages, but it's not useful in the job market concerning finding a job.
If you want to do something for yourself—then yes—it's pretty nice. But besides that, not really.
A: I would invest some time into it during the semester. The reason why they teach MIPS in school is because it is a reduced instruction set and less complex than the processor currently in your computer. In addition, the company was founded by an academic professor with background in the industry. The CEO of MIPS wrote one of the more well-known books on computer architecture.
Outside of the course, you will gain more benefit from understanding how the ALU, Controller, Registers, etc. work and less from the actual programming language. In my opinion, the course is really about Computer Architecture but taught through MIPS as a medium due to its relative simplicity.
A: I think it depends what area in CS you want to shoot towards after graduation. If computer architecture is what you want to do, then in my opinion I say it is. I think a good software engineer walks away with the general concept of how an assembly language works + bypassing and forwarding and finally how your code can be optimized for cache performance. (Spatial locality/temporal locality)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/99117",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "28"
}
|
Q: Would Automatic Casts be useful? Is there any downside or problem potential to change the Java compiler to automatically cast? In the example below the result of list.get(0) would automatically be casted to the type of the variable hi.
List list = new ArrayList();
list.add("hi");
String hi = list.get(0);
I know that generics allow you to reduce casting but they do so at the expense of making declaration more difficult. To me, the benefit of generics is that they allow you to have the complier enforce more rules -- not they they reduce casting (but I haven't used them much so I am somewhat uninformed). This proposal would only reduce the amount of code to type, not move it to another place.
Also there are instances where generics can't be used because a collection can have different objectis.
If that "looks too surprising" based on current usage maybe there could be a syntax tweak to use it.
From: http://jamesjava.blogspot.com/2007/01/automatic-casting.html
A: Casting is an explicit instruction to the Java compiler to ignore type safety so allowing automatic casts would remove one of the features purposely designed into the language.
I personally like compiler warnings and errors, since it's much harder to find this type of problem at run time (assuming the compiler somehow managed to force one object type to another).
A: Yes, it would move errors which are currently found at compile time to being found at runtime. While this is not considered to be a huge drawback by some, those people are using Python, Ruby or Perl and not Java ;-).
A: The biggest benefit of using generics in your example is that it changes what would be a run time error into a compile time error.
List list = new ArrayList();
list.add(new Integer(42));
String hi = (String) list.get(0); // run time error
List<String> list = new ArrayList<String>();
list.add(new Integer(42)); // compile time error
String hi = list.get(0);
Because run time errors are seen by users and compile time errors are seen by programmers, compile time errors are much, much better.
To answer your question, there would not be any drastic failures if casts were automatically made (and a ClassCastException was still thrown at runtime in your example). The benefit of requiring an explicit cast is that it requires the coder to think about what he's doing, and to realize that a cast is taking place.
Also there are instances where
generics can't be used because a
collection can have different object
You can still add different objects to a generic collection using wildcards.
A: I would avoid it, because I have a feeling it will come back and bite you later on. Generics are worth the hassle, in my opinion, because they save lots of headache down the road. Also, it's not too hard to use a "container" object for collections that hold different object types.
A: Seems to me like having type checks is a good thing. An automatic cast would remove a potentially useful compile-time error.
If you worry about the number of keystrokes, you could use an IDE like Eclipse, were the type cast can be inserted with a double-click.
A: As others have said, automatic type-casting would eliminate type safety. Generics have multiple benefits and really aren't any harder to declare. With Eclipse, you can can just declare the generic variable and then use auto-complete on the instantiation and it will automatically fill in the type you used. Plus you (or perhaps more importantly, someone else) have the advantage of actually knowing at a glance exactly what the list or whatever contains.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/99118",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: how to prevent "directory already exists error" in a makefile when using mkdir I need to generate a directory in my makefile and I would like to not get the "directory already exists error" over and over even though I can easily ignore it.
I mainly use mingw/msys but would like something that works across other shells/systems too.
I tried this but it didn't work, any ideas?
ifeq (,$(findstring $(OBJDIR),$(wildcard $(OBJDIR) )))
-mkdir $(OBJDIR)
endif
A: You can use the test command:
test -d $(OBJDIR) || mkdir $(OBJDIR)
A: ifeq "$(wildcard $(MY_DIRNAME) )" ""
-mkdir $(MY_DIRNAME)
endif
A: $(OBJDIR):
mkdir $@
Which also works for multiple directories, e.g..
OBJDIRS := $(sort $(dir $(OBJECTS)))
$(OBJDIRS):
mkdir $@
Adding $(OBJDIR) as the first target works well.
A: It works under mingw32/msys/cygwin/linux
ifeq "$(wildcard .dep)" ""
-include $(shell mkdir .dep) $(wildcard .dep/*)
endif
A: Here is a trick I use with GNU make for creating compiler-output directories. First define this rule:
%/.d:
mkdir -p $(@D)
touch $@
Then make all files that go into the directory dependent on the .d file in that directory:
obj/%.o: %.c obj/.d
$(CC) $(CFLAGS) -c -o $@ $<
Note use of $< instead of $^.
Finally prevent the .d files from being removed automatically:
.PRECIOUS: %/.d
Skipping the .d file, and depending directly on the directory, will not work, as the directory modification time is updated every time a file is written in that directory, which would force rebuild at every invocation of make.
A: If having the directory already exist is not a problem for you, you could just redirect stderr for that command, getting rid of the error message:
-mkdir $(OBJDIR) 2>/dev/null
A: Looking at the official make documentation, here is a good way to do it:
OBJDIR := objdir
OBJS := $(addprefix $(OBJDIR)/,foo.o bar.o baz.o)
$(OBJDIR)/%.o : %.c
$(COMPILE.c) $(OUTPUT_OPTION) $<
all: $(OBJS)
$(OBJS): | $(OBJDIR)
$(OBJDIR):
mkdir -p $(OBJDIR)
You should see here the usage of the | pipe operator, defining an order only prerequisite.
Meaning that the $(OBJDIR) target should be existent (instead of more recent) in order to build the current target.
Note that I used mkdir -p. The -p flag was added compared to the example of the docs.
See other answers for another alternative.
A: On UNIX Just use this:
mkdir -p $(OBJDIR)
The -p option to mkdir prevents the error message if the directory exists.
A: Inside your makefile:
target:
if test -d dir; then echo "hello world!"; else mkdir dir; fi
A: On Windows
if not exist "$(OBJDIR)" mkdir $(OBJDIR)
On Unix | Linux
if [ ! -d "$(OBJDIR)" ]; then mkdir $(OBJDIR); fi
A: A little simpler than Lars' answer:
something_needs_directory_xxx : xxx/..
and generic rule:
%/.. : ;@mkdir -p $(@D)
No touch-files to clean up or make .PRECIOUS :-)
If you want to see another little generic gmake trick, or if you're interested in non-recursive make with minimal scaffolding, you might care to check out Two more cheap gmake tricks and the other make-related posts in that blog.
A: If you explicitly ignore the return code and dump the error stream then your make will ignore the error if it occurs:
mkdir 2>/dev/null || true
This should not cause a race hazard in a parallel make - but I haven't tested it to be sure.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/99132",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "121"
}
|
Q: How do you make Vim unhighlight what you searched for? I search for "nurple" in a file. I found it, great. But now, every occurrence of "nurple" is rendered in sick black on yellow. Forever.
Forever, that is, until I search for something I know won't be found, such as "asdhfalsdflajdflakjdf" simply so it clears the previous search highlighting.
Can't I just hit a magic key to kill the highlights when I'm done searching?
A: /lkjasdf has always been faster than :noh for me.
A: I think the best answer is to have a leader shortcut:
<leader>c :nohl<CR>
Now whenever you have your document all junked up with highlighted terms, you just hit , + C (I have my leader mapped to a comma). It works perfectly.
A: I search so often that I've found it useful to map the underscore key to remove the search highlight:
nnoremap <silent> _ :nohl<CR>
A: :noh (short for nohighlight) will temporarily clear the search highlight. The next search will still be highlighted.
A: " Make double-<Esc> clear search highlights
nnoremap <silent> <Esc><Esc> <Esc>:nohlsearch<CR><Esc>
A: There is hlsearch and nohlsearch. :help hlsearch will provide more information.
If you want to bind F12 to toggle it on/off you can use this:
map <F12> :nohlsearch<CR>
imap <F12> <ESC>:nohlsearch<CR>i
vmap <F12> <ESC>:nohlsearch<CR>gv
A: I have this in my .vimrc:
nnoremap ; :set invhlsearch<CR>
This way, ; will toggle search highlighting. Normally, the ; key repeats the latest t/T/f/F command, but I never really used that functionality. I find this setting much more useful, because I can change search highlighting on and off very quickly and can easily get a sense of where my search results are, at a glance.
A: I think this answer in "Vim clear last search highlighting" is better:
:let @/ = ""
A: Then I prefer this:
map <F12> :set hls!<CR>
imap <F12> <ESC>:set hls!<CR>a
vmap <F12> <ESC>:set hls!<CR>gv
And why? Because it toggles the switch: if highlight is on, then pressing F12 turns it off. And vica versa. HTH.
A: Just put this in your .vimrc
" <Ctrl-l> redraws the screen and removes any search highlighting.
nnoremap <silent> <C-l> :nohl<CR><C-l>
A: Append the following line to the end of your .vimrc to prevent highlighting altogether:
set nohlsearch
A:
*:noh* *:nohlsearch*
:noh[lsearch] Stop the highlighting for the 'hlsearch' option. It
is automatically turned back on when using a search
command, or setting the 'hlsearch' option.
This command doesn't work in an autocommand, because
the highlighting state is saved and restored when
executing autocommands |autocmd-searchpat|.
Same thing for when invoking a user function.
I found it just under :help #, which I keep hitting all the time, and which highlights all the words on the current page like the current one.
A: Also, if you want to have a toogle and be sure that the highlight will be reactivate for the next time you search something, you can use this
nmap <F12> :set hls!<CR>
nnoremap / :set hls<CR>/
A: I add the following mapping to my ~/.vimrc
map e/ /sdfdskfxxxxy
And in ESC mode, I press e/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/99161",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "258"
}
|
Q: Iterate with for loop or while loop? I often see code like:
Iterator i = list.iterator();
while(i.hasNext()) {
...
}
but I write that (when Java 1.5 isn't available or for each can't be used) as:
for(Iterator i = list.iterator(); i.hasNext(); ) {
...
}
because
*
*It is shorter
*It keeps i in a smaller scope
*It reduces the chance of confusion. (Is i used outside the
while? Where is i declared?)
I think code should be as simple to understand as possible so that I only have to make complex code to do complex things. What do you think? Which is better?
From: http://jamesjava.blogspot.com/2006/04/iterating.html
A: I prefer the for loop because it also sets the scope of the iterator to just the for loop.
A: Why not use the for-each construct? (I haven't used Java in a while, but this exists in C# and I'm pretty sure Java 1.5 has this too):
List<String> names = new ArrayList<String>();
names.add("a");
names.add("b");
names.add("c");
for (String name : names)
System.out.println(name.charAt(0));
A: I think scope is the biggest issue here, as you have pointed out.
In the "while" example, the iterator is declared outside the loop, so it will continue to exist after the loop is done. This may cause issues if this same iterator is used again at some later point. E. g. you may forget to initialize it before using it in another loop.
In the "for" example, the iterator is declared inside the loop, so its scope is limited to the loop. If you try to use it after the loop, you will get a compiler error.
A: if you're only going to use the iterator once and throw it away, the second form is preferred; otherwise you must use the first form
A: IMHO, the for loop is less readable in this scenario, if you look at this code from the perspective of English language. I am working on a code where author does abuse for loop, and it ain't pretty. Compare following:
for (; (currUserObjectIndex < _domainObjectReferences.Length) && (_domainObjectReferences[currUserObjectIndex].VisualIndex == index); ++currUserObjectIndex)
++currNumUserObjects;
vs
while (currUserObjectIndex < _domainObjectReferences.Length && _domainObjectReferences[currUserObjectIndex].VisualIndex == index)
{
++currNumUserObjects;
++currUserObjectIndex;
}
A: There are appropriate uses for the while, the for, and the foreach constructs:
*
*while - Use this if you are iterating and the deciding factor for looping or not is based merely on a condition. In this loop construct, keeping an index is only a secondary concern; everything should be based on the condition
*for - Use this if you are looping and your primary concern is the index of the array/collection/list. It is more useful to use a for if you are most likely to go through all the elements anyway, and in a particular order (e.g., going backwards through a sorted list, for example).
*foreach - Use this if you merely need to go through your collection regardless of order.
Obviously there are exceptions to the above, but that's the general rule I use when deciding to use which. That being said I tend to use foreach more often.
A: I would agree that the "for" loop is clearer and more appropriate when iterating.
The "while" loop is appropriate for polling, or where the number of loops to meet exit condition will change based on activity inside the loop.
A: Not that it probably matters in this case, but Compilers, VMs and CPU's normally have special optimization techniques they user under the hood that will make for loops performance better (and in the near future parallel), in general they don't do that with while loops (because its harder to determine how it's actually going to run). But in most cases code clarity should trump optimization.
A: Using for loop you can work with a single variable, as it sets the scope of variable for a current working for loop only. However this is not possible in while loop.
For Example:
int i; for(i=0; in1;i++) do something..
for(i=0;i n2;i+=2) do something.
So after 1st loop i=n1-1 at the end. But while using second loop you can set i again to 0.
However
int i=0;
while(i less than limit) { do something ..; i++; }
Hence i is set to limit-1 at the end. So you cant use same i in another while loop.
A: Either is fine. I use for () myself, and I don't know if there are compile issues. I suspect they both get optimized down to pretty much the same thing.
A: Although both are really fine, I tend to use the first example because it is easier to read.
There are fewer operations happening on each line with the while() loop, making the code easier for someone new to the code to understand what's going on.
That type of construct also allows me to group initializations in a common location (at the top of the method) which also simplifies commenting for me, and conceptualization for someone reading it for the first time.
A: I agree that the for loop should be used whenever possible but sometimes there's more complex logic that controls the iterator in the body of the loop. In that case you have to go with while.
A: I was the for loop for clarity. While I use the while loop when faced with some undeterministic condition.
A: Both are fine, but remember that sometimes access to the Iterator directly is useful (such as if you are removing elements that match a certain condition - you will get a ConcurrentModificationException if you do collection.remove(o) inside a for(T o : collection) loop).
I prefer to write the for(blah : blah) [foreach] syntax almost all of the time because it seems more naturally readable to me. The concept of iterators in general don't really have parallels outside of programming
A: Academia tends to prefer the while-loop as it makes for less complicated reasoning about programs. I tend to prefer the for- or foreach-loop structures as they make for easier-to-read code.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/99164",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "44"
}
|
Q: Should selecting by first letter show as many as possible that start with that letter? When I am in a list and I press a letter to jump to the first entry that starts with that letter why does it leave that entry on the bottom of the visible entries? It should make the entry the top visable entry so that many entries that start with that letter can be seen.
In more concrete terms if I am selecting a state from a drop-down list and press "w" it should make "Washington" visible at the top instead of the bottom so that I can see Wisconsin without scrolling.
Agreed? Are there good reasons to keep it the current way?
From: http://jamesjava.blogspot.com/2005/05/gui-designers-take-note-selecting-by.html
A: How about having the first option starting with the letter you pressed be in the middle of the ones that are seen?
To extend your example, if you press "N" in the State dropdown, the choices you see might be:
*
*Missouri
*Montana
*Nebraska <-- First "N" choice
*Nevada
*New Hampshire
Now you can see not only what comes after, but also what comes before your choice. This allows you to find the first couple of options beginning with your choice and the last couple of options beginning with the letter before your choice.
Finding a state that begins with "N", but is near the end of the "Ns" (like "North Carolina"), is faster if you press "O" because it's closer to "Ohio" than "Nebraska":
*
*North Carolina
*North Dakota
*Ohio <-- First "O" choice
*Oklahoma
*Oregon
A: I agree. Especially if you have to continue hitting that letter to get to the next option.
A: I think that it may be just the default way Windows handles changing the selected index of the default combo box control. It'll scroll down only as much as it needs to show the selected item, it doesn't care about what comes before or after.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/99187",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: How do I get Haml to work with Rails? I am trying to get Haml to work with my Ruby on Rails project. I am new to Ruby on Rails and I really like it. However, when I attempt to add an aplication.html.haml or index.html.haml for a view, I just receive errors.
I am using NetBeans as my IDE.
A: Haml with Rails 3
For Rails 3 all you need to do is add gem "haml", '3.0.25' to your Gemfile. No need to install plugin or run haml --rails ..
Just:
$ cd awesome-rails-3-app.git
$ echo 'gem "haml"' >> Gemfile
And you're done.
A: The answers above are spot-on. You just need to put gem 'haml' in your Gemfile.
One other tip that was not mentioned: to have rails generators use haml instead of erb, add the following to config/application.rb:
config.generators do |g|
g.template_engine :haml
# you can also specify a different test framework or ORM here
# g.test_framework :rspec
# g.orm :mongoid
end
A: First, install haml as a gem in bundler by adding this to your Gemfile:
gem "haml"
Run bundle install, then make sure your views are named with a *.html.haml extension. For example:
`-- app
`-- views
|-- layouts
| `-- application.html.haml
`-- users
|-- edit.html.haml
|-- index.html.haml
|-- new.html.haml
`-- show.html.haml
A: This may be an old question but I think the answer is using haml-rails at https://github.com/indirect/haml-rails
A: Add haml to your Gemfile:
gem "haml"
If you want to use the scaffold-functions too, add haml-rails within your development-group:
gem 'haml-rails', :group => :development
Don't forget to run:
$ bundle install
A: Before trying to use haml in your rails application, you can verify that the command line executable is installed correctly:
$ haml
%p
%span Hello World!
Then press CTRL-D and you should see:
<p>
<span>Hello World!</span>
</p>
A: First, make sure you have the HAML gem.
gem list --local | grep haml
If haml doesn't show up in the list, then do this:
sudo gem install haml
Then do this from your project directory:
# cd ../
# haml --rails <yourproject>
That should install everything you need, and the HAML views should stop complaining and parse correctly.
A: if for some reason you installed haml, but you haml doesn't start. try
sudo ln haml /usr/bin/
in the bin directory of your haml gem
for some reason this didn't happen automatically on my ubuntu 9.04 Jaunty.
A: If you are using Pow you will need to restart it also. Ideally you are using powder (gem install powder), because then you can just run this at the terminal
$ powder restart
A: make sure to add haml gem into your Gemfile
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/99211",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "77"
}
|
Q: Is there any way to get access to the DOM from Objective-C when using UIWebView? UIWebView is fine for displaying HTML, but I'd like to modify the loaded DOM from my Objective-C program. Does anybody know how to do that? This is a third party page, so I can't really include any custom JS to do so...unless I can modify the DOM somehow.
A: This may be of some help, as not to plagiarize the solution provider in the link, here's the link:
http://lists.apple.com/archives/safari-iphone-web-dev/2008/Sep/msg00001.html
A: Some more related techniques around Obj-C / JS communication:
Using UIWebView for local resources:
http://dominiek.com/articles/2008/7/19/iphone-app-development-for-web-hackers
Google Maps API for iPhone:
http://code.google.com/p/iphone-google-maps-component/
Bidirectional calling between Obj-C and Javascript:
http://tetontech.wordpress.com/2008/08/14/calling-objective-c-from-javascript-in-an-iphone-uiwebview/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/99241",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: RMI server: rmiregistry or LocateRegistry.createRegistry For RMI on server-side, do we need to start rmiregistry program, or just call LocateRegistry.createRegistry?
If both are possible, what are the advantages and disadvantages?
A: They're the same thing... rmiregistry is a separate program, which you can run from a command line or a script, while LocateRegistry.createRegistry does the same thing programatically.
In my experience, for "real" servers you will want to use rmiregistry so that you know it's always running regardless of whether or not the client application is started. createRegistry is very useful for testing, as you can start and stop the registry from your test as necessary.
A: If we start rmiregistry first, RmiServiceExporter would register itself to the running rmiregistry. In this case, we have to set the system property 'java.rmi.server.codebase' to where the 'org.springframework.remoting.rmi.RmiInvocationWrapper_Stub' class can be found. Otherwise, the RmiServiceExporter would not be started and got the exception "
ClassNotFoundException class not found: org.springframework.remoting.rmi.RmiInvocationWrapper_Stub; nested exception is: ..."
If your rmi server, rmi client and rmiregistry can access the same filesystem, you may want the system property to be automatically configured to where the spring.jar can be found on the shared filesystem. The following utility classes and spring configuration show how this can be achieved.
abstract public class CodeBaseResolver {
static public String resolveCodeBaseForClass(Class<?> clazz) {
Assert.notNull(clazz);
final CodeSource codeSource = clazz.getProtectionDomain().getCodeSource();
if (codeSource != null) {
return codeSource.getLocation().toString();
} else {
return "";
}
}
}
public class SystemPropertyConfigurer {
private Map<String, String> systemProperties;
public void setSystemProperties(Map<String, String> systemProperties) {
this.systemProperties = systemProperties;
}
@PostConstruct
void init() throws BeansException {
if (systemProperties == null || systemProperties.isEmpty()) {
return;
}
for (Map.Entry<String, String> entry : systemProperties.entrySet()) {
final String key = entry.getKey();
final String value = SystemPropertyUtils.resolvePlaceholders(entry.getValue());
System.setProperty(key, value);
}
}
}
<bean id="springCodeBase" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="staticMethod" value="xx.CodeBaseResolver.resolveCodeBaseForClass" />
<property name="arguments">
<list>
<value>org.springframework.remoting.rmi.RmiInvocationWrapper_Stub</value>
</list>
</property>
</bean>
<bean id="springCodeBaseConfigurer" class="xx.SystemPropertyConfigurer"
depends-on="springCodeBase">
<property name="systemProperties">
<map>
<entry key="java.rmi.server.codebase" value-ref="springCodeBase" />
</map>
</property>
</bean>
<bean id="rmiServiceExporter" class="org.springframework.remoting.rmi.RmiServiceExporter" depends-on="springCodeBaseConfigurer">
<property name="serviceName" value="XXX" />
<property name="service" ref="XXX" />
<property name="serviceInterface" value="XXX" />
<property name="registryPort" value="${remote.rmi.port}" />
</bean>
The above example shows how system property be set automatically only when rmi server, rmi client and rmi registry can access the same filesystem. If that is not true or spring codebase is shared via other method (e.g. HTTP), you may modify the CodeBaseResolver to fit your need.
A: If you are writing a standalone java application you would want to start your own rmiregistry but if you are writing a J2EE app that obviously runs inside a J2EE container then you want to "LocateRegistry" as there is already one running on the app server!
A: If you use Spring to export your RMI services, it automatically starts a registry if one is not already running. See RmiServiceExporter
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/99242",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
}
|
Q: What is the most common feature that demands the use of Visual Studio Professional over Standard? I'm afraid my trial of VS 2008 is running out soon, and unless a client pays for it, I might be shelling out some cash for it. I've been looking through the comparison chart to compare VS Professional to Standard, and so far I think I'm safe. I wanted to hear from you on what the most important features are that I would be missing.
Of course, you don't know all the details of my situation - but please just answer based on what you perceive as most important.
A: Developing Windows Mobile Applications and availability of Database Projects are the showstoppers for me (this applies to Visual Studio 2008).
That's it really. This was a dealbreaker for me though since I wanted to join this mobile application programming contest and was floored when I found out I couldn't do it with Standard.
Otherwise you're fine with Standard edition.
A: The major downside of the Express Edition is they don't support addons - so you have to make sure your Source Control software has a standalone client.
A: Remote Debugging, Server Explorer, Compact Development (With Device Emulator). It really does depend on your situation but I don't think you'll be without a paddle in general.
A: "Attach to remote process" is a must. It lets you debug your application in several virtual (or physical) machines running different versions of Windows without installing Visual Studio on each such machine: you would run Visual Studio on your main development computer and attach it to the instance of your application running on another machine, and debug it that way. That's the only way I debug my applications, I never debug them on the development computer. HTH.
A: Very little difference between the two. The only one I can think of is remote debugging is not available in standard.
A: You may want to look into the VS 2008 Express editions. Install them and see if you can do everything you need to using the Express editions. Most things that you need/use are in the Express editions, and they're Free. Also, you can use them for commercial use all you want.
A: For me OMP support in "standard" is what's nice to have, if your into that
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/99262",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: C# COM Office Automation - RPC_E_SYS_CALL_FAILED I'm writing a C# program that acts as a PowerPoint 2007 plugin. On some machines, some calls to the PowerPoint object model throw a COMException with the message RPC_E_SYS_CALL_FAILED. I couldn't find any specific advice on what to do regarding this error, or how to avoid it. From Googling it looks like something to do with the message queue or Single-Threaded Apartments. Or am I way off?
Example of the error message is:
System call failed. (Exception from HRESULT: 0x80010100 (RPC_E_SYS_CALL_FAILED))
at Microsoft.Office.Interop.PowerPoint._Presentation.get_FullName()
Unfortunately, the problem is occurring on a client's machine, so I have no easy way to debug it! Should I just retry the calls whenever I get this error?
Any advice to help me resolve this problem would be greatly appreciated!
A: I don't know it is related to your problem, but all your COM calls must come from within the same thread your add-in was created on. If you created new threads you must take special care. Details are described in these two articles:
*
*Implementing IMessageFilter in an Office add-in and
*Why your COMAddIn.Object should derive from StandardOleMarshalObject
A: are you making the call from a thread with its ApartmentState set? if not, that might be the culprit - COM interop is pretty finicky about that sort of thing
A: What are the security settings of the client? It is quite possible that the security settings of the client (either Windows/OS settings or PowerPoint/App settings) won't allow your plug-in to communicate via RPC.
A: This can very easily happen if you make any calls to the Powerpoint object model from a background thread. One plausible scenario is having a timer that periodically checks some sort of status value. If, when the timer fires, Powerpoint is busy (for example a dialog box is open) the call will fail.
This Microsoft article gives an overview of threading support in Office:
http://msdn.microsoft.com/en-us/library/8sesy69e.aspx
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/99271",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: How do you parse a web page and extract all the href links? I want to parse a web page in Groovy and extract all of the href links and the associated text with it.
If the page contained these links:
<a href="http://www.google.com">Google</a><br />
<a href="http://www.apple.com">Apple</a>
the output would be:
Google, http://www.google.com<br />
Apple, http://www.apple.com
I'm looking for a Groovy answer. AKA. The easy way!
A: A quick google search turned up a nice looking possibility, TagSoup.
A: I don't know java but I think that xpath is far better than classic regular expressions in order to get one (or more) html elements.
It is also easier to write and to read.
<html>
<body>
<a href="1.html">1</a>
<a href="2.html">2</a>
<a href="3.html">3</a>
</body>
</html>
With the html above, this expression "/html/body/a" will list all href elements.
Here's a good step by step tutorial http://www.zvon.org/xxl/XPathTutorial/General/examples.html
A: Assuming well-formed XHTML, slurp the xml, collect up all the tags, find the 'a' tags, and print out the href and text.
input = """<html><body>
<a href = "http://www.hjsoft.com/">John</a>
<a href = "http://www.google.com/">Google</a>
<a href = "http://www.stackoverflow.com/">StackOverflow</a>
</body></html>"""
doc = new XmlSlurper().parseText(input)
doc.depthFirst().collect { it }.findAll { it.name() == "a" }.each {
println "${it.text()}, ${it.@href.text()}"
}
A: Use XMLSlurper to parse the HTML as an XML document and then use the find method with an appropriate closure to select the a tags and then use the list method on GPathResult to get a list of the tags. You should then be able to extract the text as children of the GPathResult.
A: Try a regular expression. Something like this should work:
(html =~ /<a.*href='(.*?)'.*>(.*?)<\/a>/).each { url, text ->
// do something with url and text
}
Take a look at Groovy - Tutorial 4 - Regular expressions basics and Anchor Tag Regular Expression Breaking.
A: Parsing using XMlSlurper only works if HTMl is well-formed.
If your HTMl page has non-well-formed tags, then use regex for parsing the page.
Ex: <a href="www.google.com">
here, 'a' is not closed and thus not well formed.
new URL(url).eachLine{
(it =~ /.*<A HREF="(.*?)">/).each{
// process hrefs
}
}
A: Html parser + Regular expressions
Any language would do it, though I'd say Perl is the fastest solution.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/99279",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
}
|
Q: Would it be useful to add extra info to stack traces? Would it be useful to be able to mark objects where the value ofString.valueOf() would included in any stack trace. In my example below I used "trace". Variables that aren't declared at the point of the stack trace would just be ingored.
It would make debugging much easier and make it much easier to write programs that are easy to debug.
Example stack trace for the code below:
java.lang.NullPointerException:
at Test.main(Test.java:7) index=0, sum=3, obj=null
public class Test {
Object obj;
public void main(String[] args) trace obj {
trace int sum = 0;
for(trace int index = 0; index < args.length; index++) {
sum += Integer.parseInt(args[index]);
sum += obj.hashCode();//Will cause NullPointerException
}
}
}
From: http://jamesjava.blogspot.com/2005/04/extra-info-in-stack-traces.html
A: this might be useful, but i think it clutters the code - presumably when the code is working you would want to remove the 'trace' keywords; perhaps some form of metadata would be more appropriate
then there's always print statements...
A: Tempting, but I don't think this feature warrants a new keyword in Java (and that much more complexity in the language).
I've found the use of Throwable.printStackTrace has usually been plenty to quickly point to the problems that need my attention.
A: Perhaps I'm missing the point, but why not use a proper logging framework (e.g. Log4j)? Then you can use nested / mapped diagnostic contexts (NDC / MDC) for outputting variable values.
A: I would rather prefer a standard (annotation based) way of describing the programmers intent for nullness (FindBugs, JSR 305). I once considered having not just the line number, but the column number included in the exception message so in long chained invocations you could easier see which dot operator caused the NPE. As stated by others in NPE related questions here on StackOverflow, in most cases you get NPE from trying to access a field/method on a null object.
A: Yes, it can be quite useful. I often do this kind of thing myself, but I only have it compile into non-production code, usually.
A: What I'd love is a property of the exception which would be a string array of all the method signatures leading up to the throw... without having to parse it out of the Exception text.
A: The Visual Studio C# debugger's call stack window includes a stack trace with all the argument values displayed.
A: Eh. Personally I don't think it would be that useful. If I'm running my code and hitting exceptions I can more easily set a breakpoint and step into the code and see what all of the variables are at that point and figure out where it's really breaking.
Using this trace method not only would I have to keep adding and removing keywords from in front of variables as I worked on different bugs but I don't think that it would be any real improvement over just adding good logging/debugging messaging (which is much easier to remove or disable when pushed to production).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/99285",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How are virtual functions and vtable implemented? We all know what virtual functions are in C++, but how are they implemented at a deep level?
Can the vtable be modified or even directly accessed at runtime?
Does the vtable exist for all classes, or only those that have at least one virtual function?
Do abstract classes simply have a NULL for the function pointer of at least one entry?
Does having a single virtual function slow down the whole class? Or only the call to the function that is virtual? And does the speed get affected if the virtual function is actually overwritten or not, or does this have no effect so long as it is virtual.
A: *
*Can the vtable be modified or even directly accessed at runtime?
Not portably, but if you don't mind dirty tricks, sure!
WARNING: This technique is not recommended for use by children, adults under the age of 969, or small furry creatures from Alpha Centauri. Side effects may include demons which fly out of your nose, the abrupt appearence of Yog-Sothoth as a required approver on all subsequent code reviews, or the retroactive addition of IHuman::PlayPiano() to all existing instances]
In most compilers I've seen, the vtbl * is the first 4 bytes of the object, and the vtbl contents are simply an array of member pointers there (generally in the order they were declared, with the base class's first). There are of course other possible layouts, but that's what I've generally observed.
class A {
public:
virtual int f1() = 0;
};
class B : public A {
public:
virtual int f1() { return 1; }
virtual int f2() { return 2; }
};
class C : public A {
public:
virtual int f1() { return -1; }
virtual int f2() { return -2; }
};
A *x = new B;
A *y = new C;
A *z = new C;
Now to pull some shenanigans...
Changing class at runtime:
std::swap(*(void **)x, *(void **)y);
// Now x is a C, and y is a B! Hope they used the same layout of members!
Replacing a method for all instances (monkeypatching a class)
This one's a little trickier, since the vtbl itself is probably in read-only memory.
int f3(A*) { return 0; }
mprotect(*(void **)x,8,PROT_READ|PROT_WRITE|PROT_EXEC);
// Or VirtualProtect on win32; this part's very OS-specific
(*(int (***)(A *)x)[0] = f3;
// Now C::f1() returns 0 (remember we made x into a C above)
// so x->f1() and z->f1() both return 0
The latter is rather likely to make virus-checkers and the link wake up and take notice, due to the mprotect manipulations. In a process using the NX bit it may well fail.
A: Usually with a VTable, an array of pointers to functions.
A: Here is a runnable manual implementation of virtual table in modern C++. It has well-defined semantics, no hacks and no void*.
Note: .* and ->* are different operators than * and ->. Member function pointers work differently.
#include <iostream>
#include <vector>
#include <memory>
struct vtable; // forward declare, we need just name
class animal
{
public:
const std::string& get_name() const { return name; }
// these will be abstract
bool has_tail() const;
bool has_wings() const;
void sound() const;
protected: // we do not want animals to be created directly
animal(const vtable* vtable_ptr, std::string name)
: vtable_ptr(vtable_ptr), name(std::move(name)) { }
private:
friend vtable; // just in case for non-public methods
const vtable* const vtable_ptr;
std::string name;
};
class cat : public animal
{
public:
cat(std::string name);
// functions to bind dynamically
bool has_tail() const { return true; }
bool has_wings() const { return false; }
void sound() const
{
std::cout << get_name() << " does meow\n";
}
};
class dog : public animal
{
public:
dog(std::string name);
// functions to bind dynamically
bool has_tail() const { return true; }
bool has_wings() const { return false; }
void sound() const
{
std::cout << get_name() << " does whoof\n";
}
};
class parrot : public animal
{
public:
parrot(std::string name);
// functions to bind dynamically
bool has_tail() const { return false; }
bool has_wings() const { return true; }
void sound() const
{
std::cout << get_name() << " does crrra\n";
}
};
// now the magic - pointers to member functions!
struct vtable
{
bool (animal::* const has_tail)() const;
bool (animal::* const has_wings)() const;
void (animal::* const sound)() const;
// constructor
vtable (
bool (animal::* const has_tail)() const,
bool (animal::* const has_wings)() const,
void (animal::* const sound)() const
) : has_tail(has_tail), has_wings(has_wings), sound(sound) { }
};
// global vtable objects
const vtable vtable_cat(
static_cast<bool (animal::*)() const>(&cat::has_tail),
static_cast<bool (animal::*)() const>(&cat::has_wings),
static_cast<void (animal::*)() const>(&cat::sound));
const vtable vtable_dog(
static_cast<bool (animal::*)() const>(&dog::has_tail),
static_cast<bool (animal::*)() const>(&dog::has_wings),
static_cast<void (animal::*)() const>(&dog::sound));
const vtable vtable_parrot(
static_cast<bool (animal::*)() const>(&parrot::has_tail),
static_cast<bool (animal::*)() const>(&parrot::has_wings),
static_cast<void (animal::*)() const>(&parrot::sound));
// set vtable pointers in constructors
cat::cat(std::string name) : animal(&vtable_cat, std::move(name)) { }
dog::dog(std::string name) : animal(&vtable_dog, std::move(name)) { }
parrot::parrot(std::string name) : animal(&vtable_parrot, std::move(name)) { }
// implement dynamic dispatch
bool animal::has_tail() const
{
return (this->*(vtable_ptr->has_tail))();
}
bool animal::has_wings() const
{
return (this->*(vtable_ptr->has_wings))();
}
void animal::sound() const
{
(this->*(vtable_ptr->sound))();
}
int main()
{
std::vector<std::unique_ptr<animal>> animals;
animals.push_back(std::make_unique<cat>("grumpy"));
animals.push_back(std::make_unique<cat>("nyan"));
animals.push_back(std::make_unique<dog>("doge"));
animals.push_back(std::make_unique<parrot>("party"));
for (const auto& a : animals)
a->sound();
// note: destructors are not dispatched virtually
}
A: Does having a single virtual function slow down the whole class?
Or only the call to the function that is virtual? And does the speed get affected if the virtual function is actually overwritten or not, or does this have no effect so long as it is virtual.
Having virtual functions slows down the whole class insofar as one more item of data has to be initialized, copied, … when dealing with an object of such a class. For a class with half a dozen members or so, the difference should be neglible. For a class which just contains a single char member, or no members at all, the difference might be notable.
Apart from that, it is important to note that not every call to a virtual function is a virtual function call. If you have an object of a known type, the compiler can emit code for a normal function invocation, and can even inline said function if it feels like it. It's only when you do polymorphic calls, via a pointer or reference which might point at an object of the base class or at an object of some derived class, that you need the vtable indirection and pay for it in terms of performance.
struct Foo { virtual ~Foo(); virtual int a() { return 1; } };
struct Bar: public Foo { int a() { return 2; } };
void f(Foo& arg) {
Foo x; x.a(); // non-virtual: always calls Foo::a()
Bar y; y.a(); // non-virtual: always calls Bar::a()
arg.a(); // virtual: must dispatch via vtable
Foo z = arg; // copy constructor Foo::Foo(const Foo&) will convert to Foo
z.a(); // non-virtual Foo::a, since z is a Foo, even if arg was not
}
The steps the hardware has to take are essentially the same, no matter whether the function is overwritten or not. The address of the vtable is read from the object, the function pointer retrieved from the appropriate slot, and the function called by pointer. In terms of actual performance, branch predictions might have some impact. So for example, if most of your objects refer to the same implementation of a given virtual function, then there is some chance that the branch predictor will correctly predict which function to call even before the pointer has been retrieved. But it doesn't matter which function is the common one: it could be most objects delegating to the non-overwritten base case, or most objects belonging to the same subclass and therefore delegating to the same overwritten case.
how are they implemented at a deep level?
I like the idea of jheriko to demonstrate this using a mock implementation. But I'd use C to implement something akin to the code above, so that the low level is more easily seen.
parent class Foo
typedef struct Foo_t Foo; // forward declaration
struct slotsFoo { // list all virtual functions of Foo
const void *parentVtable; // (single) inheritance
void (*destructor)(Foo*); // virtual destructor Foo::~Foo
int (*a)(Foo*); // virtual function Foo::a
};
struct Foo_t { // class Foo
const struct slotsFoo* vtable; // each instance points to vtable
};
void destructFoo(Foo* self) { } // Foo::~Foo
int aFoo(Foo* self) { return 1; } // Foo::a()
const struct slotsFoo vtableFoo = { // only one constant table
0, // no parent class
destructFoo,
aFoo
};
void constructFoo(Foo* self) { // Foo::Foo()
self->vtable = &vtableFoo; // object points to class vtable
}
void copyConstructFoo(Foo* self,
Foo* other) { // Foo::Foo(const Foo&)
self->vtable = &vtableFoo; // don't copy from other!
}
derived class Bar
typedef struct Bar_t { // class Bar
Foo base; // inherit all members of Foo
} Bar;
void destructBar(Bar* self) { } // Bar::~Bar
int aBar(Bar* self) { return 2; } // Bar::a()
const struct slotsFoo vtableBar = { // one more constant table
&vtableFoo, // can dynamic_cast to Foo
(void(*)(Foo*)) destructBar, // must cast type to avoid errors
(int(*)(Foo*)) aBar
};
void constructBar(Bar* self) { // Bar::Bar()
self->base.vtable = &vtableBar; // point to Bar vtable
}
function f performing virtual function call
void f(Foo* arg) { // same functionality as above
Foo x; constructFoo(&x); aFoo(&x);
Bar y; constructBar(&y); aBar(&y);
arg->vtable->a(arg); // virtual function call
Foo z; copyConstructFoo(&z, arg);
aFoo(&z);
destructFoo(&z);
destructBar(&y);
destructFoo(&x);
}
So you can see, a vtable is just a static block in memory, mostly containing function pointers. Every object of a polymorphic class will point to the vtable corresponding to its dynamic type. This also makes the connection between RTTI and virtual functions clearer: you can check what type a class is simply by looking at what vtable it points at. The above is simplified in many ways, like e.g. multiple inheritance, but the general concept is sound.
If arg is of type Foo* and you take arg->vtable, but is actually an object of type Bar, then you still get the correct address of the vtable. That's because the vtable is always the first element at the address of the object, no matter whether it's called vtable or base.vtable in a correctly-typed expression.
A: This answer has been incorporated into the Community Wiki answer
*
*Do abstract classes simply have a NULL for the function pointer of at least one entry?
The answer for that is that it is unspecified - calling the pure virtual function results in undefined behavior if it is not defined (which it usually isn't) (ISO/IEC 14882:2003 10.4-2). Some implementations do simply place a NULL pointer in the vtable entry; other implementations place a pointer to a dummy method that does something similar to an assertion.
Note that an abstract class can define an implementation for a pure virtual function, but that function can only be called with a qualified-id syntax (ie., fully specifying the class in the method name, similar to calling a base class method from a derived class). This is done to provide an easy to use default implementation, while still requiring that a derived class provide an override.
A: You can recreate the functionality of virtual functions in C++ using function pointers as members of a class and static functions as the implementations, or using pointer to member functions and member functions for the implementations. There are only notational advantages between the two methods... in fact virtual function calls are just a notational convenience themselves. In fact inheritance is just a notational convenience... it can all be implemented without using the language features for inheritance. :)
The below is crap untested, probably buggy code, but hopefully demonstrates the idea.
e.g.
class Foo
{
protected:
void(*)(Foo*) MyFunc;
public:
Foo() { MyFunc = 0; }
void ReplciatedVirtualFunctionCall()
{
MyFunc(*this);
}
...
};
class Bar : public Foo
{
private:
static void impl1(Foo* f)
{
...
}
public:
Bar() { MyFunc = impl1; }
...
};
class Baz : public Foo
{
private:
static void impl2(Foo* f)
{
...
}
public:
Baz() { MyFunc = impl2; }
...
};
A: I'll try to make it simple :)
We all know what virtual functions are in C++, but how are they implemented at a deep level?
This is an array with pointers to functions, which are implementations of a particular virtual function. An index in this array represents particular index of a virtual function defined for a class. This includes pure virtual functions.
When a polymorphic class derives from another polymorphic class, we may have the following situations:
*
*The deriving class does not add new virtual functions nor overrides any. In this case this class shares the vtable with the base class.
*The deriving class adds and overrides virtual methods. In this case it gets its own vtable, where the added virtual functions have index starting past the last derived one.
*Multiple polymorphic classes in the inheritance. In this case we have an index-shift between second and next bases and the index of it in the derived class
Can the vtable be modified or even directly accessed at runtime?
Not standard way - there's no API to access them. Compilers may have some extensions or private APIs to access them, but that may be only an extension.
Does the vtable exist for all classes, or only those that have at least one virtual function?
Only those that have at least one virtual function (be it even destructor) or derive at least one class that has its vtable ("is polymorphic").
Do abstract classes simply have a NULL for the function pointer of at least one entry?
That's a possible implementation, but rather not practiced. Instead there is usually a function that prints something like "pure virtual function called" and does abort(). The call to that may occur if you try to call the abstract method in the constructor or destructor.
Does having a single virtual function slow down the whole class? Or only the call to the function that is virtual? And does the speed get affected if the virtual function is actually overwritten or not, or does this have no effect so long as it is virtual.
The slowdown is only dependent on whether the call is resolved as direct call or as a virtual call. And nothing else matters. :)
If you call a virtual function through a pointer or reference to an object, then it will be always implemented as virtual call - because the compiler can never know what kind of object will be assigned to this pointer in runtime, and whether it is of a class in which this method is overridden or not. Only in two cases the compiler can resolve the call to a virtual function as a direct call:
*
*If you call the method through a value (a variable or result of a function that returns a value) - in this case the compiler has no doubts what the actual class of the object is, and can "hard-resolve" it at compile time.
*If the virtual method is declared final in the class to which you have a pointer or reference through which you call it (only in C++11). In this case compiler knows that this method cannot undergo any further overriding and it can only be the method from this class.
Note though that virtual calls have only overhead of dereferencing two pointers. Using RTTI (although only available for polymorphic classes) is slower than calling virtual methods, should you find a case to implement the same thing two such ways. For example, defining virtual bool HasHoof() { return false; } and then override only as bool Horse::HasHoof() { return true; } would provide you with ability to call if (anim->HasHoof()) that will be faster than trying if(dynamic_cast<Horse*>(anim)). This is because dynamic_cast has to walk through the class hierarchy in some cases even recursively to see if there can be built the path from the actual pointer type and the desired class type. While the virtual call is always the same - dereferencing two pointers.
A: How are virtual functions implemented at a deep level?
From "Virtual Functions in C++":
Whenever a program has a virtual function declared, a v - table is constructed for the class. The v-table consists of addresses to the virtual functions for classes that contain one or more virtual functions. The object of the class containing the virtual function contains a virtual pointer that points to the base address of the virtual table in memory. Whenever there is a virtual function call, the v-table is used to resolve to the function address. An object of the class that contains one or more virtual functions contains a virtual pointer called the vptr at the very beginning of the object in the memory. Hence the size of the object in this case increases by the size of the pointer. This vptr contains the base address of the virtual table in memory. Note that virtual tables are class specific, i.e., there is only one virtual table for a class irrespective of the number of virtual functions it contains. This virtual table in turn contains the base addresses of one or more virtual functions of the class. At the time when a virtual function is called on an object, the vptr of that object provides the base address of the virtual table for that class in memory. This table is used to resolve the function call as it contains the addresses of all the virtual functions of that class. This is how dynamic binding is resolved during a virtual function call.
Can the vtable be modified or even directly accessed at runtime?
Universally, I believe the answer is "no". You could do some memory mangling to find the vtable but you still wouldn't know what the function signature looks like to call it. Anything that you would want to achieve with this ability (that the language supports) should be possible without access to the vtable directly or modifying it at runtime. Also note, the C++ language spec does not specify that vtables are required - however that is how most compilers implement virtual functions.
Does the vtable exist for all objects, or only those that have at least one virtual function?
I believe the answer here is "it depends on the implementation" since the spec doesn't require vtables in the first place. However, in practice, I believe all modern compilers only create a vtable if a class has at least 1 virtual function. There is a space overhead associated with the vtable and a time overhead associated with calling a virtual function vs a non-virtual function.
Do abstract classes simply have a NULL for the function pointer of at least one entry?
The answer is it is unspecified by the language spec so it depends on the implementation. Calling the pure virtual function results in undefined behavior if it is not defined (which it usually isn't) (ISO/IEC 14882:2003 10.4-2). In practice it does allocate a slot in the vtable for the function but does not assign an address to it. This leaves the vtable incomplete which requires the derived classes to implement the function and complete the vtable. Some implementations do simply place a NULL pointer in the vtable entry; other implementations place a pointer to a dummy method that does something similar to an assertion.
Note that an abstract class can define an implementation for a pure virtual function, but that function can only be called with a qualified-id syntax (ie., fully specifying the class in the method name, similar to calling a base class method from a derived class). This is done to provide an easy to use default implementation, while still requiring that a derived class provide an override.
Does having a single virtual function slow down the whole class or only the call to the function that is virtual?
This is getting to the edge of my knowledge, so someone please help me out here if I'm wrong!
I believe that only the functions that are virtual in the class experience the time performance hit related to calling a virtual function vs. a non-virtual function. The space overhead for the class is there either way. Note that if there is a vtable, there is only 1 per class, not one per object.
Does the speed get affected if the virtual function is actually overridden or not, or does this have no effect so long as it is virtual?
I don't believe the execution time of a virtual function that is overridden decreases compared to calling the base virtual function. However, there is an additional space overhead for the class associated with defining another vtable for the derived class vs the base class.
Additional Resources:
http://www.codersource.net/published/view/325/virtual_functions_in.aspx (via way back machine)
http://en.wikipedia.org/wiki/Virtual_table
http://www.codesourcery.com/public/cxx-abi/abi.html#vtable
A: Each object has a vtable pointer that points to an array of member functions.
A: Something not mentioned here in all these answers is that in case of multiple inheritance, where the base classes all have virtual methods. The inheriting class has multiple pointers to a vmt.
The result is that the size of each instance of such an object is bigger.
Everybody knows that a class with virtual methods has 4 bytes extra for the vmt, but in case of multiple inheritance it is for each base class that has virtual methods times 4. 4 being the size of the pointer.
A: Burly's answers are correct here except for the question:
Do abstract classes simply have a NULL for the function pointer of at least one entry?
The answer is that no virtual table is created at all for abstract classes. There is no need since no objects of these classes can be created!
In other words if we have:
class B { ~B() = 0; }; // Abstract Base class
class D : public B { ~D() {} }; // Concrete Derived class
D* pD = new D();
B* pB = pD;
The vtbl pointer accessed through pB will be the vtbl of class D. This is exactly how polymorphism is implemented. That is, how D methods are accessed through pB. There is no need for a vtbl for class B.
In response to Mike's comment below...
If the B class in my description has a virtual method foo() that is not overridden by D and a virtual method bar() that is overridden, then D's vtbl will have a pointer to B's foo() and to its own bar(). There is still no vtbl created for B.
A: very cute proof of concept i made a bit earlier(to see if order of inheritence matters); let me know if your implementation of C++ actually rejects it(my version of gcc only gives a warning for assigning anonymous structs, but that's a bug), i'm curious.
CCPolite.h:
#ifndef CCPOLITE_H
#define CCPOLITE_H
/* the vtable or interface */
typedef struct {
void (*Greet)(void *);
void (*Thank)(void *);
} ICCPolite;
/**
* the actual "object" literal as C++ sees it; public variables be here too
* all CPolite objects use(are instances of) this struct's structure.
*/
typedef struct {
ICCPolite *vtbl;
} CPolite;
#endif /* CCPOLITE_H */
CCPolite_constructor.h:
/**
* unconventionally include me after defining OBJECT_NAME to automate
* static(allocation-less) construction.
*
* note: I assume CPOLITE_H is included; since if I use anonymous structs
* for each object, they become incompatible and cause compile time errors
* when trying to do stuff like assign, or pass functions.
* this is similar to how you can't pass void * to windows functions that
* take handles; these handles use anonymous structs to make
* HWND/HANDLE/HINSTANCE/void*/etc not automatically convertible, and
* require a cast.
*/
#ifndef OBJECT_NAME
#error CCPolite> constructor requires object name.
#endif
CPolite OBJECT_NAME = {
&CCPolite_Vtbl
};
/* ensure no global scope pollution */
#undef OBJECT_NAME
main.c:
#include <stdio.h>
#include "CCPolite.h"
// | A Greeter is capable of greeting; nothing else.
struct IGreeter
{
virtual void Greet() = 0;
};
// | A Thanker is capable of thanking; nothing else.
struct IThanker
{
virtual void Thank() = 0;
};
// | A Polite is something that implements both IGreeter and IThanker
// | Note that order of implementation DOES MATTER.
struct IPolite1 : public IGreeter, public IThanker{};
struct IPolite2 : public IThanker, public IGreeter{};
// | implementation if IPolite1; implements IGreeter BEFORE IThanker
struct CPolite1 : public IPolite1
{
void Greet()
{
puts("hello!");
}
void Thank()
{
puts("thank you!");
}
};
// | implementation if IPolite1; implements IThanker BEFORE IGreeter
struct CPolite2 : public IPolite2
{
void Greet()
{
puts("hi!");
}
void Thank()
{
puts("ty!");
}
};
// | imposter Polite's Greet implementation.
static void CCPolite_Greet(void *)
{
puts("HI I AM C!!!!");
}
// | imposter Polite's Thank implementation.
static void CCPolite_Thank(void *)
{
puts("THANK YOU, I AM C!!");
}
// | vtable of the imposter Polite.
ICCPolite CCPolite_Vtbl = {
CCPolite_Thank,
CCPolite_Greet
};
CPolite CCPoliteObj = {
&CCPolite_Vtbl
};
int main(int argc, char **argv)
{
puts("\npart 1");
CPolite1 o1;
o1.Greet();
o1.Thank();
puts("\npart 2");
CPolite2 o2;
o2.Greet();
o2.Thank();
puts("\npart 3");
CPolite1 *not1 = (CPolite1 *)&o2;
CPolite2 *not2 = (CPolite2 *)&o1;
not1->Greet();
not1->Thank();
not2->Greet();
not2->Thank();
puts("\npart 4");
CPolite1 *fake = (CPolite1 *)&CCPoliteObj;
fake->Thank();
fake->Greet();
puts("\npart 5");
CPolite2 *fake2 = (CPolite2 *)fake;
fake2->Thank();
fake2->Greet();
puts("\npart 6");
#define OBJECT_NAME fake3
#include "CCPolite_constructor.h"
fake = (CPolite1 *)&fake3;
fake->Thank();
fake->Greet();
puts("\npart 7");
#define OBJECT_NAME fake4
#include "CCPolite_constructor.h"
fake2 = (CPolite2 *)&fake4;
fake2->Thank();
fake2->Greet();
return 0;
}
output:
part 1
hello!
thank you!
part 2
hi!
ty!
part 3
ty!
hi!
thank you!
hello!
part 4
HI I AM C!!!!
THANK YOU, I AM C!!
part 5
THANK YOU, I AM C!!
HI I AM C!!!!
part 6
HI I AM C!!!!
THANK YOU, I AM C!!
part 7
THANK YOU, I AM C!!
HI I AM C!!!!
note since I am never allocating my fake object, there is no need to do any destruction; destructors are automatically put at the end of scope of dynamically allocated objects to reclaim the memory of the object literal itself and the vtable pointer.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/99297",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "134"
}
|
Q: Is there any downside to redundant qualifiers? Any benefit? For example, referencing something as System.Data.Datagrid as opposed to just Datagrid. Please provide examples and explanation. Thanks.
A: You're being very explicit about the type you're referencing, and that is a benefit. Although, in the very same process you're giving up code clarity, which clearly is a downside in my case, as I want code to be readable and understandable. I go for the short version unless I have a conflict in different namespaces which can only be solved with the explicit referencing to classes.. Unless I make an alias for it with the keyword using:
using Datagrid = System.Data.Datagrid;
A: Actually the full path is global::System.Data.DataGrid. The point of using a more qualified path is to avoid having to use additional using statements, especially if the introduction of another using will cause problems with type resolution. More fully qualified identifiers exist so that you can be explicit when you need to be explicit, but if the class's namespace is clear, then the DataGrid version is clearer to many.
A: The benefit is that you don't need to add an import for everything you use, especially if it's the only thing you use from a particular namespace, it also prevents collisions.
The downside, of course, is that the code balloons out in size and gets harder to read the more you use specific qualifiers.
Personally I tend to use imports for most things unless I know for sure I will only be using something from a particular namespace once or twice, so it won't impact the readability of my code.
A: I generally use the shortest form available in order to keep the code as clean and readable as possible. That's what using directives are for, after all, and tooltips in the VS editor give you instant detail on the provenance of a type.
I also tend to use a namespace tag for RCWs in a COM interop layer, to call out those variables explicitly in the code (they may need special attention on lifecycle and collection), eg
using _Interop = Some.Interop.Namespace;
A: In terms of performance there is no upside/downside. Everything is resolved at compile time and the generated MSIL is identical whether you use fully-qualified names or not.
The reason why its use is prevalent in the .NET world is because of auto-generated code, such as designer markup. In that case it would be better to fully-qualify names like class names because of possible conflicts with other classes you may have in your code.
If you have a tool like ReSharper, it will actually tell you what fully-qualified references you have are unnecessary (e.g. by graying them out) so you can lop them off. If you frequently cut-paste code across your various code bases, it would be a must to fully qualify them. (then again, why would you want to do cut-paste all the time; it's a bad form of code reuse!)
A: I don't think there is really a downside, just readability vs actual time spent coding. In general if you don't have namespaces with ambiguous object I don't think it's really needed. Another thing to consider is level of use. If you have one method that uses reflection and you are alright with typeing System.Reflection 10 times, then it's not a big deal but if you plan on using a namespace alot then I would recommend an include.
A: Depending on your situation, extra qualifiers will generate a warning (if this is what you mean by redundant). If you then treat warnings as errors, that's a pretty serious downside.
I've run into this with GCC for example.
struct A {
int A::b; // warning!
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/99299",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Would it be useful to include the class name and variable name in any NullPointerException message? Would it be useful to include the class name and variable name in any NullPointerException message? I know that it might not always be possible because of changes made by a JIT but is seems like the info should be available often (class members, etc).
From: http://jamesjava.blogspot.com/2005/04/what-was-null.html
A: That depends. If you get the stack trace, it is clear what class threw the exception. This usually leads to making sure your environment will give you stack traces when there are unhanded exceptions.
A: Providing as much information as possible during errors is a good thing... Right?
Helps out tracking the bugs.
Edit: (Yes)
A: Yes, that would be useful. Especially if you have a mechanism where the error message (exception.getMessage()) is displayed on-screen but the actual stacktrace gets hidden away in log files which you can't access immediately.
A: No, I don't think that this would at all be "useful".
Instead, you should watch out not to throw NPEs in the first place. Checking your values before you use them (null validation) and the likes. This should happen before you call a library method and after you get back a result (iff the API specifies that the method may return null. Of course, sometimes it will do so anyways, but then that's a bug).
If you think that NPEs should carry this information for debugging, think again. That's what debuggers are good for. An exception is simply there to inform you that something has gone wrong. Remember that unchecked exceptions occur at runtime - and have to be generated there. In order for the Exception to know which variable contained null, the byte code would have to know about variable names. You don't want to bloat your byte code with stuff like this. The class name is contained in every logging output I recieve from my programs. That's what logging is good for.
Java already eases the debugging process a lot by giving you the line number and full stack trace. C programs fail with Segmentation fault. You have to use strace or a debugger in order to even get so much information.
Note that javac does include a compile time option to include source file information at compile time, but this is intended to be used by a debugger, not the random Exceptions that get thrown. Quoting Sun's javac man page:
-g Generate all debugging information, including local variables.
By default, only line number and source file information is
generated.
-g:none
Do not generate any debugging information.
-g:{keyword list}
Generate only some kinds of debugging information, specified
by a comma separated list of keywords. Valid keywords are:
source
Source file debugging information
lines
Line number debugging information
vars
Local variable debugging information
Long story short: use a debugger.
A: Are you throwing NullPointerException? I think you should probably do null validation in the code.
I would also consider using open source logging tools like Log4J.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/99302",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Would it be useful to change java to support both static and dynamic types? What if a Java allow both static and dynamic types. That might allow the best of both worlds. i.e.:
String str = "Hello";
var temp = str;
temp = 10;
temp = temp * 5;
*
*Would that be possible?
*Would that be beneficial?
*Do any languages currently support both and how well does it work out?
Here is a better example (generics can't be used but the program does know the type):
var username = HttpServletRequest.getSession().getAttribute("username");//Returns a String
if(username.length() == 0) {
//Error
}
A: C# has a "var" keyword used in the manner you describe, but it ends up being a strongly typed variable based on the types of values that type checking suggests will go into it.
A: Can you explain the difference between your example and
String str = "Hello";
Object temp = str;
temp = 10;
A: Dynamic typed variables just have type Universal, such that every other type is a subtype of Universal. Any language where all types inherit from such a universal type (such as Java modulo unboxed values) already have this capability. As for usefulness - depends on what you're doing. I prefer a fully static type system where it's easy to create safe tagged unions so I can put whatever values I need into a variable, but in a more controlled way than Universal.
A: Yes, it would be beneficial, but not for the example you are showing. I think something like this would be better
public void f(var o)
{
o.method();
}
and I could call f with any object with a method called method() without needing to introduce an interface. It's nice for places where there is a convention, but not necessarily an interface. It would also be useful for interop with languages with a dynamic dispatch.
A: *
*Would that be possible?
Hardly. Java is a C-like language, which was initially designed to support only static typing. It will take a lot of time to introduce this feature to Java and I don't think developers will spend time on that.
*Would that be beneficial?
No. Java is a traditional language, and static typing is one of the base principles or it's architecture. In fact, static-typing is still more popular in programming (you can check the interesting statistics here).
*Do any languages currently support that and how well does it work out?
Well, there are a lot of languages which support dynamic typing, but I guess you know this. If the language supports dynamic typing, it doesn't make sense to introduce static typing to this language...
Also, feature which you show in your example can be implemented with static typing. jon gave you an example with "Object" class in Java. You can do similar with void* in C/C++. Still, this doesn't make language dynamic-typed.
A: @Lou: It would be just syntactic sugar for:
void doSth(Object foo) throws Exception{
Method m = foo.getClass().getMethod("foo", String.class);
m.invoke(foo, "baz");
}
I do use reflection, but I prefer it to be ugly so it's not abused.
A: Dynamic typing certainly has its uses.
However, I don't think it would make sense adding this to Java - Java is designed as a statically typed language and it would be too large a philosophical and architectural shift to try and graft on dynamic types at this point.
If you want proper dynamic typing but
still want to be part of the Java
ecosystem, take a look at one of the
other great JVM languages that
supports dynamic typing: e.g. Clojure
and Groovy.
A: Dynamically typed languages make coding somewhat simpler and faster, but they do so at the cost of pushing bugs from compile-time (very easy to find) to run-time (hard to find and unpredictable). If Java introduced it and it became prevalent, I would look for another language that cared more about code quality, and my time.
I'm doing a lot of Flex development at work as a front end to my Java work, and it frustrates me to no end that when I am working on a Flex method with parameters, most of the time the developer used Object for the parameter type, and I have absolutely no idea what properties/methods it will have without running the program with breakpoints and hoping I've tested all possible calls to the method. And even when they used a specific class for the parameter, there's no saying that properties/methods haven't been added or deleted from it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/99315",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
}
|
Q: Understanding [ClassOne, ClassTwo].each(&:my_method)
Possible Duplicate:
What does map(&:name) mean in Ruby?
I was watching a railscast and saw this code.
[Category, Product].(&:delete_all)
In regards to clearing a database.
I asked about the line in IRC and was told
(&:delete_all)
was a shortcut for
{|model| model.delete_all}
I tested this with the following
class ClassOne
def class_method
puts 1
end
end
class ClassTwo
def class_method
puts 2
end
end
[ClassOne, ClassTwo].each(&:class_method)
I received an error saying
Wrong Argument type Symbol (expected Proc)
I also tried
one = ClassOne.new
two = ClassTwo.new
[one, two].each(&:class_method)
But that still failed.
If I modified it to read
[one, two].each{|model| model.class_method}
Everything worked as expected.
So, what does &:delete_all actually do? The docs say delete_all is a method, so I am confused as to what is going on here.
A: It's some Rails specific patching of Ruby, symbol to proc.
A: This relies upon a Ruby 1.9 extension that can be done in 1.8 by including the following:
class Symbol
def to_proc
proc { |obj, *args| obj.send(self, *args) }
end
end
I believe Rails defines this in ActiveSupport.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/99318",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
}
|
Q: Grab a ProgressEvent from a POST upload in as3 Is there any way to track the status of a posted upload in AS3? There is a ProgressEvent, but it gives data back about the response, not the actual POST upload. I'm posting binary data for an image, so it's usually in the 50-100kb range.
The image data was generated inside Flash itself, so I can't use the upload method - at least as far as I know.
Thanks!
A: Perhaps you can use a function at the server side to send progress events to the flash object?
A: He's not asking about the filereference list..
He has the same problem that I have, there's not a method to have a post data transfer progress. I think that the only way is that one suggested above, sending from PHP to flash a progressEvent checking the size of the data received (If it is possible..);
Bye
A: Take a look at the FileReference class. The progress event in it will give you data about the upload:
Dispatched periodically during the file upload or download operation. The progress event is dispatched while Flash Player transmits bytes to a server, and it is periodically dispatched during the transmission, even if the transmission is ultimately not successful. To determine if and when the file transmission is actually successful and complete, listen for the complete event.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/99319",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: How do I change the colors displayed in cygwin rxvt? When I print "\[\e[34m\]sometext" I get some text in blue, but can I specify the shade of blue somewhere?
A: If your rxvt has 256 colors enabled, you can use extended color codes (e.g. "^[[38;5;36m"). Try this script to test if your terminal has 256 colors enabled. Probably you need to patch/recompile it or download another version. I recommend this tutorial.
A: You're using an ANSI escape sequence, which has very limited color options. I use an .Xdefaults file (explained in this tutorial). These options won't make your shell prompt all colorful, but is used by editors such as vim.
Be aware that .Xdefaults can be picky about UNIX (CR) vs Windows (CRLF) line endings. Use d2u or u2d to switch line endings as necessary.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/99348",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Passing PHP associative arrays to and from XML Is there an easy way to marshal a PHP associative array to and from XML? For example, I have the following array:
$items = array("1", "2",
array(
"item3.1" => "3.1",
"item3.2" => "3.2"
"isawesome" => true
)
);
How would I turn it into something similar to the following XML in as few lines as possible, then back again?
<items>
<item>1</item>
<item>2</item>
<item>
<item3_1>3.1</item3_1>
<item3_2>3.2</item3_2>
<isawesome>true</isawesome>
</item>
</items>
I don't really care if I have to change the array structure a bit or if the XML that comes out is different to the above example. I've been trying to work with PHP's XMLReader and XMLWriter, but the documentation is so poor and the code I've produced as a consequence looks nothing like what I feel it should look like:
$xml = SomeXMLWriter::writeArrayToXml($items);
$array = SomeXMLWriter::writeXmlToArray($xml);
Does it really have to be any harder than that to get a basic, raw XML dump of a PHP array without writing my own custom class?
I try to avoid PEAR. In addition to the configuration headaches I've had with it, I've never stuck with any of the packages I've ever used from it.
A: For those of you not using the PEAR packages, but you've got PHP5 installed. This worked for me:
/**
* Build A XML Data Set
*
* @param array $data Associative Array containing values to be parsed into an XML Data Set(s)
* @param string $startElement Root Opening Tag, default fx_request
* @param string $xml_version XML Version, default 1.0
* @param string $xml_encoding XML Encoding, default UTF-8
* @return string XML String containig values
* @return mixed Boolean false on failure, string XML result on success
*/
public function buildXMLData($data, $startElement = 'fx_request', $xml_version = '1.0', $xml_encoding = 'UTF-8') {
if(!is_array($data)) {
$err = 'Invalid variable type supplied, expected array not found on line '.__LINE__." in Class: ".__CLASS__." Method: ".__METHOD__;
trigger_error($err);
if($this->_debug) echo $err;
return false; //return false error occurred
}
$xml = new XmlWriter();
$xml->openMemory();
$xml->startDocument($xml_version, $xml_encoding);
$xml->startElement($startElement);
/**
* Write XML as per Associative Array
* @param object $xml XMLWriter Object
* @param array $data Associative Data Array
*/
function write(XMLWriter $xml, $data) {
foreach($data as $key => $value) {
if(is_array($value)) {
$xml->startElement($key);
write($xml, $value);
$xml->endElement();
continue;
}
$xml->writeElement($key, $value);
}
}
write($xml, $data);
$xml->endElement();//write end element
//Return the XML results
return $xml->outputMemory(true);
}
A: I've had some of these same issues, and so I created two classes:
bXml
A class that extends SimpleXml and corrects some of the problems it has. Like not being able to add CData nodes or Comment nodes. I also added some additional features, like using the php streams functionality to add child nodes $oXml->AddChild("file:///user/data.xml") or add XML string child nodes like $oXml->AddChild("<more><xml>yes</xml></more>"); but basically I just wanted to fix the simpleXML problems.
bArray
I extended the ArrayObject class so that all array functionality could be object oriented and consistent, so you don't need to remember that array_walk operates on the array by reference, while array_filter operates on the array by value. So you can do things like $oArray->flip()->Reverse()->Walk(/*callback*/); then still access the value the same way you normally would like $oArray[key].
Both of the methods output themselves as Arrays and Xml so you can jump seamlessly between them. So you can $oXml->AsArray(); or $oArray->AsXml(); I found that it was easier to do this than to constantly pass things back and forth between array2xml or xml2array methods.
http://code.google.com/p/blibrary/source
Both classes are can be overridden to make a custom class of your choosing and can be used independently of one another.
A: class Xml {
public static function from_array($arr, $xml = NULL)
{
$first = $xml;
if($xml === NULL) $xml = new SimpleXMLElement('<root/>');
foreach ($arr as $k => $v)
{
is_array($v)
? self::from_array($v, $xml->addChild($k))
: $xml->addChild($k, $v);
}
return ($first === NULL) ? $xml->asXML() : $xml;
}
public static function to_array($xml)
{
$xml = simplexml_load_string($xml);
$json = json_encode($xml);
return json_decode($json,TRUE);
}
}
$xml = xml::from_array($array);
$array = xml::to_array($xml);
A: Have you seen the PEAR package XML_Serializer?
pear_php_XML_Serializer
A: Try Zend_Config and Zend Framework in general.
I imagine it would be a 2 step process: array to Zend_Config, Zend_Config to XML.
A: Sounds like a job for SimpleXML.
I would suggest a slightly different XML structure..
And wonder why you need to convert from an array -> XML and back.. If you can modify the array structure as you said why not just generate XML instead? If some piece of code already exists that takes that array configuration, just modify it to accept the XML instead. Then you have 1 data format/ input type, and don't need to convert at all..
<items>
<item id="1"/>
<item id="2"/>
<item id="3">
<subitems>
<item id="3.1"/>
<item id="3.2" isawesome="true"/>
</subitems>
</item>
</items>
A: Here's a function that I wrote to take XML and converts it to a PHP Associative Array. One Caveat is that id does not currently handle attributes or c-data. Though it will handle repeated XML Tag at the same level by placing them into an array named after the tag.
<?php
$xml_req1 = <<<XML
<?xml version="1.0"?>
<Vastera:CustomerValidation_RequestInfo
xmlns:Vastera="http://ndc-ah-prd.am.mot.com:10653/MotVastera_CustomerValidation/MC000078/Docs/">
<PartnerID>5550000100-003</PartnerID>
<PartnerType>PTNR_INTER_CONSIGNEE</PartnerType>
<OperatingUnit>100</OperatingUnit>
<Status>ACTIVE</Status>
<CustomerSeqNumber>111</CustomerSeqNumber>
<CustomerName>Greg Co</CustomerName>
<Address1>123 Any Ln</Address1>
<Address2>?</Address2>
<Address3>?</Address3>
<Address4>?</Address4>
<Address5>?</Address5>
<City>Someplace</City>
<PostalCode>603021</PostalCode>
<State>CA</State>
<CountryCode>US</CountryCode>
<TaxReference>222</TaxReference>
<PartyRelated>Y</PartyRelated>
<BusinessUnit>GSBU</BusinessUnit>
<Region>GSRGN</Region>
<LocationName>DBA Mac Head Computing</LocationName>
<LoadOnly>N</LoadOnly>
<VSTM>333</VSTM>
<MilitaryCustomerFlag>Y</MilitaryCustomerFlag>
<USFederalGovernmentCustomer>Y</USFederalGovernmentCustomer>
<Non-USGovernmentCustomer>Y</Non-USGovernmentCustomer>
<Vastera:EPCIActivity>
<EPCIActivityNuclearCode>NUCLEAR</EPCIActivityNuclearCode>
<EPCIActivityNuclearValue>N</EPCIActivityNuclearValue>
<EPCIActivityNuclearApproveDate>2011-05-16:07:19:37</EPCIActivityNuclearApproveDate>
<EPCIActivityNuclearExpireDate>2056-12-31:12:00:00</EPCIActivityNuclearExpireDate>
<EPCIActivityNuclearCountry>US</EPCIActivityNuclearCountry>
<EPCIActivityChemBioCode>CHEM_BIO</EPCIActivityChemBioCode>
<EPCIActivityChemBioValue>N</EPCIActivityChemBioValue>
<EPCIActivityChemBioApproveDate>2011-05-16:07:19:37</EPCIActivityChemBioApproveDate>
<EPCIActivityChemBioExpireDate>2056-12-31:12:00:00</EPCIActivityChemBioExpireDate>
<EPCIActivityChemBioCountry>US</EPCIActivityChemBioCountry>
<EPCIActivityMissileCode>MISSILE</EPCIActivityMissileCode>
<EPCIActivityMissileValue>N</EPCIActivityMissileValue>
<EPCIActivityMissileApproveDate>2011-05-16:07:19:37</EPCIActivityMissileApproveDate>
<EPCIActivityMissileExpireDate>2056-12-31:12:00:00</EPCIActivityMissileExpireDate>
<EPCIActivityMissileCountry>US</EPCIActivityMissileCountry>
</Vastera:EPCIActivity>
<SourceSystem>GSB2BSS</SourceSystem>
<CreatedDate>2011-05-16:07:18:55</CreatedDate>
<CreatedBy>c18530</CreatedBy>
<LastModifiedDate>2011-05-16:07:18:55</LastModifiedDate>
<LastModifiedBy>c18530</LastModifiedBy>
<ContactName>Greg, "Da Man" Skluacek</ContactName>
<ContactTitle>Head Honcho</ContactTitle>
<ContactPhone>555-555-5555</ContactPhone>
<ContactFax>666-666-6666</ContactFax>
<ContactEmail>gskluzacek@gregco.com</ContactEmail>
<ContactWeb>www.gregco.com</ContactWeb>
</Vastera:CustomerValidation_RequestInfo>
XML;
$xml_req2 = <<<XML
<?xml version="1.0"?>
<order>
<orderNumber>123</orderNumber>
<customerAddress>
<type>Ship To</type>
<name>Bob McFly</name>
<addr1>123 Lincoln St</addr1>
<city>Chicago</city>
<state>IL</state>
<zip>60001</zip>
</customerAddress>
<customerAddress>
<type>Bill To</type>
<name>McFly Products Inc.</name>
<addr1>P.O. Box 6695</addr1>
<city>New York</city>
<state>NY</state>
<zip>99081-6695</zip>
</customerAddress>
<item>
<line>1</line>
<part>123001A</part>
<qty>5</qty>
<price>10.25</price>
</item>
<item>
<line>2</line>
<part>456002B</part>
<qty>3</qty>
<price>20.50</price>
</item>
<item>
<line>3</line>
<part>789003C</part>
<qty>1</qty>
<price>41.00</price>
</item>
<orderSubTotal>133.25</orderSubTotal>
<tax>6.66</tax>
<shipping>10.00</shipping>
<orderTotal>149.91</orderTotal>
</order>
XML;
$doc = new DOMDocument();
$doc->preserveWhiteSpace = false;
$doc->loadXML($xml_req1);
$arr = xml_to_arr($doc->documentElement);
print "\n\n----\n\n";
print_r($arr);
print "\n\n----\n\n";
$doc2 = new DOMDocument();
$doc2->preserveWhiteSpace = false;
$doc2->loadXML($xml_req2);
$arr2 = xml_to_arr($doc2->documentElement);
print "\n\n----\n\n";
print_r($arr2);
print "\n\n----\n\n";
exit;
function xml_to_arr($curr_node) {
$val_array = array();
$typ_array = array();
foreach($curr_node->childNodes as $node) {
if ($node->nodeType == XML_ELEMENT_NODE) {
$val = xml_to_arr($node);
if (array_key_exists($node->tagName, $val_array)) {
if (!is_array($val_array[$node->tagName]) || $type_array[$node->tagName] == 'hash') {
$existing_val = $val_array[$node->tagName];
unset($val_array[$node->tagName]);
$val_array[$node->tagName][0] = $existing_val;
$type_array[$node->tagName] = 'array';
}
$val_array[$node->tagName][] = $val;
} else {
$val_array[$node->tagName] = $val;
if (is_array($val)) {
$type_array[$node->tagName] = 'hash';
}
} // end if array key exists
} // end if elment node
}// end for each
if (count($val_array) == 0) {
return $curr_node->nodeValue;
} else {
return $val_array;
}
} // end function xml to arr
?>
example output
----
Array
(
[PartnerID] => 5550000100-003
[PartnerType] => PTNR_INTER_CONSIGNEE
[OperatingUnit] => 100
[Status] => ACTIVE
[CustomerSeqNumber] => 111
[CustomerName] => Greg Co
[Address1] => 123 Any Ln
[Address2] => ?
[Address3] => ?
[Address4] => ?
[Address5] => ?
[City] => Somplace
[PostalCode] => 60123
[State] => CA
[CountryCode] => US
[TaxReference] => 222
[PartyRelated] => Y
[BusinessUnit] => GSBU
[Region] => GSRGN
[LocationName] => DBA Mac Head Computing
[LoadOnly] => N
[VSTM] => 333
[MilitaryCustomerFlag] => Y
[USFederalGovernmentCustomer] => Y
[Non-USGovernmentCustomer] => Y
[Vastera:EPCIActivity] => Array
(
[EPCIActivityNuclearCode] => NUCLEAR
[EPCIActivityNuclearValue] => N
[EPCIActivityNuclearApproveDate] => 2011-05-16:07:19:37
[EPCIActivityNuclearExpireDate] => 2056-12-31:12:00:00
[EPCIActivityNuclearCountry] => US
[EPCIActivityChemBioCode] => CHEM_BIO
[EPCIActivityChemBioValue] => N
[EPCIActivityChemBioApproveDate] => 2011-05-16:07:19:37
[EPCIActivityChemBioExpireDate] => 2056-12-31:12:00:00
[EPCIActivityChemBioCountry] => US
[EPCIActivityMissileCode] => MISSILE
[EPCIActivityMissileValue] => N
[EPCIActivityMissileApproveDate] => 2011-05-16:07:19:37
[EPCIActivityMissileExpireDate] => 2056-12-31:12:00:00
[EPCIActivityMissileCountry] => US
)
[SourceSystem] => GSB2BSS
[CreatedDate] => 2011-05-16:07:18:55
[CreatedBy] => c18530
[LastModifiedDate] => 2011-05-16:07:18:55
[LastModifiedBy] => c18530
[ContactName] => Greg, "Da Man" Skluacek
[ContactTitle] => Head Honcho
[ContactPhone] => 555-555-5555
[ContactFax] => 666-666-6666
[ContactEmail] => gskluzacek@gregco.com
[ContactWeb] => www.gregco.com
)
----
Array
(
[orderNumber] => 123
[customerAddress] => Array
(
[0] => Array
(
[type] => Ship To
[name] => Bob McFly
[addr1] => 123 Lincoln St
[city] => Chicago
[state] => IL
[zip] => 60001
)
[1] => Array
(
[type] => Bill To
[name] => McFly Products Inc.
[addr1] => P.O. Box 6695
[city] => New York
[state] => NY
[zip] => 99081-6695
)
)
[item] => Array
(
[0] => Array
(
[line] => 1
[part] => 123001A
[qty] => 5
[price] => 10.25
)
[1] => Array
(
[line] => 2
[part] => 456002B
[qty] => 3
[price] => 20.50
)
[2] => Array
(
[line] => 3
[part] => 789003C
[qty] => 1
[price] => 41.00
)
)
[orderSubTotal] => 133.25
[tax] => 6.66
[shipping] => 10.00
[orderTotal] => 149.91
)
--------
A: Hey @Conrad I just modify your code to work well with numeric arrays:
/**
* Build A XML Data Set
*
* @param array $data Associative Array containing values to be parsed into an XML Data Set(s)
* @param string $startElement Root Opening Tag, default fx_request
* @param string $xml_version XML Version, default 1.0
* @param string $xml_encoding XML Encoding, default UTF-8
* @return string XML String containig values
* @return mixed Boolean false on failure, string XML result on success
*/
public static function arrayToXML($data, $startElement = 'fx_request', $xml_version = '1.0', $xml_encoding = 'UTF-8'){
if(!is_array($data)){
$err = 'Invalid variable type supplied, expected array not found on line '.__LINE__." in Class: ".__CLASS__." Method: ".__METHOD__;
trigger_error($err);
if($this->_debug) echo $err;
return false; //return false error occurred
}
$xml = new XmlWriter();
$xml->openMemory();
$xml->startDocument($xml_version, $xml_encoding);
$xml->startElement($startElement);
/**
* Write XML as per Associative Array
* @param object $xml XMLWriter Object
* @param array $data Associative Data Array
*/
function write(XMLWriter $xml, $data){
foreach($data as $key => $value){
if (is_array($value) && isset($value[0])){
foreach($value as $itemValue){
//$xml->writeElement($key, $itemValue);
if(is_array($itemValue)){
$xml->startElement($key);
write($xml, $itemValue);
$xml->endElement();
continue;
}
if (!is_array($itemValue)){
$xml->writeElement($key, $itemValue."");
}
}
}else if(is_array($value)){
$xml->startElement($key);
write($xml, $value);
$xml->endElement();
continue;
}
if (!is_array($value)){
$xml->writeElement($key, $value."");
}
}
}
write($xml, $data);
$xml->endElement();//write end element
//returns the XML results
return $xml->outputMemory(true);
}
so yo can convert this:
$mArray["invitations"]["user"][0]["name"] = "paco";
$mArray["invitations"]["user"][0]["amigos"][0] = 82;
$mArray["invitations"]["user"][0]["amigos"][1] = 29;
$mArray["invitations"]["user"][0]["amigos"][2] = 6;
$mArray["invitations"]["user"][1]["name"] = "jose";
$mArray["invitations"]["user"][1]["amigos"][0] = 43;
$mArray["invitations"]["user"][1]["amigos"][1]["tuyos"] = 32;
$mArray["invitations"]["user"][1]["amigos"][1]["mios"] = 79;
$mArray["invitations"]["user"][1]["amigos"][2] = 11;
$mArray["invitations"]["user"][2]["name"] = "luis";
$mArray["invitations"]["user"][2]["amigos"][0] = 65;
into this xml:
<invitations>
<user>
<name>paco</name>
<amigos>82</amigos>
<amigos>29</amigos>
<amigos>6</amigos>
</user>
<user>
<name>jose</name>
<amigos>43</amigos>
<amigos>
<tuyos>32</tuyos>
<mios>79</mios>
</amigos>
<amigos>11</amigos>
</user>
<user>
<name>luis</name>
<amigos>65</amigos>
</user>
I hope I can help someone with this
A: SimpleXML works great for your use.
A: I agree this is one area that PHP's documentation has dropped the ball, but for me I've always used the SimpleXML mixed with something like the xml2Array functions. The Xml you get from simpleXML isn't that hard to navigate with the help of a dumping function like print_r.
A: This builds on Ángel López's answer. Added support for attributes. If an element has attributes, prefix them with @, and refer to the actual element content with an empty string as the key.
/**
* Build an XML Data Set
*
* @param array $data Associative Array containing values to be parsed into an XML Data Set(s)
* @param string $startElement Root Opening Tag, default fx_request
* @param string $xml_version XML Version, default 1.0
* @param string $xml_encoding XML Encoding, default UTF-8
* @return string XML String containig values
* @return mixed Boolean false on failure, string XML result on success
*/
function arrayToXML($data, $startElement = 'fx_request', $xml_version = '1.0', $xml_encoding = 'UTF-8'){
if(!is_array($data)){
$err = 'Invalid variable type supplied, expected array not found on line '.__LINE__." in Class: ".__CLASS__." Method: ".__METHOD__;
trigger_error($err);
//if($this->_debug) echo $err;
return false; //return false error occurred
}
$xml = new XmlWriter();
$xml->openMemory();
$xml->startDocument($xml_version, $xml_encoding);
$xml->startElement($startElement);
/**
* Write keys in $data prefixed with @ as XML attributes, if $data is an array. When an @ prefixed key is found, a '' key is expected to indicate the element itself.
* @param object $xml XMLWriter Object
* @param array $data with attributes filtered out
*/
function writeAttr(XMLWriter $xml, $data) {
if(is_array($data)) {
$nonAttributes = array();
foreach($data as $key => $val) {
//handle an attribute with elements
if($key[0] == '@') {
$xml->writeAttribute(substr($key, 1), $val);
} else if($key == '') {
if(is_array($val)) $nonAttributes = $val;
else $xml->text("$val");
}
//ignore normal elements
else $nonAttributes[$key] = $val;
}
return $nonAttributes;
}
else return $data;
}
/**
* Write XML as per Associative Array
* @param object $xml XMLWriter Object
* @param array $data Associative Data Array
*/
function writeEl(XMLWriter $xml, $data) {
foreach($data as $key => $value) {
if(is_array($value) && isset($value[0])) { //numeric array
foreach($value as $itemValue){
if(is_array($itemValue)) {
$xml->startElement($key);
$itemValue = writeAttr($xml, $itemValue);
writeEl($xml, $itemValue);
$xml->endElement();
} else {
$itemValue = writeAttr($xml, $itemValue);
$xml->writeElement($key, "$itemValue");
}
}
} else if(is_array($value)) { //associative array
$xml->startElement($key);
$value = writeAttr($xml, $value);
writeEl($xml, $value);
$xml->endElement();
} else { //scalar
$value = writeAttr($xml, $value);
$xml->writeElement($key, "$value");
}
}
}
writeEl($xml, $data);
$xml->endElement();//write end element
//returns the XML results
return $xml->outputMemory(true);
}
so yo can convert this:
$mArray["invitations"]["user"][0]["@name"] = "paco";
$mArray["invitations"]["user"][0][""]["amigos"][0] = 82;
$mArray["invitations"]["user"][0][""]["amigos"][1] = 29;
$mArray["invitations"]["user"][0][""]["amigos"][2] = 6;
$mArray["invitations"]["user"][1]["@name"] = "jose";
$mArray["invitations"]["user"][1][""]["amigos"][0] = 43;
$mArray["invitations"]["user"][1][""]["amigos"][1]["tuyos"] = 32;
$mArray["invitations"]["user"][1][""]["amigos"][1]["mios"] = 79;
$mArray["invitations"]["user"][1][""]["amigos"][2] = 11;
$mArray["invitations"]["user"][2]["@name"] = "luis";
$mArray["invitations"]["user"][2][""]["amigos"][0] = 65;
into this xml:
<invitations>
<user name="paco">
<amigos>82</amigos>
<amigos>29</amigos>
<amigos>6</amigos>
</user>
<user name="jose">
<amigos>43</amigos>
<amigos>
<tuyos>32</tuyos>
<mios>79</mios>
</amigos>
<amigos>11</amigos>
</user>
<user name="luis">
<amigos>65</amigos>
</user>
</invitations>
Thanks Ángel.
A: Based on answers here I made github repo https://github.com/jmarceli/array2xml
Maybe not the prettiest repo on the internet but the code seems to be working fine.
Here is the code which may be used:
// Based on: http://stackoverflow.com/questions/99350/passing-php-associative-arrays-to-and-from-xml
class ArrayToXML {
private $version;
private $encoding;
/*
* Construct ArrayToXML object with selected version and encoding
*
* for available values check XmlWriter docs http://www.php.net/manual/en/function.xmlwriter-start-document.php
* @param string $xml_version XML Version, default 1.0
* @param string $xml_encoding XML Encoding, default UTF-8
*/
public function __construct($xmlVersion = '1.0', $xmlEncoding = 'UTF-8') {
$this->version = $xmlVersion;
$this->encoding = $xmlEncoding;
}
/**
* Build an XML Data Set
*
* @param array $data Associative Array containing values to be parsed into an XML Data Set(s)
* @param string $startElement Root Opening Tag, default data
* @return string XML String containig values
* @return mixed Boolean false on failure, string XML result on success
*/
public function buildXML($data, $startElement = 'data'){
if(!is_array($data)){
$err = 'Invalid variable type supplied, expected array not found on line '.__LINE__." in Class: ".__CLASS__." Method: ".__METHOD__;
trigger_error($err);
//if($this->_debug) echo $err;
return false; //return false error occurred
}
$xml = new XmlWriter();
$xml->openMemory();
$xml->startDocument($this->version, $this->encoding);
$xml->startElement($startElement);
$this->writeEl($xml, $data);
$xml->endElement();//write end element
//returns the XML results
return $xml->outputMemory(true);
}
/**
* Write keys in $data prefixed with @ as XML attributes, if $data is an array.
* When an @ prefixed key is found, a '%' key is expected to indicate the element itself,
* and '#' prefixed key indicates CDATA content
*
* @param object $xml XMLWriter Object
* @param array $data with attributes filtered out
*/
protected function writeAttr(XMLWriter $xml, $data) {
if(is_array($data)) {
$nonAttributes = array();
foreach($data as $key => $val) {
//handle an attribute with elements
if($key[0] == '@') {
$xml->writeAttribute(substr($key, 1), $val);
} else if($key[0] == '%') {
if(is_array($val)) $nonAttributes = $val;
else $xml->text($val);
} elseif($key[0] == '#') {
if(is_array($val)) $nonAttributes = $val;
else {
$xml->startElement(substr($key, 1));
$xml->writeCData($val);
$xml->endElement();
}
}
//ignore normal elements
else $nonAttributes[$key] = $val;
}
return $nonAttributes;
}
else return $data;
}
/**
* Write XML as per Associative Array
*
* @param object $xml XMLWriter Object
* @param array $data Associative Data Array
*/
protected function writeEl(XMLWriter $xml, $data) {
foreach($data as $key => $value) {
if(is_array($value) && !$this->isAssoc($value)) { //numeric array
foreach($value as $itemValue){
if(is_array($itemValue)) {
$xml->startElement($key);
$itemValue = $this->writeAttr($xml, $itemValue);
$this->writeEl($xml, $itemValue);
$xml->endElement();
} else {
$itemValue = $this->writeAttr($xml, $itemValue);
$xml->writeElement($key, "$itemValue");
}
}
} else if(is_array($value)) { //associative array
$xml->startElement($key);
$value = $this->writeAttr($xml, $value);
$this->writeEl($xml, $value);
$xml->endElement();
} else { //scalar
$value = $this->writeAttr($xml, $value);
$xml->writeElement($key, "$value");
}
}
}
/*
* Check if array is associative with string based keys
* FROM: http://stackoverflow.com/questions/173400/php-arrays-a-good-way-to-check-if-an-array-is-associative-or-sequential/4254008#4254008
*
* @param array $array Array to check
*/
protected function isAssoc($array) {
return (bool)count(array_filter(array_keys($array), 'is_string'));
}
}
After that just use the ArrayToXML class. Example:
$xml = new ArrayToXML();
print $xml->buildXML($input);
A: Following class uses simplexml to achieve the same, you just need to loop through the array and call addchild of ximplexml.
http://snipplr.com/view.php?codeview&id=3491
A: The most simple way to get assoc array from xml string:
<?
$data_array = (array) simplexml_load_string($xml_string);
?>
A: /**
* Write XML as per Associative Array
* @param object $xml XMLWriter Object
* @param array $data Associative Data Array
*/
function writeXmlRecursive(XMLWriter $xml, $data){
foreach($data as $key => $value){
if (is_array($value) && isset($value[0])){
$xml->startElement($key);
foreach($value as $itemValue){
if(is_array($itemValue)){
writeXmlRecursive($xml, $itemValue);
}
else
{
$xml->writeElement($key, $itemValue."");
}
}
$xml->endElement();
}else if(is_array($value)){
$xml->startElement($key);
writeXmlRecursive($xml, $value);
$xml->endElement();
continue;
}
if (!is_array($value)){
$xml->writeElement($key, $value."");
}
}
}
This is final version, that give ahat i want from array with 4 nested level
<items>
<item>
<id_site>59332</id_site>
<id>33</id>
<code>196429985</code>
<tombid>23</tombid>
<tombcode>196429985</tombcode>
<religion></religion>
<lastname>lastname</lastname>
<firstname>name</firstname>
<patronymicname>patronymicname</patronymicname>
<sex>1</sex>
<birthday>2</birthday>
<birthmonth>4</birthmonth>
<birthyear>1946</birthyear>
<deathday>13</deathday>
<deathmonth>5</deathmonth>
<deathyear>2006</deathyear>
<s_comments></s_comments>
<graveyard>17446</graveyard>
<latitude></latitude>
<longitude></longitude>
<images>
<image>
<siteId>52225</siteId>
<fileId>62</fileId>
<prefix>0</prefix>
<path>path</path>
</image>
<image>
<siteId>52226</siteId>
<fileId>63</fileId>
<prefix>0</prefix>
<path>path</path>
</image>
</images>
</item>
<items>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/99350",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "18"
}
|
Q: How to test if a line segment intersects an axis-aligned rectange in 2D? How to test if a line segment intersects an axis-aligned rectange in 2D? The segment is defined with its two ends: p1, p2. The rectangle is defined with top-left and bottom-right points.
A: Since your rectangle is aligned, Liang-Barsky might be a good solution. It is faster than Cohen-Sutherland, if speed is significant here.
Siggraph explanation
Another good description
And of course, Wikipedia
A: You could also create a rectangle out of the segment and test if the other rectangle collides with it, since it is just a series of comparisons. From pygame source:
def _rect_collide(a, b):
return a.x + a.w > b.x and b.x + b.w > a.x and \
a.y + a.h > b.y and b.y + b.h > a.y
A: The original poster wanted to DETECT an intersection between a line segment and a polygon. There was no need to LOCATE the intersection, if there is one. If that's how you meant it, you can do less work than Liang-Barsky or Cohen-Sutherland:
Let the segment endpoints be p1=(x1 y1) and p2=(x2 y2).
Let the rectangle's corners be (xBL yBL) and (xTR yTR).
Then all you have to do is
A. Check if all four corners of the rectangle are on the same side of the line.
The implicit equation for a line through p1 and p2 is:
F(x y) = (y2-y1)*x + (x1-x2)*y + (x2*y1-x1*y2)
If F(x y) = 0, (x y) is ON the line.
If F(x y) > 0, (x y) is "above" the line.
If F(x y) < 0, (x y) is "below" the line.
Substitute all four corners into F(x y). If they're all negative or all positive, there is no intersection. If some are positive and some negative, go to step B.
B. Project the endpoint onto the x axis, and check if the segment's shadow intersects the polygon's shadow. Repeat on the y axis:
If (x1 > xTR and x2 > xTR), no intersection (line is to right of rectangle).
If (x1 < xBL and x2 < xBL), no intersection (line is to left of rectangle).
If (y1 > yTR and y2 > yTR), no intersection (line is above rectangle).
If (y1 < yBL and y2 < yBL), no intersection (line is below rectangle).
else, there is an intersection. Do Cohen-Sutherland or whatever code was mentioned in the other answers to your question.
You can, of course, do B first, then A.
Alejo
A: Use the Cohen-Sutherland algorithm.
It's used for clipping but can be slightly tweaked for this task. It divides 2D space up into a tic-tac-toe board with your rectangle as the "center square".
then it checks to see which of the nine regions each of your line's two points are in.
*
*If both points are left, right, top, or bottom, you trivially reject.
*If either point is inside, you trivially accept.
*In the rare remaining cases you can do the math to intersect with whichever sides of the rectangle are possible to intersect with, based on which regions they're in.
A: Or just use/copy the code already in the Java method
java.awt.geom.Rectangle2D.intersectsLine(double x1, double y1, double x2, double y2)
Here is the method after being converted to static for convenience:
/**
* Code copied from {@link java.awt.geom.Rectangle2D#intersectsLine(double, double, double, double)}
*/
public class RectangleLineIntersectTest {
private static final int OUT_LEFT = 1;
private static final int OUT_TOP = 2;
private static final int OUT_RIGHT = 4;
private static final int OUT_BOTTOM = 8;
private static int outcode(double pX, double pY, double rectX, double rectY, double rectWidth, double rectHeight) {
int out = 0;
if (rectWidth <= 0) {
out |= OUT_LEFT | OUT_RIGHT;
} else if (pX < rectX) {
out |= OUT_LEFT;
} else if (pX > rectX + rectWidth) {
out |= OUT_RIGHT;
}
if (rectHeight <= 0) {
out |= OUT_TOP | OUT_BOTTOM;
} else if (pY < rectY) {
out |= OUT_TOP;
} else if (pY > rectY + rectHeight) {
out |= OUT_BOTTOM;
}
return out;
}
public static boolean intersectsLine(double lineX1, double lineY1, double lineX2, double lineY2, double rectX, double rectY, double rectWidth, double rectHeight) {
int out1, out2;
if ((out2 = outcode(lineX2, lineY2, rectX, rectY, rectWidth, rectHeight)) == 0) {
return true;
}
while ((out1 = outcode(lineX1, lineY1, rectX, rectY, rectWidth, rectHeight)) != 0) {
if ((out1 & out2) != 0) {
return false;
}
if ((out1 & (OUT_LEFT | OUT_RIGHT)) != 0) {
double x = rectX;
if ((out1 & OUT_RIGHT) != 0) {
x += rectWidth;
}
lineY1 = lineY1 + (x - lineX1) * (lineY2 - lineY1) / (lineX2 - lineX1);
lineX1 = x;
} else {
double y = rectY;
if ((out1 & OUT_BOTTOM) != 0) {
y += rectHeight;
}
lineX1 = lineX1 + (y - lineY1) * (lineX2 - lineX1) / (lineY2 - lineY1);
lineY1 = y;
}
}
return true;
}
}
A: Wrote quite simple and working solution:
bool SegmentIntersectRectangle(double a_rectangleMinX,
double a_rectangleMinY,
double a_rectangleMaxX,
double a_rectangleMaxY,
double a_p1x,
double a_p1y,
double a_p2x,
double a_p2y)
{
// Find min and max X for the segment
double minX = a_p1x;
double maxX = a_p2x;
if(a_p1x > a_p2x)
{
minX = a_p2x;
maxX = a_p1x;
}
// Find the intersection of the segment's and rectangle's x-projections
if(maxX > a_rectangleMaxX)
{
maxX = a_rectangleMaxX;
}
if(minX < a_rectangleMinX)
{
minX = a_rectangleMinX;
}
if(minX > maxX) // If their projections do not intersect return false
{
return false;
}
// Find corresponding min and max Y for min and max X we found before
double minY = a_p1y;
double maxY = a_p2y;
double dx = a_p2x - a_p1x;
if(Math::Abs(dx) > 0.0000001)
{
double a = (a_p2y - a_p1y) / dx;
double b = a_p1y - a * a_p1x;
minY = a * minX + b;
maxY = a * maxX + b;
}
if(minY > maxY)
{
double tmp = maxY;
maxY = minY;
minY = tmp;
}
// Find the intersection of the segment's and rectangle's y-projections
if(maxY > a_rectangleMaxY)
{
maxY = a_rectangleMaxY;
}
if(minY < a_rectangleMinY)
{
minY = a_rectangleMinY;
}
if(minY > maxY) // If Y-projections do not intersect return false
{
return false;
}
return true;
}
A: A quick Google search popped up a page with C++ code for testing the intersection.
Basically it tests the intersection between the line, and every border or the rectangle.
Rectangle and line intersection code
A: Here's a javascript version of @metamal's answer
var isRectangleIntersectedByLine = function (
a_rectangleMinX,
a_rectangleMinY,
a_rectangleMaxX,
a_rectangleMaxY,
a_p1x,
a_p1y,
a_p2x,
a_p2y) {
// Find min and max X for the segment
var minX = a_p1x
var maxX = a_p2x
if (a_p1x > a_p2x) {
minX = a_p2x
maxX = a_p1x
}
// Find the intersection of the segment's and rectangle's x-projections
if (maxX > a_rectangleMaxX)
maxX = a_rectangleMaxX
if (minX < a_rectangleMinX)
minX = a_rectangleMinX
// If their projections do not intersect return false
if (minX > maxX)
return false
// Find corresponding min and max Y for min and max X we found before
var minY = a_p1y
var maxY = a_p2y
var dx = a_p2x - a_p1x
if (Math.abs(dx) > 0.0000001) {
var a = (a_p2y - a_p1y) / dx
var b = a_p1y - a * a_p1x
minY = a * minX + b
maxY = a * maxX + b
}
if (minY > maxY) {
var tmp = maxY
maxY = minY
minY = tmp
}
// Find the intersection of the segment's and rectangle's y-projections
if(maxY > a_rectangleMaxY)
maxY = a_rectangleMaxY
if (minY < a_rectangleMinY)
minY = a_rectangleMinY
// If Y-projections do not intersect return false
if(minY > maxY)
return false
return true
}
A: I did a little napkin solution..
Next find m and c and hence the equation y = mx + c
y = (Point2.Y - Point1.Y) / (Point2.X - Point1.X)
Substitute P1 co-ordinates to now find c
Now for a rectangle vertex, put the X value in the line equation, get the Y value and see if the Y value lies in the rectangle bounds shown below
(you can find the constant values X1, X2, Y1, Y2 for the rectangle such that)
X1 <= x <= X2 &
Y1 <= y <= Y2
If the Y value satisfies the above condition and lies between (Point1.Y, Point2.Y) - we have an intersection.
Try every vertex if this one fails to make the cut.
A: I was looking at a similar problem and here's what I came up with. I was first comparing the edges and realized something. If the midpoint of an edge that fell within the opposite axis of the first box is within half the length of that edge of the outer points on the first in the same axis, then there is an intersection of that side somewhere.
But that was thinking 1 dimensionally and required looking at each side of the second box to figure out.
It suddenly occurred to me that if you find the 'midpoint' of the second box and compare the coordinates of the midpoint to see if they fall within 1/2 length of a side (of the second box) of the outer dimensions of the first, then there is an intersection somewhere.
i.e. box 1 is bounded by x1,y1 to x2,y2
box 2 is bounded by a1,b1 to a2,b2
the width and height of box 2 is:
w2 = a2 - a1 (half of that is w2/2)
h2 = b2 - b1 (half of that is h2/2)
the midpoints of box 2 are:
am = a1 + w2/2
bm = b1 + h2/2
So now you just check if
(x1 - w2/2) < am < (x2 + w2/2) and (y1 - h2/2) < bm < (y2 + h2/2)
then the two overlap somewhere.
If you want to check also for edges intersecting to count as 'overlap' then
change the < to <=
Of course you could just as easily compare the other way around (checking midpoints of box1 to be within 1/2 length of the outer dimenions of box 2)
And even more simplification - shift the midpoint by your half lengths and it's identical to the origin point of that box. Which means you can now check just that point for falling within your bounding range and by shifting the plain up and to the left, the lower corner is now the lower corner of the first box. Much less math:
(x1 - w2) < a1 < x2
&&
(y1 - h2) < b1 < y2
[overlap exists]
or non-substituted:
( (x1-(a2-a1)) < a1 < x2 ) && ( (y1-(b2-b1)) < b1 < y2 ) [overlap exists]
( (x1-(a2-a1)) <= a1 <= x2 ) && ( (y1-(b2-b1)) <= b1 <= y2 ) [overlap or intersect exists]
A: coding example in PHP (I'm using an object model that has methods for things like getLeft(), getRight(), getTop(), getBottom() to get the outer coordinates of a polygon and also has a getWidth() and getHeight() - depending on what parameters were fed it, it will calculate and cache the unknowns - i.e. I can create a polygon with x1,y1 and ... w,h or x2,y2 and it can calculate the others)
I use 'n' to designate the 'new' item being checked for overlap ($nItem is an instance of my polygon object) - the items to be tested again [this is a bin/sort knapsack program] are in an array consisting of more instances of the (same) polygon object.
public function checkForOverlaps(BinPack_Polygon $nItem) {
// grab some local variables for the stuff re-used over and over in loop
$nX = $nItem->getLeft();
$nY = $nItem->getTop();
$nW = $nItem->getWidth();
$nH = $nItem->getHeight();
// loop through the stored polygons checking for overlaps
foreach($this->packed as $_i => $pI) {
if(((($pI->getLeft() - $nW) < $nX) && ($nX < $pI->getRight())) &&
((($pI->getTop() - $nH) < $nY) && ($nY < $pI->getBottom()))) {
return false;
}
}
return true;
}
A: Some sample code for my solution (in php):
// returns 'true' on overlap checking against an array of similar objects in $this->packed
public function checkForOverlaps(BinPack_Polygon $nItem) {
$nX = $nItem->getLeft();
$nY = $nItem->getTop();
$nW = $nItem->getWidth();
$nH = $nItem->getHeight();
// loop through the stored polygons checking for overlaps
foreach($this->packed as $_i => $pI) {
if(((($pI->getLeft() - $nW) < $nX) && ($nX < $pI->getRight())) && ((($pI->getTop() - $nH) < $nY) && ($nY < $pI->getBottom()))) {
return true;
}
}
return false;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/99353",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "40"
}
|
Q: Is there a good reference on how java executes bytecode? I'm interested in how java organizes memory and executes code (like what gets put in the stack or the heap), from the start of main, to assigning variables, calling functions, passing parameters, returning values, instantiating objects, etc. Has anyone found a good, beginner-friendly article/reference on it?
A: The canonical reference is the JVM spec. However, different JVMs can implement the spec in different ways. You can also check out the open source Java platform implementation, OpenJDK.
A: I don't know exactly how they execute their bytecode, but I found this link describing java's bytecode. I am not sure if it helps, but at least it's something to start on.
Quote:
This article gives you an understanding of Java bytecode that will enable you to be a better programmer. Like a C or C++ compiler translates source code into assembler code, Java compilers translate Java source code into bytecode. Java programmers should take the time to understand what the bytecode is, how it works, and most importantly, what bytecode is being generated by the Java compiler. In some cases, the bytecode generated is not what you expect.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/99389",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do I fix this Subversion MKCOL error? When I commit I get this error from Subversion:
bash-2.05b$ svn commit -m "testing subversion, still"
Adding baz
svn: Commit failed (details follow):
svn: MKCOL of '/viper/!svn/wrk/6b9bcd38-b2fe-0310-95ff-9d1a44098866/sandboxes/ohammersmith/trunk/baz': 405 Method Not Allowed (http://svn.example.com)
A: This happens when you have added a directory that someone else has also added and already committed.
This is something to indicate conflict but at Directories level (just to understand).
To resolve this, just do svn update before committing your changes
A: This happens when you have added a directory that someone else has also added and already committed. The error message on a commit is really confusing, but if you do an svn up instead you'll see this message:
bash-2.05b$ svn up
svn: Failed to add directory 'baz': object of the same name already exists
To resolve the issue, remove your directory (or move it aside) and do an svn update to get the version on the server and re-do your changes.
As a general rule, be sure to do svn update since the error messages tend to be more helpful.
A: Sometimes this happens.
Solution:
When you create any new repository must add read.me file to create a default branch(trunk) so that it will find a proper path to push your stuff.
If you create a repository and do not add read. me and if it is blank then upload a file like test.txt and take that uploaded file as latest update in your local folder and then try to push your code from that updated folder. This works for me.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/99391",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "76"
}
|
Q: How to check if a folder exists in Cocoa & Objective-C? How to check if a folder (directory) exists in Cocoa using Objective-C?
A: NSFileManager is the best place to look for file related APIs. The specific API you require is
- fileExistsAtPath:isDirectory:.
Example:
NSString *pathToFile = @"...";
BOOL isDir = NO;
BOOL isFile = [[NSFileManager defaultManager] fileExistsAtPath:pathToFile isDirectory:&isDir];
if(isFile)
{
//it is a file, process it here how ever you like, check isDir to see if its a directory
}
else
{
//not a file, this is an error, handle it!
}
A: Use NSFileManager's fileExistsAtPath:isDirectory: method. See Apple's docs here.
A: If your have a NSURL object as path, it's better to use path to convert it into NSString.
NSFileManager*fm = [NSFileManager defaultManager];
NSURL* path = [[[fm URLsForDirectory:NSDocumentDirectory
inDomains:NSUserDomainMask] objectAtIndex:0]
URLByAppendingPathComponent:@"photos"];
NSError *theError = nil;
if(![fm fileExistsAtPath:[path path]]){
NSLog(@"dir doesn't exists");
}else
NSLog(@"dir exists");
A: Some good advice from Apple in the NSFileManager.h regarding checking the file system:
"It's far better to attempt an operation (like loading a file or creating a directory) and handle the error gracefully than it is to try to figure out ahead of time whether the operation will succeed. Attempting to predicate behavior based on the current state of the filesystem or a particular file on the filesystem is encouraging odd behavior in the face of filesystem race conditions."
A: [NSFileManager fileExistsAtPath:isDirectory:]
Returns a Boolean value that indicates whether a specified file exists.
- (BOOL)fileExistsAtPath:(NSString *)path isDirectory:(BOOL *)isDirectory
Parameters
path
The path of a file or directory. If path begins with a tilde (~), it must first be expanded with stringByExpandingTildeInPath, or this method will return NO.
isDirectory
Upon return, contains YES if path is a directory or if the final path element is a symbolic link that points to a directory, otherwise contains NO. If path doesn’t exist, the return value is undefined. Pass NULL if you do not need this information.
Return Value
YES if there is a file or directory at path, otherwise NO. If path specifies a symbolic link, this method traverses the link and returns YES or NO based on the existence of the file or directory at the link destination.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/99395",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "46"
}
|
Q: What is the easiest FLV player for embedding video on a website? I have video that I've converted to FLV format. I'd rather host it on my own site than use a service like YouTube. What is the easiest player to use? I'd like to just put the .swf file of the player somewhere on my server, and give it the video as a parameter.
A: I haven't tried yet Flowplayer which seems well documented
it is featured on arctic startup and only restriction to use it with opensource licence is to have their logo displayed
A: Take a look at OSflv.
A: http://flv-player.net/
*
*Options from minimalist to feature rich.
*Simple but very effective HTML generator lets you play with their code for the demo
*.swf as small as 5KB
*Creative Commons BY SA and MPL 1.1 licences
A: JW FLV Player : http://www.jeroenwijering.com/?item=JW_FLV_Media_Player
A: This could be the obvious answer but the FLVPlayBack component is really nice if you have a single video you need to throw on a website in hurry. Drag it on the stage - select a control panel - double click controls to edit with the Flash drawing tools - post to the website.You might have to use a FlashVar to get the url into the url but that's fairly trivial...
http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/fl/video/FLVPlayback.html
A: I prefer the new open source player directly from Adobe: Strobe Media Playback. It's totally free and open source, BSD license.
Has plugins for commercialization and CDN. has youtube plugin. You can easily create new themes.
However - documentation at this point is not very good.
A: I have tried many FLV players and i came across Applian FLV Player. this one has got to be my best. it is light weight, its free comes with an optional audio recorder and no spyware or such. check it out here
With this however you will not be able to embed it into your regular web page.
A: I'm personally a big fan of JW, though I've heard Floplayer is good too. JW has an enormous number of features and has a very clean interface. It takes less than a minute to set up a video online; I host all my videos myself, mostly video game clips and x264 demos. (Example 1 Example 2 Example 3 Example 4 Example 5)
A: I use JW FLV Player and it's very good.
It also supports FLV streaming so if you use mod_flv with Lighttpd for example you can make you own little youtube.
There's also a mod_flv for apache and you also can use a php(or any language of your choice) script to enable streaming.
A: Any FLV Player, compact easy to use
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/99406",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "35"
}
|
Q: What is the best way to store software documentation? An obvious answer is "an internal wiki". What are the pros and cons of a wiki used for software documentation? Any other suggestions? What are you using for your software documentation?
Loren Segal - Unfortunately we don't have support for any doc tool to compile information from the source code comments but I agree it would be the best way to store technical documentation. My question was about every kind of documentation tho - from sysadmin type to user documentation.
A: That's a very open ended question, and depends on many factors.
Generally speaking, if you use a language that has good documentation generation tools (javadoc, doxygen, MS's C# stuff), you should write your documentation above your methods and have your tools generate the pages. The advantage is that you keep the source of your text alongside your code which means it is orgnanized in the logically correct place and easily editable when you make a change to the behaviour of the method.
If you don't have good doc tool support or don't have access to source code, wiki's aren't a bad idea, but they're a second choice to the above.
Note: I'm talking only about code documentation here. Other artifacts obviously cannot be stored alongside code-- a wiki is a great place to put those documents. Alternatively if you use some CMS you can simply commit them in some docs/ folder as text/pdf/whatever files to be editable via the repository. The advantage there is that they stay with the repository if it is moved whereas a wiki does not (necessarily).
A: Tools are important, but don't get too bogged down in finding the magic tool. No tool I've found yet has a "document everything magically using tiny invisible elves" tickbox. :-)
A wiki will work fine. Or Sharepoint. Or Google docs. Or you could use a SVN repository. Hell you could do it with pens, notepaper, and a file cabinets if you really really had to. (I really don't recommend that!)
The big important key is you need to have buy-in throughout the organization. What happens in a lot of shops is they go and spend a bunch of time and money on some fancy solution like Sharepoint, and then everyone uses it religiously for about two weeks, and then people get busy with hitting the latest milestone and that's the last anyone hears about it.
Depending on your organization, field, the type of products your developing, etc., there are a few solutions to that, but one way or another you need to set up a system and use it. Appoint someone the official documentation czar, give them a cluebat, and tell them to hit people in the head everytime they say "oh yeah, I'll finish documenting that next week...". if that's what it takes. :-)
As for tools... I'd recommend Confluence by Atlassian. It's a fine wiki, it's designed to work in an enterprise environment, it has a lot of nifty features, it's customizable, it integrates well with some of the Atlassian's other nifty tools, and is basically a pretty solid product.
A: «Software documentation» is a very general term. There is «End User documentation», «Developer documentation», «QA Documentation». First one is usually developed by qualified techwriters. Other ones may be dynamically formed from wikis, documentation comments from source code etc. All this stuff maintenance process usually is very complex and each software company follow its own way. But there is one necessary point for all these ways: each code commiter, architect, manager, qa engineer MUST store well arranged each piece of information which may be helpful for the others. And someone else MUST keep an eye on this pieces storage and rearrange pieces if required. All this steps greatly improve all activities related to development process.
A: Assuming you are talking about code documentation versus user documentation, an internal wiki is great if you do not need to distribute the documentation for the code outside of your organization, to contractors or partners.
Javadoc or DOxygen is more suitable if you want distributable code documentation.
If you are referring to user documentation, you may want to have a look at DITA.
A: We currently use inline documentation parsed by an external application (PHP + PhpDocumenter) plus various internal wikis. At times it's painful at best (mainly because only one person update the wikis or the docs...)
However, I've been looking at using ikiwiki to do internal docs. It integrate with your source countrol system (including Git, Subversion, Mercurial, Bazaar, TLA and Monotone) so all your docs track with your project. It is built in Perl and has an extensive plugin system (including multiple markup languages, with the default being Markdown). Also, the source control system is plugin based, so if what you use isn't immediately supported you could add your own. In your preferred language, if need be, since it supports non-perl plugins, too.
A: I started experimenting with a way to do user documentation with these goals:
Markdown/Html/Javascript/file-based relatively linked documents for portability (can run on local file system or you can throw it on a webserver), built-in handling of screenshots (interactively resize), and open source in case anyone else may want to do something with the crazy thing.
Your document source is written in Markdown and rendered to Html via Javascript at browser runtime.
Mandown - http://wittman.org/mandown/
A: My company uses a variety of Sharepoint and a wiki. Sharepoint for specific documents like requirements, presentations, contracts, etc, while the wiki is used as a help guide a developer repository for tutorials on using internally developed libraries.
A: Yeah, we use a wiki, we also use Google documents. I find that Google documents is better than most wikis I've tried and, if you don't need to track all changes, you lose nothing. Google docs provides a good collaboration framework.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/99419",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Does writing and speaking on software make you a better programmer? Do you think that writing about software (i.e. having a blog) and speaking on software (and concepts) make you a better programmer?
A: I believe that is the case. As with teaching, you develop a firmer grasp on the subject when you have to explain to someone else. You get to see what you understand and don't understand in greater detail.
A: Yes. In the work force, being able to communicate effectively is as, and sometimes more important than knowing every obscure detail about language X.
A: Absolutely yes. You have the chance to be challenged and questioned and second-guessed in ways you'd never think of on your own. It also gives you a chance to work on the organization and presentation of your ideas. All of this will feed back into the decisions that you make when you're writing code.
A: Statistically speaking yes. You only retain about 20% of what you read and hear, but 80% of what you teach.
By writing about something or teaching about it, you force yourself to understand the concepts on a much deeper level.
UPDATE:
I wanted to update this with some links to more concrete data to support the statistics that I have been taught numerous times about learning retention rates. However, it would appear there is some controversy surrounding these numbers, even though the NTL Institute for Applied Behavioral Science maintains that research was done to back them up.
A: I would argue the opposite: that in general the good programmers love to write and speak about software. It shows that they are passionate about it, and won't accept crap.
A: Absolutely. Knowledge without regular using is useless. Talking about technologies, languages, methods, development processes, books etc. greatly improves overall experience and points possible ways of professional evolution.
A: Absolutely, for one simple reason: It challenges your preconditions. You could write an article about how perfect .NET is for a given situation, only to find someone has used it, and it turned out badly.
A: I think the main thing these activities do is force one to more thoroughly research things and research new things. Does this make you a better programmer? I think so.
A: I think it encourages you to be a better programmer generally by visualizing your opinions and by reading users responses. I don't think the fact that you have a blog or can display the ability that you are knowledgable about developing makes you better inherently but it might help motivate you to be better so you can keep up with your posts.
A: If you tend to write or speak about software then that means you're thinking about it and you have opinions. Caring about it enough to write makes you a better programmer.
A: I think that being able to speak and write well make you a better developer. Not necessarily because it will improve your programming skills, but because software development is a lot more than just banging out code. Whether it's for a company or an open source project, all but the smallest pieces of software are team products. In this environment, it's going to be the developer who can best communicate that will make the biggest contribution, not the one who is necessarily the best coder.
A: Teaching about software absolutely makes you a better programmer. Writing on a blog is not so far off.
A: Most of the things that I learned about .NET, I learned when I was reviewing it to be able to train newbie devs. So yes, speaking on software helps a whole lot.
A: Yes. If you get feedback (eg, blog comments), then doubly so. Others will invariably think of something that you didn't, but may never have had the chance to tell you if you didn't speak up first.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/99460",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: Retrieve multiple rows from an ODBC source with a UNION query I am retrieving multiple rows into a listview control from an ODBC source. For simple SELECTs it seems to work well with a statement attribute of SQL_SCROLLABLE. How do I do this with a UNION query (with two selects)?
The most likely server will be MS SQL Server (probably 2005). The code is C for the Win32 API.
This code sets (what I think is) a server side cursor which feeds data into the ODBC driver that roughly corresponds with the positional fetches of SQLFetchScroll, which is turn feeds the cache for the listview. (Sometimes using SQL_FETCH_FIRST or SQL_FETCH_LAST as well as):
SQLSetStmtAttr(hstmt1Fetch,
SQL_ATTR_CURSOR_SCROLLABLE,
(SQLPOINTER)SQL_SCROLLABLE,
SQL_IS_INTEGER);
SQLSetStmtAttr(hstmt1Fetch,
SQL_ATTR_CURSOR_SENSITIVITY,
(SQLPOINTER)SQL_INSENSITIVE,
SQL_IS_INTEGER);
...
retcode = SQLGetStmtAttr(hstmt1Fetch,
SQL_ATTR_ROW_NUMBER,
&CurrentRowNumber,
SQL_IS_UINTEGER,
NULL);
...
retcode = SQLFetchScroll(hstmt1Fetch, SQL_FETCH_ABSOLUTE, Position);
(The above is is a fragment from working code for a single SELECT).
Is this the best way to do it? Given that I need to retrieve the last row to get the number of rows and populate the end buffer is there a better way of doing it? (Can I use forward only scrolling?)
Assuming yes to the above, how do I achieve the same result with a UNION query?
LATE EDIT: The problem with the union query being that effectively it forces forward only scrolling which breaks SQLFetchScroll(hstmt1Fetch, SQL_FETCH_ABSOLUTE, Position). The answer is I suspect: "you can't". And it really means redesigning the DB to included either a view or a single table to replace the UNION. But I'll leave the question open in case I have missed something.
A: can you not define a view on the db server that does the union query for you, so from the client code it just looks like a single select?
if you can't, can you just issue the union operation as part of your select, e.g.
select some_fields from table1
union
select same_fields from table2
and treat the result as a single result set?
A: If the issue is just needing to get the last row to get the number of rows and caching the last few rows (I assume if there are a million items in the select that you're not populating a drop-list with all of them) then you may be able to take advantage of the ROW_NUMBER() function of SQL Server 2005
You could:
select count(*)
from (select blah UNION select blah)
to get the number of rows.
Then:
select ROW_NUMBER() as rownum,blah
from (select blah UNION select blah)
where rownum between minrow and maxrow
to just fetch the rows that you need to display/cache
But seriously folks, if you're selecting items from a million-row table, you might want to consider a different mechanism
Good luck!
A: Have you tried using union to make a derived table ?
select * from
(select field1, field from table1
union all
slect field1, filed2 from table2) a
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/99468",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: how to handle code that is deemed dangerous to change, but stable? What is the best way to handle a big team that has access to a stable but no so pretty code, that is easy to introduce bugs into?
I'm looking for something along the lines of SVN locking the file(s).
A: Tell them to leave it alone.
It works, what is the benefit of changing it other than prettying it up (and the potential cost is high) so you just need to explain the cost/benefit analysis.
I would hope your developers would be smart enough to understand this and, if not, you can use your source code control system logs, rolled up tightly, to beat them to death:-) .
A: Svn does have a setting for locking the file to prevent concurrent access (similar to Source Safe) but I would recommend building some automated unit tests and integration tests around the fearful code. Hopefully you have a solid QA group as a safety net as well.
A: *
*Write automated unit tests. If you have tests that test the code you are maintaining you can be assured that any modifications haven't broken it. Test frameworks such as JUnit can help.
*Get a copy of Martin Fowler's classic book Refactoring and read it. Pay particular attention to the concept of code smells. This will point you to particular refactorings that will help with your situation.
*Get a good IDE that has refactoring support built in. IDEs won't support all of the refactorings in the book but many of them will have a number of them. Eclipse and NetBeans in the Java world are free and support refactoring well.
*Consider a continuous integration server like Hudson to track whether your tests are failing.
A: Yeah, lock it until you can write a more maintainable replacement for it.
Michael Feathers' book on legacy code will be a good read for that team. Of course, easier said than done, but that particular code can become a design debt for your software in the long run.
A: Write unit tests if you don't have them already. Then start refactoring, and keep doing regression tests upon every commit.
A: Black-box it in a library so it can't be messed with. Document the interface well.
A: Produce complete unit tests so that if it has to change, you know it still works.
A: If you have Subversion, locking files isn't terribly unless the code is just a few files. Subversion doesn't let you lock sub-directories, just individual files. Plus the lock can be broken.
What you probably want is a pre-commit hook script. You can do pretty much anything, but I've used it to restrict access to a certain subdirectory to specific people (branches, SQL scripts). Also, unless you have access to the server you can't break a pre-commit hook.
See the Version Control with Subversion book on Implementing Repository Hooks. The Subversion distribution should include some good examples of how to do exactly this.
A: I'm thinking more like refacter, if the code is hard to work with then it needs to be redone, it may take some time but it will likely be better in the long run as you won't cause as many problems.
A: Set up automated builds and unit tests. Any kind of repository that tracks changes is good, but won't prevent bugs.
Also, only make changes that you can run right away. The Agile methodology that says release early and often helps here. That way, you can get a better understanding of the code as you get deeper into it.
Basically, if you can, start with refactoring that doesn't change the functionality. Then introduce new functionality on top of the refactored code. Do it slowly with small, deliberate changes.
Locking the source while changes are made probably won't help as much as communicating what is changing and where. Your best approach is to make open communication channels. Set up a forum using something like Slashcode where they can discuss things openly and ask questions, and leave a record.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/99474",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Visual C++/Studio: Application configuration incorrect? My C(++) program, written and compiled using Visual C(++)/Visual Studio, runs fine on my own machine, but refuses to run on another machine. The error message I get is "This application has failed to start because the application configuration is incorrect. Reinstalling the application may fix this problem."
A: If you write a C++ program, it links dynamically to the C Runtime Library, or CRT for short. This library contains your printf, your malloc, your strtok, etcetera. The library is contained in the file called MSVCR80.DLL. This file is not by default installed on a Windows system, hence the application cannot run.
The solution? Either install the DLL on the target machine through VCREDIST.EXE (the Visual C++ Redistributable Package), or link to the CRT statically (plug the actual code for the used functions straight into your EXE).
Distributing and installing VCREDIST along with a simple application is a pain in the arse, so I went for the second option: static linking. It's really easy: go to your project's properties, unfold C/C++, click Code Generation, and set the Runtime Library to one of the non-DLL options. That's all there is to it.
A: The problem here is a missing DLL dependency, such as the CRT (C Runtime Library). A good tool for diagnosing this sort of problem is Dependency Walker (depends.exe), which you can find here:
http://www.dependencywalker.com/
You would run this program on the computer that generates the error message you posted, and use it to open the exe that's generating this error. Dependency Walker will quickly and graphically indicate any DLLs that are required but not available on the machine.
A: Chances are high that you miss the runtime libraries of Visual Studio (CRT amongst others), you can either get rid of those dependencies (link statically) or install the VC redist packages on the target computer.
Depending on the Visual C++ version you use, you have to install different packages :
Visual C++ 2005
Visual C++ 2005 SP1
Visual C++ 2008
Warning : those packages only contain release versions of the libraries, if you want to be able to distribute debug builds of your application you'll have to take care of the required DLL yourself.
A: It is much the simplest to link to the runtime statically.
c++ -> Code Generation -> Runtime Library and select "multi-threaded /MT"
However, this does make your executable a couple hundred KByte larger. This might be a problem if you are installing a large number of small programs, since each will be burdened by its very own copy of the runtime. The answer is to create an installer.
New project -> "setup and deployment" -> "setup project"
Load the output from your application projects ( defined using the DLL version of the runtime ) into the installer project and build it. The dependency on the runtime DLL will be noticed, included in the installer package, and neatly and unobtrusively installed in the correct place on the target machine.
A: The correct VC Redist package for you is part of your Visual Studio installation. For VC 8, you can find it here:
\Program Files\Microsoft Visual Studio 8\SDK\v2.0\BootStrapper\Packages\vcredist_x86
A: POSSIBLE SOLUTION........
EDIT: (removed most of my post)
Long story short, I was having similar problems, getting the "Application Configuration Incorrect" messages, etc etc.
Depends.exe was only finding ieshims.dll and wer.dll as possible issues, but this is not the problem.
I ended up using the Multithreaded (/mt) compile option.
What HAS worked though, as a workable solution, is making an installer with InstallShield.
I've selected several merge modules in installshield builder and this seems to have fixed my problem. The modules selected were:
VC++ 9.0 CRT, VC++ 9.0 DEBUG CRT, and the CRT WinSXS MSM merge module.
I'm pretty sure its the WinSXS merge module that has fixed it.
DEBUG CRT: I noticed somewhere that (no matter how hard I tried, and obviously failed thus far), my Release version still depended on the DEBUG CRT. If this is still the case, the InstallShield merge module has now placed the DEBUG CRT folder in my WinSXS folder :) Being somewhat of a novice with VC++ I assume that this would normally be used to distribute debug versions of your programs to other people. To test if this is what fixed my problem I removed the DEBUG CRT folder from the WinSXS folder and the application still worked. (Unless something is still running in the background etc etc - I'm not that into it)
Anyway, this has got things working for me on an XP SP3 fully updated machine, and also on a VMWare XP SP3 machine with the bare bones (.net 3.5 and VC++ 2008 RTM basically) - and also on a mate's XP machine where it previously wasn't working.
So give these things a try, you might have some luck.
A: First thing you must use
#define _BIND_TO_CURRENT_VCLIBS_VERSION 1
or add _BIND_TO_CURRENT_VCLIBS_VERSION=1 to the preprocessor directives.
The problem is related to binding and the manifest types, you can find more http://www.nuonsoft.com/blog/2008/10/29/binding-to-the-most-recent-visual-studio-libraries/
By doing this your application will run with a larger range of runtime libraries versions.
A: Often times this error is the result of attempting to run the debug version of an application that uses .NET. Since the .NET redistributable package doesn't include the debug versions of the dlls that are installed with Visual Studio, your application will often get this error when running it on any other machine that doesn't have Visual Studio installed. If you haven't already, try building a release version of your application and see if that works.
A: Note also - that if you change to static runtime, you will have to do the same for MFC if your app uses MFC. Those settings are in properties->Configuration/General
A: I ran into this problem and was able to fix it very simply.
Visual studio gives you the option (on by default) to build a manifest for each build.
The manifest was put in the release folder, but it was a different release folder than the exe.
Even when using the setup utilities it was not packaged.
You should look for a file names something like myprogram.exe.indermediate.manifest
If this is in the same folder as the exe (and you have all the dlls) it should run
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/99479",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How do I change the colors of an arbitrary widget in GTK+? If I'm writing an application that wants to communicate some information through the use of color, how can I change the background and foreground colors of a given widget? I would like to know how to do this in glade if it's possible, as well as programmatically (to a computed color).
I want to know how to do this to a complex widget as well, for example, an HBox that contains a VBox that contains some Labels.
Ideally this would also include a solution solution that allows me to tint the widget's existing colors, and identify the average colors of any images in use by the theme, so that I can programmatically compensate for any color choices which might make text unreadable or otherwise clashing - but I would be happy if I could just turn a button red.
A: Example program:
#include <gtk/gtk.h>
static void on_destroy(GtkWidget* widget, gpointer data)
{
gtk_main_quit ();
}
int main (int argc, char* argv[])
{
GtkWidget* window;
GtkWidget* button;
gtk_init(&argc, &argv);
window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
g_signal_connect(G_OBJECT (window), "destroy",
G_CALLBACK (on_destroy), NULL);
button = gtk_button_new_with_label("Hello world!");
GdkColor red = {0, 0xffff, 0x0000, 0x0000};
GdkColor green = {0, 0x0000, 0xffff, 0x0000};
GdkColor blue = {0, 0x0000, 0x0000, 0xffff};
gtk_widget_modify_bg(button, GTK_STATE_NORMAL, &red);
gtk_widget_modify_bg(button, GTK_STATE_PRELIGHT, &green);
gtk_widget_modify_bg(button, GTK_STATE_ACTIVE, &blue);
gtk_container_add(GTK_CONTAINER(window), button);
gtk_widget_show_all(window);
gtk_main();
return 0;
}
A: The best documentation that I know of is the one available here: http://ometer.com/gtk-colors.html
A: You can always use gtk_widget_override_color () and gtk_widget_override_background_color (). These two functions allow you to change the color of a widget. But it is better to use CSS classes and regions in your widget/container implementation through gtk_style_context_add_class() and gtk_style_context_add_region().
A: To modify the color of a widget you can initialize a color and use it to modify the color of the widget:
GdkColor color;
gdk_color_parse("#00FF7F", &color);
gtk_widget_modify_bg(widget, GTK_STATE_NORMAL, &color);
To use an image instead of color:
GdkPixbuf *image = NULL;
GdkPixmap *background = NULL;
GtkStyle *style = NULL;
image = gdk_pixbuf_new_from_file ("background.jpg", NULL);
gdk_pixbuf_render_pixmap_and_mask (image, &background, NULL, 0);
style = gtk_style_new ();
style->bg_pixmap [0] = background;
gtk_widget_set_style (GTK_WIDGET(widget), GTK_STYLE (style));
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/99488",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: What are some different ways of implementing a plugin system? I'm not looking so much for language-specific answers, just general models for implementing a plugin system (if you want to know, I'm using Python). I have my own idea (register callbacks, and that's about it), but I know others exist. What's normally used, and what else is reasonable?
What do you mean by a plugin system? Does Dependency Injection and IOC containers sounds like a good solution?
I mean, uh, well, a way to insert functionality into the base program without altering it. I didn't intend to define it when I set out. Dependency Injection doesn't look particularly suitable for what I'm doing, but I don't know much about them.
A: A simple plugin architecture can define a plugin interface with all the methods the plugin ought to implement. The plugin handles event from the application, and can use the application's standard code, model objects, etc. to get things done. Basically the same as an ASP.NET Form does, except that you're overriding rather than implementing.
Nobody taught me this part, and I'm no expert, but I feel: In general a plugin will be less stable than its application, so the application should always be in control and only give the plugin periodic opportunities to act. If a plugin can register an Observer, then calls to the delegate should be tried/caught.
A: In Python you can use the entry-point system provided by setuptools and pkg_resources. Each entry point should be a function that returns information about the plugin -- name, author, setup and teardown functions, etc.
A: There is a very good episode of Software Engineering Radio, which you may be interested in.
For future reference, I have reproduced here the "Rules for Enablers" (alternative link) given in the excellent Contributing to Eclipse by Erich Gamma, Kent Beck.
*
*Invitation Rule - Whenever possible, let others contribute to your contributions.
*Lazy Loading Rule - Contributions are only loaded when they are needed.
*Safe Platform Rule - As the provider of an extension point, you must protect yourself against misbehavior on the part of extenders.
*Fair Play Rule - All clients play by the same rules, even me.
*Explicit Extension Rule - Declare explicitly where a platform can be extended.
*Diversity Rule - Extension points accept multiple extensions.
*Good Fences Rule - When passing control outside your code, protect yourself.
*Explicit API Rule - separate the API from internals.
*Stability Rule - Once you invite someone to contribute, don?t change the rules.
*Defensive API Rule - Reveal only the API in which you are confident, but be prepared to reveal more API as clients ask for it.
A: How about abstract factory? Your base program defines how the abstract concepts interact with each other, but the caller has to provide the implementation.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/99497",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Does several levels of base classes slow down a class/struct in c++? Does having several levels of base classes slow down a class? A derives B derives C derives D derives F derives G, ...
Does multiple inheritance slow down a class?
A: [Deep inheritance hierarchies] greatly increases the maintenance burden by adding unnecessary complexity, forcing users to learn the interfaces of many classes even when all they want to do is use a specific derived class. It can also have an impact on memory use and program performance by adding unnecessary vtables and indirection to classes that do not really need them. If you find yourself frequently creating deep inheritance hierarchies, you should review your design style to see if you've picked up this bad habit. Deep hierarchies are rarely needed and almost never good. And if you don't believe that but think that "OO just isn't OO without lots of inheritance," then a good counter-example to consider is the [C++] standard library itself. -- Herb Sutter
A: *
*Does multiple inheritance slow down
a class?
As mentioned several times, a deeply nested single inheritance hierarchy should impose no additional overhead for a virtual call (above the overhead imposed for any virtual call).
However, when multiple inheritance is involved, there is sometimes a very slight additional overhead when calling the virtual function through a base class pointer. In this case some implementations have the virtual function go through a small thunk that adjusts the 'this' pointer since
(static_cast<Base*>( this) == this)
Is not necessarily true depending on the object layout.
Note that all of this is very, very implementation dependent.
See Lippman's "Inside the C++ Object Model" Chapter 4.2 - Virtual Member Functions/Virtual Functions under MI
A: Non-virtual function-calls have absolutely no performance hit at run-time, in accordance with the c++ mantra that you shouldn't pay for what you don't use.
In a virtual function call, you generally pay for an extra pointer lookup, no matter how many levels of inheritance, or number of base classes you have.
Of course this is all implementation defined.
Edit: As noted elsewhere, in some multiple inheritance scenarios, an adjustment to the 'this' pointer is required before making the call. Raymond Chen describes how this works for COM objects. Basically, calling a virtual function on an object that inherits from multiple bases can require an extra subtraction and a jmp instruction on top of the extra pointer lookup required for a virtual call.
A: There is no speed difference between virtual calls at different levels since they all get flattened out into the vtable (pointing to the most derived versions of the overridden methods). So, calling ((A*)inst)->Method() when inst is an instance of B is the same overhead as when inst is an instance of D.
Now, a virtual call is more expensive than a non-virtual call, but this is because of the pointer dereference and not a function of how deep the class hierarchy actually is.
A: Virtual calls themselves are more time consuming than normal calls because it has to lookup the address of the actual function to call from the vtable
Additionally compiler optimizations like inlining might be hard to perform due to the lookup requirement. Situations where inlining is not possible itself can lead to quite a high overhead due to stack pop and push and jump operations
Here is a proper study which says the overhead can be as high as 50% http://www.cs.ucsb.edu/~urs/oocsb/papers/oopsla96.pdf
Here is another resource that looks at a side effect of having a large library of virtual classes http://keycorner.org/pub/text/doc/kde-slow.txt
The dispatching of the virtual calls with multiple inheritances is compiler specific, so the implementation will also have an effect in this case.
Regarding your specific question of having a large no of base classes, usually the memory layout of a class object would have the vtbl ptrs for all the other constituent classes within it.
Check this page for a sample vtable layout - http://www.codesourcery.com/public/cxx-abi/cxx-vtable-ex.html
So a call to a method implemented by a class deeper into the heierarchy would still only be a single indirection and not multiple indirections as you seem to think. The call does not have to navigate from class to class to finally find the exact function to call.
However if you are using composition instead of inheritance each pointer call would be a virtual call and that overhead would be present and if within that virtual call if that class uses more compositio,n more virtual calls would be made. That kindof a design would be slower depending on the amount of calls you made.
A: Almost all answers point toward whether or not virtual methods would be slower in the OP's example, but I think the OP is simply asking if having several level of inheritance in and of itself is slow. The answer is of course no since this all happens at compile-time in C++. I suspect the question is driven from experience with script languages where such inheritance graphs can be dynamic, and in that case, it potentially could be slower.
A: If there are no virtual functions, then it shouldn't. If there are then there is a performance impact in calling the virtual functions as these are called via function pointers or other indirect methods (depends on the situation). However, I do not think that the impact is related to the depth of the inheritance hierarchy.
Brian, to be clear and answer your comment. If there are no virtual functions anywhere in your inheritance tree, then there is no performance impact.
A: Having non-trivial constructors in a deep inheritance tree can slow down object creation, when every creation of a child results in function calls to all the parent constructors all the way up to the base.
A: Yes, if you're referencing it like this:
// F is-a E,
// E is-a D and so on
A* aObject = new F();
aObject->CallAVirtual();
Then you're working with a pointer to an A type object. Given you're calling a function that is virtual, it has to look up the function table (vtable) to get the correct pointers. There is some overhead to that, yes.
A: Calling a virtual function is slightly slower than calling a nonvirtual function. However, I don't think it matters how deep your inheritance tree is.
But this is not a difference that you should normally be worried about.
A: While I'm not completely sure, I think that unless you're using virtual methods, the compiler should be able to optimize it well enough that inheritance shouldn't matter too much.
However, if you're calling up to functions in the base class which call functions in its base class, and so on, a lot, it could impact performance.
In essence, it highly depends on how you've structured your inheritance tree.
A: As pointed out by Corey Ross the vtable is known at compile time for any leaf derived class, and so the cost of the virtual call really should be the same irrespective of the structure of the hierarchy.
This, however, cannot be said for dynamic_cast. If you consider how you might implement dynamic_cast, a basic approach will be have an O(n) search through your hierarchy!
In the case of a multiple inheritance hierarchy, you are also paying a small cost to convert between different classes in the hierarchy:
sturct A { int i; };
struct B { int j; };
struct C : public A, public B { int k ; };
// Let's assume that the layout of C is: { [ int i ] [ int j ] [int k ] }
void foo (C * c) {
A * a = c; // Probably has zero cost
B * b = c; // Compiler needed to add sizeof(A) to 'c'
c = static_cast<B*> (b); // Compiler needed to take sizeof(A)' from 'b'
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/99510",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "19"
}
|
Q: Is it possible to get Code Coverage Analysis on an Interop Assembly? I've asked this question over on the MSDN forums also and haven't found a resolution:
http://forums.microsoft.com/msdn/ShowPost.aspx?PostID=3686852&SiteID=1
The basic problem here as I see it is that an interop assembly doesn't actually contain any IL that can be instrumented (except for maybe a few delegates). So, although I can put together a test project that exercises the interop layer, I can't get a sense for how many of those methods and properties I'm actually calling.
Plan B is to go and write a code generator that creates a library of RCWWs (Runtime Callable Wrapper Wrappers), and instrument that for the purposes of code coverage.
Edit: @Franci Penov,
Yes that's exactly what I want to do. The COM components delivered to us constitute a library of some dozen DLLs containing approx. 3000 types. We consume that library in our application and are charged with testing that Interop layer, since the group delivering the libraries to us does minimal testing. Code coverage would allow us to ensure that all interfaces and coclasses are exercised. That's all I'm attempting to do. We have separate test projects that exercise our own managed code.
Yes, ideally the COM server team should be testing and analyzing their own code, but we don't live in an ideal world and I have to deliver a quality product based on their work. If can produce a test report indicating that I've tested 80% of their code interfaces and 50% of those don't work as advertised, I can get fixes done where fixes need to be done, and not workaround problems.
The mock layer you mentioned would be useful, but wouldn't ultimately be achieving the goal of testing the Interop layer itself, and I certainly would not want to be maintaining it by hand -- we are at the mercy of the COM guys in terms of changes to the interfaces.
Like I mentioned above -- the next step is to generate wrappers for the wrappers and instrument those for testing purposes.
A: To answer your question - it's not possible to instrument interop assemblies for code coverage. They contain only metadata, and no executable code as you mention yourself.
Besides, I don't see much point in trying to code coverage the interop assembly. You should be measuring the code coverage of code you write.
From the MDN forums thread you mention, it seems to me you actually want to measure how your code uses the COM component. Unless your code's goal is to enumerate and explicitly call all methods and properties of the COM object, you don't need to measure code coverage. You need unit/scenario testing to ensure that your code is calling the right methods/properties at the right time.
Imho, the right way to do this would be to write a mock layer for the COM object and test that you are calling all the methods/properties as expected.
A: Plan C:
use something like Mono.Cecil to weave simple execution counters into the interop assembly. For example, check out this one section in the Faq: "I would like to add some tracing functionality to an assembly I can’t debug, is it possible using Cecil?"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/99520",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: What is a good PHP library to handle file uploads? I am looking to use a PHP library for uploading pictures to a web server so that I can use something that has been tested and hopefully not have to design one myself. Does anyone know of such a library?
Edit: I am aware that file uploads are built into PHP, I am looking for a library that may make the process simpler and safer.
A: I personally use HTTP_Upload from PEAR. It works pretty well for our purposes (uplaoding media files into a development system and uploading arbitrary files for an educational system)
A: The cunningly name upload class is very good and has a very responsive and supportive developer. Apart from uploading, it also has built-in support for lots of common image functions.
A: The Zend Framework has classes for everything under the sun, including file uploads. Check out the Zend_HTTP class for what you want.
A: Check this example of SWFUpload, the source code is available in PHP.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/99528",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "18"
}
|
Q: What tools do you use for Automated Builds / Automated Deployments? Why? What tools do you use for Automated Builds / Automated Deployments? Why?
What tools do you recommend?
A: Hudson for automated builds. I chose it because it was the easiest to setup and demo. A system that's too complex and isn't slick-looking won't impress management enough to get them on-board for automated builds. Especially in a project that has a lot of inertia.
A: NAnt for builds (but MSBuild, Rake, almost anything would be fine) and CruiseControl.NET for deployments. I'm currently working with the new Cruise from ThoughtWorks studios as it provides a better way to stage the various pipelines and let's me deploy any version I want to a target environment.
A: We use TeamCity, from JetBrains. They also make Resharper And IntelliJ.
We use it for building our .Net applications, and it has been quite easy to set up, connect to TFS, and run additional tools from. It is very polished, and actually kinda reminds me of this site. Found it much nicer than CruiseControl, and for our team size it is free. If you need lots of different builds, more per-user builds, and so on then it costs a bit (but still quite reasonable).
A: Funnily enough I just spent two weeks overhauling (read implementing from scratch) our nightly build process. Great fun (no, really). I toyed with the idea of installing Team Foundation Server, but we use Perforce for source control and I didn't think it was worth the hassle.
Our process is now a set of Powershell scripts that run on a dedicated build/test server that do the following on a scheduled task:
Wipe out the entire source tree (check that you didn't have anything checked out first!)
Bring down the entire source tree from Perforce (from the last labelled build)
Generate a change report (by syncing to HEAD and watching what comes down)
Build the App
Index the PDB files to the Perforce sources
Store the binaries and symbols in a dedicated symbol server
Run the test projects
Build the installer
Label
Send out emails to the group with status reports on all of the above
Works well.
A: make and bash on linux
make and cmd on windows
A: Visual Build Pro
A: We use a combination of build tools and continuous integration server:
Build tools:
*
*Maven
*SBT
*Gradle
*Rake
Continuous Integration Servers:
*
*Jenkins
*Hudson
*Travis CI
A: Automated Build Studio.
Instead of letting you mes with scripts or xml files, it comes with predefined graphical macro operations that allows you to create tasks easily.
A: For our Windows-compilable stuff, we use FinalBuilder.
A: CruiseControl for automated builds. Works great.
A: For automated builds, I think the best tool going right now is JetBrain's Team City. The free version has all the features you'll need for most 5-10 person teams. Set up is easy, configuring new projects is painless (relatively), and most importantly, it's reliable.
For automated migrations, nothing beats PowerShell.
A: UppercuT uses NAnt to build and it is the insanely easy to use Build Framework.
Automated Builds as easy as (1) solution name, (2) source control path, (3) company name for most projects!
http://code.google.com/p/uppercut/
Some good explanations here: UppercuT
More information
UppercuT is a conventional automated build, which means you set up a config file and then you get a bunch of features for free. Arguably the most powerful feature is the ability to specify environment settings in ONE place and have them applied everywhere, including documentation when it builds the source.
Documentation available: https://github.com/chucknorris/uppercut/wiki
Features :
*
*Simple setup
*Simple upgrades
*Custom extension points (pre, post, and replace) for each step of the build process http://uppercut.pbworks.com/CustomizeUsingExtensionPoints
*Has documentation for integration w/Team City, CruiseControl.NET, and Jenkins (formerly Hudson) https://github.com/chucknorris/uppercut/tree/master/docs
*Works on Linux w/Mono
*Versioning DLLs based on build number and source control revisions (SVN, TFS, Git, HG)
*Compile activities - F5 or Ctrl + Shift + B
*Strong naming made as easy as true/false
*Code Testing and Analysis
*
*Testing
*
*NUnit
*MbUnit v2
*Gallio
*xUnit
*NCover
*NDepend
*Nitriq
*Mono Migration Analyzer
*Obfuscation
*ILMerge
*Environment Templating and Building (ConfigBuilder, DocBuilder, SQLBuilder, DeploymentBuilder) https://github.com/chucknorris/uppercut/blob/master/docs/ConfigBuilder.doc?raw=true
*Packaging output to prepare for deployment
*Zips up output
A: At work we use good ol' Ant to build our Java servlets.
A: We used to use Visual Build from Kinook software, but recently with our new application we switched to MSBuild since it had better integration with TFS and the ability to create custom tasks.
A: The GNU Autotools definitely. The autoconf and automake are de-facto standard for unix systems.
A: I've had success using buildbot, triggered by a post-commit script on a subversion repository. This has been used for both automated builds and automated testing.
A: ANT for both build and deployment/installs.
Makes a great cross-platform installer.
A: We use Hericus Zed Builds And Bugs Management for our automated builds.
We have 4 branches of code, each with java, c++, C#, cross platform compiles and installers for 5 OS's.
A: Make for the builds.
Debian packages for deployments (since our production servers runs it).
A: TeamCity running NAnt scripts for building/packaging and PowerShell for deployment.
I've found that using NAnt, powered by TeamCity, instead of the native TeamCity runners allows us to have a much richer build process (eg. css minimiser, etc). It also means the full build/package process can be run on any developers PC instead of just the TeamCity servers making it much easier to customise and debug problems in the build process.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/99535",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: Point-Triangle Collision Detection in 3D How do I correct for floating point error in the following physical simulation:
*
*Original point (x, y, z),
*Desired point (x', y', z') after forces are applied.
*Two triangles (A, B, C) and (B, C, D), who share edge BC
I am using this method for collision detection:
For each Triangle
If the original point is in front of the current triangle, and the desired point is behind the desired triangle:
Calculate the intersection point of the ray (original-desired) and the plane (triangle's normal).
If the intersection point is inside the triangle edges (!)
Respond to the collision.
End If
End If
Next Triangle
The problem I am having is that sometimes the point falls into the grey area of floating point math where it is so close to the line BC that it fails to collide with either triangle, even though technically it should always collide with one or the other since they share an edge. When this happens the point passes right between the two edge sharing triangles. I have marked one line of the code with (!) because I believe that's where I should be making a change.
One idea that works in very limited situations is to skip the edge testing. Effectively turning the triangles into planes. This only works when my meshes are convex hulls, but I plan to create convex shapes.
I am specifically using the dot product and triangle normals for all of my front-back testing.
A: It sounds like you ain't including testing if it's ON the edge (you're writing "Inside triangle edges"). Try changing code to "less than or equal" (inside, or overlapping).
A: This is an inevitable problem when shooting a single ray against some geometry with edges and vertices. It's amazing how physical simulations seem to seek out the smallest of numerical inaccuracies!
Some of the explanations and solutions proposed by other respondents will not work. In particular:
*
*Numerical inaccuracy really can cause a ray to "fall through the gap". The problem is that we intersect the ray with the plane ABC (getting the point P, say) before testing against line BC. Then we intersect the ray with plane BCD (getting the point Q, say) before testing against line BC. P and Q are both represented by the closest floating-point approximation; there's no reason to expect that these exactly lie on the planes that they are supposed to lie on, and so every possibility that you can have both P to the left of BC and Q to the right of BC.
*Using less-than-or-equal test won't help; it's inaccuracy in the intersection of the ray and the plane that's the trouble.
*Square roots are not the issue; you can do all of the necessary computations using dot products and floating-point division.
Here are some genuine solutions:
*
*For convex meshes, you can just test against all the planes and ignore the edges and vertices, as you say (thus avoiding the issue entirely).
*Don't intersect the ray with each triangle in turn. Instead, use the scalar triple product. (This method makes the exact same sequence of computations for the ray and the edge BC when considering each triangle, ensuring that any numerical inaccuracy is at least consistent between the two triangles.)
*For non-convex meshes, give the edges and vertices some width. That is, place a small sphere at each vertex in the mesh, and place a thin cylinder along each edge of the mesh. Intersect the ray with these spheres and cylinders as well as with the triangles. These additional geometric figures stop the ray passing through edges and vertices of the mesh.
Let me strongly recommend the book Real-Time Collision Detection by Christer Ericson. There's a discussion of this exact problem on pages 446–448, and an explanation of the scalar triple product approach to intersecting a ray with a triangle on pages 184–188.
A: I find it somewhat unlikely that your ray would fall exactly between the triangles in a way that the floating point precision would take effect. Are you absolutely positive that this is indeed the problem?
At any rate, a possible solution is instead of shooting just one ray to shoot three that are very close to each other. If one falls exactly in between that atleast one of the other two is guaranteed to fall on a triangle.
This will atleast allow you to test if the problem is really the floating point error or something more likely.
A: @Statement: I am indeed already using a "greater than or equal to" comparison in my code, thank you for the suggestion. +1
My current solution is to add a small nudge amount to the edge test. Basically when each triangle is tested, its edges are pushed out by a very small amount to counteract the error in floating point. Sort of like testing if the result of a floating point calculation is less than 0.01 rather than testing for equality with zero.
Is this a reasonable solution?
A: If you are doing distance measurements, watch out for square roots. They have a nasty habit of throwing away half of your precision. If you stack a few of these calculations up, you can get in big trouble fast. Here is a distance function I have used.
double Distance(double x0, double y0, double x1, double y1)
{
double a, b, dx, dy;
dx = abs(x1 - x0);
dy = abs(y1 - y0);
a = max(dx, dy));
if (a == 0)
return 0;
b = min(dx, dy);
return a * sqrt( 1 + (b*b) / (a*a) );
}
Since the last operation isn't a square root, you don't lose the precision any more.
I discovered this in a project I was working on. After studying it and figuring out what it did I tracked down the programmer who I thought was responsible to congratulate him, but he had no idea what I was talking about.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/99542",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: How can I grab single key hit in D Programming Language + Tango? I read this article and try to do the exercise in D Programming Language, but encounter a problem in the first exercise.
(1) Display series of numbers
(1,2,3,4, 5....etc) in an infinite
loop. The program should quit if
someone hits a specific key (Say
ESCAPE key).
Of course the infinite loop is not a big problem, but the rest is. How could I grab a key hit in D/Tango? In tango FAQ it says use C function kbhit() or get(), but as I know, these are not in C standard library, and does not exist in glibc which come with my Linux machine which I use to programming.
I know I can use some 3rd party library like ncurses, but it has same problem just like kbhit() or get(), it is not standard library in C or D and not pre-installed on Windows. What I hope is that I could done this exercise use just D/Tango and could run it on both Linux and Windows machine.
How could I do it?
A: Here's how you do it in the D programming language:
import std.c.stdio;
import std.c.linux.termios;
termios ostate; /* saved tty state */
termios nstate; /* values for editor mode */
// Open stdin in raw mode
/* Adjust output channel */
tcgetattr(1, &ostate); /* save old state */
tcgetattr(1, &nstate); /* get base of new state */
cfmakeraw(&nstate);
tcsetattr(1, TCSADRAIN, &nstate); /* set mode */
// Read characters in raw mode
c = fgetc(stdin);
// Close
tcsetattr(1, TCSADRAIN, &ostate); // return to original mode
A: kbhit is indeed not part of any standard C interfaces, but can be found in conio.h.
However, you should be able to use getc/getchar from tango.stdc.stdio - I changed the FAQ you mention to reflect this.
A: D generally has all the C stdlib available (Tango or Phobos) so answers to this question for GNU C should work in D as well.
If tango doesn't have the needed function, generating the bindings is easy. (Take a look at CPP to cut through any macro junk.)
A: Thanks for both of your replies.
Unfortunately, my main development environment is Linux + GDC + Tango, so I don't have conio.h, since I don't use DMC as my C compiler.
And I also found both getc() and getchar() is also line buffered in my development environment, so it could not achieve what I wish I could do.
In the end, I've done this exercise by using GNU ncurses library. Since D could interface C library directly, so it does not take much effort. I just declare the function prototype that I used in my program, call these function and linking my program against ncurses library directly.
It works perfectly on my Linux machine, but I still not figure out how could I do this without any 3rd party library and could run on both Linux and Windows yet.
import tango.io.Stdout;
import tango.core.Thread;
// Prototype for used ncurses library function.
extern(C)
{
void * initscr();
int cbreak ();
int getch();
int endwin();
int noecho();
}
// A keyboard handler to quit the program when user hit ESC key.
void keyboardHandler ()
{
initscr();
cbreak();
noecho();
while (getch() != 27) {
}
endwin();
}
// Main Program
void main ()
{
Thread handler = new Thread (&keyboardHandler);
handler.start();
for (int i = 0; ; i++) {
Stdout.format ("{}\r\n", i).flush;
// If keyboardHandler is not ruuning, it means user hits
// ESC key, so we break the infinite loop.
if (handler.isRunning == false) {
break;
}
}
return 0;
}
A: As Lars pointed out, you can use _kbhit and _getch defined in conio.h and implemented in (I believe) msvcrt for Windows. Here's an article with C++ code for using _kbhit and _getch.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/99546",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Has anybody compared WCF and ZeroC ICE? ZeroC's ICE (www.zeroc.com) looks interesting and I am interested in looking at it and comparing it to our existing software that uses WCF. In particular, our WCF app uses server callbacks (via HTTP).
Anybody who's compared them? How did it go? I'm particularly interested in the performance aspect, since interoperability isn't much of a concern for us right now. Thanks!
A: Apache Thrift is another contender to ICE and WCF. It was developed and open sourced by Facebook. Apache Thrift is nice in some ways because its not only extremely efficient on the encoding side, it also supports adding of fields to structures without breaking all of the clients (something we found extremely useful for our projects).
Google Protocol Buffers would seem not really a contender as it doesn't mention .NET support on the home page. However, some community addons support C#. In addition, ICE provides emulation for Google Protocol Buffers if you're working with existing services.
A: I did a very terse review of ICE a few years ago, and although I haven't compared them directly before, having reasonable knowledge of WCF my thoughts might have some relevance.
Firstly, it's not entierely fair to compare WCF with ICE as WCF as ICE is a specific remote communication mechanism and WCF is a higher level remote communications framework.
While WCF is often thought of as implementing SOAP web services, and that is indeed its main use to date, it can also be used for implementing remote services using all manner of encodings and transport channels, which means it can theoretically be used for performant comms between applications.
In comparison, ICE is a cross-platform remote communicaton mechanism that uses binary encoding for performant communications between applications. It's something of a simplified evolution of CORBA and is more directly comparable to CORBA, DCOM, .NET Remoting, and JNI.
However, even though there's no direct correspondence between ICE and WCF, if you need your .NET app to communicate remotely then they're both contenders. Some of the decision points you might want to consider include:
*
*Resourcing. It'll be easier to find developers with WCF experience than ICE experience.
*Performance. If you want performance then ICE performs fast, but WCF can also be used in a performant configuration. Alternatively, .NET Remoting can provide very good performance, and whatever the MS-sponsored benchmarks say I've seen it outperform WCF by 10%.
*Cross-platform. If you need to communicate with non-Windows applications then you're limited with the WCF options you can use. In addition, since every SOAP stack seems to implement the standards differently it can be a pain creating truly generic Web Services (though WS-I helps)
If you don't need every ounce of performance from day one, then I'd personally plump for WCF to start with, and then consider ICE if performance ever becomes critical. Even then it might be cheaper to scale out your service boxes than it is to move to ICE, and if you don't have any exotic cross-platform needs then you could always look at reconfiguring WCF for binary encoding etc
A: Michi Henning from ZeroC has recently published a white paper on just this topic -- "Choosing Middleware: Why Performance and Scalability do (and do not) Matter". It compares Ice, WCF (binary & SOAP), and RMI with various performance metrics, platforms, languages, etc. There's more information on Michi's blog, but the white paper is also quite readable, with all the standard caveats of any benchmark.
Disclaimer: I've used Ice and RMI extensively, but never WCF.
A: Data point: we just converted a callback multi-platform and multi-language project from Ice to Thrift with pretty good results. Ice does a lot for you, so we had to implement disconnection listeners, connection events, etc. ourselves. And in one case we got bit in the proverbial with a big object lock that Ice was letting us get away with -- this caused a deadlock in the Thrift server but it was easily fixed by less lazy coding on the C# side.
I've just finished benchmarking, and in our application anything that pushes large amounts of data is faster than, or on par with, Ice. Shorter messages with more over-head (i.e., a "heartbeat" that updates a status over the protocol) is a bit slower.
The most important bit was that in order to implement the callback service correctly we had to extend Thrift interfaces and define our own protocol, along with a Thrift "Processor" and callback client-server. But I freely admit our application is /very/ special. The existing protocols and servers should be sufficient. But extending them, even to use multiplex sockets from .Net, was not terribly difficult.
A: We are using ICE to integrate modules written in both C++, Java and C#. The nice thing is that our server can access components on remote machines as well, so if we need more performance we can shift processing to different machines.
I've used both WCF and ICE, and I'd say that ICE is cleaner on the implementation side. ICE also has very detailed and readable documentation.
ICE supports some things that WCF cannot do, including load balancing, automated remote client updates, etc.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/99548",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "18"
}
|
Q: Where do "pure virtual function call" crashes come from? I sometimes notice programs that crash on my computer with the error: "pure virtual function call".
How do these programs even compile when an object cannot be created of an abstract class?
A: Usually when you call a virtual function through a dangling pointer--most likely the instance has already been destroyed.
There can be more "creative" reasons, too: maybe you've managed to slice off the part of your object where the virtual function was implemented. But usually it's just that the instance has already been destroyed.
A: As well as the standard case of calling a virtual function from the constructor or destructor of an object with pure virtual functions you can also get a pure virtual function call (on MSVC at least) if you call a virtual function after the object has been destroyed. Obviously this is a pretty bad thing to try and do but if you're working with abstract classes as interfaces and you mess up then it's something that you might see. It's possibly more likely if you're using referenced counted interfaces and you have a ref count bug or if you have an object use/object destruction race condition in a multi-threaded program... The thing about these kinds of purecall is that it's often less easy to fathom out what's going on as a check for the 'usual suspects' of virtual calls in ctor and dtor will come up clean.
To help with debugging these kinds of problems you can, in various versions of MSVC, replace the runtime library's purecall handler. You do this by providing your own function with this signature:
int __cdecl _purecall(void)
and linking it before you link the runtime library. This gives YOU control of what happens when a purecall is detected. Once you have control you can do something more useful than the standard handler. I have a handler that can provide a stack trace of where the purecall happened; see here: http://www.lenholgate.com/blog/2006/01/purecall.html for more details.
(Note you can also call _set_purecall_handler() to install your handler in some versions of MSVC).
A: They can result if you try to make a virtual function call from a constructor or destructor. Since you can't make a virtual function call from a constructor or destructor (the derived class object hasn't been constructed or has already been destroyed), it calls the base class version, which in the case of a pure virtual function, doesn't exist.
class Base
{
public:
Base() { reallyDoIt(); }
void reallyDoIt() { doIt(); } // DON'T DO THIS
virtual void doIt() = 0;
};
class Derived : public Base
{
void doIt() {}
};
int main(void)
{
Derived d; // This will cause "pure virtual function call" error
}
See also Raymond Chen's 2 articles on the subject
A: I ran into the scenario that the pure virtual functions gets called because of destroyed objects, Len Holgate already have a very nice answer, I would like
to add some color with an example:
*
*A Derived object is created, and the pointer (as Base class) is
saved somewhere
*The Derived object is deleted, but somehow the pointer is
still referenced
*The pointer which points to deleted Derived
object gets called
The Derived class destructor reset the vptr points to the Base class vtable, which has the pure virtual function, so when we call the virtual function, it actually calls into the pure virutal ones.
This could happen because of an obvious code bug, or a complicated scenario of race condition in multi-threading environments.
Here is an simple example (g++ compile with optimization turned off - a simple program could be easily optimized away):
#include <iostream>
using namespace std;
char pool[256];
struct Base
{
virtual void foo() = 0;
virtual ~Base(){};
};
struct Derived: public Base
{
virtual void foo() override { cout <<"Derived::foo()" << endl;}
};
int main()
{
auto* pd = new (pool) Derived();
Base* pb = pd;
pd->~Derived();
pb->foo();
}
And the stack trace looks like:
#0 0x00007ffff7499428 in __GI_raise (sig=sig@entry=6) at ../sysdeps/unix/sysv/linux/raise.c:54
#1 0x00007ffff749b02a in __GI_abort () at abort.c:89
#2 0x00007ffff7ad78f7 in ?? () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#3 0x00007ffff7adda46 in ?? () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#4 0x00007ffff7adda81 in std::terminate() () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#5 0x00007ffff7ade84f in __cxa_pure_virtual () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#6 0x0000000000400f82 in main () at purev.C:22
Highlight:
if the object is fully deleted, meaning destructor gets called, and memory gets reclaimed, we may simply get a Segmentation fault as the memory has returned to the operating system, and the program just can't access it. So this "pure virtual function call" scenario usually happens when the object is allocated on the memory pool, while an object is deleted, the underlying memory is actually not reclaimed by OS, it is still there accessible by the process.
A: I'd guess there is a vtbl created for the abstract class for some internal reason (it might be needed for some sort of run time type info) and something goes wrong and a real object gets it. It's a bug. That alone should say that something that can't happen is.
Pure speculation
edit: looks like I'm wrong in the case in question. OTOH IIRC some languages do allow vtbl calls out of the constructor destructor.
A: I use VS2010 and whenever I try calling destructor directly from public method, I get a "pure virtual function call" error during runtime.
template <typename T>
class Foo {
public:
Foo<T>() {};
~Foo<T>() {};
public:
void SomeMethod1() { this->~Foo(); }; /* ERROR */
};
So I moved what's inside ~Foo() to separate private method, then it worked like a charm.
template <typename T>
class Foo {
public:
Foo<T>() {};
~Foo<T>() {};
public:
void _MethodThatDestructs() {};
void SomeMethod1() { this->_MethodThatDestructs(); }; /* OK */
};
A: If you use Borland/CodeGear/Embarcadero/Idera C++ Builder, your can just implement
extern "C" void _RTLENTRY _pure_error_()
{
//_ErrorExit("Pure virtual function called");
throw Exception("Pure virtual function called");
}
While debugging place a breakpoint in the code and see the callstack in the IDE, otherwise log the call stack in your exception handler (or that function) if you have the appropriate tools for that. I personally use MadExcept for that.
PS. The original function call is in [C++ Builder]\source\cpprtl\Source\misc\pureerr.cpp
A: Here is a sneaky way for it to happen. I had this essentially happen to me today.
class A
{
A *pThis;
public:
A()
: pThis(this)
{
}
void callFoo()
{
pThis->foo(); // call through the pThis ptr which was initialized in the constructor
}
virtual void foo() = 0;
};
class B : public A
{
public:
virtual void foo()
{
}
};
B b();
b.callFoo();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/99552",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "124"
}
|
Q: Can you Distribute a Ruby on Rails Application without Source? I'm wondering if it's possible to distribute a RoR app for production use without source code? I've seen this post on SO, but my situation is a little different. This would be an app administered by people with some clue, so I'm cool with still requiring an Apache/Mongrel/MySQL setup on the customer end. All I really want is for the source to be protected. Encoding seems a popular way to go for distributing PHP apps (eg: Helpspot).
I've found these potential solutions:
*
*Zenobfuscate - not all types of Ruby code is supported however, so that counts that out
*Ruby Encoder - may be the best option, as their PHP encoder looks alright (I haven't tried it however) but it's not available yet. I've used IONcube for PHP before and it worked well, but it doesn't seem that IONcube is interested yet.
*Slingshot - it was mentioned in the other SO post, but it solves a different problem to mine and the source is still visible.
*RubyScript2Exe - from the doco, it's not production ready, so that counts that out.
I've heard that potentially using JRuby and distributing bytecode might be a way to achieve this, but I've never used JRuby so I'm not sure what's involved.
Can anyone offer any ideas and/or known examples? Ideally I'd love to have some kind of automated build scenario as well.
A: If you release the source, obfuscated or otherwise, your app will be pirated. See, for example, Mint. It depends on what you're building, but you may find that you're better off releasing the app as a hybrid of sorts: A hosted app with a well-defined API, and a component that runs on the customer's server. As long as the true value of your product lives on the server side, you don't need to obfuscate your code, and you can just release the source code unmodified. Additionally, this may also give you the opportunity to reach clients running, say, PHP rather than Ruby. See, for example, Google Analytics, HopToad, Scout, etc, etc.
A: Your best option right now is to use JRuby. A little bit of background: My company (BitRock) works with many proprietary and commercial open source vendors. We help them package their server software, which is typically based on PHP, Java or Ruby together with a web server or application server (Apache, Tomcat), the language runtime and a database (typically Postgres, MySQL) into a self-contained, easy to use installer. We have a large number of PHP-based customers (including HelpSpot, which you mention) but also several Rails-based ones. In the case of the RoR customers the norm is to use JRuby together with Tomcat or Glassfish although in some cases we also bundle a native Ruby interpreter to run specific scripts that rely on libraries not yet ported to JRuby (usually not core to the application). JRuby has matured quickly and in many cases it actually runs their code faster than regular Ruby. You will need to also consider that although porting your code to JRuby is fairly straightforward, you will need to invest some time on that. You may want to check JRuby Stack which is a free installer of everything you need to get started. Good luck!
A: You can, but it wouldn't do anything to prevent somebody from reverse-engineering or modifying it. I remember there was an article about similar attempts to obfusticate Perl and how they could be effectively bypassed by a debugger and 5 minutes of effort.
A: If you can't wait for the delivery of RubyEncoder, then I think ZenObfuscate is the most promising. Though it may require some modifications to your source code, they do say this on their site:
ZenObfuscate costs $2500 for a site license or is individually negotiable for other licensing schemes. Yes, that is expensive. That was on purpose. But don't let that thwart you too much. If your product is really cool and we want to see it succeed, we'll make it work. "Really cool" is not freecell.
Of course, for $2500 (or more), you'd hope to get a few tweaks to the compiler that'd make your codebase fully supported. It might be worth engaging them in the conversation.
A: You can also take a look at Mingle from ThoughtWorks studios as an example of using JRuby for this.
It's a Ruby on Rails app, they run it using JRuby. They've customized jruby to load encrypted .rb files.
A: Take a look at JumpBox.
I've had conversations with them on the topic, and they seem to have a solution that will work soon for Rails apps.
A: I'm wondering if you could just "compile" the ruby code into an executable using something like RubyScript2Exe ?
To be honest I haven't used it but it seems like it could be what you want, even if it just packages up the scripts with the interpreter into a single executable.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/99553",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "26"
}
|
Q: Does Ajax detoriate performance? Does excess use of AJAX affects performance? In context of big size web-applications, how do you handle AJAX requests to control asynchronous requests?
A: excess use of anything degrades performance; using AJAX where necessary will improve performance, especially if the alternative is a complete full-page round-trip to the server [a 'postback' in asp.net terminology]
A: There are two sides to this story.
AJAX generally improves the performance from the client's perspective. Rather than loading an entire page, a smaller amount of data is requested from the server when it is needed. Given that a HTML page often references many dependent files (images, css, javascript,etc, each requiring a hit from the server (or the cache)) the client performance from judicious use of AJAX can be remarkable.
On the server-side, the issue becomes one of having many more connections to manage. Polling applications, such as in-browser chat in particular, can really start to increase the load on the server because the browser is now hitting the server much more rapidly. In a typical dynamic application (where the response is generated by code rather than from a static file) you may start running into issues - but these are generally balanced by the fact that the complexity of your request is often much lower (again, you aren't generating the entire page but a small subset of the page) and so therefore your platform can probably get a higher throughput in any case.
The exact outcome of any performance issue is going to depend on a number of factors including your server, platform, framework, and prevailing climactic conditions at the time.
My ultimate advice - focus on creating a good user experience, develop intelligently, collect as many metrics as you can and optimise when you know you need it.
A: AJAX itself (being asynchronous requests).. No not generally.
However if you have an abundance of javascript and markup and have large amounts of data transferred via your xmlhttprequests then yes you can see a performance hit. It really depends on how you want your website to function any degredation is generally avoidable if sculpted correctly.
A: Performance of what exactly? I'm going to assume you meant performance of an application in terms of user experience.
What Ajax appears to be best at is causing network traffic only when it's needed. Rather than downloading a honkin' great web page in one hit, it downloads only what's needed in as quick a manner as possible.
Then, if you do something that needs more info, it goes and gets it from the network then.
This means unused stuff is never downloaded (if you design it right, of course - bad code can be written in Ajax as much as any other environment).
I prefer to mix Ajax methods for data transfer and a client-side library like jQuery for pretty interface.
A: Depending on the situation, AJAX may have a performance overhead or it can actually have better performance than an equivelantly functioning web site that doesn't use AJAX.
It's very easy to overuse AJAX to overload the server with tons of frivilous requests and it can also be a burden on the client's CPU. Conversely, AJAX can also be used to deliver small bits of HTML and other code rather than a whole page for each request, which is at least less of a burden on the server.
A: Ajax is just an ordinary HTTP request, so as long as your server can handle those requests it won't be a problem. The upside to Ajax is faster perceived performance by the user, since the page doesn't have to reload and redraw itself for every user action.
If scalability is a concern, I'm sure you are also looking at scaling the system horizontally by adding more web servers to the farm. Same goes with even non-Ajax web apps anyway.
A: AJAX, like any technology can be a good thing or a bad thing depending on the situation and how it is implemented. If you have a specific need for the asynchronous process then it is a good tool to use. However, if you use it irresponsibly you can get into trouble. If you do use it, try to find a good framework that does most of the heavy lifting and be aware of some of the downsides of AJAX...
http://learningremix.net/w2007integ/vangoori/2007/01/the_downsides_of_ajax.shtml
A: I would agree with quite a few other posts in here. If you are using it in an intelligent way (ie, not using ajax every 30 seconds), then it will be fine. I use ajax on my website (and there is also a js free version) and from a clients perspective, the ajax version loads at anywhere from near-equal speeds to four times faster. It all depends on the design (graphics and other content) of the website and what you are updating.
The downside is, since you have to load some frameworks (even if you create your own like I have) you will have a bit slower of a load for the first page, or any full refreshes, and it does increase the processing load a bit. But that is just because the ajax has increased productivity and therefore the user can make more requests/updates
A: If the site is busy then it will, eventually, kill the server, unless your in a farm.
As to the site itself it shouldn't.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/99557",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: When is it appropriate to use Time#utc in Rails 2.1? I am working on a Rails application that needs to handle dates and times in users' time zones. We have recently migrated it to Rails 2.1 and added time zone support, but there are numerous situations in which we use Time#utc and then compare against that time. Wouldn't that be the same as comparing against the original Time object?
When is it appropriate to use Time#utc in Rails 2.1? When is it inappropriate?
A: If you've set:
config.time_zone = 'UTC'
In your environment.rb (it's there by default), then times will automagically get converted into UTC when ActiveRecord stores them.
Then if you set Time.zone (in a before_filter on application.rb is the usual place) to the user's Time Zone, all the times will be automagically converted into the user's timezone from the utc storage.
Just be careful with Time.now.
Also see:
http://mad.ly/2008/04/09/rails-21-time-zone-support-an-overview/
http://errtheblog.com/posts/49-a-zoned-defense - you can use the JS here to detect zones
Hope that helps.
A: If your application has users in multiple time zones, you should always store your times in UTC (any timezone would work, but you should stick with the most common convention).
Let the user input in local time, but convert to UTC to store (and compare, and manipulate). Then, convert back from UTC to display in each users' local time zone.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/99560",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: How to draw in the nonclient area? I'd like to be able to do some drawing to the right of the menu bar, in the nonclient area of a window.
Is this possible, using C++ / MFC?
A: In order to draw in the non-client area, you need to get the "window" DC (rather than "client" DC), and draw in the "window" DC.
A: You should try handling WM_NCPAINT. This is similar to a normal WM_PAINT message, but deals with the entire window, rather than just the client area. The MSDN documents on WM_NCPAINT provide the following sample code:
case WM_NCPAINT:
{
HDC hdc;
hdc = GetDCEx(hwnd, (HRGN)wParam, DCX_WINDOW|DCX_INTERSECTRGN);
// Paint into this DC
ReleaseDC(hwnd, hdc);
}
This code is intended to be used in the message loop of your applicaton, which is canonically organized using a large 'switch' statement.
As noted in the MFC example from Shog, make sure to call the default version, which in this example would mean a call to DefWindowProc.
A: If you just want something in the menu bar, maybe it is easier/cleaner to add it as a right-aligned menu item. This way it'll also work with different Windows themes, etc.
A: Charlie hit on the answer with WM_NCPAINT. If you're using MFC, the code would look something like this:
// in the message map
ON_WM_NCPAINT()
// ...
void CMainFrame::OnNcPaint()
{
// still want the menu to be drawn, so trigger default handler first
Default();
// get menu bar bounds
MENUBARINFO menuInfo = {sizeof(MENUBARINFO)};
if ( GetMenuBarInfo(OBJID_MENU, 0, &menuInfo) )
{
CRect windowBounds;
GetWindowRect(&windowBounds);
CRect menuBounds(menuInfo.rcBar);
menuBounds.OffsetRect(-windowBounds.TopLeft());
// horrible, horrible icon-drawing code. Don't use this. Seriously.
CWindowDC dc(this);
HICON appIcon = (HICON)::LoadImage(AfxGetResourceHandle(), MAKEINTRESOURCE(IDR_MAINFRAME), IMAGE_ICON, 16, 16, LR_DEFAULTCOLOR);
::DrawIconEx(dc, menuBounds.right-18, menuBounds.top+2, appIcon, 0,0, 0, NULL, DI_NORMAL);
::DestroyIcon(appIcon);
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/99623",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: What's the definitive Java Swing starter guide and reference? Obviously the Java API reference, but what else is there that you all use?
I've been doing web development my entire career. Lately I've been messing around a lot with Groovy and I've decided to do a small application in Griffon just to experiment more with Groovy and also break some ground in desktop development. The only thing is I'm totally green when it comes to desktop apps.
So, world, where's a good place to start?
A: The Swing Tutorial is very good. Apart from that, the Swing API is obviously the reference, however it's also a treasure trove of fairly good source code! Add the API source to your IDE and you can jump directly to the implementation to all the Swing classes. This is a great way to explore the functionality, see how various Swing components work and learn a good Swing "style". Furthermore, it's great to be able to step through the API classes if things don't seem to work and you have no idea why! Adding the API source to the IDE has the additional benefit that you get all the JavaDocs along with it, although all modern IDEs can also pull them from the net -- you do not want to program desktop Java without the documentation available from within the IDE!
NetBeans and other IDEs do make the creation of IDEs very easy, but be aware that there is a lot more to Swing than just containers and layout managers. In fact, containers and layout managers are among the easier things, and I'd recommend learning to use them by hand, too. There is nothing at all wrong with using a GUI builder, but in some cases it's overkill, and then it's nicer to just quickly whip up a GUI from source. In other cases you need to be able to create a GUI dynamically and then GUI builders are no use at all! For creating very complex layouts from source, I recommend FormLayout, which has its own set of quirks, but which does scale (in terms of programming effort) to very big frames and layouts.
If you've only done Groovy so far, you'll be surprised how well documented Swing and the rest of the Java API is and how well everything is integrated. It might also take some getting used to a different style of programming, using the debugger more often and println-debugging less, etc. There might also be some "boiler-plate" code that will be very annoying. ;) Enjoy.
A: The Sun Java tutorials are pretty good. I cannot vouch specifically for the Swing one as it has been ages since I've done any Swing development and I have not read it myself.
Creating a GUI with JFC/Swing
A: When it comes to developing java desktop applications, I would highly recommend using the IDE environment Netbeans. Especially when it comes to the development of Swing based applications.
A: I recommend you to play around with netbeans. It will allow you to build complete GUIs using only your mouse. Once you get familiar with Swing components, start using the Java API. Thats how I started.
A: The O'Reilly Swing Book is a pretty good reference, it has a good overview of general Swing concepts and covers each of the major classes. I used it recently when I had to refresh my memory on Swing.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/99626",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: How can I create a Netflix-style iframe overlay without a huge javascript library? I'm trying to use a link to open an overlay instead of in a separate popup window. This overlay should consist of a semi-transparent div layer that blocks the whole screen from being clicked on. I also aim to disable scrolling at this point. Not matter where you are on the main page, when the link is clicked, the overlay should be in the center of the screen's X and Y origins. Inside of this overlay div, should be an iframe configured such that 3 sizes of content can be loaded.
A: Shadowbox is a nice script for inline "popups". It can work with any of the usual JS libraries if you use any (jQuery, Prototype, etc) or on its own, has a pretty comprehensive skinning system so you can adapt the looks without having to go into the source code itself.
It is also the only such script (there are dozens) I've tried that would work reliably across all usual browsers.
It won't disable scrolling for you (you can still see the normal page background scroll by through the dark overlay), but the "popup" will in any case stay fixed on the screen.
A: http://onehackoranother.com/projects/jquery/boxy/
jQuery.boxy is another nice, lightweight modal dialog plugin.
A: You might want to check out an old JS lib I wrote, called SubModal.
Easy to understand and modify. Go to town ;)
Once you've modded it, use Minify in combination with gzip on your server. The lib size will be teeny tiny.
A: I usually use ThickBox for this. It works really well and degrades nicely if the user does not have JS turned on.
It does use jQuery, but you can load it from Google: http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js and maybe get the benefit of caching.
A: Grab the javascript ext library. It has functionality for overlays that are modal.
A: ThickBox (no longer developed) led me to this library which seems to work very well:
http://fancybox.net
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/99640",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: ResourceManager and Unit Testing I was curious if anyone had any problems creating unit tests around using the ResourceManager. I am using Visual Studio test edition and it appears that the satellite assemblies don't get loaded during the test. When I try to get a resource for another culture, the test always fails and the resource manager always falls back to the default culture. The exact same code runs fine within the normal application.
A: That got me going in the right direction. Adding the files to the deployment config didn't help, but disabling deployment did work.
For future reference, Visit this blog post and scroll down to the section "Managing Test Runs" for details of creating a test configuration and how to disable the deployment
A: If you are running MSTest and you want to access a resource other than the neutral culture, you need to ensure, that the satellite assembly for the specific culture is deployed to the test directory in your solution folder.
Just add this attribute to your unit test:
[DeploymentItem( @"de-DE\AssemblyName.resources.dll", "de-DE")]
This will deploy the resources assembly to the test directory in the specified culture dependent sub directory.
Source
A: I've had similar problems in the past with satellite assemblies. Try
adding the satellite assemblies to the unit projects dependecies. In Visual Studio
Test -- Edit Test Run configuration. Select Deployment and add the files
here.
On executing all applications, dlls, etc are copied to a special directory.
Strong named dll's may be ignored as these are expected to be in the GAC.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/99642",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: CSS Reset, default styles for common elements After applying a CSS reset, I want to get back to 'normal' behavior for html elements like: p, h1..h6, strong, ul and li.
Now when I say normal I mean e.g. the p element adds spacing or a carriage return like result when used, or the size of the font and boldness for a h1 tag, along with the spacing.
I realize it is totally up to me how I want to set the style, but I want to get back to normal behavior for some of the more common elements (at least as a starting point that I can tweak later on).
A: You mean like:
* {
padding: 0;
margin: 0;
}
h1, h2, h3, h4, h5, h6, p, blockquote, form, label, ul, ol, dl, fieldset, address {
margin-bottom: 1em;
}
?
Actually, sorry I mis-read your question, you're after something more like Eric Meyer's total reset @ http://meyerweb.com/eric/tools/css/reset/
A: Rather than using a total CSS reset, think about using something like Normalize, which "preserves useful defaults".
To find out what your browser thinks of as default, open a plain HTML file with lists and view the lists with a CSS debugger like Firebug, and look under the Computed tab.
A: Check out YUI (Yahoo's open source user interface conventions).
They have a base stylesheet that undoes their own reset css.
They dont actaully recommend you use it in production - since its counter productive but definitely might be worth checking out the file to get relevant snippets for what you want to 'undo'.
I recommend you watch the 40 minute talk to get up to speed.
Heres a short snippet of their base.css file :
ol li {
/*giving OL's LIs generated numbers*/
list-style: decimal outside;
}
ul li {
/*giving UL's LIs generated disc markers*/
list-style: disc outside;
}
dl dd {
/*giving UL's LIs generated numbers*/
margin-left:1em;
}
th,td {
/*borders and padding to make the table readable*/
border:1px solid #000;
padding:.5em;
}
th {
/*distinguishing table headers from data cells*/
font-weight:bold;
text-align:center;
}
Download the full stylesheets below or read full documentation.
Yahoo reset css | Yahoo base (undo) reset css
A: YUI provides a base CSS file that will give consistent styles across all 'A-grade' browsers. They also provide a CSS reset file, so you could use that as well, but you say you've already reset the CSS. For further details go to the YUI website. This is what I've been using and it works really well.
A: I'm personally a big fan of BlueprintCSS. It resets styles across browsers and provides some really convenient defaults (that are what you want 90% of the time). It also provides a layout grid, but you don't have to use that if you don't need it.
A: If you want to see the css defaults for firefox, look for a file called 'html.css' in the distribution (there should be some other useful css files in the same directory). You could pick out the rules that you want, and apply them after a reset.
Also, the CSS2 standard has a sample stylesheet for html 4.
A: Normal behaviour for WebKit h1:
h1 {
display: block;
font-size: 2em;
margin: .67__qem 0 .67em 0;
font-weight: bold
}
Normal behaviour for Gecko h1:
h1 {
display: block;
font-size: 2em;
font-weight: bold;
margin: .67em 0;
}
The rest of the elements should be there if you search the files.
A: One of the rules in applying CSS styles is "last in wins." This means if your CSS reset styles set elements to margin:0; padding:0 you can then override these rules by declaring your desired values for the same elements afterwards.
You can do this in the same file (YUI offers a one-liner reset I think so I sometimes include it as the first line in my CSS file) or in a separate file that appears after the reset CSS <link/> tag.
I think by normal behavior you mean "the defaults for my favorite browser." Your building up CSS rules for these elements is a part of the reset exercise.
Now you might want to look into Blueprint CSS or other grid frameworks. These grid frameworks almost always first reset styles to nothing, then build up the typography for common elements, etc. This could save you some time and effort.
A: "After applying a CSS reset, I want to get back to 'normal' behavior for html elements..."
If you've applied a reset, you would then have to add the rules for what you believe to be normal behavior. Since normal behavior varies from browser to browser this question is something of a non sequitur. I like @da5id's answer - use one of the many available resets and tweak it to suit your needs.
A: Once you have assigned a value to a CSS property of an element, there is no way getting back the “normal” value for it, assuming “normal” means “browser default”, as it seems to mean here. So the only way to have, say, an h1 element have the browser default font-size is to not set the property at all for it in your CSS code.
Thus, to exempt some properties and elements from CSS reset, you need to use a more limited CSS reset. For example, you must not use * { font-size: 100% } but replace * by a list of selectors, like input, textarea { font-size: 100% } (the list could be rather long, but e.g. browser defaults for font-size differ from 100% for a few elements only).
It is of course possible to set properties to values that you expect to be browser defaults. There is no guarantee that this will have the desired effect on all browsers, current and future. But for some properties and elements, this can be relatively safe, because the defaults tend to be similar.
In particular, you might use section Rendering in HTML5 CR. It describes “expected rendering” – not a requirement, though browser vendors may decide to claim conformance to them if they so wish, and generally this will probably keep implementations rather similar in this respect. For example, for h1 the expected settings are (collected here into one rule – in HTML5 CR they are scattered around):
h1 {
unicode-bidi: isolate;
display: block;
margin-top: 0.67em;
margin-bottom: 0.67em;
font-size: 2.00em;
font-weight: bold;
}
(There are additional contextual rules. E.g., nesting h1 inside section is expected to affect the settings.)
A: I'm not resetting all the elements by default because the default styles are somehow browser depended, so they varies from browser to browser. Instead of using something like ul, ol { list-style: none; }, I'm adding a CSS class like r or reset and then I specify that if that is a ul which has a r class, reset it or otherwise please leave it to be untouched.
By the way you need to add class="reset" (for example) to all of those elements, which is extra work and code, however you'd have all of your default styles untouched at the end in return!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/99643",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "54"
}
|
Q: Scalable socket event queue processing My C# class must be able to process a high volume of events received via a tcp stream style socket connection. The volume of event messages received from the tcp server by the class's socket is completely variable. For instance, sometimes it will only receive one event message in a period of ten seconds and at other times it will receive a sixty event messages within a second.
I am using Socket.ReceiveAsync to receive messages. ReceiveAsync returns true if the receive operation is pending or false if there is already data on the wire and the receive operation completed synchronously. If the operation is pending, the Socket will call my callback on an IO completion thread, otherwise I call my own callback in the current (IOC) thread. Furthermore, mixed in with event messages I also receive responses to commands that were sent to this tcp server. Response messages are processed right away; individually, by firing off a threadpool worker.
However, I would like to queue event messages until I have "enough" (N) of them OR until there are no more on the wire...and then fire off a threadpool worker to process a batch of event messages. Also, I want all events to be processed sequentially so I only want one threadpool worker to be working on this at a time.
The processor of event messages need only copy the message buffer into an object, raise an event and then release the message buffer back into the ring-buffer pool. So my question is...what do you think is the best strategy to accomplish this?
Do you need more info? Let me know. Thanks!!
A: I would not call 60 events per second high volume. At that low level of activity any socket processing method at all with be fine. I've handled 5,000 events per second on a single thread using hardware that's much less capable than current machines, just using select.
I will say that if you are looking to scale, handing off messages individually between threads is going to be a disaster. You need to batch or your context switches will kill performance.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/99651",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Associating a ListView with a collection of objects How can you use a ListView to show the user a collection of objects, and to manage those objects?
A: For the purpose of argument, here's our design goal: We've got a "monster" object, and that "monster" will have several "powers." The user interacts with the powers via a ListView item.
First, we create a Power object. Give the object the following method:
public ListViewItem makeKey()
{
return new ListViewItem(name);
}
where name is the name of the power, and a string. This ListViewItem will serve as a key, allowing us to identify and retrieve this power later.
Next, we need to add somewhere in the Monster object to keep track of all these powers.
public Dictionary<ListViewItem,Power> powers;
So now we need a way to add powers to the monster.
public void addPower(Power newPower) {
ListViewItem key = newPower.makeKey();
monster.powers.add(key, newPower);
}
Ok, almost done! Now we've got a dictionary of ListViewItems which are tied to the monster's powers. Just grab the keys from that dictionary and stick them in a ListView:
foreach (ListViewItem key in powers.Keys)
powerList.Items.Add(key);
Where powerList is the ListView we're adding the ListViewItems to.
Alright, so we've got the ListViewItems in the ListView! Now, how do we interact with those? Make a button and then a function something like this:
private void powerRemoveButton_Click(object sender, EventArgs e)
{
if (powerList.SelectedIndices.Count > 0)
{
int n = powerList.SelectedIndices[0];
ListViewItem key = powerList.Items[n];
monster.powers.Remove(key);
powerList.Items.Remove(key);
}
else
{
MessageBox.Show("No power selected.");
}
}
And that's that. I hope you've found this helpful. I'm not sure if this was an intentional aspect of their design, but ListViews and Dictionaries blend together so amazingly well when you use a ListViewItem as a key that it's a joy!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/99653",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Multi-purpose 3d Artificial Life Engine? Studying emergence, it's quite useful to have a development framework to build upon to quickly test out new ideas. 3d with physics collision would be nice, and open-source would be a big plus. For this purpose 'breve' looks quite promising, but I was wondering if anyone had used it or knows of any other suitable engines?
A: For quick development, breve does look appropriate. If you want to write something more from scratch, ODE, Bullet and Tokamak are all good open-source 3D physics and collision detection libraries.
A: If I understand the question right, what you're looking for is more a programmable 3D graphics / physics engine sandbox to try out ideas, than anything specifically to do with artificial life.
If so, you might want to take a look at fluxus - it's basically that, where the "programmable" part is Scheme. It's designed for interactive programming (draw 3D scenes and animations, then change them in real time), so I'd guess it should be flexible enough for agent-based AI/AL.
A: I would go ahead and use breve. If you hadn't mentioned breve in your question, I would have recommended it.
A: Actually, I think that something like Microsoft Robotics Studio would be good for this.
A: Maybe not 100% what you are looking for, but you can try Open steer as a possible starting point.
A: I would personally code it up myself with Processing or ODE. It would be really fast, as there are numerous librairies out there available for both.
But I guess you can also use one of these (non-exhaustive list):
*
*Breve: http://spiderland.org/
*Jinngine: https://code.google.com/p/jinngine/
A: I asked a similar question recently with respect to robotics simulation.
JBullet (a Java port of the Bullet Physics engine) came out as the top recommendation.
I'm using this in combination with jMonkeyEngine (which is a fully featured and popular game engine) for the rendering, camera control, scene graph management etc. This seems to be working very nicely so far as the two have been designed to work together.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/99682",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Which, and why, do you prefer Exceptions or Return codes? My question is what do most developers prefer for error handling, Exceptions or Error Return Codes. Please be language(or language family) specific and why you prefer one over the other.
I'm asking this out of curiosity. Personally I prefer Error Return Codes since they are less explosive and don't force user code to pay the exception performance penalty if they don't want to.
update: thanks for all the answers! I must say that although I dislike the unpredictability of code flow with exceptions. The answer about return code (and their elder brother handles) do add lots of Noise to the code.
A: Exceptions should only be returned where something happens that you were not expecting.
The other point of exceptions, historically, is that return codes are inherently proprietary, sometimes a 0 could be returned from a C function to indicate success, sometimes -1, or either of them for a fail with 1 for a success. Even when they are enumerated, enumerations can be ambiguous.
Exceptions can also provide a lot more information, and specifically spell out well 'Something Went Wrong, here's what, a stack trace and some supporting information for the context'
That being said, a well enumerated return code can be useful for a known set of outcomes, a simple 'heres n outcomes of the function, and it just ran this way'
A: Always use exceptions by default, BUT consider providing an additional tester-doer option (TryX)!
For me the answer is really clear. When the context dictates a Try or Tester-Doer pattern (ie cpu intensive or public api), I will ADDITIONALLY provide those methods to the exception throwing version. I think blanket rules of avoiding exceptions are misguided, unsupported, and likely cause far more expense in terms of bugs, than any performance issues they claim to prevent.
No, Microsoft does NOT say to not use exceptions (common misinterpretation).
It says if you're designing an API provide ways to help a user of that API to avoid THROWING exceptions if they need too (Try and Tester-Doer patterns)
❌ DO NOT use exceptions for the normal flow of control, if possible.
Except for system failures and operations with potential race
conditions, framework designers should design APIs so users can write
code that does not throw exceptions. For example, you can provide a
way to check preconditions before calling a member so users can write
code that does not throw exceptions.
What is inferred here is that the non-tester-doer/non-try implementation SHOULD throw an exception upon failure and then the user CAN change that to one of your tester-doer or try methods for performance. Pit of success is maintained for safety and the user OPTS INTO the more dangerous but more performant method.
Microsoft DOES say to NOT use return codes TWICE, here:
❌ DO NOT return error codes.
Exceptions are the primary means of reporting errors in frameworks.
✔️ DO report execution failures by throwing exceptions.
and here:
❌ DO NOT use error codes because of concerns that exceptions might
affect performance negatively.
To improve performance, it is possible to use either the Tester-Doer
Pattern or the Try-Parse Pattern, described in the next two sections.
If you're not using exceptions you're probably breaking this other rule of returning return codes or booleans from a non-tester/non-try implementation.
Again, TryParse does not replace Parse. It is provided in addition to Parse
MAIN REASON: Return codes fail the "Pit of Success" test for me almost every time.
*
*It is far too easy to forget to check a return code and then have a red-herring error later on.
*
*var success = Save()? How much performance is worth someone forgetting an if check here?
*var success = TrySave()? Better, but are we going to abuse everything with the TryX pattern? Did you still provide a Save method?
*Return codes don't have any of the great debugging information on them like call stack, inner exceptions.
*Return codes do not propagate which, along with the point above, tends to drive excessive and interwoven diagnostic logging instead of logging in one centralized place (application and thread level exception handlers).
*Return codes tend to drive messy code in the form of nested 'if' blocks
*Developer time spent debugging an unknown issue that would otherwise have been an obvious exception (pit of success) IS expensive.
*If the team behind C# didn't intend for exceptions to govern control flow, execeptions wouldn't be typed, there would be no "when" filter on catch statements, and there would be no need for the parameter-less 'throw' statement.
Regarding Performance:
*
*Exceptions may be computationally expensive RELATIVE to not throwing at all, but they're called EXCEPTIONS for a reason. Speed comparisons always manage to assume a 100% exception rate which should never be the case. Even if an exception is 100x slower, how much does that really matter if it only happens 1% of the time?
*Context is everything. For example, A Tester-Doer or Try option to avoid a unique key violation is likely to waste more time and resources on average (checking for existance when a collision is rare) than just assuming a successful entry and catching that rare violation.
*Unless we're talking floating point arithmetic for graphics applications or something similar, CPU cycles are cheap compared to developer time.
*Cost from a time perspective carries the same argument. Relative to database queries or web service calls or file loads, normal application time will dwarf exception time. Exceptions were nearly sub-MICROsecond in 2006
*I dare anybody that works in .net, to set your debugger to break on all exceptions and disable just my code and see how many exceptions are already happening that you don't even know about.
*Jon Skeet says "[Exceptions are] not slow enough to make it worth avoiding them in normal use". The linked response also contains two articles from Jon on the subject. His generalized theme is that exceptions are fine and if you're experiencing them as a performance problem, there's likely a larger design issue.
A: In Java, I use (in the following order):
*
*Design-by-contract (ensuring preconditions are met before trying anything that might fail). This catches most things and I return an error code for this.
*Returning error codes whilst processing work (and performing rollback if needed).
*Exceptions, but these are used only for unexpected things.
A: I dislike return codes because they cause the following pattern to mushroom throughout your code
CRetType obReturn = CODE_SUCCESS;
obReturn = CallMyFunctionWhichReturnsCodes();
if (obReturn == CODE_BLOW_UP)
{
// bail out
goto FunctionExit;
}
Soon a method call consisting of 4 function calls bloats up with 12 lines of error handling.. Some of which will never happen. If and switch cases abound.
Exceptions are cleaner if you use them well... to signal exceptional events .. after which the execution path cannot continue. They are often more descriptive and informational than error codes.
If you have multiple states after a method call that should be handled differently (and are not exceptional cases), use error codes or out params. Although Personaly I've found this to be rare..
I've hunted a bit about the 'performance penalty' counterargument.. more in the C++ / COM world but in the newer languages, I think the difference isn't that much. In any case, when something blows up, performance concerns are relegated to the backburner :)
A: I wrote a blog post about this a while ago.
The performance overhead of throwing an exception should not play any role in your decision. If you're doing it right, after all, an exception is exceptional.
A: I use both actually.
I use return codes if it's a known, possible error. If it's a scenario that I know can, and will happen, then there's a code that gets sent back.
Exceptions are used solely for things that I'm NOT expecting.
A: A great piece of advice I got from The Pragmatic Programmer was something along the lines of "your program should be able to perform all its main functionality without using exceptions at all".
A: I have a simple set of rules:
1) Use return codes for things you expect your immediate caller to react to.
2) Use exceptions for errors that are broader in scope, and may reasonable be expected to be handled by something many levels above the caller so that awareness of the error does not have to percolate up through many layers, making code more complex.
In Java I only ever used unchecked exceptions, checked exceptions end up just being another form of return code and in my experience the duality of what might be "returned" by a method call was generally more of a hinderance than a help.
A: I use Exceptions in python in both Exceptional, and non-Exceptional circumstances.
It is often nice to be able to use an Exception to indicate the "request could not be performed", as opposed to returning an Error value. It means that you /always/ know that the return value is the right type, instead of arbitarily None or NotFoundSingleton or something. Here is a good example of where I prefer to use an exception handler instead of a conditional on the return value.
try:
dataobj = datastore.fetch(obj_id)
except LookupError:
# could not find object, create it.
dataobj = datastore.create(....)
The side effect is that when a datastore.fetch(obj_id) is run, you never have to check if its return value is None, you get that error immediately for free. This is counter to the argument, "your program should be able to perform all its main functionality without using exceptions at all".
Here is another example of where exceptions are 'exceptionally' useful, in order to write code for dealing with the filesystem that isn't subject to race conditions.
# wrong way:
if os.path.exists(directory_to_remove):
# race condition is here.
os.path.rmdir(directory_to_remove)
# right way:
try:
os.path.rmdir(directory_to_remove)
except OSError:
# directory didn't exist, good.
pass
One system call instead of two, no race condition. This is a poor example because obviously this will fail with an OSError in more circumstances than the directory doesn't exist, but it's a 'good enough' solution for many tightly controlled situations.
A: I believe the return codes adds to code noise. For example, I always hated the look of COM/ATL code due to return codes. There had to be an HRESULT check for every line of code. I consider the error return code is one of the bad decisions made by architects of COM. It makes it difficult to do logical grouping of the code, thus code review becomes difficult.
I am not sure about the performance comparison when there is an explicit check for the return code every line.
A: Exceptions are not for error handling, IMO. Exceptions are just that; exceptional events that you did not expect. Use with caution I say.
Error codes can be OK, but returning 404 or 200 from a method is bad, IMO. Use enums (.Net) instead, that makes the code more readable and easier to use for other developers. Also you don't have to maintain a table over numbers and descriptions.
Also; the try-catch-finally pattern is an anti-pattern in my book. Try-finally can be good, try-catch can also be good but try-catch-finally is never good. try-finally can often times be replaced by a "using" statement (IDispose pattern), which is better IMO. And Try-catch where you actually catch an exception you're able to handle is good, or if you do this:
try{
db.UpdateAll(somevalue);
}
catch (Exception ex) {
logger.Exception(ex, "UpdateAll method failed");
throw;
}
So as long as you let the exception continue to bubble it's OK. Another example is this:
try{
dbHasBeenUpdated = db.UpdateAll(somevalue); // true/false
}
catch (ConnectionException ex) {
logger.Exception(ex, "Connection failed");
dbHasBeenUpdated = false;
}
Here I actually handle the exception; what I do outside of the try-catch when the update method fails is another story, but I think my point has been made. :)
Why is then try-catch-finally an anti-pattern? Here's why:
try{
db.UpdateAll(somevalue);
}
catch (Exception ex) {
logger.Exception(ex, "UpdateAll method failed");
throw;
}
finally {
db.Close();
}
What happens if the db object has already been closed? A new exception is thrown and it has to be handled! This is better:
try{
using(IDatabase db = DatabaseFactory.CreateDatabase()) {
db.UpdateAll(somevalue);
}
}
catch (Exception ex) {
logger.Exception(ex, "UpdateAll method failed");
throw;
}
Or, if the db object does not implement IDisposable do this:
try{
try {
IDatabase db = DatabaseFactory.CreateDatabase();
db.UpdateAll(somevalue);
}
finally{
db.Close();
}
}
catch (DatabaseAlreadyClosedException dbClosedEx) {
logger.Exception(dbClosedEx, "Database connection was closed already.");
}
catch (Exception ex) {
logger.Exception(ex, "UpdateAll method failed");
throw;
}
That's my 2 cents anyway! :)
A: I generally prefer return codes because they let the caller decide whether the failure is exceptional.
This approach is typical in the Elixir language.
# I care whether this succeeds. If it doesn't return :ok, raise an exception.
:ok = File.write(path, content)
# I don't care whether this succeeds. Don't check the return value.
File.write(path, content)
# This had better not succeed - the path should be read-only to me.
# If I get anything other than this error, raise an exception.
{:error, :erofs} = File.write(path, content)
# I want this to succeed but I can handle its failure
case File.write(path, content) do
:ok => handle_success()
error => handle_error(error)
end
People mentioned that return codes can cause you to have a lot of nested if statements, but that can be handled with better syntax. In Elixir, the with statement lets us easily separate a series of happy-path return value from any failures.
with {:ok, content} <- get_content(),
:ok <- File.write(path, content) do
IO.puts "everything worked, happy path code goes here"
else
# Here we can use a single catch-all failure clause
# or match every kind of failure individually
# or match subsets of them however we like
_some_error => IO.puts "one of those steps failed"
_other_error => IO.puts "one of those steps failed"
end
Elixir still has functions that raise exceptions. Going back to my first example, I could do either of these to raise an exception if the file can't be written.
# Raises a generic MatchError because the return value isn't :ok
:ok = File.write(path, content)
# Raises a File.Error with a descriptive error message - eg, saying
# that the file is read-only
File.write!(path, content)
If I, as the caller, know that I want to raise an error if the write fails, I can choose to call File.write! instead of File.write.
Or I can choose to call File.write and handle each of the possible reasons for failure differently.
Of course it's always possible to rescue an exception if we want to. But compared to handling an informative return value, it seems awkward to me. If I know that a function call can fail or even should fail, its failure isn't an exceptional case.
A: According to Chapter 7 titled "Exceptions" in Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries, numerous rationales are given for why using exceptions over return values is necessary for OO frameworks such as C#.
Perhaps this is the most compelling reason (page 179):
"Exceptions integrate well with object-oriented languages. Object-oriented languages tend to impose constraints on member signatures that are not imposed by functions in non-OO languages. For example, in the case of constructors, operator overloads, and properties, the developer has no choice in the return value. For this reason, it is not possible to standardize on return-value-based error reporting for object-oriented frameworks. An error reporting method, such as exceptions, which is out of band of the method signature is the only option."
A: With any decent compiler or runtime environment exceptions do not incur a significant penalty. It's more or less like a GOTO statement that jumps to the exception handler. Also, having exceptions caught by a runtime environment (like the JVM) helps isolating and fixing a bug a lot easier. I'll take a NullPointerException in Java over a segfault in C any day.
A: I prefer to use exceptions for error handling and return values (or parameters) as the normal result of a function. This gives an easy and consistent error-handling scheme and if done correctly it makes for much cleaner looking code.
A: One of the big differences is that exceptions force you to handle an error, whereas error return codes can go unchecked.
Error return codes, if used heavily, can also cause very ugly code with lots of if tests similar to this form:
if(function(call) != ERROR_CODE) {
do_right_thing();
}
else {
handle_error();
}
Personally I prefer to use exceptions for errors that SHOULD or MUST be acted upon by the calling code, and only use error codes for "expected failings" where returning something is actually valid and possible.
A: There is many reason to prefer Exceptions over return code:
*
*Usually, for readibility, people try to minimize the number of return statement in a method. Doing so, exceptions prevent to do some extra work while in a incoorect state, and thus prevent to potentially damage more data.
*Exception are generally more verbose arn more easilly extensible than return value. Assume that a method return natural number and that you use negative numbers as return code when an error occurs, if the scope of you method change and now return integers, you'll have to modify all the method calls instead of just tweaking a little bit the exception.
*Exceptions allows more easilly to separate error handling of normal behaviour. They allows to ensure that some operations performs somehow as an atomic operation.
A: For some languages (i.e. C++) Resources leak should not be a reason
C++ is based on RAII.
If you have code that could fail, return or throw (that is, most normal code), then you should have your pointer wrapped inside a smart pointer (assuming you have a very good reason to not have your object created on stack).
Return codes are more verbose
They are verbose, and tend to develop into something like:
if(doSomething())
{
if(doSomethingElse())
{
if(doSomethingElseAgain())
{
// etc.
}
else
{
// react to failure of doSomethingElseAgain
}
}
else
{
// react to failure of doSomethingElse
}
}
else
{
// react to failure of doSomething
}
In the end, you code is a collection of idented instructions (I saw this kind of code in production code).
This code could well be translated into:
try
{
doSomething() ;
doSomethingElse() ;
doSomethingElseAgain() ;
}
catch(const SomethingException & e)
{
// react to failure of doSomething
}
catch(const SomethingElseException & e)
{
// react to failure of doSomethingElse
}
catch(const SomethingElseAgainException & e)
{
// react to failure of doSomethingElseAgain
}
Which cleanly separate code and error processing, which can be a good thing.
Return codes are more brittle
If not some obscure warning from one compiler (see "phjr" 's comment), they can easily be ignored.
With the above examples, assume than someone forgets to handle its possible error (this happens...). The error is ignored when "returned", and will possibly explode later (i.e. a NULL pointer). The same problem won't happen with exception.
The error won't be ignored. Sometimes, you want it to not explode, though... So you must chose carefully.
Return Codes must sometimes be translated
Let's say we have the following functions:
*
*doSomething, which can return an int called NOT_FOUND_ERROR
*doSomethingElse, which can return a bool "false" (for failed)
*doSomethingElseAgain, which can return an Error object (with both the __LINE__, __FILE__ and half the stack variables.
*doTryToDoSomethingWithAllThisMess which, well... Use the above functions, and return an error code of type...
What is the type of the return of doTryToDoSomethingWithAllThisMess if one of its called functions fail ?
Return Codes are not a universal solution
Operators cannot return an error code. C++ constructors can't, too.
Return Codes means you can't chain expressions
The corollary of the above point. What if I want to write:
CMyType o = add(a, multiply(b, c)) ;
I can't, because the return value is already used (and sometimes, it can't be changed). So the return value becomes the first parameter, sent as a reference... Or not.
Exception are typed
You can send different classes for each kind of exception. Ressources exceptions (i.e. out of memory) should be light, but anything else could be as heavy as necessary (I like the Java Exception giving me the whole stack).
Each catch can then be specialized.
Don't ever use catch(...) without re-throwing
Usually, you should not hide an error. If you do not re-throw, at the very least, log the error in a file, open a messagebox, whatever...
Exception are... NUKE
The problem with exception is that overusing them will produce code full of try/catches. But the problem is elsewhere: Who try/catch his/her code using STL container? Still, those containers can send an exception.
Of course, in C++, don't ever let an exception exit a destructor.
Exception are... synchronous
Be sure to catch them before they bring out your thread on its knees, or propagate inside your Windows message loop.
The solution could be mixing them?
So I guess the solution is to throw when something should not happen. And when something can happen, then use a return code or a parameter to enable to user to react to it.
So, the only question is "what is something that should not happen?"
It depends on the contract of your function. If the function accepts a pointer, but specifies the pointer must be non-NULL, then it is ok to throw an exception when the user sends a NULL pointer (the question being, in C++, when didn't the function author use references instead of pointers, but...)
Another solution would be to show the error
Sometimes, your problem is that you don't want errors. Using exceptions or error return codes are cool, but... You want to know about it.
In my job, we use a kind of "Assert". It will, depending on the values of a configuration file, no matter the debug/release compile options:
*
*log the error
*open a messagebox with a "Hey, you have a problem"
*open a messagebox with a "Hey, you have a problem, do you want to debug"
In both development and testing, this enable the user to pinpoint the problem exactly when it is detected, and not after (when some code cares about the return value, or inside a catch).
It is easy to add to legacy code. For example:
void doSomething(CMyObject * p, int iRandomData)
{
// etc.
}
leads a kind of code similar to:
void doSomething(CMyObject * p, int iRandomData)
{
if(iRandomData < 32)
{
MY_RAISE_ERROR("Hey, iRandomData " << iRandomData << " is lesser than 32. Aborting processing") ;
return ;
}
if(p == NULL)
{
MY_RAISE_ERROR("Hey, p is NULL !\niRandomData is equal to " << iRandomData << ". Will throw.") ;
throw std::some_exception() ;
}
if(! p.is Ok())
{
MY_RAISE_ERROR("Hey, p is NOT Ok!\np is equal to " << p->toString() << ". Will try to continue anyway") ;
}
// etc.
}
(I have similar macros that are active only on debug).
Note that on production, the configuration file does not exist, so the client never sees the result of this macro... But it is easy to activate it when needed.
Conclusion
When you code using return codes, you're preparing yourself for failure, and hope your fortress of tests is secure enough.
When you code using exception, you know that your code can fail, and usually put counterfire catch at chosen strategic position in your code. But usually, your code is more about "what it must do" then "what I fear will happen".
But when you code at all, you must use the best tool at your disposal, and sometimes, it is "Never hide an error, and show it as soon as possible". The macro I spoke above follow this philosophy.
A: My preference (in C++ and Python) is to use exceptions. The language-provided facilities make it a well-defined process to both raise, catch and (if necessary) re-throw exceptions, making the model easy to see and use. Conceptually, it's cleaner than return codes, in that specific exceptions can be defined by their names, and have additional information accompanying them. With a return code, you're limited to just the error value (unless you want to define an ReturnStatus object or something).
Unless the code you're writing is time-critical, the overhead associated with unwinding the stack is not significant enough to worry about.
A: I only use exceptions, no return codes. I'm talking about Java here.
The general rule I follow is if I have a method called doFoo() then it follows that if it doesn't "do foo", as it were, then something exceptional has happened and an Exception should be thrown.
A: One thing I fear about exceptions is that throwing an exception will screw up code flow. For example if you do
void foo()
{
MyPointer* p = NULL;
try{
p = new PointedStuff();
//I'm a module user and I'm doing stuff that might throw or not
}
catch(...)
{
//should I delete the pointer?
}
}
Or even worse what if I deleted something I shouldn't have, but got thrown to catch before I did the rest of the cleanup. Throwing put a lot of weight on the poor user IMHO.
A: My general rule in the exception vs. return code argument:
*
*Use errorcodes when you need localization/internationalization -- in .NET, you could use these errorcodes to reference a resource file which will then display the error in the appropriate language. Otherwise, use exceptions
*Use exceptions only for errors that are really exceptional. If it's something that happens fairly often, either use a boolean or an enum errorcode.
A: I don't find return codes to be less ugly than exceptions. With the exception, you have the try{} catch() {} finally {} where as with return codes you have if(){}. I used to fear exceptions for the reasons given in the post; you don't know if the pointer needs to be cleared, what have you. But I think you have the same problems when it comes to the return codes. You don't know the state of the parameters unless you know some details about the function/method in question.
Regardless, you have to handle the error if possible. You can just as easily let an exception propagate to the top level as ignore a return code and let the program segfault.
I do like the idea of returning a value (enumeration?) for results and an exception for an exceptional case.
A: For a language like Java, I would go with Exception because the compiler gives compile time error if exceptions are not handled.This forces the calling function to handle/throw the exceptions.
For Python, I am more conflicted. There is no compiler so it's possible that caller does not handle the exception thrown by the function leading to runtime exceptions. If you use return codes you might have unexpected behavior if not handled properly and if you use exceptions you might get runtime exceptions.
A: There are some important aspects that remain unmentioned in this - very interesting - discussion so far.
First, it is important to note that exceptions don't apply to distributed computing, but error codes still do. Imagine communicating services distributed over multiple servers. Some communication might even be asynchronous. And the services might even use different technology stacks. Cleary, an error-handling concept is crucial here. And clearly, exceptions can't be used in this most general case, since errors have to be serialized things sent "through the cable", perhaps even in a language-neutral way. From that angle, error codes (really, error messages) are more universal than exceptions. One needs good error-message Kung Fu once one assumes a system-architect view and things need to scale.
The second point is a very different, it is about if or how a language represents discriminated unions. The question was strictly speaking about "error codes". And so were some the answers, mentioning that error codes cannot transport information as nicely as exceptions. This is true if an error code is a number. But for a fairer contrasting with exceptions, one should probably consider error values of discriminated union type. So, the return value of the callee would be of discriminated union type, and it would either be the desired happy-path value or the payload the exception would otherwise have. How often this approach is elegant enough to be preferable depends on the programming language. For example, F# has super elegant discriminated unions and the according pattern matching. In such a language it would be more seductive to avoid exceptions than in, say, C++.
The third and final point is about functional programming and pure functions. Exceptions are (in a practical way and in a theoretical-computer-science way) "side effects". In other words, functions or methods that deal with exceptions are not pure. (One practical consequence is that with exceptions one must pay attention to evaluation order.) By contrast, error values are pure, because the are just ordinary return values, with no side effects involved. Therefore, functional programmers may more likely frown upon exceptions than object-oriented programmers. (In particular if the language also has an elegant representation of the aforementioned discriminated unions.)
A: I prefer exceptions over return codes.
Consider a scenario when I call a function foo and forget to handle potential errors (exceptions).
*
*If errors in foo are passed via return codes (error codes),
*
*at compile time, I won't be alerted
*if I run the code
*
*if the error doesn't happen, I don't notice my mistake
*if the error happens but doesn't affect the code after calling foo, I don't notice my mistake
*if the error happens and affects the code after calling foo, I notice my mistake, but it may be hard to locate the problem
*If errors in foo are passed via exceptions that are thrown,
*
*at compile time, I won't be alerted
*if I run the code
*
*if the error doesn't happen, I don't notice my mistake
*if the error happens, I'm assured to notice my mistake
From the comparison above, my conclusion is that exceptions are better than error codes.
However, exceptions are not perfect. There are at least two critical problems:
*
*As discussed above, if I forget to handle a potential exception, I won't be alerted until I run the code and the exception is actually thrown.
*It's hard to determine all the exceptions foo may throw, especially when foo calls other functions (which may also throw exceptions).
A feature in Java, “checked exceptions”, solves both problems.
In Java, when defining a function foo, I'm required to explicitly specify what exceptions it may throw using the throws keyword. Example:
private static void foo() throws FileNotFoundException {
File file = new File("not_existing_file.txt");
FileInputStream stream = new FileInputStream(file);
}
If I call foo and forget to handle the potential FileNotFoundException, the compiler produces an error. I get alerted at compile time (problem 1 solved). And all possible exceptions are listed explicitly (problem 2 solved).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/99683",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "103"
}
|
Q: Message passing between objects - How to refer to the target object? The most basic task in an object oriented environment is executing a method on an object. To do this, you have to have a reference to the object on which you are invoking the method. Is the proper way to establish this reference to pass the object as a parameter to the constructor (or initializer method) of the calling object?
If object foo calls into object bar, is it correct to say (in pseudo-code):
bar = new barClass()
foo = new fooClass(bar)
What happens if you need to pass messages back and forth? Do you need a method for registering the target object?
foo = new fooClass()
bar = new barClass()
foo.register(bar)
bar.register(foo)
Is there a pattern that addresses this?
A: Dependency injection frameworks like Spring and Guice provide a solution to cyclical dependencies in Java by using proxies which can resolve the receiver of a message the first time it is required. This isn't a generally applicable OO pattern, however.
A: Generally dependency injection is the way to go. If you're just talking about two objects communicating then pass an instance of one in as a paramter to the other, as in your first example. Passing in the constructor ensure the reference is always valid. Otherwise you'd have to test to ensure register had been called. Also you'd need to make sure calling register more than once wouldn't have adverse effects.
What if you want a controlling object, to which other objects register for events. It would then be suitable to use a Register method ( which may add to a delegate).
See Observer Pattern
A: Well, depending on the level of messaging, you could implement a messaging service. Objects listen for messages, or register as a MessageListener on some MessageProvider.
You end up with cyclical dependencies if two objects have references to each other, which I would consider bad in most cases.
A: One of your object types could be a factory for the other. When Foo poops out a new Bar, the connection has already been made:
foo = new Foo();
bar = Foo.Poop();
function Foo::Poop()
{
bar = new Bar(this);
myChildren.Add(bar);
return bar;
}
bar.SayHiToParent();
foo.SayHiToChildren();
A: I think that it highly depends on what the exact relation is between the two objects.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/99684",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Why do C# and VB have Generics? What benefit do they provide? Generics, FTW From Wikipedia:
Generic programming is a style of
computer programming in which
algorithms are written in terms of
to-be-specified-later types that are
then instantiated when needed for
specific types provided as parameters
and was pioneered by Ada which
appeared in 1983. This approach
permits writing common functions or
types that differ only in the set of
types on which they operate when used,
thus reducing duplication.
Generics provide the ability to define types that are specified later. You don't have to cast items to a type to use them because they are already typed.
Why does C# and VB have Generics? What benefit do they provide? What benefits do you find using them?
What other languages also have generics?
A: C# and VB have generics to take advantage of generics support in the underlying CLR (or is the other way around?). They allow you to write code ina statically-typed language that can apply to more than one kind of type without rewriting the code for each type you use them for (the runtime will do that for you) or otherwise using System.Object and casting everywhere (like we had to do with ArrayList).
Did you read the article?
These languages also have generics:
*
*C++ (via templates)
*Ada (via templates)
*Eiffel
*D (via templates)
*Haskell
*Java
A: Personally, I think they allows to save a lot of time. I'm still using .NET Framework 1.1 and every time you want a specific collection, you need to create a strongly typed collection by implementing CollectionBase. With Generics, you just need to declare your collection like that List<MyObject> and it's done.
A: Consider these method signatures:
//Old and busted
public abstract class Enum
{
public static object Parse(Type enumType, string value);
}
//To call it:
MyEnum x = (MyEnum) Enum.Parse(typeof(MyEnum), someString);
//New and groovy
public abstract class Enum
{
public static T Parse<T>(string value);
}
//To call it:
MyEnum x = Enum.Parse<MyEnum>(someString);
Look ma: No runtime type manipulation.
A: From MSDN:
Generics provide the solution to a
limitation in earlier versions of the
common language runtime and the C#
language in which generalization is
accomplished by casting types to and
from the universal base type Object.
By creating a generic class, you can
create a collection that is type-safe
at compile-time.
Read the rest of that article to see some examples of how Generics can improve the readability and performance of your code.
A: Probably the most common use for them is having strongly typed ArrayLists. In .NET 1.1, you'd either have to cast everything from object to your desired Type, or use something like CodeSmith to generate a strongly typed ArrayList.
Additionally, they help decrease boxing. Again, in .NET 1.x, if you tried to use an ArrayList with a Value Type, you'd end up boxing and unboxing the objects all over the place. Generics avoid that by letting you define the Type, whether Reference or Value.
There are other handy uses for them too, event handlers, LINQ queries, etc.
A: Generics in .NET are excellent for object collections. You can define your object type however you want and be able to have, say, a List without writing any code for that, and have access to all the efficient functionality of the .NET List generic collection while being type-safe to T. It's great stuff.
A: Generics are build on the concept of templates in c++ if you are familiar with them.
Its a way to implement an algorithm or data structure but delaying the actual type it is used on.
List can then be assigned with any type of your choice int, string and even custom types the type is assigned on construction of the list. But you will be able to use the list operations add remove etc.
You can really save a lot of coding effort by getting used to generics. And you don't have to box and unbox between types.
Java have generics as well. They are called wildcards.
A: Generics in .net, like inheritence and extension methods, allows for reduction of code duplication. Let me explain by way of refactoring.
If all classes with a common ancestor have a common method, place the common method in the classes' common ancestor (inheritence).
If some classes have a common method that uses a public contract to achieve some result, make the common method into an extension method on that public contract.
If some several methods or classes have the same code that differs only by the types acted upon (especially where the details of the type are not relevant to the operation of the method), collect those methods or classes into a generic.
A: They increase performance for collections using value types, since no boxing/unboxing will be required. They're a lot cleaner to use since you won't have to cast an object (for example using ArrayList) to the desired type - and likewise they help enforce type safety.
A: Biggest advantage of generics over non generic types in C# (not Java, Java is a different story) is that they are much faster. The JIT generates the best machine code it can come up with for a given type. List<int> is actually a list of ints and not integer objects wrapping an int. This makes generic types awesomely fast and also type safe which can help you detect an awesome lot of errors at compile time :)
A: The common example is collections. e.g. a set of type T, as an Add(T) method and a T get() method. Same code, different type safe collections.
C++, D, Ada and others have templates, a superset of generics that do it a little different bug get the same end result (and then some).
IIRC Java has generics, but I don't do Java.
A: The easiest way to explain it is to give an example. Say you want two hashtables, one that maps objects of type string to type int and one that maps objects of type string to type double. You could define Hashtable and then use the K and V types. Without generics, you'd have to use the 'object' type which, in addition to having to be cast to be meaningful, gives up typesafety. Just instantiate Hashtable and Hashtable and you've got your hash tables with proper typechecking and all.
A: Java also has generics. C++ has templates.
Dynamic languages like Perl and Javascript don't have the same type restrictions so they get mostly the same benefits with less work.
A: In objective-C you can use protocols to achieve the aims of generics. Since the language is weakly typed however, it's generally not as much of a concern as when you are fighting the type system to use one code path for many types.
A: Personally I am a huge fan of generics because of all of the code I don't have to write.
What is Inversion of Control?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/99686",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Private vs. Public members in practice (how important is encapsulation?) One of the biggest advantages of object-oriented programming is encapsulation, and one of the "truths" we've (or, at least, I've) been taught is that members should always be made private and made available via accessor and mutator methods, thus ensuring the ability to verify and validate the changes.
I'm curious, though, how important this really is in practice. In particular, if you've got a more complicated member (such as a collection), it can be very tempting to just make it public rather than make a bunch of methods to get the collection's keys, add/remove items from the collection, etc.
Do you follow the rule in general? Does your answer change depending on whether it's code written for yourself vs. to be used by others? Are there more subtle reasons I'm missing for this obfuscation?
A: Yes, encapsulation matters. Exposing the underlying implementation does (at least) two things wrong:
*
*Mixes up responsibilities. Callers shouldn't need or want to understand the underlying implementation. They should just want the class to do its job. By exposing the underlying implementation, you're class isn't doing its job. Instead, it's just pushing the responsibility onto the caller.
*Ties you to the underlying implementation. Once you expose the underlying implementation, you're tied to it. If you tell callers, e.g., there's a collection underneath, you cannot easily swap the collection for a new implementation.
These (and other) problems apply regardless of whether you give direct access to the underlying implementation or just duplicate all the underlying methods. You should be exposing the necessary implementation, and nothing more. Keeping the implementation private makes the overall system more maintainable.
A: I prefer to keep members private as long as possible and only access em via getters, even from within the very same class. I also try to avoid setters as a first draft to promote value style objects as long as it is possible. Working with dependency injection a lot you often have setters but no getters, as clients should be able to configure the object but (others) not get to know what's acutally configured as this is an implementation detail.
Regards,
Ollie
A: I tend to follow the rule pretty strictly, even when it's just my own code. I really like Properties in C# for that reason. It makes it really easy to control what values it's given, but you can still use them as variables. Or make the set private and the get public, etc.
A: Basically, information hiding is about code clarity. It's designed to make it easier for someone else to extend your code, and prevent them from accidentally creating bugs when they work with the internal data of your classes. It's based on the principle that nobody ever reads comments, especially ones with instructions in them.
Example: I'm writing code that updates a variable, and I need to make absolutely sure that the Gui changes to reflect the change, the easiest way is to add an accessor method (aka a "Setter"), which is called instead of updating data is updated.
If I make that data public, and something changes the variable without going through the Setter method (and this happens every swear-word time), then someone will need to spend an hour debugging to find out why the updates aren't being displayed. The same applies, to a lesser extent, to "Getting" data. I could put a comment in the header file, but odds are that no-one will read it till something goes terribly, terribly wrong. Enforcing it with private means that the mistake can't be made, because it'll show up as an easily located compile-time bug, rather than a run-time bug.
From experience, the only times you'd want to make a member variable public, and leave out Getter and Setter methods, is if you want to make it absolutely clear that changing it will have no side effects; especially if the data structure is simple, like a class that simply holds two variables as a pair.
This should be a fairly rare occurence, as normally you'd want side effects, and if the data structure you're creating is so simple that you don't (e.g a pairing), there will already be a more efficiently written one available in a Standard Library.
With that said, for most small programs that are one-use no-extension, like the ones you get at university, it's more "good practice" than anything, because you'll remember over the course of writing them, and then you'll hand them in and never touch the code again. Also, if you're writing a data structure as a way of finding out about how they store data rather than as release code, then there's a good argument that Getters and Setters will not help, and will get in the way of the learning experience.
It's only when you get to the workplace or a large project, where the probability is that your code will be called to by objects and structures written by different people, that it becomes vital to make these "reminders" strong. Whether or not it's a single man project is surprisingly irrelevant, for the simple reason that "you six weeks from now" is as different person as a co-worker. And "me six weeks ago" often turns out to be lazy.
A final point is that some people are pretty zealous about information hiding, and will get annoyed if your data is unnecessarily public. It's best to humour them.
A: As someone having to maintain several-year-old code worked on by many people in the past, it's very clear to me that if a member attribute is made public, it is eventually abused. I've even heard people disagreeing with the idea of accessors and mutators, as that's still not really living up to the purpose of encapsulation, which is "hiding the inner workings of a class". It's obviously a controversial topic, but my opinion would be "make every member variable private, think primarily about what the class has got to do (methods) rather than how you're going to let people change internal variables".
A: It depends. This is one of those issues that must be decided pragmatically.
Suppose I had a class for representing a point. I could have getters and setters for the X and Y coordinates, or I could just make them both public and allow free read/write access to the data. In my opinion, this is OK because the class is acting like a glorified struct - a data collection with maybe some useful functions attached.
However, there are plenty of circumstances where you do not want to provide full access to your internal data and rely on the methods provided by the class to interact with the object. An example would be an HTTP request and response. In this case it's a bad idea to allow anybody to send anything over the wire - it must be processed and formatted by the class methods. In this case, the class is conceived of as an actual object and not a simple data store.
It really comes down to whether or not verbs (methods) drive the structure or if the data does.
A: C# Properties 'simulate' public fields. Looks pretty cool and the syntax really speeds up creating those get/set methods
A: Keep in mind the semantics of invoking methods on an object. A method invocation is a very high level abstraction that can be implemented my the compiler or the run time system in a variety of different ways.
If the object who's method you are invoking exists in the same process/ memory map then a method could well be optimized by a compiler or VM to directly access the data member. On the other hand if the object lives on another node in a distributed system then there is no way that you can directly access it's internal data members, but you can still invoke its methods my sending it a message.
By coding to interfaces you can write code that doesn't care where the target object exists or how it's methods are invoked or even if it's written in the same language.
In your example of an object that implements all the methods of a collection, then surely that object actually is a collection. so maybe this would be a case where inheritance would be better than encapsulation.
A: It's all about controlling what people can do with what you give them. The more controlling you are the more assumptions you can make.
Also, theorectically you can change the underlying implementation or something, but since for the most part it's:
private Foo foo;
public Foo getFoo() {}
public void setFoo(Foo foo) {}
It's a little hard to justify.
A: Encapsulation is important when at least one of these holds:
*
*Anyone but you is going to use your class (or they'll break your invariants because they don't read the documentation).
*Anyone who doesn't read the documentation is going to use your class (or they'll break your carefully documented invariants). Note that this category includes you-two-years-from-now.
*At some point in the future someone is going to inherit from your class (because maybe an extra action needs to be taken when the value of a field changes, so there has to be a setter).
If it is just for me, and used in few places, and I'm not going to inherit from it, and changing fields will not invalidate any invariants that the class assumes, only then I will occasionally make a field public.
A: My tendency is to try to make everything private if possible. This keeps object boundaries as clearly defined as possible and keeps the objects as decoupled as possible. I like this because when I have to rewrite an object that I botched the first (second, fifth?) time, it keeps the damage contained to a smaller number of objects.
If you couple the objects tightly enough, it may be more straightforward just to combine them into one object. If you relax the coupling constraints enough you're back to structured programming.
It may be that if you find that a bunch of your objects are just accessor functions, you should rethink your object divisions. If you're not doing any actions on that data it may belong as a part of another object.
Of course, if you're writing a something like a library you want as clear and sharp of an interface as possible so others can program against it.
A: Fit the tool to the job... recently I saw some code like this in my current codebase:
private static class SomeSmallDataStructure {
public int someField;
public String someOtherField;
}
And then this class was used internally for easily passing around multiple data values. It doesn't always make sense, but if you have just DATA, with no methods, and you aren't exposing it to clients, I find it a quite useful pattern.
The most recent use I had of this was a JSP page where I had a table of data being displayed, defined at the top declaratively. So, initially it was in multiple arrays, one array per data field... this ended in the code being rather difficult to wade through with fields not being next to eachother in definition that would be displayed together... so I created a simple class like above which would pull it together... the result was REALLY readable code, a lot more so than before.
Moral... sometimes you should consider "accepted bad" alternatives if they may make the code simpler and easier to read, as long as you think it through and consider the consequences... don't blindly accept EVERYTHING you hear.
That said... public getters and setters is pretty much equivalent to public fields... at least essentially (there is a tad more flexibility, but it is still a bad pattern to apply to EVERY field you have).
Even the java standard libraries has some cases of public fields.
A: When I make objects meaningful they are easier to use and easier to maintain.
For example: Person.Hand.Grab(howquick, howmuch);
The trick is not to think of members as simple values but objects in themselves.
A: I would argue that this question does mix-up the concept of encapsulation with 'information hiding'
(this is not a critic, since it does seem to match a common interpretation of the notion of 'encapsulation')
However for me, 'encapsulation' is either:
*
*the process of regrouping several items into a container
*the container itself regrouping the items
Suppose you are designing a tax payer system. For each tax payer, you could encapsulate the notion of child into
*
*a list of children representing the children
*a map of to takes into account children from different parents
*an object Children (not Child) which would provide the needed information (like total number of children)
Here you have three different kinds of encapsulations, 2 represented by low-level container (list or map), one represented by an object.
By making those decisions, you do not
*
*make that encapsulation public or protected or private: that choice of 'information hiding' is still to be made
*make a complete abstraction (you need to refine the attributes of object Children and you may decide to create an object Child, which would keep only the relevant informations from the point of view of a tax payer system)
Abstraction is the process of choosing which attributes of the object are relevant to your system, and which must be completely ignored.
So my point is:
That question may been titled:
Private vs. Public members in practice (how important is information hiding?)
Just my 2 cents, though. I perfectly respect that one may consider encapsulation as a process including 'information hiding' decision.
However, I always try to differentiate 'abstraction' - 'encapsulation' - 'information hiding or visibility'.
A: @VonC
You might find the International Organisation for Standardization's, "Reference Model of Open Distributed Processing," an interesting read. It defines: "Encapsulation: the property that the information contained in an object is accessible only through interactions at the interfaces supported by the object."
I tried to make a case for information hiding's being a critical part of this definition here:
http://www.edmundkirwan.com/encap/s2.html
Regards,
Ed.
A: I find lots of getters and setters to be a code smell that the structure of the program is not designed well. You should look at the code that uses those getters and setters, and look for functionality that really should be part of the class. In most cases, the fields of a class should be private implementation details and only the methods of that class may manipulate them.
Having both getters and setters is equal to the field being public (when the getters and setters are trivial/generated automatically). Sometimes it might be better to just declare the fields public, so that the code will be more simple, unless you need polymorphism or a framework requires get/set methods (and you can't change the framework).
But there are also cases where having getters and setters is a good pattern. One example:
When I create the GUI of an application, I try to keep the behaviour of the GUI in one class (FooModel) so that it can be unit tested easily, and have the visualization of the GUI in another class (FooView) which can be tested only manually. The view and model are joined with simple glue code; when the user changes the value of field x, the view calls setX(String) on the model, which in turn may raise an event that some other part of the model has changed, and the view will get the updated values from the model with getters.
In one project, there is a GUI model which has 15 getters and setters, of which only 3 get methods are trivial (such that the IDE could generate them). All the others contain some functionality or non-trivial expressions, such as the following:
public boolean isEmployeeStatusEnabled() {
return pinCodeValidation.equals(PinCodeValidation.VALID);
}
public EmployeeStatus getEmployeeStatus() {
Employee employee;
if (isEmployeeStatusEnabled()
&& (employee = getSelectedEmployee()) != null) {
return employee.getStatus();
}
return null;
}
public void setEmployeeStatus(EmployeeStatus status) {
getSelectedEmployee().changeStatusTo(status, getPinCode());
fireComponentStateChanged();
}
A: In practice I always follow only one rule, the "no size fits all" rule.
Encapsulation and its importance is a product of your project. What object will be accessing your interface, how will they be using it, will it matter if they have unneeded access rights to members? those questions and the likes of them you need to ask yourself when working on each project implementation.
A: I base my decision on the Code's depth within a module.
If I'm writting code that is internal to a module, and does not interface with the outside world I don't encapsulate things with private as much because it affects my programmer performance (how fast I can write and rewrite my code).
But for the objects that server as the module's interface with user code, then I adhere to strict privacy patterns.
A: Certainly it makes a difference whether your writing internal code or code to be used by someone else (or even by yourself, but as a contained unit.) Any code that is going to be used externally should have a well defined/documented interface that you'll want to change as little as possible.
For internal code, depending on the difficulty, you may find it's less work to do things the simple way now, and pay a little penalty later. Of course Murphy's law will ensure that the short term gain will be erased many times over in having to make wide-ranging changes later on where you needed to change a class' internals that you failed to encapsulate.
A: Specifically to your example of using a collection that you would return, it seems possible that the implementation of such a collection might change (unlike simpler member variables) making the utility of encapsulation higher.
That being said, I kinda like Python's way of dealing with it. Member variables are public by default. If you want to hide them or add validation there are techniques provided, but those are considered the special cases.
A: I follow the rules on this almost all the time. There are four scenarios for me - basically, the rule itself and several exceptions (all Java-influenced):
*
*Usable by anything outside of the current class, accessed via getters/setters
*Internal-to-class usage typically preceded by 'this' to make it clear that it's not a method parameter
*Something meant to stay extremely small, like a transport object - basically a straight shot of attributes; all public
*Needed to be non-private for extension of some sort
A: There's a practical concern here that isn't being addressed by most of the existing answers. Encapsulation and the exposure of clean, safe interfaces to outside code is always great, but it's much more important when the code you're writing is intended to be consumed by a spatially- and/or temporally-large "user" base. What I mean is that if you plan on somebody (even you) maintaining the code well into the future, or if you're writing a module that will interface with code from more than a handful of other developers, you need to think much more carefully than if you're writing code that's either one-off or wholly written by you.
Honestly, I know what wretched software engineering practice this is, but I'll oftentimes make everything public at first, which makes things marginally faster to remember and type, then add encapsulation as it makes sense. Refactoring tools in most popular IDEs these days makes which approach you use (adding encapsulation vs. taking it away) much less relevant than it used to be.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/99688",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "22"
}
|
Q: Maintaining Automated Browser UI Testing What's the best way to manage a slew of browser UI tests? I'm looking for an approach that may have worked for you in the past when dealing with numerous automated browser tests. Obvious answers such as "they should be refactored into lower-level UI tests" aren't what I'm looking for. Ultimately these tests are incredibly time consuming to both run and maintain. I'm looking for the best ways to minimize this problem.
I must also mention that I'm confined to free software that's particularly focused on .NET (WatiN, CC.net, Fitnesse, etc.).
A: In other threads about Web UI testing, Selenium was a popular and highly recommended choice.
A: Selenium is good, but kindof slow. Since unit tests should rarely (if ever) go out of process, they should be much faster than your selenium tests.
If you do use it for automated UI testing, I would put them all in a separate build which can run in parallel with your unit tests.
I prefer to treat my automated UI tests as regression tests.
A: Factor out common sequences of actions and just put them in one subtest each. Run only the subtests you need for any given feature.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/99716",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: What is the difference between, IsAssignableFrom and GetInterface? Using reflection in .Net, what is the differnce between:
if (foo.IsAssignableFrom(typeof(IBar)))
And
if (foo.GetInterface(typeof(IBar).FullName) != null)
Which is more appropriate, why?
When could one or the other fail?
A: If you just want to see if a type implements a given interface, either is fine, though GetInterface() is probably faster since IsAssignableFrom() does more internal checks than GetInterface(). It'll probably even faster to check the results of Type.GetInterfaces() which returns the same internal list that both of the other methods use anyway.
A: Edit: This answer is wrong! Please see comments.
There is a difference in how internal classes are handled. Take the following class:
public interface IFoo
{
}
internal class Foo: IFoo
{
}
This will give you a list of one item:
var types = typeof(IFoo).Assembly.GetTypes()
.Where(x => x.GetInterface(typeof(IFoo).FullName) != null)
.ToList();
Whereas this will give you an empty list:
var types = typeof(IFoo).Assembly.GetTypes()
.Where(x => x.IsAssignableFrom(typeof(IFoo))
.ToList();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/99732",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "19"
}
|
Q: What Are Some Decent ISPs That Host Subversion I want a recommendation on an ISP which has Subversion installed so I can get a repository started. So far I found out discount.asp doesn't have that on their servers and will not support it. So I'm looking for a recommendation
A: What's your price range?
Do you want a straght SVN provider or do you want to host a website too?
For Straight SVN Hosting Check out
http://cvsdude.com/
http://www.assembla.com/
Only Hosting provider I can think of with SVN support (outside of a VPS provider) would be
http://www.dreamhost.com
A: I'd like to second www.dreamhost.com as a superb solution / value for money.
I've been with them for about 2 years, there are limits on size/bandwidth, but they're so ridiculously high you can basically consider it unlimited for any reasonable project.
I've never had a server issue or any downtime (although I have heard others have). They seem open and trustworthy.
A: I haven't used them yet, but after reading about their offering, I am seriously considering using http://projectlocker.com/ for my next subversion based project. The have fairly cheap pricing (free up to $30 a month), and they recently got a plug from Scott Mitchell.
A: Are these sites trustworthy enough? After all they have your intellectual property on file. You don't want them to use it themselves or give it to your competitors.
A: I recommend http://beanstalkapp.com/
A: There are some restrictions on the free accounts (namely 200MB) but we've recently set up an account with Assembla for a small project. It provides SVN (optionally externally hosted), Trac, a wiki, and several other built-in tools, similar to SourceForge. Your project does not need to be open source.
A: I have been using wush.net for about 9 months and am pretty stoked. Especially considering the fact that you get integrated Trac when you upgrade to pro (which kinda pays for itself if you have a few repo's because you get discounts on the additional).
A: csoft.net is pretty good. They've been around for a long time, they're cheap, good, open source friendly, very geek friendly, and accounts come with SVN (and with the more expensive plans, a ton of other features). Also, ever tried to deal with frontline tech support at a big host (like, ick, 1&1) where you had a sneaking suspicion you were actually dealing with a very poorly programmed Eliza bot rather than a human? Yeah, well, csoft isn't like that. :-)
If you're looking for something a little more user friendly, you might check out Unfuddle. I haven't used them personally but they get a lot of good press here on SO, and they've got a nice feature set.
A: I use http://devguard.com/ . Very cheap, but also very reliable. Integrated Trac, SSL, web-based ACL and user management. SVN scripts, eg. commit hooks. I tried CVSDude before and that didn't work out.
A: I have an account with www.codespaces.com They have svn hosting, wiki, forum, project management, issue tracking and admin all built in. I have been using the service for 6 months and I am happy with the level of service they off.
A: I've used csoft.net for 6 years. They've been reliable, and inexpensive. Their documentation is good.
A: Site5 offers ssh access, which means you can use svn+ssh for very cheap repositories with practically unlimited size/bandwidth.
A: I will vote for Assembla, its big feature set can not be compared with unfuddle, beanstalkapp or any other svn only hosting provider.
A: I've used unfuddle for several projects, and I'm really happy with them. Their admin UI is great and they also have some project management tools that are fairly useful.
They have a free version that's decent if you don't need much.
A: I've used SVN through Dreamhost for quite some time and I've found them to be really good. A bit slow for me as I'm based in Australia but otherwise excellent
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/99743",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: How important do you think Progressive Enhancement is? Progressive Enhancement is a web development methodology that not only allows greater portability and accessibility but in my opinion, makes the development process easier.
What I want is to know what the rest of the community think of this approach.
In particular: What do you believe is the minimum set of technologies that a web application should support?
A: If it remains usable in a text-only browser (without CSS and Javascript, of course) and also in a screen-reader, you're on the right track. But these are about the highest standards that you'll find :)
A: I personally block referrers, cookies and JavaScript by default and re-enable them temporarily or permanently on a site-by-site basis.
I'll forgive a web site for not working without cookies for signed-in users, however I get quite upset when they won't work without JavaScript if it's being used for trivial purposes.
Minimum requirements: HTML with basic structural elements + links, HTML forms + maybe cookies for applications.
Site could be run in a vt100, a "normal" browser, a phone, a screen reader...
-z
A: I would feel comfortable targeting HTML4 and CSS2, with the basic content structured with screenreaders in mind as a baseline experience for most websites. The key is to keep in mind a layout that is functional for text-based browsers and screenreaders and use that as the basis for the enhanced page.
A:
So "Progressive Enhancement" is just
another term for "Graceful
Degradation"?
False. They are two different sides of the coin. It shows where your focus is.
Developing a site that is 100% useful without css, javascript, etc. and then adding all the pretty/fancy stuff for javascript users is an example of Progressive Enhancement.
However, when you code the site with fancy/pretty and then go back and turn off javascript and css to see how it looks, that is graceful degradation.
The group you focus on first really decides this. It is possible that you could arrive at the same conclusion but it is unlikely. Your focus determines the ending point really.
A: So "Progressive Enhancement" is just another term for "Graceful Degradation"?
In which case, it's the way all websites should be done.
Web Apps should be built in HTML (4 or later), semantically and against the standards.
All CSS should be optional - content & forms should work without it, but look prettier with it.
All JavaScript should be optional - pages & forms should work without, but work easier with it.
All code should be written according to the standards & checked in each major rendering engine - but don't work around flaws in browsers unless absolutely necessary; it's up to the browsers to respect standards, not developers to grovel after bad rendering engines.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/99748",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: How do I get the "Command Buffer" in Solaris 10? When working on a linx CShell u get the option to press the up / down arrows to select the last command/s typed or the Command Buffer. This even works on Windows.
However this is not functional when working on Solaris, to which i recently switched. I am guessing that the shell is also a CShell.
Please tell me what key combination is required to have this feature on Solaris ?
A: The default shell in Solaris has command history, but you can also use Bash instead, it's more user friendly. Just type 'bash' (no quotes) at the command line. You can also edit /etc/passwd to make bash your default shell.
A: The "official" default shell for Solaris is actually sh, the original Bourne shell (see Chapter 10 of the Advanced User Guide for Solaris for more info). If you'd like to change it to csh or tcsh—and you're not root (it's generally considered bad practice to use anything but sh as root's default)—just issue passwd -e /path/to/shell_of_your_choice <loginname>. I'm guessing this would probably look like passwd -e /bin/csh <loginname>, but you'd probably want to make sure it exists, first.
A: It may be that it's the Korn shell in which case try <ESC>k.
bash at least will allow you to switch modes with "set -o vi" or "set -o emacs".
A: Maybe you can use the !! command, to repeat the previous one.
A: Use "echo $SHELL" to see what your login shell is. If it's ksh or bash, try "set -o emacs". If that works, you'll be able to use ^P to go back a command. ^R lets you search for a command, ^F and ^B to move around within the command.
A: If you can´t change your default shell, or you just want to try out one that works, you can kick off any other shell from your command line. I recommend you tcsh, which will have good command line editing and history using the arrow keys. Type /bin/tcsh at your prompt to try it out. You can use the earlier responses to change your default shell if you like tcsh. Make sure your have the following in your $HOME/.cshrc file:
set filec
set history=1000 # or some other large number
set autologout=0 # if you are logging in remotely under your account.
I hope this helps.
A: You enable history temporarily if you use BASH by typing
HISTSIZE=1000
which will enable up and down keys and store 1000 commands. After termal disconnetion all history will be gone.
This works on solaris 10.
For permanent solution add these lines to ~/.bashrc
HISTSIZE=1000
HISTFILESIZE=1000
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/99755",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How can I create a directory listing of a subversion repository I have a client that is asking me to give them a listing of every file and folder in the source code (and then a brief explanation of the source tree). Is there an easy way to create some sort of decently formatted list like this from a subversion repository?
A: You'll want the list command. Assuming you're using the command line client
svn list -R http://example.com/path/to/repos
This will give you a full recursive list of everything that's in the repository. Redirect it to a text file
svn list -R http://example.com/path/to/repos > file.txt
and then format to your heart's content.
A: More generally, you can use the tree utility (in *Nix systems) to print out such a list for any directory structure. It is installed by default in many distros. If it isn't in yours, you might check the standard repositories for it. For example, in Ubuntu, with the default repositories, "sudo apt-get install tree" should do the trick. Alternatively, there's a shell script using sed that implements it here. Once you have tree, just cd to the directory you'd like to print the listing for and type "tree" (redirect it to a file if you like).
This does require that you have a checkout of the repository, but you'll probably already have one in most cases. Note that this will also include the .svn directories, which is kind of a pain, but you can always pipe the output through a "grep -v .svn" that will strip out these lines, possibly with some additional magic to take out anything "underneath" such a .svn-containing line in the hierarchy (using sed or a procedural shell-script loop or similar).
A: try: svn list -R
with the root of the branch you're trying to list.
A: Do a checkout, then drop into a command prompt, cd to the right directory, and type something like
dir /a:d /s /b > listing.txt
(Assuming that you're on Windows, of course.)
A: svn list -R svn://svnlocation
This should list all the files and folders, could outout this to a text file
A: Assuming it's available via HTTP - why not just give them a read-only login, and point them at the web address?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/99781",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: What JavaScript Repository should I use? Many languages have standard repositories where people donate useful libraries that they want others to have access to. For instance Perl has CPAN, PHP has PEAR, Ruby has RubyGems, and so on. What is the best option for JavaScript?
I ask because a few months ago I ported Statistics::Distributions from Perl to JavaScript. (When I say ported I mean, "Ran text substitutions, fixed a few things by hand." I did not rewrite it.) Since I've used this module a number of times in Perl, I figure that statistics-distributions.js is likely to be useful to someone. So I've put it under the same open source license as the original (your choice of the GPL or the Artistic License). But I have no idea where to put it so that people who might want it are likely to find it.
It doesn't fit into any sort of framework. It is just a standalone library that gives you the ability to calculate a number of useful statistics distributions to 5 digits of accuracy. In JavaScript.
A: JSAN (JavaScript Archive Network) sounds like the kind of thing you're looking for, but I've never personally used anything from it apart from Test.Builder.
As long as your JavaScript can be dropped in to people's projects without polluting the global namespace or doing things which are liable to cause breakage in other people's code (adding to Object.prototype, for example) I would just stick it somewhere like Google Code as already suggested.
A: There is no centralized repository for JavaScript. JS Libraries usually have their own plugin-repositories, but for stand-alone scripts, The best way to promote it is to send it to famous website such as ajaxian or mashable
A: AFAIK, there is no central JavaScript repository, but you might have success promoting it on Snipplr or as a project on Google Code.
A: You could start a project on SourceForge to contain useful snippets of code like this (or google for snippets to find one).
A: Perl, Ruby, PHP, etc all have distribution mechanisms built into the language to consume such libraries.
There's not such a thing built into JS.
There are tons of script archives out there - but no "central" JS repo.
A: Consider packaging it up as a plugin for one of the major Javascript libraries such as jQuery - see http://docs.jquery.com/Plugins/Authoring for more details. This way it can be included on their plugin page which will get it good exposure as they have a huge developer base and it'll be one of their first ports of call when a need arises for such functionality.
Whilst jQuery is one of the most popular frameworks (if not the most) out there, there are a host if other libraries you could consider using in addition to/instead of it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/99785",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: Is it safe to add delegates to events with keyword new? One thing I am concerned with is that I discovered two ways of registering delegates to events.
*
*OnStuff += this.Handle;
*OnStuff += new StuffEventHandler(this.Handle);
The first one is clean, and it makes sense doing "OnStuff -= this.Handle;" to unregister from the event... But with the latter case, should I do "OnStuff -= new StuffEventHandler(this.Handle);"? It feels like I am not removing anything at all, since I'm throwing in another StuffEventHandler reference. Does the event compare the delegate by reference? I am concerned I could start a nasty memory pool here. Get me? I don't have the reference to the "new StuffEventHandler" I previously registered.
What is the downside of doing #1?
What is benefit of doing #2?
A: You don't need to worry about keeping a reference to the originally registered delegate, and you will not start a "nasty memory pool".
When you call "OnStuff -= new StuffEventHandler(this.Handle);" the removal code does not compare the delegate you are removing by reference: it checks for equality by comparing references to the target method(s) that the delegate will call, and removes the matching delegates from "OnStuff".
By the way, "OnStuff" itself is a delegate object (the event keyword that I assume you have in your declaration simply restricts the accessibility of the delegate).
A: I was under the impression that 2 is just syntax sugar. They should be exactly the same thing.
A: Number one is just shorthand that will generate the same MSIL as the 2nd one, at compile type it'll look at this.Handle and infer the delegate to instantiate. But you should never unsubscribe by using new.
So there is no difference between the 2, just some syntactic sugar to make our code cleaner.
A: If I remember correctly, the first alternative is merely syntactic sugar for the second.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/99790",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: What problems do you encounter with VFP apps in a 64 bit environment? I know that there are issues with the VFP OLEDB provider on 64 bit machines. ... but what issues do you encounter while actually running a VFP application - on a 64 bit machine? Has anyone had any experience in this area?
My first thought was that it would just run as a 32bit app, without making use of the 64 bit power. However, I ran into difficulties with a FoxPro application connecting to a SQL Server database (probably an OLEDB issue as well). Are there other issues as well?
A: This is somewhat of a specialized scenario, and it may not be related to 64 bitness, but since you asked...
My organization recently hosted a legacy VFP 7 app on a Windows Server 2008 Enterprise 64 bit server for access over Terminal Services. The app runs fine, but there is some kind of bug with the TS Easy Print technology. When you print from the app to a redirected client printer over Easy Print, the top, left, and bottom sides of each page of the document get clipped. The workaround we use is to have the users print to pdfFactory on the server first, then print from pdfFactory to the redirected client printer over Easy Print. Works great.
A: This is somewhat of a stab in the dark...but I believe there are some drivers with MDAC that aren't available in x64 windows. I think you may be able to install the normal 32-bit MDAC but it will install to the x86 folder.
A: We've seen zero problems with our VFP9 apps on 64-bit XP, Server 2003, Vista, or Server 2008.
Our print engine is a VB DLL though, so we wouldn't run into any VFP-specific printing issues.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/99793",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: When to use Binary Space Partitioning, Quadtree, Octree? I have recently learned about binary space partitioning trees and their application to 3d graphics and collision detection. I have also briefly perused material relating to quadtrees and octrees. When would you use quadtrees over bsp trees, or vice versa? Are they interchangeable? I would be satisfied if I had enough information to fill out a table like this:
| BSP | Quadtree | Octree
------------+----------------+-------
Situation A | X | |
Situation B | | X |
Situation C | | | X
What are A, B, and C?
A: A BSP is best for urban environments.
A Quadtree is best for when you use a height map for terrain, etc.
An Octree is best for when you have clumps of geometry in 3d space, such as a solar system.
A: There is no clear answer to your question. It depends entirely how your data is organized.
Something to keep in mind:
Quadtrees work best for data that is mostly two dimensional like map-rendering in navigation systems. In this case it's faster than octrees because it adapts better to the geometry and keeps the node-structures small.
Octrees and BVHs (Bounding Volume Hierarchies) benefit if the data is three dimensional. It also works very well if your geometric entities are clustered in 3D space. (see Octree vs BVH) (archived from original)
The benefit of Oc- and Quadtrees is that you can stop generating trees anytime you wish. If you want to render graphics using a graphic accelerator it allows you to just generate trees on an object level and send each object in a single draw-call to the graphics API. This performs much better than sending individual triangles (something you have to do if you use BSP-Trees to the full extent).
BSP-Trees are a special case really. They work very very well in 2D and 3D, but generating good BSP-Trees is an art form on its own. BSP-Trees have the drawback that you may have to split your geometry into smaller pieces. This can increase the overall polygon-count of your data-set. They are nice for rendering, but they are much better for collision detection and ray-tracing.
A nice property of the BSP-trees is that they decompose a polygon-soup into a structure that can be perfectly rendered back to front (and vice versa) from any camera position without doing an actual sort. The order from each viewpoint is part of the data-structure and done during BSP-Tree compilation.
That, by the way, is the reason why they were so popular 10 years ago. Quake used them because it allowed the graphic engine / software rasterizer to not use a costly z-buffer.
All the trees mentioned are just families of trees. There are loose octrees, kd-trees hybrid-trees and lots of other related structures as well.
A: BSPs are a good option for accelerating collision-detection, depending on which flavour you use. They're particularly fast at point and line or ray tests, somewhat less fast and a little more complicated for things with volume.
As for their use in graphics, BSPs are pretty much obsolete. Octrees work well for things like gross visibility culling, as do AABB trees.
A: The biggest practical difference between BSP-Trees and other kinds of 3d-trees are that BSP-Trees can be more optimal but only work on static geometry. This is because BSP-Trees are generally very slow to build, often taking hours or days for a typical static urban game level.
The two main reasons BSP-Trees take longer to build are (a) they use non-axis-aligned splitting planes, which take longer to optimally find, and (b) they subdivide geometry on axis boundaries, assuring no objects cross split planes.
Other types of 3d-trees (Octrees, Quadtrees, kd-tree, Bounding-Volume-Hierarchy) use axis-aligned bounding volumes, and volumes are (optionally) allowed to overlap, so contained objects don't need to be cut on volume boundaries. These both make the trees less optimal than BSP-trees, but quicker to build, and easier to change for dynamic objects.
Extrapolating these factors into situations...
Outdoor areas typically use height-field based ground representations, either simple heightmaps or more complex geo-mip-mapping techniques like ROAM. The ground itself doesn't participate in the 3d space partitioning, only objects placed on the ground.
Worlds with lots of instances of simpler and similar geometry (houses, trees, asteroids, etc) will often use a non-BSP-tree (such as a BVH), because putting the geometry into a BSP-tree would mean duplicating and splitting the detail geometry for every instance.
Conversely, a large custom static mesh with no instancing, such as an urban scene, or a complex indoor environment, will typically use a BSP-Tree for improved runtime performance. The fact that the BSP-Tree splits geometry on node-boundaries is helpful for rendering performance, because the BSP nodes can be used as pre-organized triangle rendering batches. The BSP-Tree can also be optimized for occlusion, avoiding the need to draw portions of the BSP-Tree which are known to be behind other geometry.
See also: Octree vs BVH (archived from original), Bounding Volume Hierarchy Tutorial, BSP Tutorial.
A: I don't have much experience with BSPs, but I can say that you should go with octrees over quadtrees when you the scene you're rendering is tall. That is, the height is more than half the width and depth -- little rule of thumb. Generally, octrees won't bring a huge cost over quadtrees and they have the potential to speed things up a decent bit. YMMV.
A: Usually these things don't have a clear-cut answer. I would suggest that A,B, and C are the result of a function of the size of your space and the amount of stuff you are differentiating.
A: A BSP is better for a smaller, simpler space that you only want to do occlusion with. If you want all intersections for a given ray, you'll need to upgrade to a quad/octree.
As for quadtree vs. octree - how many dimensions do you care a lot about? Two dimensions means a quadtree, four an octree. As stated, as quadtree can work in three-space, but if you want each dimension given a proper treatment, an octree is the way to go.
A: Unless you know what you are doing always go for the octrees so you can stop focusing on overoptimizing and start working on more serious features. Seriously the bottlenecks will always be somewhere else, or you are designing you code around a optimized system which in the end prevents certain types of changes later.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/99796",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "82"
}
|
Q: Convert/extract phpinfo() into php.ini I am thinking along the lines of replicating a web hosts PHP setup environment for offline local development. The idea is to parse the output of phpinfo() and write any setup values it contains into a local php.ini. I would imagine everything ism included in phpinfo and that certain things would only be specific to the environment it is running on (paths).
A: You will probably get more usable results from ini_get_all()
http://us.php.net/manual/en/function.ini-get-all.php
You could then traverse the associated array to reconstruct an ini file without the hassle of interpreting the output of phpinfo()
A: It's quite likely to just be a stock install. Even then, I'd still want to make the local development environment subtly different to the live php.ini, to ensure that it showed all errors that were being produced (as opposed to hiding, or just logging them on the live site).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/99802",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: What are some useful TextMate shortcuts? Macs are renowned (or bemoaned) for having an extensive number of shortcuts. However, OS X itself pales in comparison to the shortcut lists in TextMate and its bundles.
What are some useful keyboard shortcuts you use?
A: Control-T(ControlT): Transpose (works in most Cocoa-native text fields and areas, but TextMate enhances the behavior).
*
*Place your caret between two characters, hit ControlT, and the characters switch places (this is standard Mac behavior). Awesome for typos.
*Select a word or series of characters on a single line, hit ControlT, and the characters in the selection will now be reversed (not too useful, but this is a TextMate enhancement)
*Select a series of characters that spans more than one line, hit ControlT, and the lines will reverse. Characters within the line will still be in order. Most useful when selecting whole lines, but still works with partial lines selected, just so long as there is at least one newline character selected (TextMate enhancement).
A: My favourites are:
*
*option+command+[ to clean up your indentation
*"lorem", TAB to insert placeholder text
A: Personally two of my favourite shortcuts are:
*
*⌃⇧L (that's ctrl+shift+L): Which wraps the currently selected text with a link to whatever's in the clipboard, and works for every text language I've tried it in.
*⌃⇧⌘L (that's ctrl+shift+cmd+L): Which googles for the selected text and links to the top result.
The are both super useful for writing text and blogging, (and stackoverflow).
Codewise, I think that I prefer snippets to key shortcuts. Being able to type if⇥ etc., in almost any language is ridiculously useful, and the consistent interface is what keeps me using TextMate.
I also found this quite amusing. But I prefer to learn my shortcuts in small steps, and often find that just looking in the gear menu (⌃⎋) works.
A: shift+ctrl+alt+v sends selected text to pastie.org
also, using the PHP Bundle, try to start writing a function name and do the following:
str + alt + F3 = list of available functions
str + alt + F1 = short description of the function you've just completed.
A: Look word up in dictionary, in any Cocoa app (not just Textmate): ctrl + cmd + D
A: These are my favorite shortcuts:
*
*cmd+t Start typing name of a file to open it
*ctrl+w Select word
*cmd+r Run the ruby or php-script that is open
*cmd+opt+m Define a new macro
*cmd+shift+m Run the macro
*opt Switch to vertical selection mode
*cmd+opt+a Edit ends of selected lines
A: Wrap each selected line in markup tags: SHIFT + CONTROL + COMMAND + W
For example, if you have:
This is a
few sample
list items
Highlight all three lines and presss SHIFT + CONTROL + COMMAND + W to create:
<li>This is a </li>
<li>few sample</li>
<li>list items</li>
A: Generate Lorem ipsum: lorem + TAB
Will generate:
Lorem ipsum dolor sit amet,
consectetur adipisicing elit, sed do
eiusmod tempor incididunt ut labore et
dolore magna aliqua. Ut enim ad minim
veniam, quis nostrud exercitation
ullamco laboris nisi ut aliquip ex ea
commodo consequat. Duis aute irure
dolor in reprehenderit in voluptate
velit esse cillum dolore eu fugiat
nulla pariatur. Excepteur sint
occaecat cupidatat non proident, sunt
in culpa qui officia deserunt mollit
anim id est laborum.
A: Selecting text using alt (via click and drag)
then use ⌘ + ] to indent (or [ to dedent)
A: Delete the current line: CONTROL + SHIFT + K
A: Format CSS: CONTROL + Q
Select some CSS and press CONTROL + Q to turn this:
body { background: red; font-size: 10px; color: black; }
Into this:
body {
background: red;
font-size: 10px;
color: black;
}
A: Look up property specifications in W3C: CONTROL + H
This works for both HTML and CSS. Place your carrot over whatever property you'd like to look up and press CONTROL + h. This will open a new window listing the W3C info.
For example, place your carrot over background:
body {
background: red;
}
Hit command + h and you'll see something like:
A: Edit the end of multiple selected lines simultaneously : COMMAND + OPTION + A
A: Toggle between {} and do end blocks. Place your cursor on the block arugument (i.e. the word after the keyword do between the two pipes) and press Shift + Control + {
For example, converts:
@post.each do |post|
puts post.name
end
to:
@post.each { |post| puts post.name }
A: CMD + / comments out a line and it's smart enough to format based on language. I use it all the time.
A: *
*ctrl+shift+K deletes current line
*ctrl+shift+J merges current line with the next line
A: Close the nearest open html/xml tag: OPTION + COMMAND + PERIOD
For example, if you have:
<div>Lorem ipsum dolor sit amet, consectetur
CONTROL + COMMAND + D will automatically add the closing </div> tag to create:
<div>Lorem ipsum dolor sit amet, consectetur</div>
A: Switch between tabs:
*
*Left: SHIFT + COMMAND + [
*Right: SHIFT + COMMAND + ]
A: Esc auto completes common words in the document you are working in.
For example if you are using a function alot called LongFuntionNameThatChecksStuff, you can type Lon and pressEsc and it should auto complete.
A: in the cftextmate bundle you can type any cfml tag without the opening "<" or closing ">" and press tab and it completes the entire tag and you can then tab to each of the tag attributes. i'm not sure if this type of shortcut works for other languages.
A: I just found a list of shortcut key symbols w/ definitions under Bundles > HTML > Entities - helpful for me in figuring out the whole short-cut bonanza going on with TextMate.
A: You can get a really great desktop background here. It has a ton of really useful keyboard shortcuts. I used it for a couple of days before memorizing the most useful ones.
A: Wrap selected text in markup tags: SHIFT + CONTROL + W
For example, if you have:
Lorem ipsum dolor sit amet, consectetur
Highlight the text and press SHIFT + CONTROL + W to create:
<p>Lorem ipsum dolor sit amet, consectetur</p>
A: Go to File: ⌘ + T
Find in Project: ⌘ + SHIFT + F
A: Eliminate all whitespace / carriage returns between the location of your caret and the start of the next piece of content: SHIFT + CONTROL + J
For example, if you have:
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do
eiusmod tempor incididunt ut labore et
dolore magna aliqua.
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris
nisi ut aliquip.
Place your caret at the end of the first paragraph and press SHIFT + CONTROL + J to remove the space in between the paragraphs:
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip.
A: (these are mostly html-related)
*
*cmd + option + closes current open html tag
*shift + cmd + w wrap selection in tags
*ctrl + return insert escaped line end, i.e. \n or <br> depending on the occasion.
A: Copy and Paste Clipboard: ⌘ + SHIFT + V
A: Titleize selected text: CONTROL + OPTION + U
Will turn:
Lorem ipsum dolor sit amet,
consectetur adipisicing elit.
Into:
Lorem Ipsum Dolor Sit Amet,
Consectetur Adipisicing Elit.
A: Downcase selected text: CONTROL + SHIFT + U
Will turn:
Lorem ipsum dolor sit amet,
consectetur adipisicing elit.
Into:
lorem ipsum dolor sit amet,
consectetur adipisicing elit.
A: Upcase selected text: CONTROL + SHIFT + U
Will turn:
Lorem ipsum dolor sit amet,
consectetur adipisicing elit.
Into:
LOREM IPSUM DOLOR SIT AMET,
CONSECTETUR ADIPISICING ELIT.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/99807",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "43"
}
|
Q: Attaching an ID/Label to LINQ to SQL generated code? I'm interested in tracing database calls made by LINQ to SQL back to the .NET code that generated the call. For instance, a DBA might have a concern that a particular cached execution plan is doing poorly. If for example a DBA were to tell a developer to address the following code...
exec sp_executesql N'SELECT [t0].[CustomerID]
FROM [dbo].[Customers] AS [t0]
WHERE [t0].[ContactName] LIKE @p0
ORDER BY [t0].[CompanyName]',
'N'@p0 nvarchar(2)',@p0=N'c%'
...it's not immediately obvious which LINQ statement produced the call. Sure you could search through the "Customers" class in the auto-generated data context, but that'd just be a start. With a large application this could quickly become unmanageable.
Is there a way to attach an ID or label to SQL code generated and executed by LINQ to SQL? Thinking out loud, here's an extension function called "TagWith" that illustrates conceptually what I'm interested in doing.
var customers = from c in context.Customers
where c.CompanyName.StartsWith("c")
orderby c.CompanyName
select c.CustomerID;
foreach (var CustomerID in customers.TagWith("CustomerList4"))
{
Console.WriteLine(CustomerID);
}
If the "CustomerList4" ID/label ends up in the automatically-generated SQL, I'd be set. Thanks.
A: Have you looked at capturing the T-SQL with the DataContext.Log property? If you were able to capure it into an object that also had your tag property you might be able to catalog the SQL your application executes.
A: There is no public way to modify the underlying SQL that LINQ to SQL generates to implement such a tagging facility. You could implement the Log property in such a way it writes out a text log file with some call stack information to show which methods generated which SQL statements for reference.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/99827",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Eclipse text comparison order I'm using Eclipse 3.4 (on Mac) and I've got an annoyance with the text comparison having the files I'm comparing in a specific order which is not what I want.
When I compare two files it always seems to put the first file (alphabetically) on the left, and the latter one on the right, but I want to be able to change this on a comparison by comparison basis.
IE comparing 'file-a' and 'file-b' will always have 'file-a' on the left, but that isn't always what I want. I seem to recall in earlier versions of Eclipse that changing the file that was right-clicked when choosing Compare With -> Each Other changed the order, but that isn't working for me in 3.4.
An example of why I care:
I've just performed a subversion merge and had a conflict, so I now have the following files:
file
file.merge-left
file.merge-right
file.working
I've made changes to file and now want to compare file to file.merge-right and file.working to file.merge-left and split the editors so I can have the working/left changes sitting above the file/right changes, and then just page through the compare editors and make sure the differences between this file and the file that the merge comes from have been preserved, but file is on the left while file.working is on the right, and hence the differences need to be compared diagonally rather than just comparing top and bottom.
A: Yes, that's actually very annoying. We use an external tool called Beyond Compare (we have a corporate licence) which can swap the two sides easily.
What you should probably do is raise an enhancement request on the relevant Eclipse team with Bugzilla. If there's enough demand, it'll either make it into the next release or someone will write a new (or modify the existing) plug-in to allow swaps.
A: There's a "Swap From and To" button when the Compare screen comes up. Using Eclipse 3.6. I'm actually looking for a way to change default behavior. For example, when I compare revisions, it always have the latest revision on the left side instead of right unless I click the swap button before comparing.
A: As I mentioned here, Eclipse Neon.2 (4.6.2) has a button to swap the views:
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/99830",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: Biggest GWT Pitfalls? I'm at the beginning/middle of a project that we chose to implement using GWT. Has anyone encountered any major pitfalls in using GWT (and GWT-EXT) that were unable to be overcome? How about from a performance perspective?
A couple things that we've seen/heard already include:
*
*Google not being able to index content
*CSS and styling in general seems to be a bit flaky
Looking for any additional feedback on these items as well. Thanks!
A: I'm working on a project right now that uses EXT GWT (GXT) not to be confused with GWT EXT. There is a difference, EXT GWT is the one that is actually produced by the company that wrote ExtJS the javascript library. GWT EXT is a GWT wrapper around the ExtJS library. GXT is native GWT.
Anyways, GXT is still somewhat immature and lacks a solid community that I feel GWT EXT has. However, the future is with GXT, as it's native GWT and actually developed by the company that made ExtJS. GWT EXT is somewhat crippled as the license changed on the ExtJS library, thus slowing the development of GWT EXT.
Overall, I think GWT/GXT is a good solution for developing a web application. I actually quite like hosted mode for development, it makes things quick and easy. You also get the benefit of being able to debug your code as well. Unit testings with JUnit is pretty solid as well. I haven't yet seen a great JavaScript unit testing framework that I felt was mature enough for testing an enterprise application.
For more information on GWT EXT:
http://gwt-ext.com/
For more information on EXT GWT (GXT):
http://extjs.com/products/gxt/
A: We have been working with gwt for almost 2 years. We have learned a lot of lessons. Here is what we think:
*
*Dont use third party widget libraries especially gwt-ext. It will kill your debugging, development and runtime performance. If you have questions about how this happens, contact me directly.
*Use gwt to only fill in the dynamic parts of your apps. So if you have some complex user interactions with lots of fields. However, don't use the panels that come with it. Take your existing stock designer supplied pages. Carve out the areas that will contain the controls for your app. Attach these controls to the page within onModuleLoad(). This way you can use the standard pages from your designer and also do all the styling outside the gwt.
*Don't build the entire app as one standard page that then dynamically builds all the pieces. If you do what I suggest in item 2, this won't happen anyway. If you build everything dynamically you will kill performance and consume huge amounts of memory for medium to large apps. Also, if you do what I am suggesting, the back button will work great, so will search engine indexing etc.
The other commenters also had some good suggestions. The rule of thumb i use is to create pages like you were doing a standard web page. Then carve out the pieces that need to be dynamic. Replace them with elements that have id's and then use RootPanel.get( id ).add( widget ) to fill those areas in.
A: No major pitfalls that I haven't been able to overcome easily. Use hosted mode heavily.
As you are using GWT-ext you will almost never need to touch CSS yourself unless you want to tweak the out of the box look.
My recommendation is to use a GWT "native" widget over a library one where they are close in features.
Re search engine indexing: yes the site will not have navigable URLs normally (unless you are only adding widgets to elements of a regular web site). You can do history back/forward functionality though.
A: I used GWT and GWT-ext together on a project a while ago. I found the experience quite smooth as web development goes, but my advice would be this:
Don't mix GWT native widgets with EXT widgets. It's confusing as hell, since usually the names are the same (GWT.Button or GWText.Button?)
One thing that happened to me that really made the code more complex than I'd like, was that I wanted a Panel that was
a) dynamically updatable
b) cascadable
GWT native panels are dynamic, Ext panels are cascadable. Solution? A GWT.VerticalPanel wrapping a GWTExt Panel... Chaos. :)
But hey, it works. ;)
A: I second the comment from ykagano, the biggest disadvantage is losing the V in MVC. Although you can separate the true ui class from the rest of your client side code, you cannot easily use an HTML page generated by a graphic/web designer. This means you need a developer to translate HTML into java.
Get a wysiwyg ui editor, it will save you lots of time. I use GWTDesigner.
The biggest upside of GWT is being able to forget about cross browser issues. Its not 100% but takes almost all that pain away. Combined with the benefit of hosted mode debugging (as opposed to Firebug which is excellent but not the same as a java debugger) it gives the developer a huge advantage in generating complex ajax apps.
Oh and its fast at runtime, especially if you use a gzip filter.
A: Slightly off-topic, but the #gwt channel on irc is very helpful, in-case you have a persistent problem.
A: GWT is pretty straight-forward and intuitive.
Especially with the release of UIBinder to allow GWT widgets to be laid out in XML and then coded-behind in Java.
So if you have used other Ajax or Flash design tools, or Silverlight, etc, GWT is very easy to learn.
The major hurdle, if not pitfall, is GWT RPC. The very reason you wish to use GWT is because of GWT async RPC. Otherwise, why not just rely on css to format your page?
GWT RPC is that element that allows your server to refresh data on your server without having to refresh the page. This is an absolute requirement for pages such as stock performance monitoring (or the current national and public debt of the US or the number of unborn babies aborted worldwide by the second).
GWT RPC takes some effort to understand but given a few hours, it should come all clear.
Above that, after putting in some effort to learn GWT RPC, you finally discover that you cannot use JSPs as the service component for RPC, unless ... I have an 8 part (I think) series on my blog on how to use JSP as the GWT RPC servicer. However, since you had not asked for answers but just issues, I shall desist from advertising my blog.
So. I very much believe that the worst roadblocks/pitfalls to using GWT is finding out how to properly deploy GWT async RPC and how to enable it to use JSP servicers.
A: We've had a very hard time marrying our GWT codebase with HTML web templates that we got from a web designer (static HTML pages with specific div ids that we wanted GWT to manage). At least back when we used it, we couldn't get GWT to integrate with parts of our website that were not coded in GWT. We had it working eventually, but it was a big hack.
A: *
*The Async interface you have to write for each service interface looks like something that could have been automatically generated by the GWT compiler.
*Compile times become long for large projects
But for a large Javascript project it's the best choice
A: GWT 2.4 has fixed many of the aforementioned issues and a great widget library is just coming out of Beta (Ext GWT 3.0.4 a.k.a. GXT), which is written completely in GWT, not a wrapper of a JS lib.
Remaining pain:
*
*Lack of CSS3 selector support, you can use "literal()" in some cases to get around it.
*Lack of support for CSS3 and modern browser events like transitionEnd.
*Lack of Java Calendar class support (many years later).
*Lack of JUnit4 support (5 years and counting).
*Lack of clear road map and release schedule from Google GWT team.
A: I'll start by saying that I'm a massive GWT fan, but yes there are many pitfalls, but most if not all we were able to overcome:
Problem: Long compile times, as your project grows so does the amount of time it takes to compile it. I've heard of reports of 20 minute compiles, but mine are on average about 1 minute.
Solution: Split your code into separate modules, and tell ant to only build it when it's changed. Also while developing, you can massively speed up compile times by only building for one browser. You can do this by putting this into your .gwt.xml file:
<set-property name="user.agent" value="gecko1_8" />
Where gecko1_8 is Firefox 2+, ie6 is IE, etc.
Problem: Hosted mode is very slow (on OS X at least) and does not come close to matching the 'live' changes you get when you edit things like JSPs or Rails pages and hit refresh in your browser.
Solution: You can give the hosted mode more memory (I generally got for 512M) but it's still slow, I've found once you get good enough with GWT you stop using this. You make a large chunk of changes, then compile for just one browser (generally 20s worth of compile) and then just hit refresh in your browser.
Update: With GWT 2.0+ this is no longer an issue, because you use the new 'Development Mode'. It basically means you can run code directly in your browser of choice, so no loss of speed, plus you can firebug/inspect it, etc.
http://code.google.com/p/google-web-toolkit/wiki/UsingOOPHM
Problem: GWT code is java, and has a different mentality to laying out a HTML page, which makes taking a HTML design and turning it into GWT harder
Solution: Again you get used to this, but unfortunately converting a HTML design to a GWT design is always going to be slower than doing something like converting a HTML design to a JSP page.
Problem: GWT takes a bit of getting your head around, and is not yet mainstream. Meaning that most developers that join your team or maintain your code will have to learn it from scratch
Solution: It remains to be seen if GWT will take off, but if you're a company in control of who you hire, then you can always choose people that either know GWT or want to learn it.
Problem: GWT is a sledgehammer compared to something like jquery or just plain javascript. It takes a lot more setup to get it happening than just including a JS file.
Solution: Use libraries like jquery for smaller, simple tasks that are suited to those. Use GWT when you want to build something truly complex in AJAX, or where you need to pass your data back and forth via the RPC mechanism.
Problem: Sometimes in order to populate your GWT page, you need to make a server call when the page first loads. It can be annoying for the user to sit there and watch a loading symbol while you fetch the data you need.
Solution: In the case of a JSP page, your page was already rendered by the server before becoming HTML, so you can actually make all your GWT calls then, and pre-load them onto the page, for an instant load. See here for details:
Speed up Page Loading by pre-serializing your GWT calls
I've never had any problems CSS styling my widgets, out of the box, custom or otherwise, so I don't know what you mean by that being a pitfall?
As for performance, I've always found that once compiled GWT code is fast, and AJAX calls are nearly always smaller than doing a whole page refresh, but that's not really unique to GWT, though the native RPC packets that you get if you use a JAVA back end are pretty compact.
A: Pitfalls that we've run into:
*
*While you can get a lot of mileage from using something like GWT EXT, any time you use this sort of thin veneer on top of a JavaScript library, you lose the ability to debug. More than once I've bashed my head on the desk because I cannot inspect (inside my IntelliJ debugger) what's happening in the GWT EXT table class... All you can see is that it's a JavaScriptObject. This makes it quite difficult to figure out what's gone wrong...
*Not having someone on your team who knows CSS. From my experience, it didn't matter that the person wasn't expert...it's enough that he has some good working knowledge, and knows the right terms to google when necessary.
*Debugging across browsers. Keep an eye on Out of Process Hosted Mode[1][2][3], hopefully coming in GWT 1.6... For now, you just have to get things good with hosted mode, then use the "Compile/Browse" button, where you can play with other browsers. For me, working on Windows, this means I can view my work in FireFox, and use FireBug to help tweak and make things better.
*IE6. It's amazing how different IE 6 will render things. I've taken the approach of applying a style to the outermost "viewport" according to the browser so that I can have CSS rules like:
.my-style { /* stuff that works most everywhere */ }
.msie6 .my-style { /* "override" so that styles work on IE 6 */ }
Finally, make sure you use an editor that helps you. I use IntelliJ -- it's got lots of GWT smarts. E.g., If I try to use a class that isn't handled by the JRE emulation, it lets me know; if I specify a style for a widget, and I haven't defined that style yet, the code gets the little red squiggly... Or, when looking at the CSS, it will tell me when I've specified conflicting attributes in a single rule. (I haven't tried it yet, but I understand that version 8 has even better GWT support, like keeping the "local" and "async" RPC interfaces and implementations in sync.)
A: Regarding GWT 2.4, Use Firefox when debugging GWT, it alot more faster then using chrome.
And if you'll using only firefox, consider putting this line in your project.gwt.xml file
<set-property name="user.agent" value="gecko1_8" />
Also, If you're using eclipse, then add the following under arguments -> VM arguments:
-Xmx512m -XX:MaxPermSize=1024m -XX:PermSize=1024m
You can divide your server and client, and use the following under arguments -> Program arguments:
-codeServerPort 9997 -startupUrl http://yourserver/project -noserver
Also, to prevent refreshing your server on each change, use JRebel
http://zeroturnaround.com/blog/how-to-rock-out-with-jrebel-and-google-web-toolkit-gwt/
And here's a live demo
http://www.youtube.com/watch?feature=player_embedded&v=4JGGFCzspaY
A: GWT 2.0, which is supposed to come out sometime in the next few months, solves a lot of the issues discussed.
*
*Create layouts using an html/xml like syntax
*Dynamic Script Loading - only the essential JS will be downloaded initially. The rest will be downloaded as needed
*In-Browser Hosted Mode - This might take care of the hosted mode speed issues discussed, among other benefits
*"Compiler Optimizations" - Faster compilation, hopefully
GWT 2.0 Preview Video at Google I/O
A: Not "unable to be overcome" but a bit of a pain for something basic.
Date handling:
GWT uses the deprecated java.util.Date which can lead to unexpected behaviour when dealing with dates on the client side. java.util.Calendar is not supported by GWT. More info here.
Related problem examples:
*
*GWT java.util.Date serialization bug
*Get Date details (day, month, year) in GWT
*Client side time zone support in GWT
A: I'll add some points to the ones already mentioned:
*
*Databinding/validation. GWT doesn't have a databinding/validation support out of the box, although there are some projects on this area starting to emerge. You'll find yourself writing alot of this:
TextField fname, faddress;
...
fname.setText(person.getName());
faddress.setText(person.getAddress());
...
*
*Lazy loading. Since gwt is on the client side, lazy loading is really not an option. You'll have to design your RPCs and Domain Objects carefully in order to
*
*send all your object data that is needed
*avoid eager fetching all of your data
*You'll have also to make sure that you will not send proxies/non serializable objects. hibernate4gwt can help you with these points.
*UI design. It is harder to visualize an UI in java (Panels, Buttons, etc) than in html.
*History support. GWT does not ship with a History subsystem, nor does it ship with any subsystem for nice urls or statefull bookmarking. You'll have to roll your own (although it has support for History tokens, which is a start). This happens with all AJAX toolkits AFAIK.
IMHO, GWT is missing a framework that has out of the box support for all of the issues mentioned on this 'thread'.
A: One major pitfall is that sometimes you need to explicitly assign an id to what ultimately becomes an HTML element to be able to use certain CSS styles. For instance: a GWT TabPanel will only do :hover over tabBarItems when the tabBar of the tabPanel has been assigned an id and you specify a :hover on that elementId.
I wrote about some other disadvantages of GWT elsewhere, but they are already covered by rustyshelfs answer :).
A: I have done a lot of work on GWT recently, and this is wht i have to say:
*
*CSS styling is tricky only sometimes, use IE developer tool in IE and firebug in Firefox to figure out what exactly is happening and you will get a clear idea of what css needs to be changed
*You can use tricks to get google to index it. A very famous site is http://examples.roughian.com/ check its ratings at google. A far less famous site is www.salvin.in (couldnt resist to mention that), i optimised it to words: salvin home page (search google for these three words)
I do not know much about GWT-EXT, But i too am of the belief that there is no need to include Third party libraries.
Best of luck on your decision :)
A: GWT does Browser Sniffing instead of Feature Detection and your application will not work on some browsers (specially new ones)
Here are some references of the problem:
*
*google-web-toolkit Issue 2938: RFE: improve the user.agent property-provider to cope for userAgent string "masking"
*Iceweasel no longer supported? - Google Docs Help
*GWT implementations for every browser
Here are some references to Feature Detection:
*
*Browser Detecting (and what to do Instead)
*Feature Detection: State of the Art Browser Scripting
*Browser Feature Detection
Extracted from Comparison of JavaScript frameworks - Wikipedia
A: The GWT team make a lot of great improvements in to last year releasing GWT 2.7. One major weakness of GWT was that compilation takes to much time in GWT 2.6 and below. This is now gone GWT has not incremental compile which is super fast and compiles only the changes.
GWT 2.7 now has (Source):
*
*Incremental builds now just seconds
*More compact, more accurate SourceMaps
*GSS support
*JSInterop
*Great JavaScript Performance
*Smaller Code Size
A: The best way to get reliable facts are from the gwt survey. One of the biggest issues with GWT has always been a long compile time. Fortunately, it's improving very quickly so it won't be a significant issue in the near future. Another pitfall is that GWT is dramatically more complicated because Java is a more complicated language that resists bad coders every step of the way. In addition, compiling adds a layer. For example, js interop requires a little boilerplate. The fundamental issue is that GWT wasn't designed to be simple. It was designed from the ground up for extremely complicated web apps and the entire community consistently prioritizes, performance, code quality, architecture etcetera over easy coding.
Remember that you can use js in GWT at any point so if you are struggling with GWT consider using js. At the end of the day GWT is js so you can do anything in GWT that you can in js. In fact, most GWT projects use js. The problem is that GWT is drastically more complicated. Nevertheless, it's sometimes worth the extra complexity.
It's worth noting that GWT 3.0 will bring massive improvements.
A: Re-using RPC service objects.
It causes race conditions with symptoms that look like the app hanging.
A: Pitfalls I ran into
1. Different behaviour in superdev mode. E.g. Someclass.class.getName() works absolutely fine in Superdev mode and returns the fully qualified name of the class. In productive mode this does not work.
*addWidget(widget) will call widget's removefromparent()
A: GWT is a technology masterpiece. It unites client and server programming making it one coherent application - the way software was written before "layering", and the way it should be written. It eliminates different skills sets, miscommunication between team members, and generally the whole Web Design phase: both the artistic and programming. And it is the closest you'd get to mobile e.g. Android development. In fact GWT was designed to generate different native UIs, not just HTML. Though it requires enormous discipline to ensure such decoupling - to keep your inner layers presentation-agnostic.
The first mistake you should avoid, which took me four years to realize, is using third-party extensions like EXT-GWT aka GXT and SmartGWT. It is very tempting to start using their pretty desktopish widgets instead of investing in your own styling, but I cannot tell how many problems I had with SmartGWT until I finally got fed up. In short it freezes the core GWT feature set at the certain (pretty outdated) level and then builds on top of it. Also keep in mind, that chiseled desktop look and feel looks silly nowadays, not to mention the sluggish performance, tons of bugs, and compatibility features - especially on mobile devices. You want to stay as close to the native browser controls, as possible i.e. dropdowns rendered as native <select> elements, not some custom-painted controls.
Thanks to mobile trends the whole UX is becoming simpler and flatter, so you don't need to do much to style a sharp-looking application. Though if you want "3D" look, there are also gradients. CSS3 made everything easy, and GWT wraps it an elegant object-oriented manner unlike the raw CSS. So don't be discouraged by looking at rather ugly barebones controls in the GWT Showcase. The GWT team intentionally didn't offer any styling, because it it the developer's job.
The rest is pretty much conventional browser programming in strongly typed Java with beautiful concise APIs. But of course never forgetting your code runs inside the browser, so all of the calls are asynchronous e.g. you cannot call GWT-RPC methods in a loop (to populate some list), but need to recursively chain them if you ever come to to this situation.
There are some self-proclaimed "anti-patterns" like don't use GWT-RPC. It's been good to me so far: for 10 years. Simplicity is key. I wouldn't think even a second to sacrifice some marginal performance for code elegance and maintainability. besides this is not where your bottlenecks would be - in the database. Of course mind how much data you are sending to the client.
And if you cannot find or style the existing gadget - read rich HTML5 element set, you can always wrap a third-party one. I did it with a popular jQuery FullCalendar. Not rocket science at all. Everything else like Google Maps and Google Charts has semi-official GWT wrappers.
GWT is perfect. The only reason it doesn't get enough love is because early Internet adopters who still influence the industry didn't come from Computer Science and object-oriented languages to appreciate them. They have either artistic (Photoshop/WordPress) or network (Perl/Python) background.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/99866",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "189"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.