text
stringlengths
8
267k
meta
dict
Q: Python Dependency Injection Framework Is there a framework equivalent to Guice (http://code.google.com/p/google-guice) for Python? A: pinject (https://github.com/google/pinject) is a newer alternative. It seems to be maintained by Google and follows a similar pattern to Guice (https://code.google.com/p/google-guice/), it's Java counterpart. A: Besides that: * *Zope component architekture *pyContainer A: If you just want to do dependency injection in Python, you don't need a framework. Have a look at Dependency Injection the Python Way. It's really quick and easy, and only c. 50 lines of code. A: There is a somewhat Guicey python-inject project. It's quite active, and a LOT less code then Spring-python, but then again, I haven't found a reason to use it yet. A: Spring Python is an offshoot of the Java-based Spring Framework and Spring Security, targeted for Python. This project currently contains the following features: * *Inversion Of Control (dependency injection) - use either classic XML, or the python @Object decorator (similar to the Spring JavaConfig subproject) to wire things together. While the @Object format isn't identical to the Guice style (centralized wiring vs. wiring information in each class), it is a valuable way to wire your python app. *Aspect-oriented Programming - apply interceptors in a horizontal programming paradigm (instead of vertical OOP inheritance) for things like transactions, security, and caching. *DatabaseTemplate - Reading from the database requires a monotonous cycle of opening cursors, reading rows, and closing cursors, along with exception handlers. With this template class, all you need is the SQL query and row-handling function. Spring Python does the rest. *Database Transactions - Wrapping multiple database calls with transactions can make your code hard to read. This module provides multiple ways to define transactions without making things complicated. *Security - Plugin security interceptors to lock down access to your methods, utilizing both authentication and domain authorization. *Remoting - It is easy to convert your local application into a distributed one. If you have already built your client and server pieces using the IoC container, then going from local to distributed is just a configuration change. *Samples - to help demonstrate various features of Spring Python, some sample applications have been created: * *PetClinic - Spring Framework's sample web app has been rebuilt from the ground up using python web containers including: CherryPy. Go check it out for an example of how to use this framework. (NOTE: Other python web frameworks will be added to this list in the future). *Spring Wiki - Wikis are powerful ways to store and manage content, so we created a simple one as a demo! *Spring Bot - Use Spring Python to build a tiny bot to manage the IRC channel of your open source project. A: I like this simple and neat framework. http://pypi.python.org/pypi/injector/ Dependency injection as a formal pattern is less useful in Python than in other languages, primarily due to its support for keyword arguments, the ease with which objects can be mocked, and its dynamic nature. That said, a framework for assisting in this process can remove a lot of boiler-plate from larger applications. That's where Injector can help. It automatically and transitively provides keyword arguments with their values. As an added benefit, Injector encourages nicely compartmentalized code through the use of Module s. While being inspired by Guice, it does not slavishly replicate its API. Providing a Pythonic API trumps faithfulness. A: Will leave my 5 cents here :) https://pypi.python.org/pypi/dependency_injector """Pythonic way for Dependency Injection.""" from dependency_injector import providers from dependency_injector import injections @providers.DelegatedCallable def get_user_info(user_id): """Return user info.""" raise NotImplementedError() @providers.Factory @injections.inject(get_user_info=get_user_info) class AuthComponent(object): """Some authentication component.""" def __init__(self, get_user_info): """Initializer.""" self.get_user_info = get_user_info def authenticate_user(self, token): """Authenticate user by token.""" user_info = self.get_user_info(user_id=token + '1') return user_info print AuthComponent print get_user_info @providers.override(get_user_info) @providers.DelegatedCallable def get_user_info(user_id): """Return user info.""" return {'user_id': user_id} print AuthComponent().authenticate_user(token='abc') # {'user_id': 'abc1'} UPDATED Some time passed and Dependency Injector is a bit different now. It's better to start from Dependency Injector GitHub page for getting actual examples - https://github.com/ets-labs/python-dependency-injector A: After years using Python without any DI autowiring framework and Java with Spring I've come to realize that plain simple Python code often doesn't need a framework for dependency injection autowiring (autowiring is what Guice and Spring both do in Java), i.e., just doing something like this is enough: def foo(dep = None): # great for unit testing! ... This is pure dependency injection (quite simple) but without magical frameworks for automatically injecting them for you. Though as I dealt with bigger applications this approach wasn't cutting it anymore. So I've come up with injectable a micro-framework that wouldn't feel non-pythonic and yet would provide first class dependency injection autowiring. Under the motto Dependency Injection for Humans™ this is what it looks like: # some_service.py class SomeService: @autowired def __init__( self, database: Autowired(Database), message_brokers: Autowired(List[Broker]), ): pending = database.retrieve_pending_messages() for broker in message_brokers: broker.send_pending(pending) # database.py @injectable class Database: ... # message_broker.py class MessageBroker(ABC): def send_pending(messages): ... # kafka_producer.py @injectable class KafkaProducer(MessageBroker): ... # sqs_producer.py @injectable class SQSProducer(MessageBroker): ... A: I haven't used it, but the Spring Python framework is based on Spring and implements Inversion of Control. There also appears to be a Guice in Python project: snake-guice A: As an alternative to monkeypatching, I like DI. A nascent project such as http://code.google.com/p/snake-guice/ may fit the bill. Or see the blog post Dependency Injection in Python by Dennis Kempin (Aug '08). A: Here is a small example for a dependency injection container that does constructor injection based on the constructor argument names: http://code.activestate.com/recipes/576609-non-invasive-dependency-injection/ A: I made a lib to do this https://github.com/ettoreleandrotognoli/python-cdi I hope that helps It's available on pypi: https://pypi.python.org/pypi/pycdi With it you can make injections with python2 import logging from logging import Logger from pycdi import Inject, Singleton, Producer from pycdi.shortcuts import call @Producer(str, _context='app_name') def get_app_name(): return 'PyCDI' @Singleton(produce_type=Logger) @Inject(app_name=str, _context='app_name') def get_logger(app_name): return logging.getLogger(app_name) @Inject(name=(str, 'app_name'), logger=Logger) def main(name, logger): logger.info('I\'m starting...') print('Hello World!!!\nI\'m a example of %s' % name) logger.debug('I\'m finishing...') call(main) And using type hints from python3 import logging from logging import Logger from pycdi import Inject, Singleton, Producer from pycdi.shortcuts import call @Producer(_context='app_name') def get_app_name() -> str: return 'PyCDI' @Singleton() @Inject(logger_name='app_name') def get_logger(logger_name: str) -> Logger: return logging.getLogger(logger_name) @Inject(name='app_name') def main(name: str, logger: Logger): logger.info('I\'m starting...') print('Hello World!!!\nI\'m a example of %s' % name) logger.debug('I\'m finishing...') call(main) A: Enterprython is a small framework providing dependency-injection, building the object graph automatically based on type hints. A: Here's a good comparison (19 September 2020): Comparison of Dependency Injection Libraries in Python, and my favorite one His winners are: * *proofit404/dependencies (Injector) "simple, but provided all the necessary features. If you need something that’s not provided then just think about the design in your application, cause the flow might be somewhere there. Beautiful configuration. Perfect match for agile projects" *ets-labs/python-dependency-injector "very expanded library, with constant support, the problem is it’s boilerplate, if that does not bother you, then it’s a great choice" A: If you prefer a really tiny solution there's a little function, it is just a dependency setter. https://github.com/liuggio/Ultra-Lightweight-Dependency-Injector-Python A: There's dyject (http://dyject.com), a lightweight framework for both Python 2 and Python 3 that uses the built-in ConfigParser A: If you want a guice like (the new new like they say), I recently made something close in Python 3 that best suited my simple needs for a side project. All you need is an @inject on a method (__init__ included of course). The rest is done through annotations. from py3njection import inject from some_package import ClassToInject class Demo: @inject def __init__(self, object_to_use: ClassToInject): self.dependency = object_to_use demo = Demo() https://pypi.python.org/pypi/py3njection A: I recently released a neat (IMHO) micro library for DI in python: https://github.com/suned/serum A: I'm actively developing pinject for Python >= 3.6. It's quite easy to use: class MyObject: my_service: MyService = INJECTED my_config: str = INJECTED
{ "language": "en", "url": "https://stackoverflow.com/questions/156230", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "52" }
Q: Asp.net MVC View Testing? With more and more code pushed to the Views in Asp.Net MVC (i.e. AJAX, JQuery, etc...), how do you maintain the 'testability'? * *How do you test your Views? *How do you test your views with client-side jscript code? *How do you test your Views with Async behavior? It seems that most examples on the testability of MVC deal with controllers. What about Views? A: Selenium is a great tool for testing the front end of any web app. It is written in the browser's native language, JavaScript. Having the browser run the test framework code gives your tests the ability to expose browser incompatibility issues. It is free and open source. A: Also see other free browser automation tools like ArtOfTest and WatiN. The Selenium stack can be a little complicated to set up.
{ "language": "en", "url": "https://stackoverflow.com/questions/156232", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: Object allocate and init in Objective C What is the difference between the following 2 ways to allocate and init an object? AController *tempAController = [[AController alloc] init]; self.aController = tempAController; [tempAController release]; and self.aController= [[AController alloc] init]; Most of the apple example use the first method. Why would you allocate, init and object and then release immediately? A: Every object has a reference count. When it goes to 0, the object is deallocated. Assuming the property was declared as @property (retain): Your first example, line by line: * *The object is created by alloc, it has a reference count of 1. *The object is handed over to self's setAController: method, which sends it a retain message (because the method doesn't know where the object is coming from), incrementing its reference count to 2. *The calling code no longer needs the object itself, so it calls release, decrementing the reference count to 1. Your second example basically does steps 1 and 2 but not 3, so at the end the object's reference count is 2. The rule is that if you create an object, you are responsible for releasing it when you're done with it. In your example, the code is done with tempAController after it sets the property. It is the setter method's responsibility to call retain if it needs that object to stick around. It's important to remember that self.property = foo; in Objective-C is really just shorthand for [self setProperty:foo]; and that the setProperty: method is going to be retaining or copying objects as needed. If the property was declared @property (copy), then the object would have been copied instead of retained. In the first example, the original object would be released right away; in the second example, the original object's reference count would be 1 even though it should be 0. So you would still want to write your code the same way. If the property was declared @property (assign), then self isn't claiming ownership of the object, and somebody else needs to retain it. In this case, the first example would be incorrect. These sorts of properties are rare, usually only used for object delegates. A: Note also that your desire to cut the code down to one line is why many people use Autorelease: self.aController = [[[AController alloc] init] autorelease]; Though in theory on the iPhone autorelease is somehow more expensive (never heard a clear explanation why) and thus you may want to explicitly release right after you assign the object elsewhere. A: If you're using Xcode, it can help you detect such code with the static analyzer. Just hit Build >> Build and Analyze This will show you a very helpful message at such pieces of code. A: One other thing to note is that your example depends on the @property definition of aController also. If it were defined as @property (readwrite, retain) id aController; then your example works, while if it is defined as @property (readwrite, assign) id aController; then the extra call to release would cause your object to be deallocated. A: As others have noted, the two code snippets you show are not equivalent (for memory management reasons). As to why the former is chosen over the latter: The correct formulation of the latter would be self.aController= [[[AController alloc] init] autorelease]; Compared with the former, this adds additional overhead through use of the autorelease pool, and in some circumstances will lead to the lifetime of the object being unnecessarily extended (until the autorelease pool is released) which will increase your application's memory footprint. The other "possible" implementation (depending on where the example is from) is simply: aController = [[AController alloc] init]; However, setting an instance variable directly is strongly discouraged anywhere other than in an init or dealloc method. Elsewhere you should always use accessor methods. This brings us then to the implementation shown in sample code: AController *tempAController = [[AController alloc] init]; self.aController = tempAController; [tempAController release]; This follows best practice since: * *It avoids autorelease; *It makes the memory management semantics immediately clear; *It uses an accessor method to set the instance variable. A: You could also do @property (nonatomic, retain)AController *aController; ... self.aController= [[AController alloc] init]; [aController release]; with a retaining property, and it would function the same way, but its better to use the other way (for retaining properties) because it's less confusing, that code makes it look like you assign aController and then it gets deleted from memory, when actually it doesn't because setAController retains it.
{ "language": "en", "url": "https://stackoverflow.com/questions/156243", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "56" }
Q: Notification of object destruction in Ruby I have written a custom Rails model. This model is backed by an actually server not by a database table (so it does not inherit from ActiveRecord::Base). In order to get the requested information from the server I open a SSH connection to it. Because rails does not reuse object a new object, as well as a new SSH connection to the server, will be created for ever request that is received. To reduce server stress I want to close the SSH connection before the model object gets garbage collected. I am wondering does ruby provide a notification mechanism to inform the object that it will be destroyed? If so I could use this notification to know when to close the SSH connections. If not I will need to do it manual when I know I am finished with the object. If I need to manually take care of this, can I explicitly destroy the object? Or is the best i can do is object = nil? A: If you need to control what happens when an object is destroyed, you really should be explicitly destroying it yourself - this is by design. You're not supposed to be able to destroy an object explicitly either - this is also by design. In other words, from the perspective of your program, an object is never destroyed or destroyable. For these reasons you should re-think the problem (this is not an uncommon need - release of resources when the object is no longer needed) so it fits into the Ruby paradigm. Setting the object to nil gives a hint to the garbage collector, but does not necessarily immediately destroy it. However, if you must have the garbage collector handle it, then read on. There is no direct support for a destructor, but you can have it call a finalizer function when it is destroyed. According to http://pleac.sourceforge.net/pleac_ruby/classesetc.html it may not be garbage collected if it contains a reference to the original object, so must be a class method and not an instance method. class MyClass def initialize ObjectSpace.define_finalizer(self, self.class.method(:finalize).to_proc) end def MyClass.finalize(id) puts "Object #{id} dying at #{Time.new}" end end
{ "language": "en", "url": "https://stackoverflow.com/questions/156248", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: WPF: Calling TextBox.Clear() from LostFocus handler causes NullReferenceException when window closes The sample below has two TextBoxes. The second TextBox has a handler for the LostFocus event which calls Clear() on itself. Changing focus between the two text boxes works fine; however, if the focus is on the second text box when the window is closed, TextBox.Clear() generates a NullReferenceException. Is this a bug in WPF? How can I easily detect this situation so I can avoid calling Clear() when the window is closing? Edit: Possibly relevant - The window is the application's main window. Test is not null at the time Clear() is called. The exception is thrown from somewhere within the call. using System.Windows; namespace TextBoxClear { public partial class Window1 : Window { public Window1() { InitializeComponent(); } private void Test_LostFocus(object sender, RoutedEventArgs e) { Test.Clear(); } } } <Window x:Class="TextBoxClear.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <StackPanel> <TextBox /> <TextBox LostFocus="Test_LostFocus" Name="Test" /> </StackPanel> </Window> Assembly references: * *mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 *PresentationCore, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35 *PresentationFramework, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35 *System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 *WindowsBase, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35 A: Could the Test property be null by the time the LostFocus event is fired? Try: private void Test_LostFocus(object sender, RoutedEventArgs e) { if (Test != null) Test.Clear(); } EDIT: I'm having trouble reproducing the NullReferenceException with the code you posted. Which version of .NET are you using? A: Hooking LostKeyboardFocus instead of LostFocus works OK for my situation and stops the event handler throwing exceptions.
{ "language": "en", "url": "https://stackoverflow.com/questions/156256", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: AI Applications in C++: How costly are virtual functions? What are the possible optimizations? In an AI application I am writing in C++, * *there is not much numerical computation *there are lot of structures for which run-time polymorphism is needed *very often, several polymorphic structures interact during computation In such a situation, are there any optimization techniques? While I won't care to optimize the application just now, one aspect of selecting C++ over Java for the project was to enable more leverage to optimize and to be able to use non-object oriented methods (templates, procedures, overloading). In particular, what are the optimization techniques related to virtual functions? Virtual functions are implemented through virtual tables in memory. Is there some way to pre-fetch these virtual tables onto L2 cache (the cost of fetching from memory/L2 cache is increasing)? Apart from this, are there good references for data locality techniques in C++? These techniques would reduce the wait time for data fetch into L2 cache needed for computation. Update: Also see the following related forums: Performance Penalty for Interface, Several Levels of Base Classes A: Have you actually profiled and found where, and what needs optimization? Work on actually optimizing virtual function calls when you have found they actually are the bottleneck. A: The only optimization I can think of is Java's JIT compiler. If I understand it correctly, it monitors the calls as the code runs, and if most calls go to particular implementation only, it inserts conditional jump to implementation when the class is right. This way, most of the time, there is no vtable lookup. Of course, for the rare case when we pass a different class, vtable is still used. I am not aware of any C++ compiler/runtime that uses this technique. A: Virtual functions tend to be a lookup and indirection function call. On some platforms, this is fast. On others, e.g., one popular PPC architecture used in consoles, this isn't so fast. Optimizations usually revolve around expressing variability higher up in the callstack so that you don't need to invoke a virtual function multiple times within hotspots. A: Virtual functions are very efficient. Assuming 32 bit pointers the memory layout is approximately: classptr -> [vtable:4][classdata:x] vtable -> [first:4][second:4][third:4][fourth:4][...] first -> [code:x] second -> [code:x] ... The classptr points to memory that is typically on the heap, occasionally on the stack, and starts with a four byte pointer to the vtable for that class. But the important thing to remember is the vtable itself is not allocated memory. It's a static resource and all objects of the same class type will point to the exactly the same memory location for their vtable array. Calling on different instances won't pull different memory locations into L2 cache. This example from msdn shows the vtable for class A with virtual func1, func2, and func3. Nothing more than 12 bytes. There is a good chance the vtables of different classes will also be physically adjacent in the compiled library (you'll want to verify this is you're especially concerned) which could increase cache efficiency microscopically. CONST SEGMENT ??_7A@@6B@ DD FLAT:?func1@A@@UAEXXZ DD FLAT:?func2@A@@UAEXXZ DD FLAT:?func3@A@@UAEXXZ CONST ENDS The other performance concern would be instruction overhead of calling through a vtable function. This is also very efficient. Nearly identical to calling a non-virtual function. Again from the example from msdn: ; A* pa; ; pa->func3(); mov eax, DWORD PTR _pa$[ebp] mov edx, DWORD PTR [eax] mov ecx, DWORD PTR _pa$[ebp] call DWORD PTR [edx+8] In this example ebp, the stack frame base pointer, has the variable A* pa at zero offset. The register eax is loaded with the value at location [ebp], so it has the A*, and edx is loaded with the value at location [eax], so it has class A vtable. Then ecx is loaded with [ebp], because ecx represents "this" it now holds the A*, and finally the call is made to the value at location [edx+8] which is the third function address in the vtable. If this function call was not virtual the mov eax and mov edx would not be needed, but the difference in performance would be immeasurably small. A: You can implement polymorfism in runtime using virtual functions and in compile time by using templates. You can replace virtual functions with templates. Take a look at this article for more information - http://www.codeproject.com/KB/cpp/SimulationofVirtualFunc.aspx A: A solution to dynamic polymorphism could be static polymmorphism, usable if your types are known at compile type: The CRTP (Curiously recurring template pattern). http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern The explanation on Wikipedia is clear enough, and perhaps It could help you if you really determined virtual method calls were source of performance bottlenecks. A: Virtual calls do not present much greater overhead over normal functions. Although, the greatest loss is that a virtual function when called polymorphically cannot be inlined. And inlining will in a lot of situations represent some real gain in performance. Something You can do to prevent wastage of that facility in some situations is to declare the function inline virtual. Class A { inline virtual int foo() {...} }; And when you are at a point of code you are SURE about the type of the object being called, you may make an inline call that will avoid the polymorphic system and enable inlining by the compiler. class B : public A { inline virtual int foo() { //...do something different } void bar() { //logic... B::foo(); // more logic } }; In this example, the call to foo() will be made non-polymorphic and bound to B implementation of foo(). But do it only when you know for sure what the instance type is, because the automatic polymorphism feature will be gone, and this is not very obvious for later code readers. A: I'm reinforcing all answers that say in effect: * *If you don't actually know it's a problem, any concern about fixing it is probably misplaced. What you want to know is: * *What fraction of execution time (when it's actually running) is spent in the process of invoking methods, and in particular, which methods are the most costly (by this measure). Some profilers can give you this information indirectly. They need to summarize at the statement level, but exclusive of the time spent in the method itself. My favorite technique is to just pause it a number of times under a debugger. If the time spent in the process of virtual function invocations is significant, like say 20%, then on the average 1 out of 5 samples will show, at the bottom of the call stack, in the disassembly window, the instructions for following the virtual function pointer. If you don't actually see that, it is not a problem. In the process, you will probably see other things higher up the call stack, that actually are not needed and could save you a lot of time. A: As already stated by the other answers, the actual overhead of a virtual function call is fairly small. It may make a difference in a tight loop where it is called millions of times per second, but it's rarely a big deal. However, it may still have a bigger impact in that it's harder for the compiler to optimize. It can't inline the function call, because it doesn't know at compile-time which function will be called. That also makes some global optimizations harder. And how much performance does this cost you? It depends. It is usually nothing to worry about, but there are cases where it may mean a significant performance hit. And of course it also depends on the CPU architecture. On some, it can become quite expensive. But it's worth keeping in mind that any kind of runtime polymorphism carries more or less the same overhead. Implementing the same functionality via switch statements or similar, to select between a number of possible functions may not be cheaper. The only reliable way to optimize this would be if you could move some of the work to compile-time. If it is possible to implement part of it as static polymorphism, some speedup may be possible. But first, make sure you have a problem. Is the code actually too slow to be acceptable? Second, find out what makes it slow through a profiler. And third, fix it. A: Static polymorphism, as some users answered here. For example, WTL uses this method. A clear explanation of the WTL implementation can be found at http://www.codeproject.com/KB/wtl/wtl4mfc1.aspx#atltemplates A: Section 5.3.3 of the draft Technical Report on C++ Performance is entirely devoted to the overhead of virtual functions. A: You rarely have to worry about cache in regards to such commonly used items, since they're fetched once and kept there. Cache is only generally an issue when dealing with large data structures that either: * *Are large enough and used for a very long time by a single function so that function can push everything else you need out of the cache, or *Are randomly accessed enough that the data structures themselves aren't necessarily in cache when you load from them. Things like Vtables are generally not going to be a performance/cache/memory issue; usually there's only one Vtable per object type, and the object contains a pointer to the Vtable instead of the Vtable itself. So unless you have a few thousand types of objects, I don't think Vtables are going to thrash your cache. 1), by the way, is why functions like memcpy use cache-bypassing streaming instructions like movnt(dq|q) for extremely large (multi-megabyte) data inputs. A: The cost is more or less the same than normal functions nowadays for recent CPUS, but they can't be inlined. If you call the function millions times, the impact can be significant (try calling millions of times the same function, for example, once with inline once without, and you will see it can be twice slower if the function itself does something simple; this is not a theoritical case: it is quite common for a lot of numerical computation). A: With modern, ahead-looking, multiple-dispatching CPUs the overhead for a virtual function might well be zero. Nada. Zip. A: If an AI application does not require great deal of number crunching, I wouldn't worry about performance disadvantage of virtual functions. There will be a marginal performance hit, only if they appear in the complex computations which are evaluated repeatedly. I don't think you can force virtual table to stay in L2 cache either. There are a couple of optimizations available for virtual functions, * *People have written compilers that resort to code analysis and transformation of the program. But, these aren't a production grade compilers. *You could replace all virtual functions with equivalent "switch...case" blocks to call appropriate functions based on the type in the hierarchy. This way you'll get rid of compiler managed virtual table and you'll have your own virtual table in the form of switch...case block. Now, chances of your own virtual table being in the L2 cache are high as it in the code path. Remember, you'll need RTTI or your own "typeof" function to achieve this.
{ "language": "en", "url": "https://stackoverflow.com/questions/156257", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "17" }
Q: What is the equivalent of the C++ Pair in Java? Is there a good reason why there is no Pair<L,R> in Java? What would be the equivalent of this C++ construct? I would rather avoid reimplementing my own. It seems that 1.6 is providing something similar (AbstractMap.SimpleEntry<K,V>), but this looks quite convoluted. A: The biggest problem is probably that one can't ensure immutability on A and B (see How to ensure that type parameters are immutable) so hashCode() may give inconsistent results for the same Pair after is inserted in a collection for instance (this would give undefined behavior, see Defining equals in terms of mutable fields). For a particular (non generic) Pair class the programmer may ensure immutability by carefully choosing A and B to be immutable. Anyway, clearing generic's warnings from @PeterLawrey's answer (java 1.7) : public class Pair<A extends Comparable<? super A>, B extends Comparable<? super B>> implements Comparable<Pair<A, B>> { public final A first; public final B second; private Pair(A first, B second) { this.first = first; this.second = second; } public static <A extends Comparable<? super A>, B extends Comparable<? super B>> Pair<A, B> of(A first, B second) { return new Pair<A, B>(first, second); } @Override public int compareTo(Pair<A, B> o) { int cmp = o == null ? 1 : (this.first).compareTo(o.first); return cmp == 0 ? (this.second).compareTo(o.second) : cmp; } @Override public int hashCode() { return 31 * hashcode(first) + hashcode(second); } // TODO : move this to a helper class. private static int hashcode(Object o) { return o == null ? 0 : o.hashCode(); } @Override public boolean equals(Object obj) { if (!(obj instanceof Pair)) return false; if (this == obj) return true; return equal(first, ((Pair<?, ?>) obj).first) && equal(second, ((Pair<?, ?>) obj).second); } // TODO : move this to a helper class. private boolean equal(Object o1, Object o2) { return o1 == o2 || (o1 != null && o1.equals(o2)); } @Override public String toString() { return "(" + first + ", " + second + ')'; } } Additions/corrections much welcome :) In particular I am not quite sure about my use of Pair<?, ?>. For more info on why this syntax see Ensure that objects implement Comparable and for a detailed explanation How to implement a generic max(Comparable a, Comparable b) function in Java? A: Good News JavaFX has a key value Pair. Just add JavaFX as a dependency and import javafx.util.Pair, and use simply as in C++. Pair <Key, Value> e.g. Pair <Integer, Integer> pr = new Pair<Integer, Integer>() pr.get(key);// will return corresponding value A: In my opinion, there is no Pair in Java because, if you want to add extra functionality directly on the pair (e.g. Comparable), you must bound the types. In C++, we just don't care, and if types composing a pair do not have operator <, the pair::operator < will not compile as well. An example of Comparable with no bounding: public class Pair<F, S> implements Comparable<Pair<? extends F, ? extends S>> { public final F first; public final S second; /* ... */ public int compareTo(Pair<? extends F, ? extends S> that) { int cf = compare(first, that.first); return cf == 0 ? compare(second, that.second) : cf; } //Why null is decided to be less than everything? private static int compare(Object l, Object r) { if (l == null) { return r == null ? 0 : -1; } else { return r == null ? 1 : ((Comparable) (l)).compareTo(r); } } } /* ... */ Pair<Thread, HashMap<String, Integer>> a = /* ... */; Pair<Thread, HashMap<String, Integer>> b = /* ... */; //Runtime error here instead of compile error! System.out.println(a.compareTo(b)); An example of Comparable with compile-time check for whether type arguments are comparable: public class Pair< F extends Comparable<? super F>, S extends Comparable<? super S> > implements Comparable<Pair<? extends F, ? extends S>> { public final F first; public final S second; /* ... */ public int compareTo(Pair<? extends F, ? extends S> that) { int cf = compare(first, that.first); return cf == 0 ? compare(second, that.second) : cf; } //Why null is decided to be less than everything? private static < T extends Comparable<? super T> > int compare(T l, T r) { if (l == null) { return r == null ? 0 : -1; } else { return r == null ? 1 : l.compareTo(r); } } } /* ... */ //Will not compile because Thread is not Comparable<? super Thread> Pair<Thread, HashMap<String, Integer>> a = /* ... */; Pair<Thread, HashMap<String, Integer>> b = /* ... */; System.out.println(a.compareTo(b)); This is good, but this time you may not use non-comparable types as type arguments in Pair. One may use lots of Comparators for Pair in some utility class, but C++ people may not get it. Another way is to write lots of classes in a type hierarchy with different bounds on type arguments, but there are too many possible bounds and their combinations... A: Map.Entry interface come pretty close to c++ pair. Look at the concrete implementation, like AbstractMap.SimpleEntry and AbstractMap.SimpleImmutableEntry First item is getKey() and second is getValue(). A: The shortest pair that I could come up with is the following, using Lombok: @Data @AllArgsConstructor(staticName = "of") public class Pair<F, S> { private F first; private S second; } It has all the benefits of the answer from @arturh (except the comparability), it has hashCode, equals, toString and a static “constructor”. A: As many others have already stated, it really depends on the use case if a Pair class is useful or not. I think for a private helper function it is totally legitimate to use a Pair class if that makes your code more readable and is not worth the effort of creating yet another value class with all its boiler plate code. On the other hand, if your abstraction level requires you to clearly document the semantics of the class that contains two objects or values, then you should write a class for it. Usually that's the case if the data is a business object. As always, it requires skilled judgement. For your second question I recommend the Pair class from the Apache Commons libraries. Those might be considered as extended standard libraries for Java: https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/tuple/Pair.html You might also want to have a look at Apache Commons' EqualsBuilder, HashCodeBuilder and ToStringBuilder which simplify writing value classes for your business objects. A: According to the nature of Java language, I suppose people do not actually require a Pair, an interface is usually what they need. Here is an example: interface Pair<L, R> { public L getL(); public R getR(); } So, when people want to return two values they can do the following: ... //Calcuate the return value final Integer v1 = result1; final String v2 = result2; return new Pair<Integer, String>(){ Integer getL(){ return v1; } String getR(){ return v2; } } This is a pretty lightweight solution, and it answers the question "What is the semantic of a Pair<L,R>?". The answer is, this is an interface build with two (may be different) types, and it has methods to return each of them. It is up to you to add further semantic to it. For example, if you are using Position and REALLY want to indicate it in you code, you can define PositionX and PositionY that contains Integer, to make up a Pair<PositionX,PositionY>. If JSR 308 is available, you may also use Pair<@PositionX Integer, @PositionY Ingeger> to simplify that. EDIT: One thing I should indicate here is that the above definition explicitly relates the type parameter name and the method name. This is an answer to those argues that a Pair is lack of semantic information. Actually, the method getL means "give me the element that correspond to the type of type parameter L", which do means something. EDIT: Here is a simple utility class that can make life easier: class Pairs { static <L,R> Pair<L,R> makePair(final L l, final R r){ return new Pair<L,R>(){ public L getL() { return l; } public R getR() { return r; } }; } } usage: return Pairs.makePair(new Integer(100), "123"); A: JavaFX (which comes bundled with Java 8) has the Pair< A,B > class A: You can use javafx utility class, Pair which serves the same purpose as pair <> in c++. https://docs.oracle.com/javafx/2/api/javafx/util/Pair.html A: In a thread on comp.lang.java.help, Hunter Gratzner gives some arguments against the presence of a Pair construct in Java. The main argument is that a class Pair doesn't convey any semantics about the relationship between the two values (how do you know what "first" and "second" mean ?). A better practice is to write a very simple class, like the one Mike proposed, for each application you would have made of the Pair class. Map.Entry is an example of a pair that carry its meaning in its name. To sum up, in my opinion it is better to have a class Position(x,y), a class Range(begin,end) and a class Entry(key,value) rather than a generic Pair(first,second) that doesn't tell me anything about what it's supposed to do. A: Apache Commons Lang 3.0+ has a few Pair classes: http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/tuple/package-summary.html A: Collections.singletonMap(left, rigth); A: another terse lombok implementation import lombok.Value; @Value(staticConstructor = "of") public class Pair<F, S> { private final F first; private final S second; } A: Another way to implement Pair with. * *Public immutable fields, i.e. simple data structure. *Comparable. *Simple hash and equals. *Simple factory so you don't have to provide the types. e.g. Pair.of("hello", 1); public class Pair<FIRST, SECOND> implements Comparable<Pair<FIRST, SECOND>> { public final FIRST first; public final SECOND second; private Pair(FIRST first, SECOND second) { this.first = first; this.second = second; } public static <FIRST, SECOND> Pair<FIRST, SECOND> of(FIRST first, SECOND second) { return new Pair<FIRST, SECOND>(first, second); } @Override public int compareTo(Pair<FIRST, SECOND> o) { int cmp = compare(first, o.first); return cmp == 0 ? compare(second, o.second) : cmp; } // todo move this to a helper class. private static int compare(Object o1, Object o2) { return o1 == null ? o2 == null ? 0 : -1 : o2 == null ? +1 : ((Comparable) o1).compareTo(o2); } @Override public int hashCode() { return 31 * hashcode(first) + hashcode(second); } // todo move this to a helper class. private static int hashcode(Object o) { return o == null ? 0 : o.hashCode(); } @Override public boolean equals(Object obj) { if (!(obj instanceof Pair)) return false; if (this == obj) return true; return equal(first, ((Pair) obj).first) && equal(second, ((Pair) obj).second); } // todo move this to a helper class. private boolean equal(Object o1, Object o2) { return o1 == null ? o2 == null : (o1 == o2 || o1.equals(o2)); } @Override public String toString() { return "(" + first + ", " + second + ')'; } } A: Simple way Object [] - can be use as anу dimention tuple A: Despite being syntactically similar, Java and C++ have very different paradigms. Writing C++ like Java is bad C++, and writing Java like C++ is bad Java. With a reflection based IDE like Eclipse, writing the necessarily functionality of a "pair" class is quick and simple. Create class, define two fields, use the various "Generate XX" menu options to fill out the class in a matter of seconds. Maybe you'd have to type a "compareTo" real quick if you wanted the Comparable interface. With separate declaration / definition options in the language C++ code generators aren't so good, so hand writing little utility classes is more time consuming tedium. Because the pair is a template, you don't have to pay for functions you don't use, and the typedef facility allows assigning meaningful typenames to the code, so the objections about "no semantics" don't really hold up. A: How about http://www.javatuples.org/index.html I have found it very useful. The javatuples offers you tuple classes from one to ten elements: Unit<A> (1 element) Pair<A,B> (2 elements) Triplet<A,B,C> (3 elements) Quartet<A,B,C,D> (4 elements) Quintet<A,B,C,D,E> (5 elements) Sextet<A,B,C,D,E,F> (6 elements) Septet<A,B,C,D,E,F,G> (7 elements) Octet<A,B,C,D,E,F,G,H> (8 elements) Ennead<A,B,C,D,E,F,G,H,I> (9 elements) Decade<A,B,C,D,E,F,G,H,I,J> (10 elements) A: Pair would be a good stuff, to be a basic construction unit for a complex generics, for instance, this is from my code: WeakHashMap<Pair<String, String>, String> map = ... It is just the same as Haskell's Tuple A: For programming languages like Java, the alternate data structure used by most programmers to represent pair like data-structures are two array, and data is accessed via the same index example: http://www-igm.univ-mlv.fr/~lecroq/string/node8.html#SECTION0080 This isn't ideal as the data should be bound together, but also turn out to be pretty cheap. Also, if your use case demands storing co-ordinates then its better to build your own data structure. I've something like this in my library public class Pair<First,Second>{.. } A: You can use Google's AutoValue library - https://github.com/google/auto/tree/master/value. You create a very small abstract class and annotate it with @AutoValue and the annotation processor generates a concrete class for you that has a value semantic. A: Here are some libraries that have multiple degrees of tuples for your convenience: * *JavaTuples. Tuples from degree 1-10 is all it has. *JavaSlang. Tuples from degree 0-8 and lots of other functional goodies. *jOOλ. Tuples from degree 0-16 and some other functional goodies. (Disclaimer, I work for the maintainer company) *Functional Java. Tuples from degree 0-8 and lots of other functional goodies. Other libraries have been mentioned to contain at least the Pair tuple. Specifically, in the context of functional programming which makes use of a lot of structural typing, rather than nominal typing (as advocated in the accepted answer), those libraries and their tuples come in very handy. A: Brian Goetz, Paul Sandoz and Stuart Marks explain why during QA session at Devoxx'14. Having generic pair class in standard library will turn into technical debt once value types introduced. See also: Does Java SE 8 have Pairs or Tuples? A: This is Java. You have to make your own tailored Pair class with descriptive class and field names, and not to mind that you will reinvent the wheel by writing hashCode()/equals() or implementing Comparable again and again. A: android provides Pairclass (http://developer.android.com/reference/android/util/Pair.html) , here the implementation: public class Pair<F, S> { public final F first; public final S second; public Pair(F first, S second) { this.first = first; this.second = second; } @Override public boolean equals(Object o) { if (!(o instanceof Pair)) { return false; } Pair<?, ?> p = (Pair<?, ?>) o; return Objects.equal(p.first, first) && Objects.equal(p.second, second); } @Override public int hashCode() { return (first == null ? 0 : first.hashCode()) ^ (second == null ? 0 : second.hashCode()); } public static <A, B> Pair <A, B> create(A a, B b) { return new Pair<A, B>(a, b); } } A: It depends on what you want to use it for. The typical reason to do so is to iterate over maps, for which you simply do this (Java 5+): Map<String, Object> map = ... ; // just an example for (Map.Entry<String, Object> entry : map.entrySet()) { System.out.printf("%s -> %s\n", entry.getKey(), entry.getValue()); } A: HashMap compatible Pair class: public class Pair<A, B> { private A first; private B second; public Pair(A first, B second) { super(); this.first = first; this.second = second; } public int hashCode() { int hashFirst = first != null ? first.hashCode() : 0; int hashSecond = second != null ? second.hashCode() : 0; return (hashFirst + hashSecond) * hashSecond + hashFirst; } public boolean equals(Object other) { if (other instanceof Pair) { Pair otherPair = (Pair) other; return (( this.first == otherPair.first || ( this.first != null && otherPair.first != null && this.first.equals(otherPair.first))) && ( this.second == otherPair.second || ( this.second != null && otherPair.second != null && this.second.equals(otherPair.second))) ); } return false; } public String toString() { return "(" + first + ", " + second + ")"; } public A getFirst() { return first; } public void setFirst(A first) { this.first = first; } public B getSecond() { return second; } public void setSecond(B second) { this.second = second; } } A: I noticed all the Pair implementations being strewn around here attribute meaning to the order of the two values. When I think of a pair, I think of a combination of two items in which the order of the two is of no importance. Here's my implementation of an unordered pair, with hashCode and equals overrides to ensure the desired behaviour in collections. Also cloneable. /** * The class <code>Pair</code> models a container for two objects wherein the * object order is of no consequence for equality and hashing. An example of * using Pair would be as the return type for a method that needs to return two * related objects. Another good use is as entries in a Set or keys in a Map * when only the unordered combination of two objects is of interest.<p> * The term "object" as being a one of a Pair can be loosely interpreted. A * Pair may have one or two <code>null</code> entries as values. Both values * may also be the same object.<p> * Mind that the order of the type parameters T and U is of no importance. A * Pair&lt;T, U> can still return <code>true</code> for method <code>equals</code> * called with a Pair&lt;U, T> argument.<p> * Instances of this class are immutable, but the provided values might not be. * This means the consistency of equality checks and the hash code is only as * strong as that of the value types.<p> */ public class Pair<T, U> implements Cloneable { /** * One of the two values, for the declared type T. */ private final T object1; /** * One of the two values, for the declared type U. */ private final U object2; private final boolean object1Null; private final boolean object2Null; private final boolean dualNull; /** * Constructs a new <code>Pair&lt;T, U&gt;</code> with T object1 and U object2 as * its values. The order of the arguments is of no consequence. One or both of * the values may be <code>null</code> and both values may be the same object. * * @param object1 T to serve as one value. * @param object2 U to serve as the other value. */ public Pair(T object1, U object2) { this.object1 = object1; this.object2 = object2; object1Null = object1 == null; object2Null = object2 == null; dualNull = object1Null && object2Null; } /** * Gets the value of this Pair provided as the first argument in the constructor. * * @return a value of this Pair. */ public T getObject1() { return object1; } /** * Gets the value of this Pair provided as the second argument in the constructor. * * @return a value of this Pair. */ public U getObject2() { return object2; } /** * Returns a shallow copy of this Pair. The returned Pair is a new instance * created with the same values as this Pair. The values themselves are not * cloned. * * @return a clone of this Pair. */ @Override public Pair<T, U> clone() { return new Pair<T, U>(object1, object2); } /** * Indicates whether some other object is "equal" to this one. * This Pair is considered equal to the object if and only if * <ul> * <li>the Object argument is not null, * <li>the Object argument has a runtime type Pair or a subclass, * </ul> * AND * <ul> * <li>the Object argument refers to this pair * <li>OR this pair's values are both null and the other pair's values are both null * <li>OR this pair has one null value and the other pair has one null value and * the remaining non-null values of both pairs are equal * <li>OR both pairs have no null values and have value tuples &lt;v1, v2> of * this pair and &lt;o1, o2> of the other pair so that at least one of the * following statements is true: * <ul> * <li>v1 equals o1 and v2 equals o2 * <li>v1 equals o2 and v2 equals o1 * </ul> * </ul> * In any other case (such as when this pair has two null parts but the other * only one) this method returns false.<p> * The type parameters that were used for the other pair are of no importance. * A Pair&lt;T, U> can return <code>true</code> for equality testing with * a Pair&lt;T, V> even if V is neither a super- nor subtype of U, should * the the value equality checks be positive or the U and V type values * are both <code>null</code>. Type erasure for parameter types at compile * time means that type checks are delegated to calls of the <code>equals</code> * methods on the values themselves. * * @param obj the reference object with which to compare. * @return true if the object is a Pair equal to this one. */ @Override public boolean equals(Object obj) { if(obj == null) return false; if(this == obj) return true; if(!(obj instanceof Pair<?, ?>)) return false; final Pair<?, ?> otherPair = (Pair<?, ?>)obj; if(dualNull) return otherPair.dualNull; //After this we're sure at least one part in this is not null if(otherPair.dualNull) return false; //After this we're sure at least one part in obj is not null if(object1Null) { if(otherPair.object1Null) //Yes: this and other both have non-null part2 return object2.equals(otherPair.object2); else if(otherPair.object2Null) //Yes: this has non-null part2, other has non-null part1 return object2.equals(otherPair.object1); else //Remaining case: other has no non-null parts return false; } else if(object2Null) { if(otherPair.object2Null) //Yes: this and other both have non-null part1 return object1.equals(otherPair.object1); else if(otherPair.object1Null) //Yes: this has non-null part1, other has non-null part2 return object1.equals(otherPair.object2); else //Remaining case: other has no non-null parts return false; } else { //Transitive and symmetric requirements of equals will make sure //checking the following cases are sufficient if(object1.equals(otherPair.object1)) return object2.equals(otherPair.object2); else if(object1.equals(otherPair.object2)) return object2.equals(otherPair.object1); else return false; } } /** * Returns a hash code value for the pair. This is calculated as the sum * of the hash codes for the two values, wherein a value that is <code>null</code> * contributes 0 to the sum. This implementation adheres to the contract for * <code>hashCode()</code> as specified for <code>Object()</code>. The returned * value hash code consistently remain the same for multiple invocations * during an execution of a Java application, unless at least one of the pair * values has its hash code changed. That would imply information used for * equals in the changed value(s) has also changed, which would carry that * change onto this class' <code>equals</code> implementation. * * @return a hash code for this Pair. */ @Override public int hashCode() { int hashCode = object1Null ? 0 : object1.hashCode(); hashCode += (object2Null ? 0 : object2.hashCode()); return hashCode; } } This implementation has been properly unit tested and the use in a Set and Map has been tried out. Notice I'm not claiming to release this in the public domain. This is code I've just written for use in an application, so if you're going to use it, please refrain from making a direct copy and mess about with the comments and names a bit. Catch my drift? A: If anyone wants a dead-simple and easy to use version I made my available at https://github.com/lfac-pt/Java-Pair. Also, improvements are very much welcome! A: com.sun.tools.javac.util.Pair is an simple implementation of a pair. It can be found in jdk1.7.0_51\lib\tools.jar. Other than the org.apache.commons.lang3.tuple.Pair, it's not just an interface. A: public class Pair<K, V> { private final K element0; private final V element1; public static <K, V> Pair<K, V> createPair(K key, V value) { return new Pair<K, V>(key, value); } public Pair(K element0, V element1) { this.element0 = element0; this.element1 = element1; } public K getElement0() { return element0; } public V getElement1() { return element1; } } usage : Pair<Integer, String> pair = Pair.createPair(1, "test"); pair.getElement0(); pair.getElement1(); Immutable, only a pair ! A: Many people are posting Pair code that is usable as a key in a Map...If you're trying to use a pair as a hashing key (a common idiom), be sure to check out Guava's Table<R,C,V>: http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#Table. They give the following example usage, for graph edges: Table<Vertex, Vertex, Double> weightedGraph = HashBasedTable.create(); weightedGraph.put(v1, v2, 4); weightedGraph.put(v1, v3, 20); weightedGraph.put(v2, v3, 5); weightedGraph.row(v1); // returns a Map mapping v2 to 4, v3 to 20 weightedGraph.column(v3); // returns a Map mapping v1 to 20, v2 to 5 A Table maps two keys to a single value, and provides efficient lookups for both types of keys alone as well. I've started using this data structure instead of a Map<Pair<K1,K2>, V> in many parts of my code. There are array, tree, and other implementations for both dense and sparse uses, with the option of specifying your own intermediate map classes. A: With new version of Lombok you can compile that cute class: @Value(staticConstructor = "of") public class Pair <E> { E first, second; } and use it like: Pair<Value> pairOfValues = Pair.of(value1, value2); A: The answer by @Andreas Krey is actually good. Anything Java makes difficult, you probably shouldn't be doing. The most common uses of Pair's in my experience have been multiple return values from a method and as VALUES in a hashmap (often indexed by strings). In the latter case, I recently used a data structure, something like this: class SumHolder{MyObject trackedObject, double sum}; There is your entire "Pair" class, pretty much the same amount of code as a generic "Pair" but with the advantage of descriptive names. It can be defined in-line right in the method it's used which will eliminate typical problems with public variables and the like. In other words, it's absolutely better than a pair for this usage (due to the named members) and no worse. If you actually want a "Pair" for the key of a hashmap you are essentially creating a double-key index. I think this may be the one case where a "Pair" is significantly less code. It's not really easier because you could have eclipse generate equals/hash on your little data class, but it would be a good deal more code. Here a Pair would be a quick fix, but if you need a double-indexed hash who's to say you don't need an n-indexed hash? The data class solution will scale up, the Pair will not unless you nest them! So the second case, returning from a method, is a bit harder. Your class needs more visibility (the caller needs to see it too). You can define it outside the method but inside the class exactly as above. At that point your method should be able to return a MyClass.SumHolder object. The caller gets to see the names of the returned objects, not just a "Pair". Note again that the "Default" security of package level is pretty good--it's restrictive enough that you shouldn't get yourself into too much trouble. Better than a "Pair" object anyway. The other case I can see a use for Pairs is a public api with return values for callers outside your current package. For this I'd just create a true object--preferably immutable. Eventually a caller will share this return value and having it mutable could be problematic. This is another case of the Pair object being worse--most pairs cannot be made immutable. Another advantage to all these cases--the java class expands, my sum class needed a second sum and a "Created" flag by the time I was done, I would have had to throw away the Pair and gone with something else, but if the pair made sense, my class with 4 values still makes at least as much sense. A: Try VAVR Tuples. Not only does vavr have a good set of tuple types, it has great support for functional programming, too. A: Spring data has a Pair and can be used like below, Pair<S, T> pair = Pair.of(S type data, T type data) A: Although this question is over a decade old, I do feel the need to mention that, as of Java 14, Records can provide a very simple and light-weight solution to this problem without the need for any form of external library or dependencies. For example, the following record class declaration would be all that's required in order to achieve the desired functionality: record Pair<K, V>(K key, V value) { } Such a record class could be used as so: // Declare a pair object containing two integers var integerIntegerPair = new Pair<>(1, 2); // Declare a pair object containing a String and an integer var stringIntegerPair = new Pair<>("String", 20); // Declare a pair object containing two other pairs! var pairPairPair = new Pair<>(new Pair<>(1, 2), new Pair<>("String", 20));
{ "language": "en", "url": "https://stackoverflow.com/questions/156275", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "710" }
Q: Does setbuf() affect cout? Yet again, my teacher was unable to answer my question. I knew who may be able to... So, I've never really learned C. In C++, I would, obviously, use a cout statement all of the time. In a recent assignment, my teacher told us to make sure to put setbuf( stdout , NULL ); at the top of main() in order to get an unbuffered output, thus allowing us to see the output properly. My question is this: will this statement affect a cout statement, or simply a printf() statement that I call? Thanks in advance! A: By default, iostreams and stdio are synchronised. Reference. This doesn't mean that manually adjusting the stdio buffering is a good idea, though! You may wish to utilise std::endl or std::flush (from <ostream>), which may help you. e.g., std::cout << "Hello, world!" << std::endl; or std::cout << "Hello, world!\n" << std::flush; Both of these do the same thing. (std::endl = print endline, then flush.) A: By default, if stdout or cout is printing to a console, the output is line buffered. This means that every newline that is printed will flush the output. You can explicitly call flush() whenever you want to override the behavior just in case say, the output is going to be redirected to a file and you want to use tail -f and need certain outputs in realtime. As Chris said, sync_with_stdio should tie the unbuffered stdout with an unbuffered cout (by default), but if all you are doing is using cout, instead of using setbuf on stdout, a better option is to use pubsetbuf on the pointer returned by rdbuf. ie: // make cout unbuffered std::cout.rdbuf()->pubsetbuf(0, 0); Another function that may be interesting to look at is tie. A: Usually, when it's important to see the output immediately, we're talking about complex highly-reliable financial routine that must log a transaction all the way to hard drive before actually sending it to counterparty. Or, (much more common case) we want to see debug messages even when the program is crashing. Since you're studying, I'll assume you're dealing with the second case. In that case, my advice would be to use stderr rather than stdout. It is unbuffered by default, and you can redirect it separately from stdout, putting your output in one place and your logging in another.
{ "language": "en", "url": "https://stackoverflow.com/questions/156278", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to import a SQL Server .bak file into MySQL? The title is self explanatory. Is there a way of directly doing such kind of importing? A: I did not manage to find a way to do it directly. Instead I imported the bak file into SQL Server 2008 Express, and then used MySQL Migration Toolkit. Worked like a charm! A: The .BAK files from SQL server are in Microsoft Tape Format (MTF) ref: http://www.fpns.net/willy/msbackup.htm The bak file will probably contain the LDF and MDF files that SQL server uses to store the database. You will need to use SQL server to extract these. SQL Server Express is free and will do the job. So, install SQL Server Express edition, and open the SQL Server Powershell. There execute sqlcmd -S <COMPUTERNAME>\SQLExpress (whilst logged in as administrator) then issue the following command. restore filelistonly from disk='c:\temp\mydbName-2009-09-29-v10.bak'; GO This will list the contents of the backup - what you need is the first fields that tell you the logical names - one will be the actual database and the other the log file. RESTORE DATABASE mydbName FROM disk='c:\temp\mydbName-2009-09-29-v10.bak' WITH MOVE 'mydbName' TO 'c:\temp\mydbName_data.mdf', MOVE 'mydbName_log' TO 'c:\temp\mydbName_data.ldf'; GO At this point you have extracted the database - then install Microsoft's "Sql Web Data Administrator". together with this export tool and you will have an SQL script that contains the database. A: In this problem, the answer is not updated in a timely. So it's happy to say that in 2020 Migrating to MsSQL into MySQL is that much easy. An online converter like RebaseData will do your job with one click. You can just upload your .bak file which is from MsSQL and convert it into .sql format which is readable to MySQL. Additional note: This can not only convert your .bak files but also this site is for all types of Database migrations that you want. A: Although my MySQL background is limited, I don't think you have much luck doing that. However, you should be able to migrate over all of your data by restoring the db to a MSSQL server, then creating a SSIS or DTS package to send your tables and data to the MySQL server. hope this helps A: MySql have an application to import db from microsoft sql. Steps: * *Open MySql Workbench *Click on "Database Migration" (if it do not appear you have to install it from MySql update) *Follow the Migration Task List using the simple Wizard. A: I highly doubt it. You might want to use DTS/SSIS to do this as Levi says. One think that you might want to do is start the process without actually importing the data. Just do enough to get the basic table structures together. Then you are going to want to change around the resulting table structure, because whatever structure tat will likely be created will be shaky at best. You might also have to take this a step further and create a staging area that takes in all the data first n a string (varchar) form. Then you can create a script that does validation and conversion to get it into the "real" database, because the two databases don't always work well together, especially when dealing with dates. A: SQL Server databases are very Microsoft proprietary. Two options I can think of are: * *Dump the database in CSV, XML or similar format that you'd then load into MySQL. *Setup ODBC connection to MySQL and then using DTS transport the data. As Charles Graham has suggested, you may need to build the tables before doing this. But that's as easy as a cut and paste from SQL Enterprise Manager windows to the corresponding MySQL window. A: The method I used included part of Richard Harrison's method: So, install SQL Server 2008 Express edition, This requires the download of the Web Platform Installer "wpilauncher_n.exe" Once you have this installed click on the database selection ( you are also required to download Frameworks and Runtimes) After instalation go to the windows command prompt and: use sqlcmd -S \SQLExpress (whilst logged in as administrator) then issue the following command. restore filelistonly from disk='c:\temp\mydbName-2009-09-29-v10.bak'; GO This will list the contents of the backup - what you need is the first fields that tell you the logical names - one will be the actual database and the other the log file. RESTORE DATABASE mydbName FROM disk='c:\temp\mydbName-2009-09-29-v10.bak' WITH MOVE 'mydbName' TO 'c:\temp\mydbName_data.mdf', MOVE 'mydbName_log' TO 'c:\temp\mydbName_data.ldf'; GO I fired up Web Platform Installer and from the what's new tab I installed SQL Server Management Studio and browsed the db to make sure the data was there... At that point i tried the tool included with MSSQL "SQL Import and Export Wizard" but the result of the csv dump only included the column names... So instead I just exported results of queries like "select * from users" from the SQL Server Management Studio A: For those attempting Richard's solution above, here are some additional information that might help navigate common errors: 1) When running restore filelistonly you may get Operating system error 5(Access is denied). If that's the case, open SQL Server Configuration Manager and change the login for SQLEXPRESS to a user that has local write privileges. 2) @"This will list the contents of the backup - what you need is the first fields that tell you the logical names" - if your file lists more than two headers you will need to also account for what to do with those files in the RESTORE DATABASE command. If you don't indicate what to do with files beyond the database and the log, the system will apparently try to use the attributes listed in the .bak file. Restoring a file from someone else's environment will produce a 'The path has invalid attributes. It needs to be a directory' (as the path in question doesn't exist on your machine). Simply providing a MOVE statement resolves this problem. In my case there was a third FTData type file. The MOVE command I added: MOVE 'mydbName_log' TO 'c:\temp\mydbName_data.ldf', MOVE 'sysft_...' TO 'c:\temp\other'; in my case I actually had to make a new directory for the third file. Initially I tried to send it to the same folder as the .mdf file but that produced a 'failed to initialize correctly' error on the third FTData file when I executed the restore. A: The .bak file from SQL Server is specific to that database dialect, and not compatible with MySQL. Try using etlalchemy to migrate your SQL Server database into MySQL. It is an open-sourced tool that I created to facilitate easy migrations between different RDBMS's. Quick installation and examples are provided here on the github page, and a more detailed explanation of the project's origins can be found here.
{ "language": "en", "url": "https://stackoverflow.com/questions/156279", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "74" }
Q: Using Mercurial, is there an easy way to diff my working copy with the tip file in the default remote repository When using mercurial, I'd like to be able to diff the working copy of a file with the tip file in my default remote repository. Is there an easy way to do this? I know I can do an "hg incoming -p" to see the patch sets of changes coming in, but it'd be nice to just directly see the actual changes for a particular file that I'd get if I do a pull of the latest stuff (or what I might be about put push out). The easiest thing I can think of right now is to create a little script that takes a look at the default location in .hg/hgrc and downloads the file using curl (if it's over http, otherwise scp it over ssh, or just do a direct diff if it's on the local file system) and then to diff the working copy or the tip against that temporary copy. I'm trying to sell mercurial to my team, and one of my team members brought this up today as something that they're able to do easily in SVN with their GUI tools. A: After some digging, I came across the Rdiff extension that does most of what I want it to. It doesn't come with mercurial, but it can be installed by cloning the repository: hg clone http://hg.kublai.com/mercurial/extensions/rdiff And then modifing your ~/.hgrc file to load the extension: [extensions] rdiff=~/path/to/rdiff/repo/rdiff.py It's a little quirky in that it actually modifies the existing "hg diff" command by detecting if the first parameter is a remote URL. If it is then it will diff that file against your tip file in your local repo (not the working copy). This as the remote repo is first in the arguments, it's the reverse of what I'd expect, but you can pass "--reverse" to the hg diff command to switch that around. I could see these being potential enhancements to the extension, but for now, I can work around them with a bash/zsh shell function in my starup file. It does a temp checkin of my working copy (held by the mercurial transaction so it can be rolled back), executes the reverse diff, and then rolls the transaction back to return things back to the way they were: hgrdiff() { hg commit -m "temp commit for remote diff" && hg diff --reverse http://my_hardcoded_repo $* && hg rollback # revert the temporary commit } And then call it with: hgrdiff <filename to diff against remote repo tip> A: You could try having two repositories locally - one for incoming stuff, and one for outgoing. Then you should be able to do diff with any tools. See here: http://weblogs.java.net/blog/kohsuke/archive/2007/11/using_mercurial.html A: to expand on Lars method (for some reason comment doesn't work), you can use the -R option on the diff command to reference a local repository. That way you can use the same diff application that you've specified within hg A: Using templates you can get a list of all changed files: hg incoming --template {files}
{ "language": "en", "url": "https://stackoverflow.com/questions/156280", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: How should I order my ctor parameters for DI/IOC? I'm a bit of a DI newbie, so forgive me if this is the wrong approach or a silly question. Let's say I have a form which creates/updates an order, and I know it's going to need to retrieve a list of products and customers to display. I want to pass in the Order object that it's editing, but I also want to inject the ProductsService and CustomersService as dependencies. So I will want my IoC container (whichever one I go with) to supply the services, but it'll be up to the calling code to supply the Order object to edit. Should I declare the constructor as taking the Order object as the first parameter and the ProductsService and CustomersService after that, eg: public OrderForm(Order order, ProductsService prodsSvc, CustomersService custsSvc) ... or should the dependencies come first and the Order object last, eg: public OrderForm(ProductsService prodsSvc, CustomersService custsSvc, Order order) Does it matter? Does it depend on which IoC container I use? Or is there a "better" way? A: Matt, you shouldn't mix normal parameters with dependencies. Since your object will be created in the internals of IoC container, how are you going to specify necessary arguments? Mixing dependency and normal arguments will make logic of your program more complicated. In this case it would be better to declare dependency properties (i.e. remove dependencies from constructor) or initialize order field after IoC constructed OrderForm and resolved it's dependencies (i.e. remove normal parameters from constructor). Also you can declare all of your parameters, including order as dependencies. A: I disagree with @aku's answer. I think what you're doing is fine and there are also other ways to do it that are no more or less right. For instance, one may question whether this object should be depending on services in the first place. Regardless of DI, I feel it is helpful to clarify in your mind at least the kind of state each object holds, such as the real state (Order), derived state (if any), and dependencies (services): http://tech.puredanger.com/2007/09/18/spelunking/ On any constructor or method, I prefer the real data to be passed first and dependencies or external stuff to be passed last. So in your example I'd prefer the first. A: I feel a bit uneasy about allowing an instance of OrderForm to be instantiated without the required reference to an Order instance. One reason might be that this would prevent me from doing upfront checking for null orders. Any further thoughts? I suppose I could take some comfort in knowing that OrderForm objects will only be instantiated by a Factory method that ensures the Order property is set after making the call to the IoC framework. A: I am just a bit late to the party, but I would suggest using a factory in this case: the factory constructor would take the required *Service dependencies which the DI system would resolve and inject, while its Build() method would accept any additional state parameter - like Order. The factory would be, of course, registered itself in the DI system and would play just nicely with it. public class OrderFormFactory { private readonly ProductsService _prodsSvc; private readonly CustomersService _custsSvc; public OrderFormFactory(ProductsService prodsSvc, CustomersService custsSvc) { _prodsService = prodsService ?? throw new ArgumentNullException(nameof(prodsService)); _custsSvc = custsSvc ?? throw new ArgumentNullException(nameof(custsSvc)); } public OrderForm Build(Order order) { // TODO: Any additional logic return new OrderForm(_prodsService, _custsSvc, order); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/156292", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: C# Attributes On Fields How do I set an attribute on a field anywhere in my assembly, then reflect on those field attributes in my entire assembly and get/set the field values that the attribute is attached too? A: 1) Create custom attribute targeted for fields 2) Add it to desired fields 3) Iterate through types defined in your assembly 4) For each type: 4a) iterate through it's fields 4b) if field has your custom attribute go to step 4c 4c) get or set values of field
{ "language": "en", "url": "https://stackoverflow.com/questions/156304", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: Mask redirect to temporary domain with mod_rewrite We are putting up a company blog at companyname.com/blog but for now the blog is a Wordpress installation that lives on a different server (blog.companyname.com). The intention is to have the blog and web site both on the same server in a month or two, but that leaves a problem in the interim. At the moment I am using mod_rewrite to do the following: http://companyname.com/blog/article-name redirects to http://blog.companyname.com/article-name Can I somehow keep the address bar displaying companyname.com/blog even though the content is coming from the latter blog.companyname.com? I can see how to do this if it is on the same server and vhost, but not across a different server? Thanks A: Rather than using mod_rewrite, you could use mod_proxy to set up a reverse proxy on companyname.com, so that requests to http://companyname.com/blog/article-name are proxied (rather than redirected) to http://blog.companyname.com/article-name. Here are more instructions and examples. A: There is functionality with ZoneEdit called webforwards which could probably do this and hide what you are actually doing (unless someone looked into it). A: The only thing that mod_rewrite can do is send HTTP header redirects, and those redirects (across servers) always result in the browser address bar reflecting the reality. You should instead consider writing a 404 script that 'reflects' the blog. This would essentially be a transparent proxy, and many are already written. The script would find if the requested page (that was 404'd) started with http://mycompany.com/blog/ . If it did, it would download and then send onto the client the blog page and associated files (probably caching them as well). So requesting http://mycompany.com/blog/article_xyz would cause the 404 script to download and send http://blog.companyname.com/article_xyz. It's probably more work than it's worth, but you might be able to design a simple enough 404 script that it's worthwhile. -Adam
{ "language": "en", "url": "https://stackoverflow.com/questions/156315", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: What do people think of the fossil DVCS? fossil http://www.fossil-scm.org I found this recently and have started using it for my home projects. I want to hear what other people think of this VCS. What is missing in my mind, is IDE support. Hopefully it will come, but I use the command line just fine. My favorite things about fossil: single executable with built in web server wiki and bug tracking. The repository is just one SQLite (http://www.sqlite.org) database file, easy to do backups on. I also like that I can run fossil from and keep the repository on my thumb drive. This means my software development has become completely portable. Tell me what you think.... A: I'm not interested in using it for source-code version control, but I am interested in a distributed version-controlled personal wiki that I can sync between all the machines I use. A: After having used Fossil for more than a year now on non-trivial development projects, I feel confident enough to weigh in on this topic. Below is my experience so far. I'm comparing against git and svn at times, simply because I know those SCM's very well and comparing makes it easier for me to get the idea across. I'm totally in love with this SCM, so it's mostly points on the plus side. What I like about Fossil: * *We have a bunch of machines (win/mac/a number of Linux distros), and the single-executable installation is just as beautiful as it sounds. No dependencies; it just works. Git is a messy pile of files and the dependency hell in Subversion makes it very nasty on some Linux distributions, especially if you must build it yourself. *The default Fossil workflow suits our projects perfectly, and more git'ish workflows are possible when needed. *We've found it extremely robust, even on large projects. I wouldn't expect anything else from the guys who wrote SQLite. No crashes, no corruption, no funny business. *I'm actually very, very happy with performance. Not as fast as git on huge trees, but not much slower either. I make up any lost time by not having to consult the documentation every other command, as is the case with git. *The fact that there's a tried'n'true transactional database behind every operation makes me sleep better at night. Yes, we've been through more than one horrible incident of stale and corrupt Subversion repositories (thankfully, a helpful community helped us fix them.) I can't imagine that happening in Fossil. Even Subversion 1.7.x use SQLite now for metadata storage. (Try turning off power in the midst of a git commit - it'll leave a corrupt repos!) *The integrated issue tracker and wiki are optional, obviously, but very handy as it's always there - no installation required. I wish the issue tracker had some more features though, but hey - it's an SCM. *The built-in server and web gui is simply brilliant and quite configurable through css. *We sometimes need to import to and from git and subversion repositories. This is a no-brainer in Fossil. *Single file repository. No '.svn' directories all over the place. What I miss in / dislike about Fossil: * *Someone please write TortoiseFossil for our non-technical Windows users :) *The community isn't that large yet, so it's probably hard for a lot of people to introduce it in their company. Hopefully this will change, gaining all the benefits of a large community (documentation, more testing of new releases, etc.) *I wish the local web ui had a search feature (including searching for file content). *Fewer merge options than in git (though the Fossil workflow makes merging less likely to occur in the first place.) I hope everyone gives Fossil a run - the world is a better place with stuff that just works and which you don't need to be a rocket scientist to use. A: damian, 1/ yes, fossil doesn't support recursive add. However there are some fairly simply workarounds such as for /r %i in (*.*) do fossil add "%i" on Windows, and find . -type f -print0 | xargs -0 fossil add -- on Unix. 2/ I saw the message about malformed manifest when you are adding a file with non-ASCII characters in the filename. The problem was corrected in the last build. Regards, Petr A: I think fossil is really cool. The most important feature for me was easy installation, and developer friendly defaults. I currently use it to keep track of the local changes of my files. (Our project is hosted in sourceforge and kept track in CVS.) This way I can "commit" locally even if it would otherwise break the project, so smaller changes can be kept track as well. A: Mr. Millikin, if you will take a few moments to review some of the documentation on fossil, I think your objections are addressed there. Storing a repository in an sQLite database is arguably safer than any other approach. See link text for some of the advantages of using a transactional database to store a repository. As for bloat: The entire thing is in a single self-contained executable which seems to disprove that concern. Full disclosure: I am the author of fossil. Note that I wrote fossil because no other DVCS met my needs. On the other hand, my needs are not your needs and so only you can judge whether or not fossil is right for you. But I do encourage you to at least have a look at the documentation and try to understand the problem that fossil is trying to solve before you dismiss it. A: Fossil is small, simple, yet powerful and robust, reminds me some principles of C Culture. Likable by those who develop independently and still collaborate. Any great project should start with principles and continue them at its core as it gathers more layers (GUI, extra features). I am impressed with Fossil and starting to use... take a look at fossil cheers A: I'm landing on this page after an year of the last post, recursive add that has been mentioned here is now taken care of. Fossil mesmerizes me with simplicity especially after I struggled to get a bug-tracking system to work with mercurial. I need to see how to manage multiple projects, publish the repositories for multi-user access and how to do merging, manage patches etc. I get the feeling that it wont be disappointing going forward. A: Fossil is good. It is simple and easy to use. If fossil can provide GUI interface to check in and check out, then it would be better (prefer java gui to archive cross-platform GUI). The main advantages of Fossil are "open source" and "use SQLite database", so somebody can compile fossil source code to make fossil work on google android platform (mobile and tablet devices). A: I am trying your vcs right now. I like the idea of having all integrated. After all, is all i want when i look for a system like this. I am an active user of Mercurial. And i couldn't find an integration with a issue tracker (I try unsuccessfully to set p Trac with mercurial in the past). After some test i realize that: 1) "add" command is not recursively, or i can not found in the doc a way to do it 2) i write a bat (i work with windows) to add 750 files and i run it (it took a while). When a run commit it jumps with "manifest malformed" i think you could address this issues and others making a survey like the Mercurial's one in https://www.mercurial-scm.org/wiki/UserSurvey. you could write me at dnoseda at gmail i am interested in you work. keep improve it. regards ps.: as an mayor improvement you could add something like gitstat A: Perhaps an uneducated knee-jerk reaction, but the idea of storing a repository in a binary blob like an SQLite database terrifies me. I'm also dubious of the benefits of including wikis and bug trackers directly in the VCS -- either they're under-featured compared to full software like Trac, or the VCS is massively bloated compared to Subversion or Bazaar.
{ "language": "en", "url": "https://stackoverflow.com/questions/156322", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "124" }
Q: Is there a standard encoding for NEEDED entries in ELF? I'm trying to make some of my code a bit more friendly to non-pure-ascii systems and was wondering if there was a particular character encoding used for NEEDED entries in ELF binaries, or is it rather unstandard and based on the creating system's filesystem encoding (or even just directly the bytes that were passed to whatever created the binary) (if so is there any place in the binary that specifies the encoding? assuming the current systems encoding wouldn't work very well for my usage I think), are non-ascii names pretty much banned or something else? A: ELF format specifies NEEDED fields as "null-terminated string" and does not say more about the encoding, which pretty much implies 8-bit ASCII string. I personally don't see any point in complicating executable file format specification that does not provide any additional value for the final product or development process: the user won't see library names, so they wouldn't care about localization of thereof. You may try to use UTF-8, but actual file system encoding is not guaranteed to be UTF-8. To be sure you need to know how your target linker handles those strings. A: As far as I know, the standard Unix way of dealing with non-ASCII characters is to encode them as UTF-8.
{ "language": "en", "url": "https://stackoverflow.com/questions/156327", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: unwanted leading blank space on oracle number format I need to pad numbers with leading zeros (total 8 digits) for display. I'm using oracle. select to_char(1011,'00000000') OPE_NO from dual; select length(to_char(1011,'00000000')) OPE_NO from dual; Instead of '00001011' I get ' 00001011'. Why do I get an extra leading blank space? What is the correct number formatting string to accomplish this? P.S. I realise I can just use trim(), but I want to understand number formatting better. @Eddie: I already read the documentation. And yet I still don't understand how to get rid of the leading whitespace. @David: So does that mean there's no way but to use trim()? A: From that same documentation mentioned by EddieAwad: Negative return values automatically contain a leading negative sign and positive values automatically contain a leading space unless the format model contains the MI, S, or PR format element. EDIT: The right way is to use the FM modifier, as answered by Steve Bosman. Read the section about Format Model Modifiers for more info. A: Use FM (Fill Mode), e.g. select to_char(1011,'FM00000000') OPE_NO from dual;
{ "language": "en", "url": "https://stackoverflow.com/questions/156329", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "18" }
Q: Get timer ticks in Python I'm just trying to time a piece of code. The pseudocode looks like: start = get_ticks() do_long_code() print "It took " + (get_ticks() - start) + " seconds." How does this look in Python? More specifically, how do I get the number of ticks since midnight (or however Python organizes that timing)? A: Here's a solution that I started using recently: class Timer: def __enter__(self): self.begin = now() def __exit__(self, type, value, traceback): print(format_delta(self.begin, now())) You use it like this (You need at least Python 2.5): with Timer(): do_long_code() When your code finishes, Timer automatically prints out the run time. Sweet! If I'm trying to quickly bench something in the Python Interpreter, this is the easiest way to go. And here's a sample implementation of 'now' and 'format_delta', though feel free to use your preferred timing and formatting method. import datetime def now(): return datetime.datetime.now() # Prints one of the following formats*: # 1.58 days # 2.98 hours # 9.28 minutes # Not actually added yet, oops. # 5.60 seconds # 790 milliseconds # *Except I prefer abbreviated formats, so I print d,h,m,s, or ms. def format_delta(start,end): # Time in microseconds one_day = 86400000000 one_hour = 3600000000 one_second = 1000000 one_millisecond = 1000 delta = end - start build_time_us = delta.microseconds + delta.seconds * one_second + delta.days * one_day days = 0 while build_time_us > one_day: build_time_us -= one_day days += 1 if days > 0: time_str = "%.2fd" % ( days + build_time_us / float(one_day) ) else: hours = 0 while build_time_us > one_hour: build_time_us -= one_hour hours += 1 if hours > 0: time_str = "%.2fh" % ( hours + build_time_us / float(one_hour) ) else: seconds = 0 while build_time_us > one_second: build_time_us -= one_second seconds += 1 if seconds > 0: time_str = "%.2fs" % ( seconds + build_time_us / float(one_second) ) else: ms = 0 while build_time_us > one_millisecond: build_time_us -= one_millisecond ms += 1 time_str = "%.2fms" % ( ms + build_time_us / float(one_millisecond) ) return time_str Please let me know if you have a preferred formatting method, or if there's an easier way to do all of this! A: In the time module, there are two timing functions: time and clock. time gives you "wall" time, if this is what you care about. However, the python docs say that clock should be used for benchmarking. Note that clock behaves different in separate systems: * *on MS Windows, it uses the Win32 function QueryPerformanceCounter(), with "resolution typically better than a microsecond". It has no special meaning, it's just a number (it starts counting the first time you call clock in your process). # ms windows t0= time.clock() do_something() t= time.clock() - t0 # t is wall seconds elapsed (floating point) * *on *nix, clock reports CPU time. Now, this is different, and most probably the value you want, since your program hardly ever is the only process requesting CPU time (even if you have no other processes, the kernel uses CPU time now and then). So, this number, which typically is smaller¹ than the wall time (i.e. time.time() - t0), is more meaningful when benchmarking code: # linux t0= time.clock() do_something() t= time.clock() - t0 # t is CPU seconds elapsed (floating point) Apart from all that, the timeit module has the Timer class that is supposed to use what's best for benchmarking from the available functionality. ¹ unless threading gets in the way… ² Python ≥3.3: there are time.perf_counter() and time.process_time(). perf_counter is being used by the timeit module. A: What you need is time() function from time module: import time start = time.time() do_long_code() print "it took", time.time() - start, "seconds." You can use timeit module for more options though. A: import datetime start = datetime.datetime.now() do_long_code() finish = datetime.datetime.now() delta = finish - start print delta.seconds From midnight: import datetime midnight = datetime.datetime.now().replace(hour=0, minute=0, second=0, microsecond=0) now = datetime.datetime.now() delta = now - midnight print delta.seconds A: The time module in python gives you access to the clock() function, which returns time in seconds as a floating point. Different systems will have different accuracy based on their internal clock setup (ticks per second) but it's generally at least under 20milliseconds, and in some cases better than a few microseconds. -Adam A: If you have many statements you want to time, you could use something like this: class Ticker: def __init__(self): self.t = clock() def __call__(self): dt = clock() - self.t self.t = clock() return 1000 * dt Then your code could look like: tick = Ticker() # first command print('first took {}ms'.format(tick()) # second group of commands print('second took {}ms'.format(tick()) # third group of commands print('third took {}ms'.format(tick()) That way you don't need to type t = time() before each block and 1000 * (time() - t) after it, while still keeping control over formatting (though you could easily put that in Ticket too). It's a minimal gain, but I think it's kind of convenient.
{ "language": "en", "url": "https://stackoverflow.com/questions/156330", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "44" }
Q: Wouldn't MS Access(.mdb) file size reduce after deleting the content of database? I was inserting data into a MS Access database using JDBC-ODBC driver. The blank mdb file was 2KB. After populating this database, the size grew to 155MB. Then I was deleting the data. But I found the size of mdb remains the same as 155MB. I don't get any errors. But is it normal this way? I would expect the file size reduces. If it is designed in this way, what is the idea behind it? Thanks A: MS Access doesn't reclaim the space for records until you have compacted the database. This is something you should do to an access database as part of your regularly maintenance otherwise you will end up with some pretty painful problems. You can compact a database either through the MS Access UI (Tools -> Database Utilities -> Compact and Repair Database) of you can use the command prompt using: msaccess.exe "target database.accdb" /compact N.B. the /Compact switch must be after the target database A: The first stop, as mentioned should be attempting to compact/repair the database. However you can also get some size saving past that by creating a new database and importing all of the objects from the old. A: MS Access doesn't free up space used by records even after they are deleted. You can free the space manually when you need to or automatically each time you close the application. To do it manually, use the Compact and Repair utility: * *Backup your database, as there is a bug in Access 2007 that may delete your database during the compacting procedure. *If you are compacting a multiuser (shared) database that is located on a server or shared folder, make sure that no one else has it open. *On the Tools menu, point to Database Utilities, and then click Compact and Repair Database. To do it automatically when you close the application: * *Open the database that you want MS Access to compact automatically. *On the Tools menu, click Options, and then choose the General tab. *Select the Compact On Close check box. After deleting the data and compacting the database don't be surprised if is still larger than 100 KB. There is a certain amount of overhead that cannot be removed after you add data the first time. Also, beware that AutoNumber field values behave differently than advertised after the compacting procedure: According to the MS Access 2000 documentation, if you delete records from the end of a table that has an AutoNumber field, compacting the database resets the AutoNumber value. So the AutoNumber value of the next record you add will be one greater than the AutoNumber value of the last undeleted record in the table. I have not found this to be the case: If you have 100 Autonumbered records and delete the last 50, the next AutoNumber record (according to the documentation) should be numbered "51". But in my experience it is numbered "101", instead. A: You can compact the database from code using JRO. See: http://support.microsoft.com/kb/230501 A: The first stop, as mentioned should be attempting to compact/repair the database. However you can also get some size saving past that by creating a new database and importing all of the objects from the old. Past that, converting it to an MDE should get you a hair more. As always, don't play around with your production copy. Also if you go with an MDE, make sure you have properly split the database first. (And of course keep a copy of the source MDB should you need to make modifications in the future.)
{ "language": "en", "url": "https://stackoverflow.com/questions/156331", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "29" }
Q: Does a (.net) COM+ assembly need to be installed in the GAC? I have a .net assembly that has a COM+ ServicedCopmonent in it and at the moment I install it into the GAC to get everything working. This means that I need to have every assembly that it references in the GAC as well. During development it is quite painful to make changes to thes assemblies, re-install them to the GAC and then test. Is it possible to maintain the COM+ component but not have everything in the GAC? A: No, you don't have to install it in the GAC. You can use regsvcs (http://msdn.microsoft.com/en-us/library/04za0hca.aspx) with /appdir parameter to specify explicitly where the app is located. A: No, they need to be registered in the Registry using the regsvcs tool. It needs to be a strongly named assembly though.
{ "language": "en", "url": "https://stackoverflow.com/questions/156338", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: flash: for loops running slow I have a question about loops in flash.... In a tile game I'm making a have a mini map of the whole level. The way it renders the map is a function with a for loop in another for loop. It cycles through each tile position and attaches a map piece (basically a 3x3 pixel square) which is colored according to what the tile is. Anyway, my problem is that when the level gets big like 50x50 tiles the map redering takes forever (up to 3 seconds). Is there anyway to fix this? Or is there another way of doing a mini-map?? If the level gets ever bigger it could take like 10 seconds! Any help is appreciated! Thanks, Matt A: Flash doesn't render tiles very fast. It's great at storing graphics that don't change in a buffer and quickly displaying this buffer quickly. Every graphics object (or sprite) that is added as a child to the stage has to be rendered independently. Your problem is flash has to draw 50x50 = 2500 tiles every frame! Even if they 3x3 pixels, flash still treats them as separate objects. It would be nice if you could store everything in a buffer or in one object and display it. So try drawing these 3x3 tiles in the same object instead of multiple objects. However this might hinder your functionality as the whole object will have to be re-rendered every frame. Some other suggestions might be to render the objects in larger cells on a grid. Instead of having 50x50, start with 10x10 and then draw 5x5 cells in each cell. This would probably speed things up. Hope this helps. If you find a good solution please post! A: Yes. The loop itself does not take long at all. But in each iteration I'm attaching a movieClip from the library. By the way it's not doing this on enterFrame, just when the user presses Pause (space). A: Most likely it's (as mentioned here) your loop that's slow. Counting 0-2500 is really fast but if you're doing heavy calculations in each iteration it will add up. Of course without seeing the code we can't help you with this. While you could do tricks to get that same loop run smoother (such as running it over multiple frames) but if it's a 3sec loop there's probably a lot you can do to optimize it – maybe even to the extent where it will run smooth enough, so that it won't cause a too long hickup. A: It shouldn't take long for the loops themselves to run, but what, exactly, are you doing inside each loop? What are the operations for attaching and coloring a map piece? -Adam
{ "language": "en", "url": "https://stackoverflow.com/questions/156356", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Get all items from thread Queue I have one thread that writes results into a Queue. In another thread (GUI), I periodically (in the IDLE event) check if there are results in the queue, like this: def queue_get_all(q): items = [] while 1: try: items.append(q.get_nowait()) except Empty, e: break return items Is this a good way to do it ? Edit: I'm asking because sometimes the waiting thread gets stuck for a few seconds without taking out new results. The "stuck" problem turned out to be because I was doing the processing in the idle event handler, without making sure that such events are actually generated by calling wx.WakeUpIdle, as is recommended. A: I'd be very surprised if the get_nowait() call caused the pause by not returning if the list was empty. Could it be that you're posting a large number of (maybe big?) items between checks which means the receiving thread has a large amount of data to pull out of the Queue? You could try limiting the number you retrieve in one batch: def queue_get_all(q): items = [] maxItemsToRetrieve = 10 for numOfItemsRetrieved in range(0, maxItemsToRetrieve): try: if numOfItemsRetrieved == maxItemsToRetrieve: break items.append(q.get_nowait()) except Empty, e: break return items This would limit the receiving thread to pulling up to 10 items at a time. A: The simplest method is using a list comprehension: items = [q.get() for _ in range(q.qsize())] Use of the range function is generally frowned upon, but I haven't found a simpler method yet. A: If you're done writing to the queue, qsize should do the trick without needing to check the queue for each iteration. responseList = [] for items in range(0, q.qsize()): responseList.append(q.get_nowait()) A: If you're always pulling all available items off the queue, is there any real point in using a queue, rather than just a list with a lock? ie: from __future__ import with_statement import threading class ItemStore(object): def __init__(self): self.lock = threading.Lock() self.items = [] def add(self, item): with self.lock: self.items.append(item) def getAll(self): with self.lock: items, self.items = self.items, [] return items If you're also pulling them individually, and making use of the blocking behaviour for empty queues, then you should use Queue, but your use case looks much simpler, and might be better served by the above approach. [Edit2] I'd missed the fact that you're polling the queue from an idle loop, and from your update, I see that the problem isn't related to contention, so the below approach isn't really relevant to your problem. I've left it in in case anyone finds a blocking variant of this useful: For cases where you do want to block until you get at least one result, you can modify the above code to wait for data to become available through being signalled by the producer thread. Eg. class ItemStore(object): def __init__(self): self.cond = threading.Condition() self.items = [] def add(self, item): with self.cond: self.items.append(item) self.cond.notify() # Wake 1 thread waiting on cond (if any) def getAll(self, blocking=False): with self.cond: # If blocking is true, always return at least 1 item while blocking and len(self.items) == 0: self.cond.wait() items, self.items = self.items, [] return items A: I think the easiest way of getting all items out of the queue is the following: def get_all_queue_result(queue): result_list = [] while not queue.empty(): result_list.append(queue.get()) return result_list A: I see you are using get_nowait() which according to the documentation, "return[s] an item if one is immediately available, else raise the Empty exception" Now, you happen to break out of the loop when an Empty exception is thrown. Thus, if there is no result immediately available in the queue, your function returns an empty items list. Is there a reason why you are not using the get() method instead? It may be the case that the get_nowait() fails because the queue is servicing a put() request at that same moment.
{ "language": "en", "url": "https://stackoverflow.com/questions/156360", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "17" }
Q: What is the difference between include and extend in Ruby? Just getting my head around Ruby metaprogramming. The mixin/modules always manage to confuse me. * *include: mixes in specified module methods as instance methods in the target class *extend: mixes in specified module methods as class methods in the target class So is the major difference just this or is a bigger dragon lurking? e.g. module ReusableModule def module_method puts "Module Method: Hi there!" end end class ClassThatIncludes include ReusableModule end class ClassThatExtends extend ReusableModule end puts "Include" ClassThatIncludes.new.module_method # "Module Method: Hi there!" puts "Extend" ClassThatExtends.module_method # "Module Method: Hi there!" A: extend - adds the specified module's methods and constants to the target's metaclass (i.e. the singleton class) e.g. * *if you call Klazz.extend(Mod), now Klazz has Mod's methods (as class methods) *if you call obj.extend(Mod), now obj has Mod's methods (as instance methods), but no other instance of of obj.class has those methods added. *extend is a public method include - By default, it mixes in the specified module's methods as instance methods in the target module/class. e.g. * *if you call class Klazz; include Mod; end;, now all instances of Klazz have access to Mod's methods (as instance methods) *include is a private method, because it's intended to be called from within the container class/module. However, modules very often override include's behavior by monkey-patching the included method. This is very prominent in legacy Rails code. more details from Yehuda Katz. Further details about include, with its default behavior, assuming you've run the following code class Klazz include Mod end * *If Mod is already included in Klazz, or one of its ancestors, the include statement has no effect *It also includes Mod's constants in Klazz, as long as they don't clash *It gives Klazz access to Mod's module variables, e.g. @@foo or @@bar *raises ArgumentError if there are cyclic includes *Attaches the module as the caller's immediate ancestor (i.e. It adds Mod to Klazz.ancestors, but Mod is not added to the chain of Klazz.superclass.superclass.superclass. So, calling super in Klazz#foo will check for Mod#foo before checking to Klazz's real superclass's foo method. See the RubySpec for details.). Of course, the ruby core documentation is always the best place to go for these things. The RubySpec project was also a fantastic resource, because they documented the functionality precisely. * *#include RubySpec rubydoc *#included RubySpec rubydoc *#extend RubySpec rubydoc *#extended RubySpec rubydoc *#extend_object RubySpec rubydoc *#append_features RubySpec rubydoc A: All the other answers are good, including the tip to dig through RubySpecs: https://github.com/rubyspec/rubyspec/blob/master/core/module/include_spec.rb https://github.com/rubyspec/rubyspec/blob/master/core/module/extend_object_spec.rb As for use cases: If you include module ReusableModule in class ClassThatIncludes, the methods, constants, classes, submodules, and other declarations gets referenced. If you extend class ClassThatExtends with module ReusableModule, then the methods and constants gets copied. Obviously, if you are not careful, you can waste a lot of memory by dynamically duplicating definitions. If you use ActiveSupport::Concern, the .included() functionality lets you rewrite the including class directly. module ClassMethods inside a Concern gets extended (copied) into the including class. A: I would also like to explain the mechanism as it works. If I am not right please correct. When we use include we are adding a linkage from our class to a module which contains some methods. class A include MyMOd end a = A.new a.some_method Objects don't have methods, only clases and modules do. So when a receives mesage some_method it begin search method some_method in a's eigen class, then in A class and then in linked to A class modules if there are some (in reverse order, last included wins). When we use extend we are adding linkage to a module in object's eigen class. So if we use A.new.extend(MyMod) we are adding linkage to our module to A's instance eigen class or a' class. And if we use A.extend(MyMod) we are adding linkage to A(object's, classes are also objects) eigenclass A'. so method lookup path for a is as follows: a => a' => linked modules to a' class => A. also there is a prepend method which changes lookup path: a => a' => prepended modulesto A => A => included module to A sorry for my bad english. A: What you have said is correct. However, there is more to it than that. If you have a class Klazz and module Mod, including Mod in Klazz gives instances of Klazz access to Mod's methods. Or you can extend Klazz with Mod giving the class Klazz access to Mod's methods. But you can also extend an arbitrary object with o.extend Mod. In this case the individual object gets Mod's methods even though all other objects with the same class as o do not. A: That's correct. Behind the scenes, include is actually an alias for append_features, which (from the docs): Ruby's default implementation is to add the constants, methods, and module variables of this module to aModule if this module has not already been added to aModule or one of its ancestors. A: When you include a module into a class, the module methods are imported as instance methods. However, when you extend a module into a class, the module methods are imported as class methods. For example, if we have a module Module_test defined as follows: module Module_test def func puts "M - in module" end end Now, for include module. If we define the class A as follows: class A include Module_test end a = A.new a.func The output will be: M - in module. If we replace the line include Module_test with extend Module_test and run the code again, we receive the following error: undefined method 'func' for #<A:instance_num> (NoMethodError). Changing the method call a.func to A.func, the output changes to: M - in module. From the above code execution, it is clear that when we include a module, its methods become instance methods and when we extend a module, its methods become class methods. A: I came across a very useful article that compares include, extend and prepend methods used inside a class: include adds module methods as instance methods to the class, whereas extend adds module methods as class methods. The module being included or extended must be defined accordingly
{ "language": "en", "url": "https://stackoverflow.com/questions/156362", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "476" }
Q: Which languages support *recursive* function literals / anonymous functions? It seems quite a few mainstream languages support function literals these days. They are also called anonymous functions, but I don't care if they have a name. The important thing is that a function literal is an expression which yields a function which hasn't already been defined elsewhere, so for example in C, &printf doesn't count. EDIT to add: if you have a genuine function literal expression <exp>, you should be able to pass it to a function f(<exp>) or immediately apply it to an argument, ie. <exp>(5). I'm curious which languages let you write function literals which are recursive. Wikipedia's "anonymous recursion" article doesn't give any programming examples. Let's use the recursive factorial function as the example. Here are the ones I know: * *JavaScript / ECMAScript can do it with callee: function(n){if (n<2) {return 1;} else {return n * arguments.callee(n-1);}} *it's easy in languages with letrec, eg Haskell (which calls it let): let fac x = if x<2 then 1 else fac (x-1) * x in fac and there are equivalents in Lisp and Scheme. Note that the binding of fac is local to the expression, so the whole expression is in fact an anonymous function. Are there any others? A: C# Reading Wes Dyer's blog, you will see that @Jon Skeet's answer is not totally correct. I am no genius on languages but there is a difference between a recursive anonymous function and the "fib function really just invokes the delegate that the local variable fib references" to quote from the blog. The actual C# answer would look something like this: delegate Func<A, R> Recursive<A, R>(Recursive<A, R> r); static Func<A, R> Y<A, R>(Func<Func<A, R>, Func<A, R>> f) { Recursive<A, R> rec = r => a => f(r(r))(a); return rec(rec); } static void Main(string[] args) { Func<int,int> fib = Y<int,int>(f => n => n > 1 ? f(n - 1) + f(n - 2) : n); Func<int, int> fact = Y<int, int>(f => n => n > 1 ? n * f(n - 1) : 1); Console.WriteLine(fib(6)); // displays 8 Console.WriteLine(fact(6)); Console.ReadLine(); } A: You can do it in Perl: my $factorial = do { my $fac; $fac = sub { my $n = shift; if ($n < 2) { 1 } else { $n * $fac->($n-1) } }; }; print $factorial->(4); The do block isn't strictly necessary; I included it to emphasize that the result is a true anonymous function. A: Well, apart from Common Lisp (labels) and Scheme (letrec) which you've already mentioned, JavaScript also allows you to name an anonymous function: var foo = {"bar": function baz() {return baz() + 1;}}; which can be handier than using callee. (This is different from function in top-level; the latter would cause the name to appear in global scope too, whereas in the former case, the name appears only in the scope of the function itself.) A: In Perl 6: my $f = -> $n { if ($n <= 1) {1} else {$n * &?BLOCK($n - 1)} } $f(42); # ==> 1405006117752879898543142606244511569936384000000000 A: F# has "let rec" A: You've mixed up some terminology here, function literals don't have to be anonymous. In javascript the difference depends on whether the function is written as a statement or an expression. There's some discussion about the distinction in the answers to this question. Lets say you are passing your example to a function: foo(function(n){if (n<2) {return 1;} else {return n * arguments.callee(n-1);}}); This could also be written: foo(function fac(n){if (n<2) {return 1;} else {return n * fac(n-1);}}); In both cases it's a function literal. But note that in the second example the name is not added to the surrounding scope - which can be confusing. But this isn't widely used as some javascript implementations don't support this or have a buggy implementation. I've also read that it's slower. Anonymous recursion is something different again, it's when a function recurses without having a reference to itself, the Y Combinator has already been mentioned. In most languages, it isn't necessary as better methods are available. Here's a link to a javascript implementation. A: Most languages support it through use of the Y combinator. Here's an example in Python (from the cookbook): # Define Y combinator...come on Gudio, put it in functools! Y = lambda g: (lambda f: g(lambda arg: f(f)(arg))) (lambda f: g(lambda arg: f(f)(arg))) # Define anonymous recursive factorial function fac = Y(lambda f: lambda n: (1 if n<2 else n*f(n-1))) assert fac(7) == 5040 A: In C# you need to declare a variable to hold the delegate, and assign null to it to make sure it's definitely assigned, then you can call it from within a lambda expression which you assign to it: Func<int, int> fac = null; fac = n => n < 2 ? 1 : n * fac(n-1); Console.WriteLine(fac(7)); I think I heard rumours that the C# team was considering changing the rules on definite assignment to make the separate declaration/initialization unnecessary, but I wouldn't swear to it. One important question for each of these languages / runtime environments is whether they support tail calls. In C#, as far as I'm aware the MS compiler doesn't use the tail. IL opcode, but the JIT may optimise it anyway, in certain circumstances. Obviously this can very easily make the difference between a working program and stack overflow. (It would be nice to have more control over this and/or guarantees about when it will occur. Otherwise a program which works on one machine may fail on another in a hard-to-fathom manner.) Edit: as FryHard pointed out, this is only pseudo-recursion. Simple enough to get the job done, but the Y-combinator is a purer approach. There's one other caveat with the code I posted above: if you change the value of fac, anything which tries to use the old value will start to fail, because the lambda expression has captured the fac variable itself. (Which it has to in order to work properly at all, of course...) A: You can do this in Matlab using an anonymous function which uses the dbstack() introspection to get the function literal of itself and then evaluating it. (I admit this is cheating because dbstack should probably be considered extralinguistic, but it is available in all Matlabs.) f = @(x) ~x || feval(str2func(getfield(dbstack, 'name')), x-1) This is an anonymous function that counts down from x and then returns 1. It's not very useful because Matlab lacks the ?: operator and disallows if-blocks inside anonymous functions, so it's hard to construct the base case/recursive step form. You can demonstrate that it is recursive by calling f(-1); it will count down to infinity and eventually throw a max recursion error. >> f(-1) ??? Maximum recursion limit of 500 reached. Use set(0,'RecursionLimit',N) to change the limit. Be aware that exceeding your available stack space can crash MATLAB and/or your computer. And you can invoke the anonymous function directly, without binding it to any variable, by passing it directly to feval. >> feval(@(x) ~x || feval(str2func(getfield(dbstack, 'name')), x-1), -1) ??? Maximum recursion limit of 500 reached. Use set(0,'RecursionLimit',N) to change the limit. Be aware that exceeding your available stack space can crash MATLAB and/or your computer. Error in ==> create@(x)~x||feval(str2func(getfield(dbstack,'name')),x-1) To make something useful out of it, you can create a separate function which implements the recursive step logic, using "if" to protect the recursive case against evaluation. function out = basecase_or_feval(cond, baseval, fcn, args, accumfcn) %BASECASE_OR_FEVAL Return base case value, or evaluate next step if cond out = baseval; else out = feval(accumfcn, feval(fcn, args{:})); end Given that, here's factorial. recursive_factorial = @(x) basecase_or_feval(x < 2,... 1,... str2func(getfield(dbstack, 'name')),... {x-1},... @(z)x*z); And you can call it without binding. >> feval( @(x) basecase_or_feval(x < 2, 1, str2func(getfield(dbstack, 'name')), {x-1}, @(z)x*z), 5) ans = 120 A: It also seems Mathematica lets you define recursive functions using #0 to denote the function itself, as: (expression[#0]) & e.g. a factorial: fac = Piecewise[{{1, #1 == 0}, {#1 * #0[#1 - 1], True}}] &; This is in keeping with the notation #i to refer to the ith parameter, and the shell-scripting convention that a script is its own 0th parameter. A: I think this may not be exactly what you're looking for, but in Lisp 'labels' can be used to dynamically declare functions that can be called recursively. (labels ((factorial (x) ;define name and params ; body of function addrec (if (= x 1) (return 1) (+ (factorial (- x 1))))) ;should not close out labels ;call factorial inside labels function (factorial 5)) ;this would return 15 from labels A: Delphi includes the anonymous functions with version 2009. Example from http://blogs.codegear.com/davidi/2008/07/23/38915/ type // method reference TProc = reference to procedure(x: Integer); procedure Call(const proc: TProc); begin proc(42); end; Use: var proc: TProc; begin // anonymous method proc := procedure(a: Integer) begin Writeln(a); end; Call(proc); readln end. A: Because I was curious, I actually tried to come up with a way to do this in MATLAB. It can be done, but it looks a little Rube-Goldberg-esque: >> fact = @(val,branchFcns) val*branchFcns{(val <= 1)+1}(val-1,branchFcns); >> returnOne = @(val,branchFcns) 1; >> branchFcns = {fact returnOne}; >> fact(4,branchFcns) ans = 24 >> fact(5,branchFcns) ans = 120 A: Anonymous functions exist in C++0x with lambda, and they may be recursive, although I'm not sure about anonymously. auto kek = [](){kek();} A: 'Tseems you've got the idea of anonymous functions wrong, it's not just about runtime creation, it's also about scope. Consider this Scheme macro: (define-syntax lambdarec (syntax-rules () ((lambdarec (tag . params) . body) ((lambda () (define (tag . params) . body) tag))))) Such that: (lambdarec (f n) (if (<= n 0) 1 (* n (f (- n 1))))) Evaluates to a true anonymous recursive factorial function that can for instance be used like: (let ;no letrec used ((factorial (lambdarec (f n) (if (<= n 0) 1 (* n (f (- n 1))))))) (factorial 4)) ; ===> 24 However, the true reason that makes it anonymous is that if I do: ((lambdarec (f n) (if (<= n 0) 1 (* n (f (- n 1))))) 4) The function is afterwards cleared from memory and has no scope, thus after this: (f 4) Will either signal an error, or will be bound to whatever f was bound to before. In Haskell, an ad hoc way to achieve same would be: \n -> let fac x = if x<2 then 1 else fac (x-1) * x in fac n The difference again being that this function has no scope, if I don't use it, with Haskell being Lazy the effect is the same as an empty line of code, it is truly literal as it has the same effect as the C code: 3; A literal number. And even if I use it immediately afterwards it will go away. This is what literal functions are about, not creation at runtime per se. A: Clojure can do it, as fn takes an optional name specifically for this purpose (the name doesn't escape the definition scope): > (def fac (fn self [n] (if (< n 2) 1 (* n (self (dec n)))))) #'sandbox17083/fac > (fac 5) 120 > self java.lang.RuntimeException: Unable to resolve symbol: self in this context If it happens to be tail recursion, then recur is a much more efficient method: > (def fac (fn [n] (loop [count n result 1] (if (zero? count) result (recur (dec count) (* result count))))))
{ "language": "en", "url": "https://stackoverflow.com/questions/156369", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: in-house projects: to stable release or not? Suppose you work at a medium-to-large software company with many independently-developed projects (independent coders) but which rely on each other (dependent code). If it were up to you, would you make sure each project produced stable branches so that the other projects could more reliably use those branches, or would you encourage projects to directly use the latest-available code from other projects? The advantage of a stable release is clear to me - a higher probability that your dependencies will work as advertized. Yet I can also see some good points to avoiding stable releases - each project has a little less work to do, and you can react very quickly to bugs that affect everyone, since your code is sort-of auto-updating all the time. For example, imagine there's a subtle security flaw at timestamp X in one in-house library - it might not be noticed until that code is widely used. If you're using stable release branches, you'll have to get every other project to modify their dependencies to effect the security fix. Without release branches, the fix is picked up immediately in the next build of all other projects. I'm especially interested if anyone has industry experience with both alternatives. A: As always, there are pros and cons for each of the options. Using branches may be more stable but it requires more maintenance when you're required to update to a newer branch. It also requires their development team to spent extra time when the branch is merged with the trunk. On the other hand, using the trunk may force you to deal with other people's bugs and write messy workaround code to get around it. It may get especially messy if you get weird OutOfMemory/Performance issues that can't be pinned to a specific library (or your own code). Remember that this isn't your code, and you probably don't have the manpower to help them with their QA efforts... So I guess the final word on this is that it depends. I would suggest taking these factors into consideration: * *Is the API you're using going to change? *Is it important to work on "clean code" or can you allow yourself to mess around with other people's bugs? *Is it crucial for the application to use the "cutting-edge" version of the libraries? As a side note, and from experience, I can tell you that one of our programmers missed a couple of nights' sleep because he worked with branches and the upgrade to a newer branch changed the entire API and logic. :) HTH A: Think it really breaks down to how mission critical the software is. If you can put up with mild crashing and maybe some data corruption and it's easy to push new builds, running unstable code might be preferred. Now if lives or reputations depend on everything working correctly, or if pushing a new build is a major process, stable tested releases are the only way to go. A: Looking at other projects, it seems to me that the issue that you raise is addressed by having security branches. E.g. Debian packages. That way, you would continue using stable branch across projects. For the reasons you mention, testing / work-in-progress branches carry too much risk.
{ "language": "en", "url": "https://stackoverflow.com/questions/156372", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Using .reset() to free a boost::shared_ptr with sole ownership I'm storing an object (TTF_Font) in a shared_ptr that is provided to me from a third-party API. I cannot use new or delete on the object, so the shared_ptr is also provided a "freeing" functor. // Functor struct CloseFont { void operator()(TTF_Font* font) const { if(font != NULL) { TTF_CloseFont(font); } } }; boost::shared_ptr<TTF_Font> screenFont; screenFont = boost::shared_ptr<TTF_Font>( TTF_OpenFont("slkscr.ttf", 8), CloseFont() ); If, later, I need to explicitly free this object is it correct to do this: screenFont.reset(); And then let screenFont (the actual shared_ptr object) be destroyed naturally? A: shared_ptr<>::reset() will drop the refcount by one. If that results in the count dropping to zero, the resource pointed to by the shared_ptr<> will be freed. So I think the answer for you is, yes that will work. Or you can simply let the screenFont variable be destructed due to dropping out of scope or whatever, if that's what's about to happen. To be clear, the normal usage of shared_ptr<> is that you let it be destructed naturally, and it will deal with the refcount and freeing the resource when it drops to zero naturally. reset() is only required if you need to release that particular instance of the shared resource before the shared_ptr<> would be naturally destructed. A: Mike B's answered your question, so I'll just comment on your code. If TTF_OpenFont doesn't return null, or if TTF_CloseFont can handle nulls harmlessly, you don't need a CloseFont class at all, just use &TTF_CloseFont.
{ "language": "en", "url": "https://stackoverflow.com/questions/156373", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: How to prevent Crystal webserver refetching data on each page We're using Crystal 11 through their webserver. When we run a report, it does the Sql query and displays the first page of the report in the Crystal web reportviewer. When you hit the next page button, it reruns the Sql query and displays the next page. How do we get the requerying of the data to stop? We also have multiple people running the same reports at the same time (it is a web server after all), and we don't want to cache data between different instances of the same report, we only want to cache the data in each single instance of the report. A: The reason to have pagination is not only a presentation concern. With pagination the single most important advantage is lazy loading of data - so that in theory, depending on given filters, you load only what you need. Just imagine if you have millions of records in your db and you load all of them. First of all is gonna be a hell of a lot slower, second you're fetching a lot of stuff you don't really need. All the web models nowadays are based on lazy loading rather than bulk loading. Think about Google App Engine: you can't retrieve more than 1000 records in a given transaction from the Google Datastore - and you know that if you'll only try and display them your browser will die. I'll close with a question - do you have a performance issue of any kind? If so, you probably think you'll make it better but it's probably not the case, because you'll reduce the load on the server but each single query will be much more resource consuming. If not my advice is to leave it alone! :)
{ "language": "en", "url": "https://stackoverflow.com/questions/156391", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Method access in Ruby How is it that Ruby allows a class access methods outside of the class implicitly? Example: class Candy def land homer end end def homer puts "Hello" end Candy.new.land #Outputs Hello A: A simple way to find out what happens * *What classes/modules are searched to resolve methods used in Candy objects? p Candy.ancestors #=> [Candy, Object, Kernel] *Does Candy have method called homer? p Candy.instance_methods(false).grep("homer") #=> [] p Candy.private_instance_methods(false).grep("homer") #=> [] *OK Candy does not have any method called 'homer'. *What's next in the lookup chain (see 1) => "Object" *Does Object have a method called "homer" ? p Object.instance_methods(false).grep("homer") #=> [] p Object.private_instance_methods(false).grep("homer") #=> ["homer"] Candy has Object in its lookup chain which in turn has a private instance method "homer" so method resolution succeeds The def statement always defines the method in the class of whatever self is at the point of definition * *What is self just before homer is defined ? p self #=> main def homer puts "Hello" end *So what is its type ? p self.class #=> Object Which is why homer ends up on Object A: Technically, the definition of the homer method is actually on the Kernel module which is mixed into Object, not on Object directly. So when homer is not a local variable or an instance method defined on Candy, the Ruby method inheritance chain is followed up through Object and then to the mixed-in Kernel module and then this code is run. Edit: Sorry, I don't know why I thought this. It appears that the method really lives on Object. Not sure it makes too much of a difference in practice but I should have confirmed things before posting. A: The definition of the "homer" method is adding the method to the Object class. It is not defining a free function. Class Candy implicitly inherits from Object, and so has access to the methods in Object. When you call "homer" in the "land" method, the method resolution can't find a definition in the current class, goes to the super class, finds the method you have added to Object, and calls it. A: Ruby has no free-floating functions. Every method belongs to some object. Methods that you def at the top level are actually becoming instance methods of class Object. Because everything is an Object at some level, all objects have access to Object's instance methods.
{ "language": "en", "url": "https://stackoverflow.com/questions/156394", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Sending a message to nil in Objective-C As a Java developer who is reading Apple's Objective-C 2.0 documentation: I wonder what "sending a message to nil" means - let alone how it is actually useful. Taking an excerpt from the documentation: There are several patterns in Cocoa that take advantage of this fact. The value returned from a message to nil may also be valid: * *If the method returns an object, any pointer type, any integer scalar of size less than or equal to sizeof(void*), a float, a double, a long double, or a long long, then a message sent to nil returns 0. *If the method returns a struct, as defined by the Mac OS X ABI Function Call Guide to be returned in registers, then a message sent to nil returns 0.0 for every field in the data structure. Other struct data types will not be filled with zeros. *If the method returns anything other than the aforementioned value types the return value of a message sent to nil is undefined. Has Java rendered my brain incapable of grokking the explanation above? Or is there something that I am missing that would make this as clear as glass? I do get the idea of messages/receivers in Objective-C, I am simply confused about a receiver that happens to be nil. A: Well, I think it can be described using a very contrived example. Let's say you have a method in Java which prints out all of the elements in an ArrayList: void foo(ArrayList list) { for(int i = 0; i < list.size(); ++i){ System.out.println(list.get(i).toString()); } } Now, if you call that method like so: someObject.foo(NULL); you're going to probably get a NullPointerException when it tries to access list, in this case in the call to list.size(); Now, you'd probably never call someObject.foo(NULL) with the NULL value like that. However, you may have gotten your ArrayList from a method which returns NULL if it runs into some error generating the ArrayList like someObject.foo(otherObject.getArrayList()); Of course, you'll also have problems if you do something like this: ArrayList list = NULL; list.size(); Now, in Objective-C, we have the equivalent method: - (void)foo:(NSArray*)anArray { int i; for(i = 0; i < [anArray count]; ++i){ NSLog(@"%@", [[anArray objectAtIndex:i] stringValue]; } } Now, if we have the following code: [someObject foo:nil]; we have the same situation in which Java will produce a NullPointerException. The nil object will be accessed first at [anArray count] However, instead of throwing a NullPointerException, Objective-C will simply return 0 in accordance with the rules above, so the loop will not run. However, if we set the loop to run a set number of times, then we're first sending a message to anArray at [anArray objectAtIndex:i]; This will also return 0, but since objectAtIndex: returns a pointer, and a pointer to 0 is nil/NULL, NSLog will be passed nil each time through the loop. (Although NSLog is a function and not a method, it prints out (null) if passed a nil NSString. In some cases it's nicer to have a NullPointerException, since you can tell right away that something is wrong with the program, but unless you catch the exception, the program will crash. (In C, trying to dereference NULL in this way causes the program to crash.) In Objective-C, it instead just causes possibly incorrect run-time behavior. However, if you have a method that doesn't break if it returns 0/nil/NULL/a zeroed struct, then this saves you from having to check to make sure the object or parameters are nil. A: It means often not having to check for nil objects everywhere for safety - particularly: [someVariable release]; or, as noted, various count and length methods all return 0 when you've got a nil value, so you do not have to add extra checks for nil all over: if ( [myString length] > 0 ) or this: return [myArray count]; // say for number of rows in a table A: Don't think about "the receiver being nil"; I agree, that is pretty weird. If you're sending a message to nil, there is no receiver. You're just sending a message to nothing. How to deal with that is a philosophical difference between Java and Objective-C: in Java, that's an error; in Objective-C, it is a no-op. A: ObjC messages which are sent to nil and whose return values have size larger than sizeof(void*) produce undefined values on PowerPC processors. In addition to that, these messages cause undefined values to be returned in fields of structs whose size is larger than 8 bytes on Intel processors as well. Vincent Gable has described this nicely in his blog post A: I don't think any of the other answers have mentioned this clearly: if you're used to Java, you should keep in mind that while Objective-C on Mac OS X has exception handling support, it's an optional language feature that can be turned on/off with a compiler flag. My guess is that this design of "sending messages to nil is safe" predates the inclusion of exception handling support in the language and was done with a similar goal in mind: methods can return nil to indicate errors, and since sending a message to nil usually returns nil in turn, this allows the error indication to propagate through your code so you don't have to check for it at every single message. You only have to check for it at points where it matters. I personally think exception propagation&handling is a better way to address this goal, but not everyone may agree with that. (On the other hand, I for example don't like Java's requirement on you having to declare what exceptions a method may throw, which often forces you to syntactically propagate exception declarations throughout your code; but that's another discussion.) I've posted a similar, but longer, answer to the related question "Is asserting that every object creation succeeded necessary in Objective C?" if you want more details. A: A message to nil does nothing and returns nil, Nil, NULL, 0, or 0.0. A: All of the other posts are correct, but maybe it's the concept that's the thing important here. In Objective-C method calls, any object reference that can accept a selector is a valid target for that selector. This saves a LOT of "is the target object of type X?" code - as long as the receiving object implements the selector, it makes absolutely no difference what class it is! nil is an NSObject that accepts any selector - it just doesn't do anything. This eliminates a lot of "check for nil, don't send the message if true" code as well. (The "if it accepts it, it implements it" concept is also what allows you to create protocols, which are sorta kinda like Java interfaces: a declaration that if a class implements the stated methods, then it conforms to the protocol.) The reason for this is to eliminate monkey code that doesn't do anything except keep the compiler happy. Yes, you get the overhead of one more method call, but you save programmer time, which is a far more expensive resource than CPU time. In addition, you're eliminating more code and more conditional complexity from your application. Clarifying for downvoters: you may think this is not a good way to go, but it's how the language is implemented, and it's the recommended programming idiom in Objective-C (see the Stanford iPhone programming lectures). A: C represents nothing as 0 for primitive values, and NULL for pointers (which is equivalent to 0 in a pointer context). Objective-C builds on C's representation of nothing by adding nil. nil is an object pointer to nothing. Although semantically distinct from NULL, they are technically equivalent to one another. Newly-alloc'd NSObjects start life with their contents set to 0. This means that all pointers that object has to other objects begin as nil, so it's unnecessary to, for instance, set self.(association) = nil in init methods. The most notable behavior of nil, though, is that it can have messages sent to it. In other languages, like C++ (or Java), this would crash your program, but in Objective-C, invoking a method on nil returns a zero value. This greatly simplifies expressions, as it obviates the need to check for nil before doing anything: // For example, this expression... if (name != nil && [name isEqualToString:@"Steve"]) { ... } // ...can be simplified to: if ([name isEqualToString:@"Steve"]) { ... } Being aware of how nil works in Objective-C allows this convenience to be a feature, and not a lurking bug in your application. Make sure to guard against cases where nil values are unwanted, either by checking and returning early to fail silently, or adding a NSParameterAssert to throw an exception. Source: http://nshipster.com/nil/ https://developer.apple.com/library/ios/#documentation/cocoa/conceptual/objectivec/Chapters/ocObjectsClasses.html (Sending Message to nil). A: What it means is that the runtime doesn't produce an error when objc_msgSend is called on the nil pointer; instead it returns some (often useful) value. Messages that might have a side effect do nothing. It's useful because most of the default values are more appropriate than an error. For example: [someNullNSArrayReference count] => 0 I.e., nil appears to be the empty array. Hiding a nil NSView reference does nothing. Handy, eh? A: In the quotation from the documentation, there are two separate concepts -- perhaps it might be better if the documentation made that more clear: There are several patterns in Cocoa that take advantage of this fact. The value returned from a message to nil may also be valid: The former is probably more relevant here: typically being able to send messages to nil makes code more straightforward -- you don't have to check for null values everywhere. The canonical example is probably the accessor method: - (void)setValue:(MyClass *)newValue { if (value != newValue) { [value release]; value = [newValue retain]; } } If sending messages to nil were not valid, this method would be more complex -- you'd have to have two additional checks to ensure value and newValue are not nil before sending them messages. The latter point (that values returned from a message to nil are also typically valid), though, adds a multiplier effect to the former. For example: if ([myArray count] > 0) { // do something... } This code again doesn't require a check for nil values, and flows naturally... All this said, the additional flexibility that being able to send messages to nil does come at some cost. There is the possibility that you will at some stage write code that fails in a peculiar way because you didn't take into account the possibility that a value might be nil. A: From Greg Parker's site: If running LLVM Compiler 3.0 (Xcode 4.2) or later Messages to nil with return type | return Integers up to 64 bits | 0 Floating-point up to long double | 0.0 Pointers | nil Structs | {0} Any _Complex type | {0, 0}
{ "language": "en", "url": "https://stackoverflow.com/questions/156395", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "107" }
Q: Why does GWT ignore browser locale? GWT gets locale from either the locale property or the locale query string. If neither is specified, it uses the "default" (ie en_US) locale. Why doesn't it get it from the browser settings? It seems the only solution to this is to replace your static html launch page with something like a JSP that reads the browser locales and sets the locale or redirects using the query string. There has to be a better solution than this or simply hard-coding a locale, surely? A: You can also put this switch in your *.gwt.xml <set-configuration-property name="locale.useragent" value="Y"/> this will add language selecting based on language selected in browser. You can also control search order for locale by setting <set-configuration-property name="locale.searchorder" value="queryparam,cookie,meta,useragent"/> But beware that in IE this doesn't work - you should develop server-side language pick based on 'Accept-Language' header send by the IE. A: If you put a list of available languages into your *.gwt.xml file it will by default switch to the first language listed. <!-- Slovenian in Slovenia --> <extend-property name="locale" values="sl"/> <!-- English language, independent of country --> <extend-property name="locale" values="en"/> A: You can use a cookie to save and send this value, but for that you have to add in your *.gwt.xml first <set-configuration-property name="locale.cookie" value="yourCookieName"/> <set-configuration-property name="locale.searchorder" value="queryparam,cookie,meta,useragent"/> Note that "queryparam" has the biggest priority here, that allows to set a new locale using the http query and ignore the value on the cookie. A: If your entry page is a JSP you can inspect the request's Accept-Language header to dynamically set the locale. A: add this entry in your *.gwt.xml file to see the effect! Please check the following line for more information! <set-configuration-property name="locale.useragent" value="Y"/> A: This worked for me, I hope it also works for you. My problem was that I have not declared any locale value in .gwt.xml module descriptor. In that case only the default locale is used. GWT does that way because any different supported locale means a new compilation iteration/permutation. Therefore only declared locales are used. Here you are an example: <!-- Locales --> <extend-property name="locale" values="en_US"/> <extend-property name="locale" values="es"/> <set-property-fallback name="locale" value="en_US"/> <set-configuration-property name="locale.useragent" value="Y" /> <set-configuration-property name="locale.searchorder" value="queryparam,cookie,meta,useragent" /> The first and second lines set the available/supported locales (English from US and Spanish without specific country in my example). The third line sets the default locale in case no one is detected (this default declaration must be set after the default value is declared in a extend-property line). The fourth line enables the locale detection by means of the HTTP-Headers Accept-Language sent by browser (probably is enabled by default and not needed to set at all). The final line sets the order in which the different detection mechanisms try to detect the locale: * *As a parameter in the URL query *From cookies *As a meta value in the HTML page *From the HTTP header sent by browser
{ "language": "en", "url": "https://stackoverflow.com/questions/156412", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Is regular expression recognition of an email address hard? I recently read somewhere that writing a regexp to match an email address, taking into account all the variations and possibilities of the standard is extremely hard and is significantly more complicated than what one would initially assume. Why is that? Are there any known and proven regexps that actually do this fully? What are some good alternatives to using regexps for matching email addresses? A: There is a context free grammar in BNF that describes valid email addresses in RFC-2822. It is complex. For example: " @ "@example.com is a valid email address. I don't know of any regexps that do it fully; the examples usually given require comments to be stripped first. I wrote a recursive descent parser to do it fully once. A: I've now collated test cases from Cal Henderson, Dave Child, Phil Haack, Doug Lovell and RFC 3696. 158 test addresses in all. I ran all these tests against all the validators I could find. The comparison is here: http://www.dominicsayers.com/isemail I'll try to keep this page up-to-date as people enhance their validators. Thanks to Cal, Dave and Phil for their help and co-operation in compiling these tests and constructive criticism of my own validator. People should be aware of the errata against RFC 3696 in particular. Three of the canonical examples are in fact invalid addresses. And the maximum length of an address is 254 or 256 characters, not 320. A: It's not all nonsense though as allowing characters such as '+' can be highly useful for users combating spam, e.g. myemail+sketchysite@gmail.com (instant disposable Gmail addresses). Only when a site accepts it though. A: For the formal e-mail spec, yes, it is technically impossible via Regex due to the recursion of things like comments (especially if you don't remove comments to whitespace first), and the various different formats (an e-mail address isn't always someone@somewhere.tld). You can get close (with some massive and incomprehensible Regex patterns), but a far better way of checking an e-mail is to do the very familiar handshake: * *they tell you their e-mail *you e-mail them a confimation link with a Guid *when they click on the link you know that: * *the e-mail is correct *it exists *they own it Far better than blindly accepting an e-mail address. A: Whether or not to accept bizarre, uncommon email address formats depends, in my opinion, on what one wants to do with them. If you're writing a mail server, you have to be very exact and excruciatingly correct in what you accept. The "insane" regex quoted above is therefore appropriate. For the rest of us, though, we're mainly just interested in ensuring that something a user types in a web form looks reasonable and doesn't have some sort of sql injection or buffer overflow in it. Frankly, does anyone really care about letting someone enter a 200-character email address with comments, newlines, quotes, spaces, parentheses, or other gibberish when signing up for a mailing list, newsletter, or web site? The proper response to such clowns is "Come back later when you have an address that looks like username@domain.tld". The validation I do consists of ensuring that there is exactly one '@'; that there are no spaces, nulls or newlines; that the part to the right of the '@' has at least one dot (but not two dots in a row); and that there are no quotes, parentheses, commas, colons, exclamations, semicolons, or backslashes, all of which are more likely to be attempts at hackery than parts of an actual email address. Yes, this means I'm rejecting valid addresses with which someone might try to register on my web sites - perhaps I "incorrectly" reject as many as 0.001% of real-world addresses! I can live with that. A: Quoting and various other rarely used but valid parts of the RFC make it hard. I don't know enough about this topic to comment definitively, other than "it's hard" - but fortunately other people have written about it at length. As to a valid regex for it, the Perl Mail::Rfc822::Address module contains a regular expression which will apparently work - but only if any comments have been replaced by whitespace already. (Comments in an email address? You see why it's harder than one might expect...) Of course, the simplified regexes which abound elsewhere will validate almost every email address which is genuinely being used... A: Some flavours of regex can actually match nested brackets (e.g., Perl compatible ones). That said, I have seen a regex that claims to correctly match RFC 822 and it was two pages of text without any whitespace. Therefore, the best way to detect a valid email address is to send email to it and see if it works. A: Just to add a regex that is less crazy than the one listed by @mmaibaum: ^[a-zA-Z]([.]?([a-zA-Z0-9_-]+)*)?@([a-zA-Z0-9\-_]+\.)+[a-zA-Z]{2,4}$ It is not bulletproof, and certainly does not cover the entire email spec, but it does do a decent job of covering most basic requirements. Even better, it's somewhat comprehensible, and can be edited. Cribbed from a discussion at HouseOfFusion.com, a world-class ColdFusion resource. A: An easy and good way to check email-adresses in Java is to use the EmailValidator of the Apache Commons Validator library. I would always check an email-address in an input-form against something like this before sending an email - even if you only catch some typos. You probably don't want to write an automated scanner for "delivery failed" notification mails. :-) A: There are a number of Perl modules (for example) that do this. Don't try and write your own regexp to do it. Look at Mail::VRFY will do syntax and network checks (does and SMTP server somewhere accept this address) https://metacpan.org/pod/Mail::VRFY RFC::RFC822::Address - a recursive descent email address parser. https://metacpan.org/pod/RFC::RFC822::Address Mail::RFC822::Address - regexp-based address validation, worth looking at just for the insane regexp http://ex-parrot.com/~pdw/Mail-RFC822-Address.html Similar tools exist for other languages. Insane regexp below... (?:(?:\r\n)?[ \t])*(?:(?:(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t] )+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?: \r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:( ?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*))*@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\0 31]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\ ](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+ (?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?: (?:\r\n)?[ \t])*))*|(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z |(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n) ?[ \t])*)*\<(?:(?:\r\n)?[ \t])*(?:@(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\ r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n) ?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t] )*))*(?:,@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])* )(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t] )+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*) *:(?:(?:\r\n)?[ \t])*)?(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+ |\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r \n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?: \r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t ]))*"(?:(?:\r\n)?[ \t])*))*@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031 ]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\]( ?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(? :(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(? :\r\n)?[ \t])*))*\>(?:(?:\r\n)?[ \t])*)|(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(? :(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)? [ \t]))*"(?:(?:\r\n)?[ \t])*)*:(?:(?:\r\n)?[ \t])*(?:(?:(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]| \\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<> @,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|" (?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*))*@(?:(?:\r\n)?[ \t] )*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\ ".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(? :[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[ \]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*|(?:[^()<>@,;:\\".\[\] \000- \031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|( ?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)*\<(?:(?:\r\n)?[ \t])*(?:@(?:[^()<>@,; :\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([ ^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\" .\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\ ]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*(?:,@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\ [\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\ r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\] |\\.)*\](?:(?:\r\n)?[ \t])*))*)*:(?:(?:\r\n)?[ \t])*)?(?:[^()<>@,;:\\".\[\] \0 00-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\ .|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@, ;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(? :[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*))*@(?:(?:\r\n)?[ \t])* (?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\". \[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[ ^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\] ]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*\>(?:(?:\r\n)?[ \t])*)(?:,\s*( ?:(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\ ".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)(?:\.(?:( ?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[ \["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t ])*))*@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t ])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(? :\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+| \Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*|(?: [^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\ ]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)*\<(?:(?:\r\n) ?[ \t])*(?:@(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\[" ()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n) ?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<> @,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*(?:,@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@, ;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t] )*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\ ".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*)*:(?:(?:\r\n)?[ \t])*)? (?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\". \[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)(?:\.(?:(?: \r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\[ "()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t]) *))*@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t]) +|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\ .(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z |(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*\>(?:( ?:\r\n)?[ \t])*))*)?;\s*) A: It's really hard because there are a lot of things that can be valid in an email address according to the Email Spec, RFC 2822. Things that you don't normally see such as + are perfectly valid characters for an email address.. according to the spec. There's an entire section devoted to email addresses at http://regexlib.com, which is a great resource. I'd suggest that you determine what criteria matters to you and find one that matches. Most people really don't need full support for all possibilities allowed by the spec. A: If you're running on the .NET Framework, just try instantiating a MailAddress object and catching the FormatException if it blows up, or pulling out the Address if it succeeds. Without getting into any nonsense about the performance of catching exceptions (really, if this is just on a single Web form it is not going to make that much of a difference), the MailAddress class in the .NET framework goes through a quite complete parsing process (it doesn't use a RegEx). Open up Reflector and search for MailAddress and MailBnfHelper.ReadMailAddress() to see all of the fancy stuff it does. Someone smarter than me spent a lot of time building that parser at Microsoft, I'm going to use it when I actually send an e-mail to that address, so I might as well use it to validate the incoming address, too. A: Validating e-mail addresses aren't really very helpful anyway. It will not catch common typos or made-up email addresses, since these tend to look syntactically like valid addresses. If you want to be sure an address is valid, you have no choice but to send an confirmation mail. If you just want to be sure that the user inputs something that looks like an email rather than just "asdf", then check for an @. More complex validation does not really provide any benefit. (I know this doesn't answer your questions, but I think it's worth mentioning anyway) A: Try this one: "(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])" Have a look here for the details. However, rather than implementing the RFC822 standard, maybe it would be better to look at it from another viewpoint. It doesn't really matter what the standard says if mail servers don't mirror the standard. So I would argue that it would be better to imitate what the most popular mail servers do when validating email addresses. A: Many have tried, and many come close. You may want to read the wikipedia article, and some others. Specifically, you'll want to remember that many websites and email servers have relaxed validation of email addresses, so essentially they don't implement the standard fully. It's good enough for email to work all the time though. A: This class for Java has a validator in it: http://www.leshazlewood.com/?p=23 This is written by the creator of Shiro (formally Ki, formally JSecurity) The pros and cons of testing for e-mail address validity: There are two types of regexes that validate e-mails: * *Ones that are too loose. *Ones that are too strict. It is not possible for a regular expression to match all valid e-mail addresses and no e-mail addresses that are not valid because some strings might look like valid e-mail addresses but do not actually go to anyone's inbox. The only way to test to see if an e-mail is actually valid is to send an e-mail to that address and see if you get some sort of response. With that in mind, regexes that are too strict at matching e-mails don't really seem to have much of a purpose. I think that most people who ask for an e-mail regex are looking for the first option, regexes that are too loose. They want to test a string and see if it looks like an e-mail, if it is definitely not an email, then they can say to the user: "Hey, you are supposed to put an e-mail here and this definitely is not a valid e-mail. Perhaps you didn't realize that this field is for an e-mail or maybe there is a typo". If a user puts in a string that looks a lot like a valid e-mail, but it actually is not one, then that is a problem that should be handled by a different part of the application. A: Can anyone provide some insight as to why that is? Yes, it is an extremely complicated standard that allows lots of stuff that no one really uses today. :) Are there any known and proven regexps that actually do this fully? Here is one attempt to parse the whole standard fully... http://ex-parrot.com/~pdw/Mail-RFC822-Address.html What are some good alternatives to using regexps for matching email addresses? Using an existing framework for it in whatever language you are using I guess? Though those will probably use regexp internally. It is a complex string. Regexps are designed to parse complex strings, so that really is your best choice. Edit: I should add that the regexp I linked to was just for fun. I do not endorse using a complex regexp like that - some people say that "if your regexp is more than one line, it is guaranteed to have a bug in it somewhere". I linked to it to illustrate how complex the standard is. A: For completeness of this post, also for PHP there is a language built-in function to validate e-mails. For PHP Use the nice filter_var with the specific EMAIL validation type :) No more insane email regexes in php :D var_dump(filter_var('bob@example.com', FILTER_VALIDATE_EMAIL)); http://www.php.net/filter_var A: There always seems to be an unaccounted for format when trying to create a regular expression to validate emails. Though there are some characters that are not valid in an email, the basic format is local-part@domain and is roughly 64 chars max on the local part and roughly 253 chars on the domain. Besides that, it's kind like the wild wild west. I think the answer depends on your definition of a validated email address and what your business process has tolerance for. Regular expressions are great for making sure an email is formatted properly and as you know there are many variations of them that can work. Here are a couple of variations: Variant 1: (?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\]) Variant2: \A(?:[a-z0-9!#$%&'*+/=?^_‘{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_‘{|}~-]+)*| "(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])\z Just because an email is syntactically correct doesn't mean it is valid. An email can adhere to the RFC 5322 and pass the regex but there will be no true insight into the emails actual deliverability. What if you wanted to know if the email was a bogus email or if it was disposable or not deliverable or a known bot? What if you wanted to exclude emails that were vulgar or in some way factious or problematic? By the way, just so everyone knows, I work for a data validation company and with that I just wanted give full disclosure that I work for Service Objects but, being a professional in the email validation field, I feel the solution we offer provides better validation than a regex. Feel free to give it a look, I think it can help a lot. You can see more info about this in our dev guide. It actually does a lot of cool email checks and verification's. Here's an example: Email: mickeyMouse@gmail.com { "ValidateEmailInfo":{ "Score":4, "IsDeliverable":"false", "EmailAddressIn":"mickeyMouse@gmail.com", "EmailAddressOut":"mickeyMouse@gmail.com", "EmailCorrected":false, "Box":"mickeyMouse", "Domain":"gmail.com", "TopLevelDomain":".com", "TopLevelDomainDescription":"commercial", "IsSMTPServerGood":"true", "IsCatchAllDomain":"false", "IsSMTPMailBoxGood":"false", "WarningCodes":"22", "WarningDescriptions":"Email is Bad - Subsequent checks halted.", "NotesCodes":"16", "NotesDescriptions":"TLS" } }
{ "language": "en", "url": "https://stackoverflow.com/questions/156430", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "62" }
Q: Sorting a collection in classic ASP It's quite a simple question - how do I sort a collection? I've got a CSV file with rows in a random order. I'd like to sort the rows according to the date in one column. Do I add the rows to a recordset? Can I sort with a Scripting.Dictionary? I've clearly been spoilt with .NET and Linq, and now I find myself back in the land of classic asp, realising I must have known this 7 years ago, and missing generics immensely. I feel like a complete n00b. A: I'd go with the RecordSet approach. Use the Text Driver. You'll need to change the directory in the connection string and the filename in the select statement. the Extended Property "HDR=Yes" specifies that there's a header row in the CSV which I suggest as it will make writing the psuedo SQL easier. <% Dim strConnection, conn, rs, strSQL strConnection = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\inetpub\wwwroot\;Extended Properties='text;HDR=Yes;FMT=Delimited';" Set conn = Server.CreateObject("ADODB.Connection") conn.Open strConnection Set rs = Server.CreateObject("ADODB.recordset") strSQL = "SELECT * FROM test.csv order by date desc" rs.open strSQL, conn, 3,3 WHILE NOT rs.EOF Response.Write(rs("date") & "<br/>") rs.MoveNext WEND rs.Close Set rs = Nothing conn.Close Set conn = Nothing %> A: In this case I would get help from big brother .net. It's possible to use System.Collections.Sortedlist within your ASP app and get your key value pairs sorted. set list = server.createObject("System.Collections.Sortedlist") with list .add "something", "YY" .add "something else", "XX" end with for i = 0 to list.count - 1 response.write(list.getKey(i) & " = " & list.getByIndex(i)) next Btw if the following .net classes are available too: * *System.Collections.Queue *System.Collections.Stack *System.Collections.ArrayList *System.Collections.SortedList *System.Collections.Hashtable *System.IO.StringWriter *System.IO.MemoryStream; Also see: Marvels of COM .NET interop A: It's been a long time for me too. IIRC you don't have an option out of the box. If I were you I'd put all the data in an array and then sort the array. I found a QuickSort implementation here: https://web.archive.org/web/20210125130007/http://www.4guysfromrolla.com/webtech/012799-3.shtml A: Also look at the "Bubble Sort", works excellent with those classic asp tag cloud. https://web.archive.org/web/20180927040044/http://www.4guysfromrolla.com:80/webtech/011001-1.shtml A: A late late answer to this, but still of value. I was working with small collections so could afford the approach where I inserted the item in the correct place on each occasion, effectively reconstructing the collection on each addition. The VBScript class is as follows: 'Simple collection manager class. 'Performs the opration of adding/setting a collection item. 'Encapulated off here in order to delegate responsibility away from the collection class. Class clsCollectionManager Public Sub PopulateCollectionItem(collection, strKey, Value) If collection.Exists(strKey) Then If (VarType(Value) = vbObject) Then Set collection.Item(strKey) = Value Else collection.Item(strKey) = Value End If Else Call collection.Add(strKey, Value) End If End Sub 'take a collection and a new element as input parameters, an spit out a brand new collection 'with the new item iserted into the correct location by order 'This works on the assumption that the collection it is receiving is already ordered '(which it should be if we always use this method to populate the item) 'This mutates the passed collection, so we highlight this by marking it as byref '(this is not strictly necessary as objects are passed by reference anyway) Public Sub AddCollectionItemInOrder(byref existingCollection, strNewKey, Value) Dim orderedCollection: Set orderedCollection = Server.CreateObject("Scripting.Dictionary") Dim strExistingKey 'If there is something already in our recordset then we need to add it in order. 'There is no sorting available for a collection (or an array) in VBScript. Therefore we have to do it ourself. 'First, iterate over eveything in our current collection. We have to assume that it is itself sorted. For Each strExistingKey In existingCollection 'if the new item doesn't exist AND it occurs after the current item, then add the new item in now '(before adding in the current item.) If (Not orderedCollection.Exists(strNewKey)) And (strExistingKey > strNewKey) Then Call PopulateCollectionItem(orderedCollection, strNewKey, Value) End If Call PopulateCollectionItem(orderedCollection, strExistingKey, existingCollection.item(strExistingKey)) Next 'Finally check to see if it still doesn't exist. 'It won't if the last place for it is at the very end, or the original collection was empty If (Not orderedCollection.Exists(strNewKey)) Then Call PopulateCollectionItem(orderedCollection, strNewKey, Value) End If Set existingCollection = orderedCollection End Sub End Class
{ "language": "en", "url": "https://stackoverflow.com/questions/156436", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: What Does It Mean For a C++ Function To Be Inline? See title: what does it mean for a C++ function to be inline? A: It means one thing and one thing only: that the compiler will elide multiple definitions of the function. A function normally cannot be defined multiple times (i.e. if you place a non-inline function definition into a header and then #include it into multiple compilation units you will receive a linker error). Marking the function definition as "inline" suppresses this error (the linker ensures that the Right Thing happens). IT DOES NOT MEAN ANYTHING MORE! Most significantly, it does NOT mean that the compiler will embed the compiled function into each call site. Whether that occurs is entirely up to the whims of the compiler, and typically the inline modifier does little or nothing to change the compiler's mind. The compiler can--and does--inline functions that aren't marked inline, and it can make function calls to functions that are marked inline. Eliding multiple definitions is the thing to remember. A: The function is placed in the code, rather than being called, similar to using macros (conceptually). This can improve speed (no function call), but causes code bloat (if the function is used 100 times, you now have 100 copies). You should note this does not force the compiler to make the function inline, and it will ignore you if it thinks its a bad idea. Similarly the compiler may decide to make normal functions inline for you. This also allows you to place the entire function in a header file, rather than implementing it in a cpp file (which you can't anyways, since then you get an unresolved external if it was declared inline, unless of course only that cpp file used it). A: @OldMan The compilers only inline non marked as inline functions ONLY if you request it to do so. Only if by "request" you mean "turn on optimizations". Its correct only on the effcts nto the casuse. It's correct in both. Inline do not generate any extra info that the linker may use. Compiel 2 object files and check. It allow multiple definitions exaclty because the symbols are not exported! Not because that is its goal! What do you mean, "the symbols are not exported"? inline functions are not static. Their names are visible; they have external linkage. To quote from the C++ Standard: void h(); inline void h(); // external linkage inline void l(); void l(); // external linkage The multiple definitions thing is very much the goal. It's mandatory: An inline function shall be defined in every translation unit in which it is used and shall have exactly the same definition in every case (3.2). [Note: a call to the inline function may be encountered before its definition appears in the translation unit. ] If a function with external linkage is declared inline in one translation unit, it shall be declared inline in all translation units in which it appears; no diagnostic is required. An inline function with external linkage shall have the same address in all translation units. A: As well as the other (perfectly correct) answers about the performance implications of inline, in C++ you should also note this allows you to safely put a function in a header: // my_thing.h inline int do_my_thing(int a, int b) { return a + b; } // use_my_thing.cpp #include "my_thing.h" ... set_do_thing(&do_my_thing); // use_my_thing_again.cpp ... set_other_do_thing(&do_my_thing); This is because the compiler only includes the actual body of the function in the first object file that needs a regular callable function to be compiled (normally because it's address was taken, as I showed above). Without the inline keyword, most compilers would give an error about multiple definition, eg for MSVC: use_my_thing_again.obj : error LNK2005: "int __cdecl do_my_thing(int,int)" (?do_my_thing@@YAHHH@Z) already defined in use_my_thing.obj <...>\Scratch.exe : fatal error LNK1169: one or more multiply defined symbols found A: The function body is literally inserted inside the caller function. Thus, if you have multiple calls to this function, you get multiple copies of the code. The benefit is you get faster execution. Usually very short function are inlined, when the copy of the function body would be not much bigger than the usual prologue/epilogue code generated for the normal function call. You can read more at MSDN article about inline - http://msdn.microsoft.com/en-us/library/z8y1yy88.aspx A: Inline functions alter the performance profile of your application by possibly generating instructions that are placed in the code segment of your application. Whether a function is inlined is at the discretion of your compiler. In my experience, most modern compilers are good at determining when to comply with a user's request to inline. In many cases, inlining a function will improve its performance. There is an inherent overhead to function calls. There are reasons, however, why inlining a function could be negative: * *Increasing the size of the binary executable by duplicating code could lead to disk thrashing, slowing your application down. *Inlining code could contribute to cache misses, or possibly contribute to cache hits depending on your architecture. The C++ FAQ does a good job of explaining the intricacies of the keyword: http://www.parashift.com/c++-faq-lite/inline-functions.html#faq-9.3 A: Informally, it means that compilers are allowed to graft the contents of the function onto the call site, so that there is no function call. If your function has big control statements (e.g., if, switch, etc.), and the conditions can be evaluated at compile time at the call site (e.g., constant values used at call site), then your code ends up much smaller (the unused branches are dropped off). More formally, inline functions have different linkage too. I'll let C++ experts talk about that aspect. A: Calling a function imposes a certain performance penalty for the CPU over just having a linear stream of instructions. The CPU's registers have to be written to another location, etc. Obviously the benefits of having functions usually outweigh the performance penalty. But, where performance will be an issue, for example the fabled 'inner loop' function or some other bottleneck, the compiler can insert the machine code for the function into the main stream of execution instead of going through the CPU's tax for calling a function. A: A function that you flag as inline is allowed to be inlined by the compiler. There is no guarantee that compielr will do it. The compiler itself uses complex semantics to device when to do it or not. When the compiler decides that a function should be inlined, the call to the function, in the caller code is replaced by the code of the calee. This means you save up stack operations, the call itself and improve locality of code cache. Sometimes that may lead to huge performance gains. Specially in 1 line data access functions, like the accessors used in Object Oriented code. The cost is that usually that will result in larger code, what might hurt performance. This is why setting a function to inline is only a "green flag" to the compiler, that it does not need to follow. The compiler will try to do what is best. As a rule of thumb for beginners that don't want to deal with linkage peculiarities. inline function are to be called by other function in same compilation units. If you want to implement an inline function that can be used on multiple compilation units, make it an header file declared and implemented inline function. Why? Example: at header file inlinetest.h int foo(); inline int bar(); At the compilation unit inlinetest.cpp int foo(){ int r = bar(); return r; } inline int bar(){ return 5;}; Then at the main.cpp #include "inlinetest.h" int main() { foo(); //bar(); } Compile one object file at a time. If you uncomment that "bar" call you will have an error. Because the inline function is only implemented on the inlinetest.o object file and is not exported. At same time the foo function, very likely has embedded on it the code of the bar function (since bar is single line no I/O operation then its very likely to be inlined) But if at the header file you had declared the inline function and implemented it inline then you would be able to use it at any compilation unit that includes that header. ("code sample"); Remove the inline keyword and compiler will NOT cause the error even with bar call at main And no inline will happen unless you ask the compiler to inline all functions. That is not standard behavior on most compilers.
{ "language": "en", "url": "https://stackoverflow.com/questions/156438", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "32" }
Q: Is buffer overflow/overrun possible in completely managed asp.net c# web application Can there be buffer overflow/overrun vulnerabilities in completely managed asp.net web portal.If yes how can this be tested. A: In the general case, you don't need to worry about buffer overruns. This is one of the major advantages of managed code, garbage collection being perhaps the other major advantage. There are a few edge cases that you should be aware of - any time your managed code interacts with unmanaged code (Win32 API calls, COM interop, P/Invoke, etc) there is a potential for buffer overruns in the unmanaged code, based on parameters passed in from managed code. Also code marked as "unsafe" can directly manipulate memory addresses in such a way as to cause buffer overflow. Most C# code is written without using the "unsafe" keyword, though. A: Not unless you exploit the webserver or .NET/ASP.NET stack itself. A: I had a tool (HP Dev Inspect) detect a possible "Possible Parameter Buffer Overflow" within my ASP.NET app and it was because we didn't have a MaxLength="20" in one of our TextBoxes...
{ "language": "en", "url": "https://stackoverflow.com/questions/156445", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Enumerate errors in an error provider Is it possible to enumerate all the current errors being displayed through an "Error Provider" without having to access the controls? A: You can get all of the errors from an ErrorProvider by enumerating the Controls collection of its parent and calling GetError on each. Not efficient but it works. foreach (Control ctrl in errProv.ContainerControl.Controls) { Console.WriteLine(errProv.GetError(ctrl)); } A: For any .net WinForms people who find this in google etc... In WinForms at least enumerating all the current errors being displayed through an "Error Provider" class without accessing all the controls is not possible, there isn't even a summary validator in WinForms. However if your errors are bubbling up from a lower layer then you should have access to a collection of them somewhere anyway, as the poster Charles Graham points out. A: In WinForms, if your application is simple enough not to have any well-defined "layers" then you could wrap the ErrorProvider in a class that records and exposes all current errors. Or, if the app is really really simple, create a helper method that records/deletes an error and updates the ErrorProvider. A: There is a summary validator that will give you all of the errors, but it's pretty ugly, and I'm not sure if you can use it without displaying it on the page. Technically, if you are doing things the "right way", all of you error handling should be handled in your midddle teir and then bubbled to the screen that way, so you already have access to all the errors in a collection or dictionary.
{ "language": "en", "url": "https://stackoverflow.com/questions/156457", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Is there any benefit to this switch / pattern matching idea? I've been looking at F# recently, and while I'm not likely to leap the fence any time soon, it definitely highlights some areas where C# (or library support) could make life easier. In particular, I'm thinking about the pattern matching capability of F#, which allows a very rich syntax - much more expressive than the current switch/conditional C# equivalents. I won't try to give a direct example (my F# isn't up to it), but in short it allows: * *match by type (with full-coverage checking for discriminated unions) [note this also infers the type for the bound variable, giving member access etc] *match by predicate *combinations of the above (and possibly some other scenarios I'm not aware of) While it would be lovely for C# to eventually borrow [ahem] some of this richness, in the interim I've been looking at what can be done at runtime - for example, it is fairly easy to knock together some objects to allow: var getRentPrice = new Switch<Vehicle, int>() .Case<Motorcycle>(bike => 100 + bike.Cylinders * 10) // "bike" here is typed as Motorcycle .Case<Bicycle>(30) // returns a constant .Case<Car>(car => car.EngineType == EngineType.Diesel, car => 220 + car.Doors * 20) .Case<Car>(car => car.EngineType == EngineType.Gasoline, car => 200 + car.Doors * 20) .ElseThrow(); // or could use a Default(...) terminator where getRentPrice is a Func<Vehicle,int>. [note - maybe Switch/Case here is the wrong terms... but it shows the idea] To me, this is a lot clearer than the equivalent using repeated if/else, or a composite ternary conditional (which gets very messy for non-trivial expressions - brackets galore). It also avoids a lot of casting, and allows for simple extension (either directly or via extension methods) to more-specific matches, for example an InRange(...) match comparable to the VB Select...Case "x To y" usage. I'm just trying to gauge if people think there is much benefit from constructs like the above (in the absence of language support)? Note additionally that I've been playing with 3 variants of the above: * *a Func<TSource,TValue> version for evaluation - comparable to composite ternary conditional statements *an Action<TSource> version - comparable to if/else if/else if/else if/else *an Expression<Func<TSource,TValue>> version - as the first, but usable by arbitrary LINQ providers Additionally, using the Expression-based version enables Expression-tree re-writing, essentially inlining all the branches into a single composite conditional Expression, rather than using repeated invocation. I haven't checked recently, but in some early Entity Framework builds I seem to recall this being necessary, as it didn't like InvocationExpression very much. It also allows more efficient usage with LINQ-to-Objects, since it avoids repeated delegate invocations - tests show a match like the above (using the Expression form) performing at the same speed [marginally quicker, in fact] compared to the equivalent C# composite conditional statement. For completeness, the Func<...> based-version took 4 times as long as the C# conditional statement, but is still very quick and is unlikely to be a major bottleneck in most use-cases. I welcome any thoughts / input / critique / etc on the above (or on the possibilities of richer C# language support... here's hoping ;-p). A: The purpose of pattern matching (as described here) is to deconstruct values according to their type specification. However, the concept of a class (or type) in C# doesn't agree with you. There's nothing wrong with multi-paradigm language design, on the contrary, it's very nice to have lambdas in C#, and Haskell can do imperative stuff to e.g. IO. But it's not a very elegant solution, not in Haskell fashion. But since sequential procedural programming languages can be understood in terms of lambda calculus, and C# happens to fit well within the parameters of a sequential procedural language, it's a good fit. But, taking something from the pure functional context of, say, Haskell, and then putting that feature into a language which is not pure, well, doing just that will not guarantee a better outcome. My point is what makes pattern matching tick is tied to the language design and data model. Having said that, I don't believe pattern matching to be an useful feature of C# because it does not solve typical C# problems, nor does it fit well within the imperative programming paradigm. A: In my humble opinion, the object oriented way of doing such things is the Visitor pattern. Your visitor member methods simply act as case constructs and you let the language itself handle the appropriate dispatch without having to "peek" at types. A: Although it's not very 'C-sharpey' to switch on type, I know that construct would be pretty helpful in general use - I have at least one personal project that could use it (although its managable ATM). Is there much of a compile performance problem, with the expression tree re-writing? A: After trying to do such "functional" things in C# (and even attempting a book on it), I've come to the conclusion that no, with a few exceptions, such things don't help too much. The main reason is that languages such as F# get a lot of their power from truly supporting these features. Not "you can do it", but "it's simple, it's clear, it's expected". For instance, in pattern matching, you get the compiler telling you if there's an incomplete match or when another match will never be hit. This is less useful with open ended types, but when matching a discriminated union or tuples, it's very nifty. In F#, you expect people to pattern match, and it instantly makes sense. The "problem" is that once you start using some functional concepts, it's natural to want to continue. However, leveraging tuples, functions, partial method application and currying, pattern matching, nested functions, generics, monad support, etc. in C# gets very ugly, very quickly. It's fun, and some very smart people have done some very cool things in C#, but actually using it feels heavy. What I have ended up using often (across-projects) in C#: * *Sequence functions, via extension methods for IEnumerable. Things like ForEach or Process ("Apply"? -- do an action on a sequence item as it's enumerated) fit in because C# syntax supports it well. *Abstracting common statement patterns. Complicated try/catch/finally blocks or other involved (often heavily generic) code blocks. Extending LINQ-to-SQL fits in here too. *Tuples, to some extent. ** But do note: The lack of automatic generalization and type inference really hinder the use of even these features. ** All this said, as someone else mentioned, on a small team, for a specific purpose, yes, perhaps they can help if you're stuck with C#. But in my experience, they usually felt like more hassle than they were worth - YMMV. Some other links: * *Mono.Rocks playground has many similar things (as well as non-functional-programming-but-useful additions). *Luca Bolognese's functional C# library *Matthew Podwysocki's functional C# on MSDN A: One thing to be careful of: the C# compiler is pretty good at optimising switch statements. Not just for short circuiting - you get completely different IL depending on how many cases you have and so on. Your specific example does do something I'd find very useful - there is no syntax equivalent to case by type, as (for instance) typeof(Motorcycle) is not a constant. This gets more interesting in dynamic application - your logic here could be easily data-driven, giving 'rule-engine' style execution. A: Arguably the reason that C# doesn't make it simple to switch on type is because it is primarily an object-oriented language, and the 'correct' way to do this in object-oriented terms would be to define a GetRentPrice method on Vehicle and override it in derived classes. That said, I've spent a bit of time playing with multi-paradigm and functional languages like F# and Haskell which have this type of capability, and I've come across a number of places where it would be useful before (e.g. when you are not writing the types you need to switch on so you cannot implement a virtual method on them) and it's something I'd welcome into the language along with discriminated unions. [Edit: Removed part about performance as Marc indicated it could be short-circuited] Another potential problem is a usability one - it's clear from the final call what happens if the match fails to meet any conditions, but what is the behaviour if it matches two or more conditions? Should it throw an exception? Should it return the first or the last match? A way I tend to use to solve this kind of problem is to use a dictionary field with the type as the key and the lambda as the value, which is pretty terse to construct using object initializer syntax; however, this only accounts for the concrete type and doesn't allow additional predicates so may not be suitable for more complex cases. [Side note - if you look at the output of the C# compiler it frequently converts switch statements to dictionary-based jump tables, so there doesn't appear to be a good reason it couldn't support switching on types] A: I don't think these sorts of libraries (which act like language extensions) are likely to gain wide acceptance, but they are fun to play with, and can be really useful for small teams working in specific domains where this is useful. For instance, if you are writing tons of 'business rules/logic' that does arbitrary type tests like this and whatnot, I can see how it would be handy. I've no clue if this is ever likely to be a C# language feature (seems doubtful, but who can see the future?). For reference, the corresponding F# is approximately: let getRentPrice (v : Vehicle) = match v with | :? Motorcycle as bike -> 100 + bike.Cylinders * 10 | :? Bicycle -> 30 | :? Car as car when car.EngineType = Diesel -> 220 + car.Doors * 20 | :? Car as car when car.EngineType = Gasoline -> 200 + car.Doors * 20 | _ -> failwith "blah" assuming you'd defined a class hierarchy along the lines of type Vehicle() = class end type Motorcycle(cyl : int) = inherit Vehicle() member this.Cylinders = cyl type Bicycle() = inherit Vehicle() type EngineType = Diesel | Gasoline type Car(engType : EngineType, doors : int) = inherit Vehicle() member this.EngineType = engType member this.Doors = doors A: In C# 7, you can do: switch(shape) { case Circle c: WriteLine($"circle with radius {c.Radius}"); break; case Rectangle s when (s.Length == s.Height): WriteLine($"{s.Length} x {s.Height} square"); break; case Rectangle r: WriteLine($"{r.Length} x {r.Height} rectangle"); break; default: WriteLine("<unknown shape>"); break; case null: throw new ArgumentNullException(nameof(shape)); } A: Yes I think pattern matching syntactic constructs are useful. I for one would like to see syntactic support in C# for it. Here is my implementation of a class that provides (nearly) the same syntax as you describe public class PatternMatcher<Output> { List<Tuple<Predicate<Object>, Func<Object, Output>>> cases = new List<Tuple<Predicate<object>,Func<object,Output>>>(); public PatternMatcher() { } public PatternMatcher<Output> Case(Predicate<Object> condition, Func<Object, Output> function) { cases.Add(new Tuple<Predicate<Object>, Func<Object, Output>>(condition, function)); return this; } public PatternMatcher<Output> Case<T>(Predicate<T> condition, Func<T, Output> function) { return Case( o => o is T && condition((T)o), o => function((T)o)); } public PatternMatcher<Output> Case<T>(Func<T, Output> function) { return Case( o => o is T, o => function((T)o)); } public PatternMatcher<Output> Case<T>(Predicate<T> condition, Output o) { return Case(condition, x => o); } public PatternMatcher<Output> Case<T>(Output o) { return Case<T>(x => o); } public PatternMatcher<Output> Default(Func<Object, Output> function) { return Case(o => true, function); } public PatternMatcher<Output> Default(Output o) { return Default(x => o); } public Output Match(Object o) { foreach (var tuple in cases) if (tuple.Item1(o)) return tuple.Item2(o); throw new Exception("Failed to match"); } } Here is some test code: public enum EngineType { Diesel, Gasoline } public class Bicycle { public int Cylinders; } public class Car { public EngineType EngineType; public int Doors; } public class MotorCycle { public int Cylinders; } public void Run() { var getRentPrice = new PatternMatcher<int>() .Case<MotorCycle>(bike => 100 + bike.Cylinders * 10) .Case<Bicycle>(30) .Case<Car>(car => car.EngineType == EngineType.Diesel, car => 220 + car.Doors * 20) .Case<Car>(car => car.EngineType == EngineType.Gasoline, car => 200 + car.Doors * 20) .Default(0); var vehicles = new object[] { new Car { EngineType = EngineType.Diesel, Doors = 2 }, new Car { EngineType = EngineType.Diesel, Doors = 4 }, new Car { EngineType = EngineType.Gasoline, Doors = 3 }, new Car { EngineType = EngineType.Gasoline, Doors = 5 }, new Bicycle(), new MotorCycle { Cylinders = 2 }, new MotorCycle { Cylinders = 3 }, }; foreach (var v in vehicles) { Console.WriteLine("Vehicle of type {0} costs {1} to rent", v.GetType(), getRentPrice.Match(v)); } } A: You can achieve what you are after by using a library I wrote, called OneOf The major advantage over switch (and if and exceptions as control flow) is that it is compile-time safe - there is no default handler or fall through OneOf<Motorcycle, Bicycle, Car> vehicle = ... //assign from one of those types var getRentPrice = vehicle .Match( bike => 100 + bike.Cylinders * 10, // "bike" here is typed as Motorcycle bike => 30, // returns a constant car => car.EngineType.Match( diesel => 220 + car.Doors * 20 petrol => 200 + car.Doors * 20 ) ); It's on Nuget and targets net451 and netstandard1.6
{ "language": "en", "url": "https://stackoverflow.com/questions/156467", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "158" }
Q: Is there a good drop-in replacement for Java's JEditorPane? I'm not happy with the rendering of HTML by Swing's JEditorPane. In particular bullets for unordered lists are hideous. Customising the rendering seems extremely difficult. Therefore I'm looking for a replacement with better HTML rendering. Does this exist? (I asked Google, and found nothing except a promising dead link). A: http://today.java.net/pub/a/today/2004/05/24/html-pt1.html A: Something that I looked at extensively a while back - and there are many options - however I nearly ended up using http://lobobrowser.org/cobra.jsp, but then the project was cancelled so I can't tell you how it all turned out... A: Cobra did the trick. Almost a drop-in replacement for JEditorPane, with very nice HTML rendering. One complaint: it's a big jar to add to my little application. Thanks for the responses. A: Take a look at SwingBox. SwingBox is a Java Swing component that allows displaying the (X)HTML documents including the CSS support. It is designed as a JEditorPane replacement with considerably better rendering results. SwingBox is pure Java and it is using the CSSBox rendering engine for rendering the documents.
{ "language": "en", "url": "https://stackoverflow.com/questions/156472", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Implementing cache correctly in a class library for use in an asp.net application I'm implementing a cache in a class library that i'm using in an asp.net application. I created my cache object as a singleton pattern with a static method to update the cache which is really just loading a member variable/property with a collection of data i need cached (got some locking logic ofcourse). I figured it was a nice way to go since i can just access my data by calling MyCacheObject.Instance.MyDataCollection I'm creating a new cache object to store a pretty big amount of data partitioned by some key. What i'm saying is i'm creating a new cache but this one will not load all of the data at once, but rather store a collection for each key accessed. MyOtherCacheObject.Instance.MyOtherDataCollection(indexkey) This time the question about garbage collection was brought up. Since i'm storing a huge amount of data, wouldn't it be a waste if it got gc'ed all of a sudden? Since it's just a singleton pattern there is nothing ensuring data will stay in cache. So my question is - what is best practice for implemeting a cache to handle this situation? I really don't like a huge complex solution to this, and i know there is caching in System.Web but that seems a bit 'off' since this is just a class library, or what do you think? A: In my opinion, the best solution would have the following characteristics: * *Uses the available caching services provided by the platform trying to avoid writing your own. *Does not couple your class library to System.Web, in order to have the layers coherent. *But if the class library is running inside an ASP.NET application the solution should not require to bring another caching implementation on (for example, the Enterprise Library Caching Application Block), which requires additional configuration and setup. So, I would use an IoC strategy in order to allow the class library to use different caching implementations, based on the environment it is running on. Suppose you define your abstract caching contract as: public interface ICacheService { AddItem(...); } You could provide an implementation based on System.Web: public AspNetBasedCacheService : ICacheService { AddItem(...) { // Implementation that uses the HttpContext.Cache object } } And then have that implementation 'published' as singleton. Note that the difference with your original approach is that the singleton is just a reference to the ASP.NET cache service based implementation, instead of the full 'cache object'. public class CacheServiceProvider { public static ICacheService Instance {get; set;} } You would have to initialize the caching implementation either by performing lazy initialization, or at application startup (in Global.asax.cs) And every domain component would be able to use the published caching service without knowing that it is implemented based on System.Web. // inside your class library: ICacheService cache = CacheServiceProvider.Instance; cache.AddItem(...); I agree that it is probably not the simplest solution, but I'm aiming for taking advantage of the ASP.NET cache implementation without sacrificing code decoupling and flexibility. I hope I understood your question right. A: The data wouldn't get garbage collected as long as the cache still holds a reference to it. Also, don't ever use Singletons.
{ "language": "en", "url": "https://stackoverflow.com/questions/156478", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: How to properly implement a shared cache in ColdFusion? I have built a CFC designed to serve as a dynamic, aging cache intended for almost everything worth caching. LDAP queries, function results, arrays, ojects, you name it. Whatever takes time or resources to calculate and is needed more than once. I'd like to be able to do a few things: * *share the CFC between applications *define the scope of the cache (server / application / session / current request only) *use different cache instances at the same time, in the same request *be independent from CFCs using the cache component *generally adhere to common sense (decoupling, encapsulation, orthogonality, locking) I would of course be using a different cache instance for every distinct task, but I'd like to be able to use the same CFC across applications. The cache itself is (what else) a Struct, private to the cache instance. How would I properly implement caching and locking when the scope itself is subject to change? For locking, I use named locks ('CacheRead', 'CacheWrite') currently, this is safe but strikes me as odd. Why would I want a server-wide lock for, say, a session-only operation? (Yes, maybe this is academic, but anyway.) Passing in the APPLICATION scope as a reference when I want application level caching also seems the wrong thing to do. Is there a better way? A: Okay - since I misunderstood your question initially I've deleted my previous answer as to not cause any further confusion. To answer your question about locking: Named locks should be fine because they don't have to always have the same name. You can name them dynamically depending on what cache you are accessing. When you need to access an element of the private struct you could do something like have the named lock use the key as its name. This way, the only time a lock would have an effect is if something was trying to access the same cache by name. A: I understand your desire to avoid passing in the actual scope structure that you want to cache to, but your alternatives are limited. The first thing that comes to mind is just passing the name (a string) of the scope you want your cache stored in, and evaluating. By its nature, evaluation is inefficient and should be avoided. That said, I was curious how it might be accomplished. I don't have your code so I just made a dirt-simple "storage" abstraction CFC (skipped caching, as it's irrelevant to what I want to test) here: cache.cfc: <cfcomponent> <cfset variables.cacheScope = "session" /><!--- default to session ---> <cfset variables.cache = ""/> <cfscript> function init(scope){ variables.cacheScope = arguments.scope; return this; } function cacheWrite(key, value){ structInsert(evaluate(variables.cacheScope),arguments.key,arguments.value,true); return this; } function cacheRead(key){ if (not structKeyExists(evaluate(variables.cacheScope), arguments.key)){ return ""; }else{ variables.cache = evaluate(variables.cacheScope); return variables.cache[arguments.key]; } } </cfscript> </cfcomponent> And a view to test it: <!--- clear out any existing session vars ---> <cfset structClear(session)/> <!--- show empty session struct ---> <cfdump var="#session#" label="session vars"> <!--- create storage object ---> <cfset cacher = createObject("component", "cache").init("session")/> <!--- store a value ---> <cfset cacher.cacheWrite("foo", "bar")/> <!--- read stored value ---> <cfset rtn = cacher.cacheRead("foo")/> <!--- show values ---> <cfdump var="#rtn#"> <cfdump var="#session#" label="session vars"> Off topic: I like to write my setter functions to return "this" [as seen above] so that I can chain method calls like jQuery. Part of the view could just as easily been written as: <cfset rtn = createObject("component", "cache") .init("session") .cacheWrite("foo", "bar") .cacheRead("foo")/> It's interesting that this is possible, but I probably wouldn't use it in production due to the overhead cost of Evaluate. I'd say that this is valid enough reason to pass in the scope you want to cache into. If you're still bothered by it (and maybe rightly so?), you could create another CFC that abstracts reading and writing from the desired scope and pass that into your caching CFC as the storage location (a task well-suited for ColdSpring), that way if you ever decide to move the cache into another scope, you don't have to edit 300 pages all using your cache CFC passing in "session" to init, and instead you can edit 1 CFC or your ColdSpring config. I'm not entirely sure why you would want to have single-request caching though, when you have the request scope. If what you're looking for is a way to cache something for the current request and have it die shortly afterward, request scope may be what you want. Caching is usually more valuable when it spans multiple requests.
{ "language": "en", "url": "https://stackoverflow.com/questions/156492", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Restore Office Environment to Default after development After I develop my add-in for Microsoft Office ( and in the process messed up all my menu bars and tool bars) using Visual Studio For Office, is there anyway to restore the MS Office to default? For the record, Clean Solution alone is not enough! A: Did you try repair? Always have an updated image of the drive, it comes in handy.
{ "language": "en", "url": "https://stackoverflow.com/questions/156493", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to write an Excel workbook to a MemoryStream in .NET? How do I write an Excel workbook to a MemoryStream without first saving it to the file system? All options within the Microsoft.Office.Interop.Excel.WorkBook save options take a filename. A: I have done extensive work with the PIA and with storing Excel files in a document repository and streaming it out to the browser, and I have not been able to find a solution to using the PIA without first writing the contents to the file system first. I think that you are going to have to swallow the bullet and deal with the file system as an intermediary. The good news is that you can just give the file a unique name like a guid or use some other tempfilename method (not sure if one exists in .net) and just delete the contents when you are done. A: This can be done with Open XML SDK 2.0. Eric White has a great article on how to work with OOXML files in stream at Working with In-Memory Open XML Documents A: If you only need basic functionality from Excel, you might want to create the Workbook as an Html stream. There is another question on SO that handless this. This also solves some problems (you might not have yet) concerning the scalability of your solution. A: Another option would be to use this free library for exporting the workbook. The save method on the workbook class can either take a file name or a stream. A: The only way you could do this is if you were prepared to create a custom object that allowed you to store all the various bits and pieces of data/formulas/vba/links/ole objects that you wanted to keep, copy from your workbook to the object, and then persist that object to a memory stream. In affect using your proxy object as a go between. There is no way (as others have said) of writing an Excel file straight to memory. With Excel 2007 OpenXML format, you could use the BeforeSave event of the workbook to have a custom method that first sets the Cancel parameter of the BeforeSave event to True, and then instead serialises the resultant xml package (that represents the file) into an object in memory.
{ "language": "en", "url": "https://stackoverflow.com/questions/156500", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: How do you assert that a certain exception is thrown in JUnit tests? How can I use JUnit idiomatically to test that some code throws an exception? While I can certainly do something like this: @Test public void testFooThrowsIndexOutOfBoundsException() { boolean thrown = false; try { foo.doStuff(); } catch (IndexOutOfBoundsException e) { thrown = true; } assertTrue(thrown); } I recall that there is an annotation or an Assert.xyz or something that is far less kludgy and far more in-the-spirit of JUnit for these sorts of situations. A: In my case I always get RuntimeException from db, but messages differ. And exception need to be handled respectively. Here is how I tested it: @Test public void testThrowsExceptionWhenWrongSku() { // Given String articleSimpleSku = "999-999"; int amountOfTransactions = 1; Exception exception = null; // When try { createNInboundTransactionsForSku(amountOfTransactions, articleSimpleSku); } catch (RuntimeException e) { exception = e; } // Then shouldValidateThrowsExceptionWithMessage(exception, MESSAGE_NON_EXISTENT_SKU); } private void shouldValidateThrowsExceptionWithMessage(final Exception e, final String message) { assertNotNull(e); assertTrue(e.getMessage().contains(message)); } A: Now that JUnit 5 and JUnit 4.13 have been released, the best option would be to use Assertions.assertThrows() (for JUnit 5) and Assert.assertThrows() (for JUnit 4.13). See the JUnit 5 User Guide. Here is an example that verifies an exception is thrown, and uses Truth to make assertions on the exception message: public class FooTest { @Test public void doStuffThrowsIndexOutOfBoundsException() { Foo foo = new Foo(); IndexOutOfBoundsException e = assertThrows( IndexOutOfBoundsException.class, foo::doStuff); assertThat(e).hasMessageThat().contains("woops!"); } } The advantages over the approaches in the other answers are: * *Built into JUnit *You get a useful exception message if the code in the lambda doesn't throw an exception, and a stacktrace if it throws a different exception *Concise *Allows your tests to follow Arrange-Act-Assert *You can precisely indicate what code you are expecting to throw the exception *You don't need to list the expected exception in the throws clause *You can use the assertion framework of your choice to make assertions about the caught exception A: Just make a Matcher that can be turned off and on, like this: public class ExceptionMatcher extends BaseMatcher<Throwable> { private boolean active = true; private Class<? extends Throwable> throwable; public ExceptionMatcher(Class<? extends Throwable> throwable) { this.throwable = throwable; } public void on() { this.active = true; } public void off() { this.active = false; } @Override public boolean matches(Object object) { return active && throwable.isAssignableFrom(object.getClass()); } @Override public void describeTo(Description description) { description.appendText("not the covered exception type"); } } To use it: add public ExpectedException exception = ExpectedException.none();, then: ExceptionMatcher exMatch = new ExceptionMatcher(MyException.class); exception.expect(exMatch); someObject.somethingThatThrowsMyException(); exMatch.off(); A: We can use an assertion fail after the method that must return an exception: try{ methodThatThrowMyException(); Assert.fail("MyException is not thrown !"); } catch (final Exception exception) { // Verify if the thrown exception is instance of MyException, otherwise throws an assert failure assertTrue(exception instanceof MyException, "An exception other than MyException is thrown !"); // In case of verifying the error message MyException myException = (MyException) exception; assertEquals("EXPECTED ERROR MESSAGE", myException.getMessage()); } A: In JUnit 4 or later you can test the exceptions as follows @Rule public ExpectedException exceptions = ExpectedException.none(); this provides a lot of features which can be used to improve our JUnit tests. If you see the below example I am testing 3 things on the exception. * *The Type of exception thrown *The exception Message *The cause of the exception public class MyTest { @Rule public ExpectedException exceptions = ExpectedException.none(); ClassUnderTest classUnderTest; @Before public void setUp() throws Exception { classUnderTest = new ClassUnderTest(); } @Test public void testAppleisSweetAndRed() throws Exception { exceptions.expect(Exception.class); exceptions.expectMessage("this is the exception message"); exceptions.expectCause(Matchers.<Throwable>equalTo(exceptionCause)); classUnderTest.methodUnderTest("param1", "param2"); } } A: Update: JUnit5 has an improvement for exceptions testing: assertThrows. The following example is from: Junit 5 User Guide import static org.junit.jupiter.api.Assertions.assertThrows; @Test void exceptionTesting() { IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> { throw new IllegalArgumentException("a message"); }); assertEquals("a message", exception.getMessage()); } Original answer using JUnit 4. There are several ways to test that an exception is thrown. I have also discussed the below options in my post How to write great unit tests with JUnit Set the expected parameter @Test(expected = FileNotFoundException.class). @Test(expected = FileNotFoundException.class) public void testReadFile() { myClass.readFile("test.txt"); } Using try catch public void testReadFile() { try { myClass.readFile("test.txt"); fail("Expected a FileNotFoundException to be thrown"); } catch (FileNotFoundException e) { assertThat(e.getMessage(), is("The file test.txt does not exist!")); } } Testing with ExpectedException Rule. @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void testReadFile() throws FileNotFoundException { thrown.expect(FileNotFoundException.class); thrown.expectMessage(startsWith("The file test.txt")); myClass.readFile("test.txt"); } You could read more about exceptions testing in JUnit4 wiki for Exception testing and bad.robot - Expecting Exceptions JUnit Rule. A: Be careful using expected exception, because it only asserts that the method threw that exception, not a particular line of code in the test. I tend to use this for testing parameter validation, because such methods are usually very simple, but more complex tests might better be served with: try { methodThatShouldThrow(); fail( "My method didn't throw when I expected it to" ); } catch (MyException expectedException) { } Apply judgement. A: Additionally to what NamShubWriter has said, make sure that: * *The ExpectedException instance is public (Related Question) *The ExpectedException isn't instantiated in say, the @Before method. This post clearly explains all the intricacies of JUnit's order of execution. Do not do this: @Rule public ExpectedException expectedException; @Before public void setup() { expectedException = ExpectedException.none(); } Finally, this blog post clearly illustrates how to assert that a certain exception is thrown. A: How about this: catch a very general exception, make sure it makes it out of the catch block, then assert that the class of the exception is what you expect it to be. This assert will fail if a) the exception is of the wrong type (eg. if you got a Null Pointer instead) and b) the exception wasn't ever thrown. public void testFooThrowsIndexOutOfBoundsException() { Throwable e = null; try { foo.doStuff(); } catch (Throwable ex) { e = ex; } assertTrue(e instanceof IndexOutOfBoundsException); } A: Using an AssertJ assertion, which can be used alongside JUnit: import static org.assertj.core.api.Assertions.*; @Test public void testFooThrowsIndexOutOfBoundsException() { Foo foo = new Foo(); assertThatThrownBy(() -> foo.doStuff()) .isInstanceOf(IndexOutOfBoundsException.class); } It's better than @Test(expected=IndexOutOfBoundsException.class) because it guarantees the expected line in the test threw the exception and lets you check more details about the exception, such as message, easier: assertThatThrownBy(() -> { throw new Exception("boom!"); }) .isInstanceOf(Exception.class) .hasMessageContaining("boom"); Maven/Gradle instructions here. A: Junit4 solution with Java8 is to use this function: public Throwable assertThrows(Class<? extends Throwable> expectedException, java.util.concurrent.Callable<?> funky) { try { funky.call(); } catch (Throwable e) { if (expectedException.isInstance(e)) { return e; } throw new AssertionError( String.format("Expected [%s] to be thrown, but was [%s]", expectedException, e)); } throw new AssertionError( String.format("Expected [%s] to be thrown, but nothing was thrown.", expectedException)); } Usage is then: assertThrows(ValidationException.class, () -> finalObject.checkSomething(null)); Note that the only limitation is to use a final object reference in lambda expression. This solution allows to continue test assertions instead of expecting thowable at method level using @Test(expected = IndexOutOfBoundsException.class) solution. A: I recomend library assertj-core to handle exception in junit test In java 8, like this: //given //when Throwable throwable = catchThrowable(() -> anyService.anyMethod(object)); //then AnyException anyException = (AnyException) throwable; assertThat(anyException.getMessage()).isEqualTo("........"); assertThat(exception.getCode()).isEqualTo(".......); A: BDD Style Solution: JUnit 4 + Catch Exception + AssertJ import static com.googlecode.catchexception.apis.BDDCatchException.*; @Test public void testFooThrowsIndexOutOfBoundsException() { when(() -> foo.doStuff()); then(caughtException()).isInstanceOf(IndexOutOfBoundsException.class); } Dependencies eu.codearte.catch-exception:catch-exception:2.0 A: To solve the same problem I did set up a small project: http://code.google.com/p/catch-exception/ Using this little helper you would write verifyException(foo, IndexOutOfBoundsException.class).doStuff(); This is less verbose than the ExpectedException rule of JUnit 4.7. In comparison to the solution provided by skaffman, you can specify in which line of code you expect the exception. I hope this helps. A: It depends on the JUnit version and what assert libraries you use. * *For JUnit5 and 4.13 see answer *If you use AssertJ or google-truth, see answer The original answer for JUnit <= 4.12 was: @Test(expected = IndexOutOfBoundsException.class) public void testIndexOutOfBoundsException() { ArrayList emptyList = new ArrayList(); Object o = emptyList.get(0); } Though answer has more options for JUnit <= 4.12. Reference: * *JUnit Test-FAQ A: in junit, there are four ways to test exception. junit5.x * *for junit5.x, you can use assertThrows as following @Test public void testFooThrowsIndexOutOfBoundsException() { Throwable exception = assertThrows(IndexOutOfBoundsException.class, () -> foo.doStuff()); assertEquals("expected messages", exception.getMessage()); } junit4.x * *for junit4.x, use the optional 'expected' attribute of Test annonation @Test(expected = IndexOutOfBoundsException.class) public void testFooThrowsIndexOutOfBoundsException() { foo.doStuff(); } *for junit4.x, use the ExpectedException rule public class XxxTest { @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void testFooThrowsIndexOutOfBoundsException() { thrown.expect(IndexOutOfBoundsException.class) //you can test the exception message like thrown.expectMessage("expected messages"); foo.doStuff(); } } *you also can use the classic try/catch way widely used under junit 3 framework @Test public void testFooThrowsIndexOutOfBoundsException() { try { foo.doStuff(); fail("expected exception was not occured."); } catch(IndexOutOfBoundsException e) { //if execution reaches here, //it indicates this exception was occured. //so we need not handle it. } } *so * *if you like junit 5, then you should like the 1st one *the 2nd way is used when you only want test the type of exception *the first and last two are used when you want test exception message further *if you use junit 3, then the 4th one is preferred *for more info, you can read this document and junit5 user guide for details. A: As answered before, there are many ways of dealing with exceptions in JUnit. But with Java 8 there is another one: using Lambda Expressions. With Lambda Expressions we can achieve a syntax like this: @Test public void verifiesTypeAndMessage() { assertThrown(new DummyService()::someMethod) .isInstanceOf(RuntimeException.class) .hasMessage("Runtime exception occurred") .hasMessageStartingWith("Runtime") .hasMessageEndingWith("occurred") .hasMessageContaining("exception") .hasNoCause(); } assertThrown accepts a functional interface, whose instances can be created with lambda expressions, method references, or constructor references. assertThrown accepting that interface will expect and be ready to handle an exception. This is relatively simple yet powerful technique. Have a look at this blog post describing this technique: http://blog.codeleak.pl/2014/07/junit-testing-exception-with-java-8-and-lambda-expressions.html The source code can be found here: https://github.com/kolorobot/unit-testing-demo/tree/master/src/test/java/com/github/kolorobot/exceptions/java8 Disclosure: I am the author of the blog and the project. A: You can also do this: @Test public void testFooThrowsIndexOutOfBoundsException() { try { foo.doStuff(); assert false; } catch (IndexOutOfBoundsException e) { assert true; } } A: JUnit framework has assertThrows() method: ArithmeticException exception = assertThrows(ArithmeticException.class, () -> calculator.divide(1, 0)); assertEquals("/ by zero", exception.getMessage()); * *for JUnit 5 it's in org.junit.jupiter.api.Assertions class; *for JUnit 4.13 it's in org.junit.Assert class; *for earlier versions of JUnit 4: just add reference on org.junit.jupiter:junit-jupiter-api to your project and you'll get perfectly well working version from JUnit 5. A: IMHO, the best way to check for exceptions in JUnit is the try/catch/fail/assert pattern: // this try block should be as small as possible, // as you want to make sure you only catch exceptions from your code try { sut.doThing(); fail(); // fail if this does not throw any exception } catch(MyException e) { // only catch the exception you expect, // otherwise you may catch an exception for a dependency unexpectedly // a strong assertion on the message, // in case the exception comes from anywhere an unexpected line of code, // especially important if your checking IllegalArgumentExceptions assertEquals("the message I get", e.getMessage()); } The assertTrue might be a bit strong for some people, so assertThat(e.getMessage(), containsString("the message"); might be preferable. A: Edit: Now that JUnit 5 and JUnit 4.13 have been released, the best option would be to use Assertions.assertThrows() (for JUnit 5) and Assert.assertThrows() (for JUnit 4.13+). See my other answer for details. If you haven't migrated to JUnit 5, but can use JUnit 4.7, you can use the ExpectedException Rule: public class FooTest { @Rule public final ExpectedException exception = ExpectedException.none(); @Test public void doStuffThrowsIndexOutOfBoundsException() { Foo foo = new Foo(); exception.expect(IndexOutOfBoundsException.class); foo.doStuff(); } } This is much better than @Test(expected=IndexOutOfBoundsException.class) because the test will fail if IndexOutOfBoundsException is thrown before foo.doStuff() See this article for details. A: JUnit 5 Solution import static org.junit.jupiter.api.Assertions.assertThrows; @Test void testFooThrowsIndexOutOfBoundsException() { IndexOutOfBoundsException exception = expectThrows(IndexOutOfBoundsException.class, foo::doStuff); assertEquals("some message", exception.getMessage()); } More Infos about JUnit 5 on http://junit.org/junit5/docs/current/user-guide/#writing-tests-assertions A: tl;dr * *post-JDK8 : Use AssertJ or custom lambdas to assert exceptional behaviour. *pre-JDK8 : I will recommend the old good try-catch block. (Don't forget to add a fail() assertion before the catch block) Regardless of Junit 4 or JUnit 5. the long story It is possible to write yourself a do it yourself try-catch block or use the JUnit tools (@Test(expected = ...) or the @Rule ExpectedException JUnit rule feature). But these ways are not so elegant and don't mix well readability wise with other tools. Moreover, JUnit tooling does have some pitfalls. * *The try-catch block you have to write the block around the tested behavior and write the assertion in the catch block, that may be fine but many find that this style interrupts the reading flow of a test. Also, you need to write an Assert.fail at the end of the try block. Otherwise, the test may miss one side of the assertions; PMD, findbugs or Sonar will spot such issues. *The @Test(expected = ...) feature is interesting as you can write less code and then writing this test is supposedly less prone to coding errors. But this approach is lacking in some areas. * *If the test needs to check additional things on the exception like the cause or the message (good exception messages are really important, having a precise exception type may not be enough). *Also as the expectation is placed around in the method, depending on how the tested code is written then the wrong part of the test code can throw the exception, leading to false-positive test and I'm not sure that PMD, findbugs or Sonar will give hints on such code. @Test(expected = WantedException.class) public void call2_should_throw_a_WantedException__not_call1() { // init tested tested.call1(); // may throw a WantedException // call to be actually tested tested.call2(); // the call that is supposed to raise an exception } *The ExpectedException rule is also an attempt to fix the previous caveats, but it feels a bit awkward to use as it uses an expectation style, EasyMock users know very well this style. It might be convenient for some, but if you follow Behaviour Driven Development (BDD) or Arrange Act Assert (AAA) principles the ExpectedException rule won't fit in those writing style. Aside from that it may suffer from the same issue as the @Test way, depending on where you place the expectation. @Rule ExpectedException thrown = ExpectedException.none() @Test public void call2_should_throw_a_WantedException__not_call1() { // expectations thrown.expect(WantedException.class); thrown.expectMessage("boom"); // init tested tested.call1(); // may throw a WantedException // call to be actually tested tested.call2(); // the call that is supposed to raise an exception } Even the expected exception is placed before the test statement, it breaks your reading flow if the tests follow BDD or AAA. Also, see this comment issue on JUnit of the author of ExpectedException. JUnit 4.13-beta-2 even deprecates this mechanism: Pull request #1519: Deprecate ExpectedException The method Assert.assertThrows provides a nicer way for verifying exceptions. In addition, the use of ExpectedException is error-prone when used with other rules like TestWatcher because the order of rules is important in that case. So these above options have all their load of caveats, and clearly not immune to coder errors. *There's a project I became aware of after creating this answer that looks promising, it's catch-exception. As the description of the project says, it let a coder write in a fluent line of code catching the exception and offer this exception for the latter assertion. And you can use any assertion library like Hamcrest or AssertJ. A rapid example taken from the home page : // given: an empty list List myList = new ArrayList(); // when: we try to get the first element of the list when(myList).get(1); // then: we expect an IndexOutOfBoundsException then(caughtException()) .isInstanceOf(IndexOutOfBoundsException.class) .hasMessage("Index: 1, Size: 0") .hasNoCause(); As you can see the code is really straightforward, you catch the exception on a specific line, the then API is an alias that will use AssertJ APIs (similar to using assertThat(ex).hasNoCause()...). At some point the project relied on FEST-Assert the ancestor of AssertJ. EDIT: It seems the project is brewing a Java 8 Lambdas support. Currently, this library has two shortcomings : * *At the time of this writing, it is noteworthy to say this library is based on Mockito 1.x as it creates a mock of the tested object behind the scene. As Mockito is still not updated this library cannot work with final classes or final methods. And even if it was based on Mockito 2 in the current version, this would require to declare a global mock maker (inline-mock-maker), something that may not what you want, as this mock maker has different drawbacks that the regular mock maker. *It requires yet another test dependency. These issues won't apply once the library supports lambdas. However, the functionality will be duplicated by the AssertJ toolset. Taking all into account if you don't want to use the catch-exception tool, I will recommend the old good way of the try-catch block, at least up to the JDK7. And for JDK 8 users you might prefer to use AssertJ as it offers may more than just asserting exceptions. *With the JDK8, lambdas enter the test scene, and they have proved to be an interesting way to assert exceptional behaviour. AssertJ has been updated to provide a nice fluent API to assert exceptional behaviour. And a sample test with AssertJ : @Test public void test_exception_approach_1() { ... assertThatExceptionOfType(IOException.class) .isThrownBy(() -> someBadIOOperation()) .withMessage("boom!"); } @Test public void test_exception_approach_2() { ... assertThatThrownBy(() -> someBadIOOperation()) .isInstanceOf(Exception.class) .hasMessageContaining("boom"); } @Test public void test_exception_approach_3() { ... // when Throwable thrown = catchThrowable(() -> someBadIOOperation()); // then assertThat(thrown).isInstanceOf(Exception.class) .hasMessageContaining("boom"); } *With a near-complete rewrite of JUnit 5, assertions have been improved a bit, they may prove interesting as an out of the box way to assert properly exception. But really the assertion API is still a bit poor, there's nothing outside assertThrows. @Test @DisplayName("throws EmptyStackException when peeked") void throwsExceptionWhenPeeked() { Throwable t = assertThrows(EmptyStackException.class, () -> stack.peek()); Assertions.assertEquals("...", t.getMessage()); } As you noticed assertEquals is still returning void, and as such doesn't allow chaining assertions like AssertJ. Also if you remember name clash with Matcher or Assert, be prepared to meet the same clash with Assertions. I'd like to conclude that today (2017-03-03) AssertJ's ease of use, discoverable API, the rapid pace of development and as a de facto test dependency is the best solution with JDK8 regardless of the test framework (JUnit or not), prior JDKs should instead rely on try-catch blocks even if they feel clunky. This answer has been copied from another question that don't have the same visibility, I am the same author. A: The most flexible and elegant answer for Junit 4 I found in the Mkyong blog. It has the flexibility of the try/catch using the @Rule annotation. I like this approach because you can read specific attributes of a customized exception. package com.mkyong; import com.mkyong.examples.CustomerService; import com.mkyong.examples.exception.NameNotFoundException; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.Matchers.hasProperty; public class Exception3Test { @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void testNameNotFoundException() throws NameNotFoundException { //test specific type of exception thrown.expect(NameNotFoundException.class); //test message thrown.expectMessage(is("Name is empty!")); //test detail thrown.expect(hasProperty("errCode")); //make sure getters n setters are defined. thrown.expect(hasProperty("errCode", is(666))); CustomerService cust = new CustomerService(); cust.findByName(""); } } A: JUnit has built-in support for this, with an "expected" attribute. A: I tried many of the methods here, but they were either complicated or didn't quite meet my requirements. In fact, one can write a helper method quite simply: public class ExceptionAssertions { public static void assertException(BlastContainer blastContainer ) { boolean caughtException = false; try { blastContainer.test(); } catch( Exception e ) { caughtException = true; } if( !caughtException ) { throw new AssertionFailedError("exception expected to be thrown, but was not"); } } public static interface BlastContainer { public void test() throws Exception; } } Use it like this: assertException(new BlastContainer() { @Override public void test() throws Exception { doSomethingThatShouldExceptHere(); } }); Zero dependencies: no need for mockito, no need powermock; and works just fine with final classes. A: Java 8 solution If you would like a solution which: * *Utilizes Java 8 lambdas *Does not depend on any JUnit magic *Allows you to check for multiple exceptions within a single test method *Checks for an exception being thrown by a specific set of lines within your test method instead of any unknown line in the entire test method *Yields the actual exception object that was thrown so that you can further examine it Here is a utility function that I wrote: public final <T extends Throwable> T expectException( Class<T> exceptionClass, Runnable runnable ) { try { runnable.run(); } catch( Throwable throwable ) { if( throwable instanceof AssertionError && throwable.getCause() != null ) throwable = throwable.getCause(); //allows testing for "assert x != null : new IllegalArgumentException();" assert exceptionClass.isInstance( throwable ) : throwable; //exception of the wrong kind was thrown. assert throwable.getClass() == exceptionClass : throwable; //exception thrown was a subclass, but not the exact class, expected. @SuppressWarnings( "unchecked" ) T result = (T)throwable; return result; } assert false; //expected exception was not thrown. return null; //to keep the compiler happy. } (taken from my blog) Use it as follows: @Test public void testMyFunction() { RuntimeException e = expectException( RuntimeException.class, () -> { myFunction(); } ); assert e.getMessage().equals( "I haz fail!" ); } public void myFunction() { throw new RuntimeException( "I haz fail!" ); } A: Take for example, you want to write Junit for below mentioned code fragment public int divideByZeroDemo(int a,int b){ return a/b; } public void exceptionWithMessage(String [] arr){ throw new ArrayIndexOutOfBoundsException("Array is out of bound"); } The above code is to test for some unknown exception that may occur and the below one is to assert some exception with custom message. @Rule public ExpectedException exception=ExpectedException.none(); private Demo demo; @Before public void setup(){ demo=new Demo(); } @Test(expected=ArithmeticException.class) public void testIfItThrowsAnyException() { demo.divideByZeroDemo(5, 0); } @Test public void testExceptionWithMessage(){ exception.expectMessage("Array is out of bound"); exception.expect(ArrayIndexOutOfBoundsException.class); demo.exceptionWithMessage(new String[]{"This","is","a","demo"}); } A: With Java 8 you can create a method taking a code to check and expected exception as parameters: private void expectException(Runnable r, Class<?> clazz) { try { r.run(); fail("Expected: " + clazz.getSimpleName() + " but not thrown"); } catch (Exception e) { if (!clazz.isInstance(e)) fail("Expected: " + clazz.getSimpleName() + " but " + e.getClass().getSimpleName() + " found", e); } } and then inside your test: expectException(() -> list.sublist(0, 2).get(2), IndexOutOfBoundsException.class); Benefits: * *not relying on any library *localised check - more precise and allows to have multiple assertions like this within one test if needed *easy to use A: @Test(expectedException=IndexOutOfBoundsException.class) public void testFooThrowsIndexOutOfBoundsException() throws Exception { doThrow(IndexOutOfBoundsException.class).when(foo).doStuff(); try { foo.doStuff(); } catch (IndexOutOfBoundsException e) { assertEquals(IndexOutOfBoundsException .class, ex.getCause().getClass()); throw e; } } Here is another way to check method thrown correct exception or not. A: My solution using Java 8 lambdas: public static <T extends Throwable> T assertThrows(Class<T> expected, ThrowingRunnable action) throws Throwable { try { action.run(); Assert.fail("Did not throw expected " + expected.getSimpleName()); return null; // never actually } catch (Throwable actual) { if (!expected.isAssignableFrom(actual.getClass())) { // runtime '!(actual instanceof expected)' System.err.println("Threw " + actual.getClass().getSimpleName() + ", which is not a subtype of expected " + expected.getSimpleName()); throw actual; // throw the unexpected Throwable for maximum transparency } else { return (T) actual; // return the expected Throwable for further examination } } } You have to define a FunctionalInterface, because Runnable doesn't declare the required throws. @FunctionalInterface public interface ThrowingRunnable { void run() throws Throwable; } The method can be used as follows: class CustomException extends Exception { public final String message; public CustomException(final String message) { this.message = message;} } CustomException e = assertThrows(CustomException.class, () -> { throw new CustomException("Lorem Ipsum"); }); assertEquals("Lorem Ipsum", e.message); A: There are two ways of writing test case * *Annotate the test with the exception which is thrown by the method. Something like this @Test(expected = IndexOutOfBoundsException.class) *You can simply catch the exception in the test class using the try catch block and assert on the message that is thrown from the method in test class. try{ } catch(exception to be thrown from method e) { assertEquals("message", e.getmessage()); } I hope this answers your query Happy learning... A: I would use assertThatThrownBy @Test public void testFooThrowsIndexOutOfBoundsException() { assertThatThrownBy(() -> doStuff()).isInstanceOf(IndexOutOfBoundsException.class) } A: try { my method(); fail( "This method must thrwo" ); } catch (Exception ex) { assertThat(ex.getMessage()).isEqual(myErrormsg); } A: I wanted to comment with my solution to this problem, which avoided needing any of the exception related JUnit code. I used assertTrue(boolean) combined with try/catch to look for my expected exception to be thrown. Here's an example: public void testConstructor() { boolean expectedExceptionThrown; try { // Call constructor with bad arguments double a = 1; double b = 2; double c = a + b; // In my example, this is an invalid option for c new Triangle(a, b, c); expectedExceptionThrown = false; // because it successfully constructed the object } catch(IllegalArgumentException e) { expectedExceptionThrown = true; // because I'm in this catch block } catch(Exception e) { expectedExceptionThrown = false; // because it threw an exception but not the one expected } assertTrue(expectedExceptionThrown); }
{ "language": "en", "url": "https://stackoverflow.com/questions/156503", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2245" }
Q: How to skip the docstring using regex I'm trying to insert some import lines into a python source file, but i would ideally like to place them right after the initial docstring. Let's say I load the file into the lines variable like this: lines = open('filename.py').readlines() How to find the line number, where the docstring ends? A: If you're using the standard docstring format, you can do something like this: count = 0 for line in lines: if line.startswith ('"""'): count += 1 if count < 3: # Before or during end of the docstring continue # Line is after docstring Might need some adaptation for files with no docstrings, but if your files are formatted consistently it should be easy enough. A: Rather than using a regex, or relying on specific formatting you could use python's tokenize module. import tokenize f=open(filename) insert_index = None for tok, text, (srow, scol), (erow,ecol), l in tokenize.generate_tokens(f.readline): if tok == tokenize.COMMENT: continue elif tok == tokenize.STRING: insert_index = erow, ecol break else: break # No docstring found This way you can even handle pathological cases like: # Comment # """Not the real docstring""" ' this is the module\'s \ docstring, containing:\ """ and having code on the same line following it:'; this_is_code=42 excactly as python would handle them. A: This is a function based on Brian's brilliant answer you can use to split a file into docstring and code: def split_docstring_and_code(infile): import tokenize insert_index = None f = open(infile) for tok, text, (srow, scol), (erow,ecol), l in tokenize.generate_tokens(f.readline): if tok == tokenize.COMMENT: continue elif tok == tokenize.STRING: insert_index = erow, ecol break else: break # No docstring found lines = open(infile).readlines() if insert_index is not None: erow = insert_index[0] return "".join(lines[:erow]), "".join(lines[erow:]) else: return "", "".join(lines) It assumes that the line that ends the docstring does not contain additional code past the closing delimiter of the string.
{ "language": "en", "url": "https://stackoverflow.com/questions/156504", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Does a Silverlight memory profiler exist? CLR profiler does not seem to work with the Silverlight CLR. Does another memory profiler exist? A: Here is memory profiling in silverlight using Xperf. Get GC Information A: Try this one, it is very useful: http://www.red-gate.com/products/ants_memory_profiler/index.htm Bruno. A: Doesn't seem to be one available yet. However, as recommended in this forum thread, you can convert your Silverlight app to a WPF application and profile that: There is no tool as of now but as a workaround you can easily create a desktop (WPF) version of your Silverlight client from the same code base and few tweaks (refer Scot's blog for an example on this - http://weblogs.asp.net/scottgu/pages/silverlight-tutorial-part-8-creating-a-digg-desktop-application-using-wpf.aspx) . Once you are done with this you can run any performance profiler that works with WPF. Not an optimal solution, but it sounds like the best option for now... Update: Just saw a blog post about XPerf which is a cpu sampler for Silverlight. Not exactly a memory profiler but a good tool for testing the performance of Silverlight apps... A: VS2010/SL4 has a profiler now checkout: http://www.nachmore.com/2010/profiling-silverlight-4-with-visual-studio-2010/ http://blogs.msdn.com/b/seema/archive/2010/01/28/pdc-vs2010-profiling-silverlight-4.aspx A: Though not a full blown profiler with a yummy GUI, you could use Windbg + SOS to debug your silverlight app, it would require a lot of manual work, but you can then walk your managed heap. A: Try using Atologic SilverProfiler. Available at www.atologic.com. A: Use Silverlight Spy It has a Memory Profiler built in A: I use free XTE Profiler which also works with Silverlight Standard and Out of Browser applications. Shows live memory usage as well. A: .NET Memory Profiler starting from version 4.0 supports Silverlight profiling. Highly recommend. A: Standalone CLR profiler has been updated to work with Silverlight so you don't need to have VS Premium/Ultimate. David Broman's CLR Profiling API Blog: CLRProfiler V4 Released UI isn't that great, but it works.
{ "language": "en", "url": "https://stackoverflow.com/questions/156507", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Closing a Java FileInputStream Alright, I have been doing the following (variable names have been changed): FileInputStream fis = null; try { fis = new FileInputStream(file); ... process ... } catch (IOException e) { ... handle error ... } finally { if (fis != null) fis.close(); } Recently, I started using FindBugs, which suggests that I am not properly closing streams. I decide to see if there's anything that can be done with a finally{} block, and then I see, oh yeah, close() can throw IOException. What are people supposed to do here? The Java libraries throw too many checked exceptions. A: For Java 7 and above try-with-resources should be used: try (InputStream in = new FileInputStream(file)) { // TODO: work } catch (IOException e) { // TODO: handle error } If you're stuck on Java 6 or below... This pattern avoids mucking around with null: try { InputStream in = new FileInputStream(file); try { // TODO: work } finally { in.close(); } } catch (IOException e) { // TODO: error handling } For a more detail on how to effectively deal with close, read this blog post: Java: how not to make a mess of stream handling. It has more sample code, more depth and covers the pitfalls of wrapping close in a catch block. A: You could also use a simple static Helper Method: public static void closeQuietly(InputStream s) { if (null == s) { return; } try { s.close(); } catch (IOException ioe) { //ignore exception } } and use this from your finally block. A: Nothing much to add, except for a very minor stylistic suggestion. The canonical example of self documenting code applies in this case - give a descriptive variable name to the ignored IOException that you must catch on close(). So squiddle's answer becomes: public static void closeQuietly(InputStream s) { try { s.close(); } catch (IOException ignored) { } } A: Something like the following should do it, up to you whether you throw or swallow the IOException on attempting to close the stream. FileInputStream fis = null; try { fis = new FileInputStream(file); ... process ... } catch (IOException e) { ... blah blah blah ... } finally { try { if (fis != null) fis.close(); } catch (IOException e) { } } A: In most cases, I find it is just better not to catch the IO exceptions, and simply use try-finally: final InputStream is = ... // (assuming some construction that can't return null) try { // process is ... } finally { is.close(); } Except for FileNotFoundException, you generally can't "work around" an IOException. The only thing left to do is report an error, and you will typically handle that further up the call stack, so I find it better to propagate the exception. Since IOException is a checked exception, you will have to declare that this code (and any of its clients) throws IOException. That might be too noisy, or you might not want to reveal the implementation detail of using IO. In that case, you can wrap the entire block with an exception handler that wraps the IOException in a RuntimeException or an abstract exception type. Detail: I am aware that the above code swallows any exception from the try block when the close operation in the finally block produces an IOException. I don't think that is a big problem: generally, the exception from the try block will be the same IOException that causes the close to fail (i.e. it is quite rare for IO to work fine and then fail at the point of closing). If this is a concern, it might be worth the trouble to "silence" the close. A: You could use the try-with-resources feature added JDK7. It was created precisely to deal with this kind of things static String readFirstLineFromFile(String path) throws IOException { try (BufferedReader br = new BufferedReader(new FileReader(path))) { return br.readLine(); } } The documenation says: The try-with-resources statement ensures that each resource is closed at the end of the statement. A: The following solution correctly throws an exception if close fails without hiding a possible exception before the close. try { InputStream in = new FileInputStream(file); try { // work in.close(); } finally { Closeables.closeQuietly(in); } } catch(IOException exc) { // kernel panic } This works because calling close a second time has no effect. This relies on guava Closeables, but one can write its own closeQuietly method if preferred, as shown by squiddle (see also serg10). Reporting a close error, in the general case, is important because close might write some final bytes to the stream, e.g. because of buffering. Hence, your user wants to know if it failed, or you probably want to act somehow. Granted, this might not be true in the specific case of a FileInputStream, I don't know (but for reasons already mentioned I think it is better to report a close error if it occurs anyway). The above code is a bit difficult to grasp because of the structure of the embedded try blocks. It might be considered clearer with two methods, one that throws an IOException and one that catches it. At least that is what I would opt for. private void work() throws IOException { InputStream in = new FileInputStream(file); try { // work in.close(); } finally { Closeables.closeQuietly(in); } } public void workAndDealWithException() { try { work(); } catch(IOException exc) { // kernel panic } } Based on http://illegalargumentexception.blogspot.com/2008/10/java-how-not-to-make-mess-of-stream.html (referenced by McDowell). A: Hopefully we will get closures in Java some day, and then we will lose lots of the verbosity. So instead there will be a helper method somwhere in javaIO that you can import, it will probably takes a "Closable" interface and also a block. Inside that helper method the try {closable.close() } catch (IOException ex){ //blah} is defined once and for all, and then you will be able to write Inputstream s = ....; withClosable(s) { //your code here } A: Are you concerned primarily with getting a clean report from FindBugs or with having code that works? These are not necessarily the same thing. Your original code is fine (although I would get rid of the redundant if (fis != null) check since an OutOfMemoryException would have been thrown otherwise). FileInputStream has a finalizer method which will close the stream for you in the unlikely event that you actually receive an IOException in your processing. It's simply not worth the bother of making your code more sophisticated to avoid the extremely unlikely scenario of * *you get an IOException and *this happens so often that you start to run into finalizer backlog issues. Edit: if you are getting so many IOExceptions that you are running into problems with the finalizer queue then you have far far bigger fish to fry! This is about getting a sense of perspective.
{ "language": "en", "url": "https://stackoverflow.com/questions/156508", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "36" }
Q: Increase Stack Size on Windows (GCC) Is there a way to increase the stack size of a Windows application at compile/link time with GCC? A: You could run editbin after linking. A: IIRC, In GCC you can provide the --stack,[bytes] parameter to ld. E.g. gcc -Wl,--stack,16777216 -o file.exe file.c To have a stack of 16MiB, I think that the default size is 8MiB. A: There are two stack sizes in Windows. The initially commited size, and the total reserved size. You can set both with a STACKSIZE statement in a .def file. A: When creating threads you use the dwStackSize paremater, but I'm not sure how to change the size for the main thread, this indicates its in the exe's header, so it may be an option for the compiler/linker, else you need to find the relevant part of the header and change it yourself. http://msdn.microsoft.com/en-us/library/ms686774(VS.85).aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/156510", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Java HttpURLConnection: Can it cope with duplicate header names? I am debugging some code in the Selenium-rc proxy server. It seems the culprit is the HttpURLConnection object, whose interface for getting at the HTTP headers does not cope with duplicate header names, such as: Set-Cookie: foo=foo; Path=/ Set-Cookie: bar=bar; Path=/ The way of getting at the headers through the HttpURLConnection (using getHeaderField(int n) and getHeaderFieldKey(int n)) seems to be causing my second cookie to be lost. My question is * *Is it true that HttpURLConnection itself can't cope with it, and *If so, is there a workaround to it? A: My recommended workaround is to not use HttpUtilConnection at all, which is crude and unintuitive, but use commons-httpclient instead. http://hc.apache.org/httpclient-3.x/ A: Without actually having tried it (can't remember to have handled that topic myself), there's also getHeaderFields, inherited from UrlConnection. Does this do what you need? A: Ok, I found the problem, and the answer to the original question. Basically, the Cookie implementation I used (python's default Cookie Lib) used \r\n to delimit the different Set-Cookie headers(as supposed to \n), this confused HttpUrlConnection and caused it to stop at the first occurence of that delimiter(I am going to guess it stops at the first empty line). So the answer to the first question is: Yes, it can cope with duplicate header names, but is buggy in another way. Currently fixing the python library is a workable workaround, but it's not going to work long term because we don't own that library. I am sure using the httpclient library is a sensible way to go, but I am hoping for a solution that requires less work. So I don't know exactly what to do there yet.
{ "language": "en", "url": "https://stackoverflow.com/questions/156514", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to determine if a class is a subclass of other class? I'd like to check if a Class object represents a subclass of other class for example Class class1 = Class.forName("Class1"); Class class2 = Class.forName("Class2"); if(class1.isSubClassOf(class2)) // fake methos isSubClassOf { // do sth } How can I implement this isSubClassOf method ? A: Class.isAssignableFrom() provides more-or-less what you're after, although it handle interfaces also, so may need to do a bit more extra work to be sure that it's a subclass, direct or otherwise.
{ "language": "en", "url": "https://stackoverflow.com/questions/156527", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: What is the best way to do Java development in Emacs? What modes are the best? And any tips or tricks that make developing java in emacs a bit better. A: Eclim is a project that uses eclipse running in headless mode to provide features to Emacs such as in-line error checking, auto import management, basic refactoring, etc. It's much easier than JDEE to set up and when paired with something like YASnippet I find myself more productive than I was in Eclipse. I currently have to go back for step through debugging and some project management, but I am pretty happy with it. If combined with something like JDIbug I think I would have even less reason to ever use eclipse directly. Hope this helps A: The best Java debugger for Emacs I've used is jdibug. A: I have used JDEE over two years.Unfortunately,it was too old and stopped.JDEE doesn't support new features since Java 5,e.g, we can't create enum type using JDEE. And the author didn't answer any questions.I am still using Emacs+JDEE,but I can't see the future of JDEE. A: For anything else than casual Java editing, many people recommend the Java Development Environment for Emacs. A: Java refactoring for emacs: http://www.xref-tech.com/xrefactory-java/main.html
{ "language": "en", "url": "https://stackoverflow.com/questions/156529", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "19" }
Q: How do I import a whitespace-delimited text file into MySQL? I need to import largish (24MB) text files into a MySQL table. Each line looks like this: 1 1 0.008 0 0 0 0 0 There are one or more spaces after each field, and the last field is tailed by about 36 spaces before the newline. How do I import such a file into MySQL? From the documentation it seems that LOAD DATA expects all fields to be terminated by exactly the same string. I have tried LOAD DATA INFILE 'filename' INTO TABLE mytable FIELDS TERMINATED BY ' '; but MySQL will interpret a sequence of more than one space as delimiting an empty field. Any ideas? A: If you're on unix/linux then you can put it through sed. open a terminal and type: sed 's/ \+/ /g' thefile > thefile.new this replaces all sequences of multiple spaces with one space. A: If you're on Windows, just use Excel. Excel will import a whitespace-delimited file (check the 'treat subsequent delimiters as one' box from the import menu). Then you can simply save the file as a CSV from Excel and import into MySQL using: LOAD DATA INFILE 'filename' INTO TABLE mytable FIELDS TERMINATED BY ','; A: You can also use the same command posted by Jauco to change the delimiter to ';' or \n. That would also help. A: Is there no way you can do this pragmatically? A simple PHP script would be able to load the file in, split by spaces, and do an insert in no time at all: <?php $db = mysql_connect('host', 'user', 'password') or die('Failed to connect'); mysql_select_db('database', $db); $fileHandle= @fopen("import.file", "r"); if ($fileHandle) { while (!feof($fileHandle)) { $rawLine = fgets($fileHandle, 4096); $columns = preg_split("/\s+/", $rawLine); //Construct and run an INSERT statement here ... } fclose($fileHandle); } ?> Edit That being said, Jakal's suggestion is far neater ;)
{ "language": "en", "url": "https://stackoverflow.com/questions/156532", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Dependence on DependencyObject and DependencyProperty I'm building a Silverlight application and one of my caveats from last time was that if you need anything done right in Silverlight/WPF way you'd need to model your objects as a DependecyObject and use DependencyProperty(ies) I find this model to be rather cumbersome, requiring static fields and initializers in half the classes I use, so is it a good idea to use the good-old event-driven (observer pattern?) in place of DependencyObject? I'm aiming to minimize code bloat and boiler plates (I hate them) and really would like to know if anyone with experience in Silverlight/WPF has any tips/techniques for keeping usage of DependencyObject and DependencyProperty to a minimum? Is this a good idea? A: Actually, in Silverlight you cannot inherit DependencyObjects, and so you should (and have to) implement INotifyPropertyChanged instead. Implementing INotifyPropertyChanged has many advantages over DependencyObjects (I will abbreviate this DO to make it easier) and using DependencyProperties (DPs): * *This is more lightweight *Allows you more freedom in modeling your objects *Can be serialized easily *You can raise the event when you want, which can be useful in certain scenarios, for example when you want to bundle multiple changes in only one UI operation, or when you need to raise the event even if the data didn't change (to force redraw...) On the other hand, inheriting DOs in WPF have the following advantages: * *Easier to implement especially for beginners. *You get a callback mechanism (almost) for free, allowing you to be notified when the property value changes *You get a coercion mechanism with allows you to define rules for max, min and present value of the property. There are other considerations, but these are the main. I think the general consensus is that DPs are great for controls (and you can implement a CustomControl with custom DPs even in Silverlight), but for data objects you should rather implement INotifyPropertyChanged. HTH, Laurent A: It really depends on which objects you are referring to. If the object is intended to sit in the XAML tree, its best to use DependencyProperties (and thus inherit DependencyObject - which all UIElements do) to allow all the benefits that DependencyProperties provide (being animatable, binding, optional automatic child inheritance, etc). I highly recommend you read the MSDN overview on DependencyProperties if you haven't already. If the object is an data entity (ie. you are binding its values TO something in the XAML tree) then there is no need to inherit from DependencyObject. If the properties on the object are read-write you may want to implement INotifyPropertyChanged, which will allow bindings to automatically update when the value changes. A: I agree with Richard that it depends on the purpose of your class, but as a note it seems that you CAN inherit from DependencyObject directly in Silverlight 2.0 Release, without having to inherit from UIElement or UserControl. At least, I'm doing that in my (SilverLight 2.0 RTW) app. System.Windows.DependencyObject on MSDN It is not typical to derive directly from DependencyObject for most scenarios. Instead you might derive from a specific control, from one of the control base classes (ContentControl; Control; ItemsControl), from FrameworkElement, or from non-control classes that still participate in UI such as Panel or Grid. Deriving from DependencyObject might be appropriate if you are defining a business or data storage object where you want dependency properties to be active, or if you are creating a service support class that will own attached properties. HTH
{ "language": "en", "url": "https://stackoverflow.com/questions/156538", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Visual Studio: Automatically re-order page events according to the ASP.NET Page LifeCycle? What would be the easiest way to re-order existing page events according to the ASP.NET Page LifeCycle? I'm trying to make my events more readable and maybe make it easy to scroll into a sequentially near event. If there's no easy way, is there a non-mouse way to quickly switch to a page event without having to type the actual event in incremental search? A: The only thing I can think of is using the code window navigator. To not use the mouse you can hit Ctrl+F2, then hit tab to tab to the method drop down, and you can use the arrows, including hitting a letter to move in the list and hit enter to select.
{ "language": "en", "url": "https://stackoverflow.com/questions/156539", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Using Microsoft SMS Sender to send out smses in batch? I understand that we can use SMS Sender in command line mode. But i been getting this error same as this article http://www.oreillynet.com/pub/a/wireless/2003/10/10/sms.html The smssender.exe will use the last device that was successfully used to send messages in the Windows version of SMS Sender. But I tried it many times, and smssender.exe always complains that no last device was used. Anyone have any idea about this? A: You have to add a new registry under HKEY_Local_Machine-MMicrosoft-> SMSSender Copy registry to create from HKey_Current_User A: From 'Options', check the "Enable Logging" check-box. it has worked for me that way. Also it can also be used windows 7 x64 ( under the compatibility mode for XP )
{ "language": "en", "url": "https://stackoverflow.com/questions/156543", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Creating a two-pass PHP cache system with mutable items I want to implement a two-pass cache system: * *The first pass generates a PHP file, with all of the common stuff (e.g. news items), hardcoded. The database then has a cache table to link these with the pages (eg "index.php page=1 style=default"), the database also stores an uptodate field, which if false causes the first pass to rerun the next time the page is viewed. *The second pass fills in the minor details, such as how long ago something(?) was, and mutable items like "You are logged in as...". However I'm not sure on a efficient implementation, that supports both cached and non-cached (e.g., search) pages, without a lot of code and several queries. Right now each time the page is loaded the PHP script is run regenerating the page. For pages like search this is fine, because most searches are different, but for other pages such as the index this is virtually the same for each hit, yet generates a large number of queries and is quite a long script. The problem is some parts of the page do change on a per-user basis, such as the "You are logged in as..." section, so simply saving the generated pages would still result in 10,000's of nearly identical pages. The main concern is with reducing the load on the server, since I'm on shared hosting and at this point can't afford to upgrade, but the site is using a sizeable portion of the servers CPU + putting a fair load on the MySQL server. So basically minimising how much has to be done for each page request, and not regenerating stuff like the news items on the index all the time seems a good start, compared to say search which is a far less static page. I actually considered hard coding the news items as plain HTML, but then that means maintaining them in several places (since they may be used for searches and the comments are on a page dedicated to that news item (i.e. news.php), etc). A: I second Ken's rec of PEAR's Cache_Lite library, you can use it to easily cache either parts of pages or entire pages. If you're running your own server(s), I'd strongly recommend memcached instead. It's much faster since it runs entirely in memory and is used extensively by a lot of high-volume sites. It's a very easy, stable, trouble-free daemon to run. In terms of your PHP code, you'd use it much the same way as Cache_Lite, to cache various page sections or full pages (or other arbitrary blobs of data), and it's very easy to use since PHP has a memcache interface built in. For super high-traffic full-page caching, take a look at doing Varnish or Squid as a caching reverse proxy server. (Pages that get served by Varnish are going to come out easily 100x faster than anything that hits the PHP interpreter.) Keep in mind with caching, you really only need to cache things that are being frequently accessed. Sometimes it can be a trap to develop a really sophisticated caching strategy when you don't really need it. For a page like your home page that's getting hit several times a second, you definitely want to optimize it for speed; for a page that gets maybe a few hits an hour, like a month-old blog post, it's a bad idea to cache it, you only waste your time and make things more complicated and bug-prone. A: I recommend to don't reinvent the wheel... there are some template engines that support caching, like Smarty A: For server side caching use something like Cache_Lite (and let someone else worry about file locking, expiry dates, file corruption) A: You want to save the results to a file and use logic like this to pull them back out: if filename exists include filename else generate results render to html (as string) write to file output string or include file endif To be clear, you don't need two passes because you can save parts of the page and leave the rest dynamic. A: As always with this type of question, my response is: * *Why do you need the caching? *Is your application consuming too much IO on your database? *What metrics have you run? Your are talking about adding an extra level of complexity to your app so you need to be very sure that you actually need it. You might actually benefit from using the built-in MySQL query cache, if the database is the contention point in your system. The other option is too use Memcache. A: I would recommend using existing caching mechanism. Depending on what you really need, You might be looking for APC, memcached, various template caching libs... It easier/faster to tune written/tested code to please your need than to write everything from scratch. (usually, although there might be situations when you don't have a choisce)
{ "language": "en", "url": "https://stackoverflow.com/questions/156552", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How to fully utilize attachment students? From time to time, there will be student attached to our projects, i would certainly like to assign him/her many things to do so can learn more. But alot of times we are resigned to assigning stuff like documentaiton, updating of ui mockup screens etc. As problem is that is it bit hard to trust the quality of work provided by students and another thing is that they are still young and their enthusiam may not be there. How do we better utilize them such that they really cut down our workload and also in turns mean learning more stuff which will aid them in their future job opportunies? A: I am afraid it might sound disappointing but it is not the best idea to utilise students to cut your organisational unit workload down. Probably, if your goal is cutting workload the best thing is not to take students. Read on to understand why. Though you haven't specified the level of work-related expertise the students possess, nor did you mention the duration of their attachment, I assume from the tone of your question that their expertise is not sufficient to hit the ground running. It is also reasonable to assume that they are not staying for longer than 2-3 months. The essential benefits your organisation can extract even given the limited timeframe are: * *Notice and grab talented workers before they even get to the job market. Later in their working life they are likely not to be that easily available. *Turn every student into your organisation salesman. Let them tell everyone how good your product is, bring you in contracts in the future or make their peers envy their work experience increasing the pool of good candidates for your company. *Outsiders can help cast a fresh eye on your processes, procedures, product, expose inefficiencies etc. *Learn from them the latest stuff taught at universities. *Boost your time morale: Maslow theory, "esteem needs". Even the most junior member of your team becomes somewhat more senior, since these students have yet to achieve that position. Cutting down workload means that you'd need to find a set of tasks which is fairly independent, does not require knowledge or skills that the students do not have and needs much of your team's time to transfer. The tasks cannot be strategically important in case they cock it up, not can it be operationally important. Hence you left with some dusty requests for management reports or research and development projects. Chances are that R&D considered to be more desired work within your organisation and if you give exclusively to students some people feelings are going to get hurt. A: How long are the students around for? When we have had students on-site for up to two weeks there was not much other then testing type work we could give them. If the student has enthusiasm you code do some pair programming through a bug and let them write the unit tests for verifying the fix. A: Even if you don't normally do pair programming, I find that with a junior dev it is sometimes productive to have him/her do pair programming with a more experienced developer, for the following reasons: * *I wouldn't assign coding tasks to the junior developer alone, because his code would have to be closely reviewed by someone else anyway and quite probably rewritten or changed substantially. *On the other side, how can a junior developer learn if not by programming? So, you want him participating in some way in programming tasks. *You get some of the advantages of pair programming: the most experienced dev is less prone to make silly mistakes (even a very junior programmer can point things like 'hey, you made a typo there') and less likely to goof off checking stackoverflow.com every 10 minutes during the pair programming session. Of course I also would rotate the junior with several seniors during the day, so they don't feel 'slowed down' or annoyed by the young guy for extended periods of time. A: Why not assign one or more engineers as "sheperds" to the student and let them oversee their work or even better pair with them. The student will gain a good understanding of your project and real work and have a known fallback when in trouble and someone who can give provide direction. The sheperd/mentor gains a fresh perspective, and the joy of teaching.
{ "language": "en", "url": "https://stackoverflow.com/questions/156559", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How do you manage asp.net SQL membership roles/users in production? How do you setup an asp.net sql membership role/membership provider on a production machine? I'm trying to setup BlogEngine.NET and all the documentation says to use the ASP.NET Website Administration tool from Visual Studio but that isn't available on a production machine. Am I the first BlogEngine user to use it on a non-development box? The SQL server is completely blocked off from everything but the production box, I do have SQL Management Studio on there though. EDIT: I mean, how do you add new users/roles, not how do you create the tables. I've already ran aspnet_regsql to create the schema. EDIT2: MyWSAT doesn't work because it requires an initial user in the database as well. I need an application that will allow me to create new users in the membership database without any authentication, just a connection string. A: I solved this problem by setting up a default super user at application start up. By adding this to gobal.asax void Application_Start(object sender, EventArgs e) { // Code that runs on application startup // check that the minimal security settings are created Security.SetupSecurity(); } Then in the security class: using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; /// /// Creates minimum roles and user for application access. /// public class Security { // application roles public static string[] applicationRoles = { "Roles1", "Roles2", "Roles3", "Roles4", "Roles5" }; // super user private static string superUser = "super"; // default password, should be changed on first connection private static string superUserPassword = "default"; private Security() { // // TODO: Add constructor logic here // } /// /// Creates minimal membership environment. /// public static void SetupSecurity() { SetupRoles(); SetupSuperuser(); } /// /// Checks roles, creates missing. /// public static void SetupRoles() { // create roles for (int i = 0; i /// Checks if superuser account is created. /// Creates the account and assigns it to all roles. /// public static void SetupSuperuser() { // create super user MembershipUser user = Membership.GetUser(superUser); if (user == null) Membership.CreateUser(superUser, superUserPassword, "maintenance@acorel.com"); // assign superuser to roles for (int i = 0; i Once you have a default user, you can use AspNetWSAT or other. A: Solution 1 (standard, poor): Visual Studio -> Website menu -> ASP.NET Configuration. Solution 2 (preffered): AspNetWSAT (easy to deploy, pretty powerfull) A: The solution is simple, the WSAT tool is on the production machine, but it's unreachable, you can configure the site , and you can use it. The WSAT tool with source code is located in your C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\ASP.NETWebAdminFiles folder. To make it accessible on the network, all you have to do is go to IIS–>Create new virtual directory–>Point to the above folder and remove anonymous access from directory settings page. Then you need to access it the same way your local ASP.Net configuration tool is accessed i.e via a URL which resembles something like :http://SERVER/AdminTool/default.aspx?applicationPhysicalPath=C:\Inetpub\wwwrooot\testsite\&applicationUrl=/testsite A: You'll have to have .NET 2.0 installed on the machine, all the VS tool is is a GUI wrapper for a command line tool which is part of the framework. Check C:\Windows\Microsoft.NET\Framework\v2.0.50727 for the app aspnet_regsql.exe /? for command line switches, /W for a wizard mode A: Have you looked at the IIS capabilities to manage membership? Go to the ASP.NET tab on IIS of the production server and see if this may help you.
{ "language": "en", "url": "https://stackoverflow.com/questions/156563", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: What the best rollover log file tracelistener for .NET I'm looking for a good TraceListener for .Net that supports rolling over the log file based on size limits. Constraints * *Uses .Net built in Trace logging *Independent class or binary that's not part of some gigantic library *Allows rolling over a log file based on size A: I'm a big fan of log4net (http://logging.apache.org/log4net/index.html), it's very easy to configure and supports just about any log type you want, but can have custom ones written as well. It can also do different actions depending on the log level. We log all messages to a text file and Error -> Fatal send emails A: I am using NLog and I am very satisfied. Source code is well written and it is easy to extend and modify. Documentation is good and it is very easy to configure. Some Links: * *Using NLog To Track Events *Introduction to NLog A: FileLogTraceListener is a common suggestion but it throws away events or throws an exception when the file exceeds the given max size. We created a class that extends it, and overrides the Write/WriteLine methods. There's a try/catch (InvalidOperationException), and if that happens, we call base.Close and rename the file (FullLogFileName) as follows (we need the base.Close or else we'll get a 'file in use' error): In a loop, we add a number to the end, and see if that file exists; if not, use File.Move(FullLogFileName, newFileWithNumber), otherwise we keep incrementing the number until we find a file name that works. There's also a lock to ensure that the given instance is thread safe. A: You could use Microsoft.VisualBasic.Logging.FileLogTraceListener, which comes built-in with the .NET Framework. Don't let the VisualBasic in the namespace scare you, you'll just have to reference the microsoft.visualbasic.dll assembly and it should work fine with C#. A: I have used both Log4Net and Nlog. I prefer NLog but really once they are setup you forget they are there anyway (untill something breaks, then your glad it is there!). there should be plenty of documentation on both out in the interweb A: I keep this config snippet handy for whenever I need to do the network trace. I don't have to have a project built with explicit reference to VB DLL added as this does by adding the reference in App.config at runtime. <system.diagnostics> <sources> <source name="System.Net"> <listeners> <add name="System.Net"/> </listeners> </source> <source name="System.Net.Http"> <listeners> <add name="System.Net"/> </listeners> </source> <source name="System.Net.Sockets"> <listeners> <add name="System.Net"/> </listeners> </source> </sources> <switches> <add name="System.Net" value="Verbose"/> <add name="System.Net.Http" value="Verbose"/> <add name="System.Net.Sockets" value="Verbose"/> </switches> <sharedListeners> <add name="System.Net" type="Microsoft.VisualBasic.Logging.FileLogTraceListener, Microsoft.VisualBasic, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" traceOutputOptions="DateTime,ProcessId,ThreadId" customLocation="c:\temp" location="Custom" logFileCreationSchedule="Daily" baseFileName="NetworkTrace"/> </sharedListeners> <trace autoflush="true"/> </system.diagnostics> And add the reference at runtime <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="Microsoft.VisualBasic" culture="neutral" publicKeyToken="b03f5f7f11d50a3a"/> <codeBase version="10.0.0.0" href="file://C:/Program Files (x86)/Reference Assemblies/Microsoft/Framework/.NETFramework/v4.5/Microsoft.VisualBasic.dll"/> </dependentAssembly> </assemblyBinding> </runtime> A: Consider Enterprise Library Logging Application Block Make sure to install only the Logging block, since EntLib installer checks all blocks by default. A: As given in one of the comments: FileLogTraceListener Class Writes to a rolling text file. Remarks A new file is used when the maxFileSize is reached, as well as a daily or weekly basis as specified by logFileCreationSchedule. Each file has a name in the format "\(-)(-).log", with the local date included for daily and weekly rotation, and a sequence number appended if the file already exists. A: I had the same issue. Secure environment, no open source allowed. Painful. Here's what worked for us. Derive from TextWriterTraceListener that adds members for max log size, max rolls to keep, and uses a FileStream with Share and Access set to ReadWrite and set OpenOrCreate. It should also create and hold a mutex with a name based on the filename. Override TraceEvent method, wait for the mutex, seek the stream to end, call Write, check the size and roll if necessary. Release the mutex. For rolling, rotate the previous rolls via file move and delete, copy the current file to the first level roll name, call SetLength(0) on the stream. All done within the mutex grab, but hopefully not often. This will work across processes and will avoid that crappy {GUID}mylog.log stuff.
{ "language": "en", "url": "https://stackoverflow.com/questions/156575", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "32" }
Q: Namespace documentation on a .Net project (Sandcastle)? I started using Sandcastle some time ago to generate a Documentation Website for one of our projects. It's working quite well but we've always only written documentation for classes, methods, properties (...) in our project and had completely separate documentation for the overall project and project parts/modules/namespaces. It would be nice if I could merge that documentation together and add respective documentation to the generated helper files but I can't figure out how to do it. Just adding comments to the namespace declaration doesn't seem to work (C#): /// <summary> /// My short namespace description /// </summary> namespace MyNamespace { ... } Does anyone know how to do this? I know it's possible somehow and it would be really nice to have... :) A: Sandcastle also supports the ndoc-style namespace documentation, which allows you to stick the documentation in the source files: Simply create a non-public class called NamespaceDoc in the namespace you want to document, and the xml doc comment for that class will be used for the namespace. Adorn it with a [CompilerGenerated] attribute to prevent the class itself from showing up in the documentation. Example: namespace Some.Test { /// <summary> /// The <see cref="Some.Test"/> namespace contains classes for .... /// </summary> [System.Runtime.CompilerServices.CompilerGenerated] class NamespaceDoc { } } The work item in SandCastle is located here. A: Use Sandcastle Help File Builder. It allows to specify namespace descriptions in the XML project file Example: <namespaceSummaryItem name="System" isDocumented="True"> Generic interfaces and helper classes. </namespaceSummaryItem> References: * *example of Open Source project that generates documentation with every build (all scripts are in the trunk). *That's how the documentation by SHFB looks like on the Web (it is deployed on every forced build) . A: I know it's an old post, but this may be of help to someone else. Following this link, you can set a description for the namespaces without the need of adding a non-public class to your project. To edit the namespace summaries, expand the Summaries section within the Project Properties tab in SHFB. You will see a setting named, "NamespaceSummaries", which initially shows the value, "(None)". Click the setting to select it and a button showing an ellipsis symbol (...) appears. Click this button to display the Namespace Summaries dialog box, pictured below: A: If you use Sandcastle Help File Builder there is a dialog to enter the Namespace summaries. (Apparently also support for defining a specific class, but I wouldn't prefer it..) From the feature list: Definition of project summary and namespace summary comments that will appear in the help file. You can also easily indicate which namespaces to include or exclude from the help file. Support is also included for specifying namespace comments via a NamespaceDoc class within each namespace. A: You cant add references that way - do it via NamespaceDoc.cs instances i.e /// <summary> /// Concrete implementation of see cref="IInterface" using see cref="Concrete" /// </summary> class NamespaceDoc { } see here A: I see documentation for an "External XML Comments Files". Showing a schema like: <doc> <assembly/> <members> <member/> </members> </doc> If this is placed in a separate file, what would the extension be (xml/aml) and can this be used in the Visual Studio project? A: Here is the VB.Net version of the C# code snippet shown in Tuinstoelen's accepted answer. I am leaving this answer for those who find this question vis Google and need the VB version, since there is a gotcha waiting if you try to translate form the C# directly. Namespace Global.TestNamespace ''' <summary> ''' The <see cref="TestNamespace"/> namespace contains classes for .... ''' </summary> <System.Runtime.CompilerServices.CompilerGeneratedAttribute()> Class NamespaceDoc End Class End Namespace Note the "Global." prepended to namespace to be documented. At least for my VB project configuration, this was necessary so that the name of the namespace is not nested inside the root namespace, but is the name of the root namespace. Before I prepended the "Global.", the compiler was generating a summary for "TestNamespace.TestNamespace", rather than just "TestNamespace". Given that incorrect info in the compiler generated XML file, SandCastle was not recognizing the summary as belonging to the correct namespace.
{ "language": "en", "url": "https://stackoverflow.com/questions/156582", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "67" }
Q: Build deployment using CruiseControl.net I've seen a few examples on how to do build deployment, however I have something unique that I'd like to do: * *Deploy the build to a folder that has the build number (eg. Project\Builds\8423) *Alter the version number in the .NET AssmblyInfo.cs to match the build number Has anyone done this before with .NET projects using NAnt + CruiseControl.net? A: Check out this open-source project. Although, it uses MSBuild, the differences are minor. CC.NET passes the distrib directory and version to the Photon.ccnet script, which is a simple wrapper around Photon.build script. Version number is used in folder and package naming and also in the assembly versions. Version numbers come from the svnRevisionLabellerPlugin for CC.NET And that's how everything looks in the end. A: I'm quite new to Cruise Control and nAnt as well but I found Scott Hanselman's Blog Post very helpful. Not perfect and not pretty but it does get the job done. There is also an UpdateVersion Utility (which Scott also appears to have had a hand in). A: Deploying a build to a folder with the build number is pretty straightforward. CruiseControl.NET's NAnt task automatically passes a number of properties to your NAnt script. The CCNetLabel property is the one you'd use to create your deployment directory. There's actually a slightly out of date example NAnt script in the CruiseControl.NET documentation that does just that. Here's a nicer version of it: <target name="publish"> <if test="${not property::exists('CCNetLabel')}"> <fail message="CCNetLabel property not set, so can't create labelled distribution files" /> </if> <property name="publishDirectory" value="D:\Public\Project\Builds\${CCNetLabel}" /> <mkdir dir="${publishDirectory}" /> <copy todir="${publishDirectory}"> <fileset basedir="${buildDirectory}\bin"> <include name="*.dll" /> </fileset> </copy> </target> As far as versioning your binaries goes, I find the following approach much cleaner and easier than trying to alter your AssemblyInfo.cs files. Basically I create a CommonAssemblyInfo.cs file that lives outside of any projects, in the same directory as your solution file. This file includes things that are common to all assemblies I'm building, like company name, copyright info, and of course - version. This file is linked in each project in Visual Studio, so each project includes this info (along with a much smaller AssemblyInfo.cs file that includes assembly-specific info like assembly title). When projects are built locally, either through Visual Studio or NAnt, that CommonAssemblyInfo.cs file is used. However, when projects are built by CruiseControl.NET, I use NAnt to replace that file via the <asminfo> task. Here's what the NAnt script looks like: <target name="version"> <property name="commonAssemblyInfo" value="${buildDirectory}\CommonAssemblyInfo.cs" /> <!-- If build is initiated manually, copy standard CommonAssemblyInfo.cs file. --> <if test="${not property::exists('CCNetLabel')}"> <copy file=".\src\CommonAssemblyInfo.cs" tofile="${commonAssemblyInfo}" /> </if> <!-- If build is initiated by CC.NET, create a custom CommonAssemblyInfo.cs file. --> <if test="${property::exists('CCNetLabel')}"> <asminfo output="${commonAssemblyInfo}" language="CSharp"> <imports> <import namespace="System" /> <import namespace="System.Reflection" /> </imports> <attributes> <attribute type="AssemblyCompanyAttribute" value="My Company" /> <attribute type="AssemblyCopyrightAttribute" value="Copyright © 2008 My Company" /> <attribute type="AssemblyProductAttribute" value="My Product" /> <attribute type="AssemblyVersionAttribute" value="1.0.0.${CCNetLabel}" /> <attribute type="AssemblyInformationalVersionAttribute" value="1.0.0.${CCNetLabel}" /> </attributes> <references> <include name="System.dll" /> </references> </asminfo> </if> </target> <target name="build-my-project" depends="version"> <csc target="library" output="${buildDirectory}\bin\MyProject.dll"> <sources> <include name=".\src\MyProject\*.cs"/> <include name=".\src\MyProject\**\*.cs"/> <include name="${commonAssemblyInfo}"/> </sources> </csc> </target> Note where the AssemblyVersionAttribute and AssemblyInformationalVersionAttribute values are set in the version target. The CCNetLabel property is inserted into the version numbers. For added benefit, you could use a CruiseControl.NET plugin like the previously mentioned SvnRevisionLabeller. Using that, we get builds with labels like "2.1.8239.0", where the "8239" corresponds to the Subversion revision number we're building from. We dump this build number directly into our AssemblyVersionAttribute and AssemblyInformationalVersionAttributes, and our build numbers and the version numbers on our assemblies can all be easily traced back to a specific revision in our version control system. A: i haven't done it with nant, but we have written a custom application in C# that reads the assembly and increments the release number. we call it from an exec block in the ccnet config. creating a folder and copying files would be trivial to add to that application our thinking was we use C# all day, so it would be quicker to fix/alter the build program written in C#, then if we had to learn the intracies of nant scripts on top of that obviously if you use nant all the time, there would be no reason not to build a custom nant plugin to do the job A: I agree with BumperBox, a separate assembly to do the heavy(?) lifting of incrementing the build number is the route I took a couple of years ago, too. It has the advantage of being able to cope with other external factors, too. For example, you might want to increment the release or build numbers if a certain criteria exists within a config file. A: You can use the CCNetLabel property that is passed into your NAnt script to set where it deploys to. As for the AssemblyInfo, for MSBuild there is a Task in MSBuildCommunityTasks that works well. Don't know what the NAnt equivalent would be although you could run an MSBuild script before your NAnt script that changed it. Configuration is simple: <AssemblyInfo CodeLanguage="C#" OutputFile="%(YourProjects.RootDir)%(Directory)Properties\AssemblyInfo.cs" AssemblyVersion="$(CCNetLabel)" /> You will need to add whatever other attributes you need as well as this will overwrite the AssemblyInfo file.
{ "language": "en", "url": "https://stackoverflow.com/questions/156584", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Can Dns.GetHostEntry ever return an IPHostEntry with an empty AddressList? I'm just wondering if there can be a case where the hostname can be successfully resolved but the returned hostEntry.AddressList is empty. Currently I'm doing something like this: IPHostEntry hostEntry = Dns.GetHostEntry("some.hostname.tld"); if (hostEntry.AddressList.Count() < 1) { // can that ever happen? throw new ArgumentException("hostName has no assigned IP-Address"); } TcpClient client = new TcpClient(hostEntry.AddressList[0], 1234); My assumption is that Dns.GetHostEntry either throws an exception if the hostname is not found or otherwise the AddressList is nonempty, but I'm not sure about that. A: No, you'll not see an empty address list: even if you query a DNS label that does exist, but has no A or AAAA (IPv6) records, a SocketException ("No Such Host is Known") will be thrown. You can verify this by looking at the function InternalGetHostByName(string hostName, bool includeIPv6) in DNS.cs from the .NET Reference Source release. With the exception of some platform-specific precautions, DNS lookups are a simple wrapper around the Winsock gethostbyname function. Gethostbyname will either fail, or return an address list. An empty address list is never returned, because the function will fail with WSANO_DATA ("Valid name, no data record of requested type") in this case, which translates to the socket exception we already saw in .NET. EDIT May 2012, prompted by responses stating that an empty list is returned anyway: do note that this answer only applies to Win32, and that platforms like WinCE may behave quite differently. If you're seeing 'empty list' behavior on Win32, and the request you're making is against a publicly available DNS server, please post your code... A: Just for the records. Thanks to mdb's accepted answer I took a look at the description of the WSANO_DATA error: The requested name is valid and was found in the database, but it does not have the correct associated data being resolved for. The usual example for this is a host name-to-address translation attempt (using gethostbyname or WSAAsyncGetHostByName) which uses the DNS (Domain Name Server). An MX record is returned but no A record—indicating the host itself exists, but is not directly reachable. So this pretty much answers my question :) A: You have three possible situations here: * *The hostname exists (DNS has an A Record) and resolves to an IP Address * *Condition is never hit *The hostname exists (DNS knows about the domain) however no A records exists. * *This is an extremely unlikely scenario, and I think this can never happen in the first place. *The hostname doesn't exist * *Exception is thrown, you never get there. So no, I don't think that can ever happen. A: The answer is YES. The GetHostEntry method queries a DNS server for the IP addresses and aliases associated with an IP address. IPv6 addresses are filtered from the results of the GetHostEntry method if the local computer does not have IPv6 installed. As a result, it is possible to get back an empty IPHostEntry instance if only IPv6 results where available for the address parameter. The Aliases property of the IPHostEntry instance returned is not populated by this method and will always be empty.
{ "language": "en", "url": "https://stackoverflow.com/questions/156585", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: In Java, how to reload dynamically resources bundles in a web application? We are using fmt:setBundle to load a resource bundle from a database (we extended the ResourceBundle class to do that). When we modify a value in database, we have to reload the web server to display the new value on the web app. Is there any simple way to use the new value without restarting the web server ? (We do not want to always look up the value from database but we would like to invalidate the cache, for example by calling a special 'admin' URL) EDIT : We are using JDK 1.4, so I would prefer a solution on that version. :) A: If you're using JDK 1.6 you can use the callback methods getTimeToLive() and needsReload() in ResourceBundle.Control to control if the bundle cache needs to be loaded with new values from the database. A: As others have pointed out in the comments, you might want to look into Spring - particularly the ReloadableResourceBundleMessageSource. A: First you can create a class which extends from ReloadableResourceBundleMessageSource to expose its inner class protected method called getProperties. This method return a concurrent map from PropertiesHolder object. Second you should configure a bean of that extended class in you web configuration class. Now you able to use messageSource in your service or business layer. Here is the reference link Configure reloadable message source bundle
{ "language": "en", "url": "https://stackoverflow.com/questions/156586", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: What is the best way to handle English and Chinese in a Flex application? I have a requirement to be able to provide a flex component in English and several asian languages. I have looked at the flex documentation and it seems that I have to build several swf's, which feels wrong. Does anyone know of a straightforward and practical way of bundling string resources in different languages and handling the fonts? A: I guess you know the basics of how to localize a Flex application, but if you would like to know more there's a good and thorough description here: Runtime Localization. In Flex 3 you have three options on how to solve your problem: * *compile all languages into the SWF and switch language at runtime *compile a separate SWF for each language *compile no, or a default, language into the SWF and load additional languages at runtime The first option is probably the most common, the least complex and doesn't have many drawbacks. The other two can be used if you have special needs, like having to keep down the size of the SWF at all cost, or need to load all strings from a database at runtime. To implement the first option you create a resource bundle for each language (basically a number of .properties files that lives in a directory named after the locale, for example en_US for US English or sv_SE for Swedish). In the code you refer to strings by calling the resource manager: <Label text="{resourceManager.getString('mybundle', 'mystring")'}/> That will retrieve a string called "mystring" in the resource bundle compiled from "mybundle.properties" in the current locale. To make sure each locale is actually compiled into the application you add -locale=en_US,sv_SE to the compiler flags (but change the en_US,sv_SE part to the languages you have resource bundles for). You also need to add the location of the directories to the source path: -source-path+=locale/{locale} (the "{locale}" part will automatically be replaced by the values of the -locale flag). Now you have compiled all your languages into the SWF and can change languages at runtime. The way to do that is to modify the localeChain property of the resource manager: resourceManager.localeChain = ["sv_SE", "en_US"]; With the settings shown above the resource manager will first look in the Swedish resource bundle, and secondly in the one for US English. You can set another order at any time, and doing so will change all texts in the application then and there. I encourage you to read the description I referred to above, it explains this in greater detail, and most likely in a more understandable way. It also explains how to do some preparations you need to do before you can compile applications with locales other than en_US. The other problem you have is with fonts. That one is trickier. The best thing would be to have a font that had the full Unicode range of characters, that way you would only need to embed that and any text could be displayed. However, that means that your options are a bit more limited. I know that there is at least one version of Aria in Windows that has an enourmous number of characters, and on the Mac there is a Helvetica (I think, or it might be Lucida Grande, or both) that also has most of the ones you need to display many asian languages. Embedding all languages into the same SWF usually does very little to increase the file size, because text is very lightweight, but fonts are definitely not. Embedding a the whole Unicode version of Arial can increase the file size of a SWF by several megabyte, which kind of sucks for web applications. Depending on the situation you may have to compile one SWF per language, just because the font data would otherwise make the SWF unwieldy. A: Beware of fonts. System fonts aren't the prettiest but Asian fonts are too large to embed. We resorted to embedding Latin fonts for English and switching to system fonts for Chinese. Be careful about rotating system fonts - your text will disappear. I think Flash 10 might have fixed this. Also, be very careful with the font string you specify for Chinese. Most OSes have nifty fall-back logic - if you specify Trebuchet and try to render a Chinese character, your OS might decide to use some Asian font instead. Flash seems to mess up this fall-back logic and switch between two or more Asian fonts dynamically. We had cases where mousing over a text block would switch the font. To fix this, specify a font which includes all the characters you need (without falling back to some other font). You will need to test this across OSes, etc. A: We use Flex for the client part of our application and support I18N via ResourceBundles. A: In Flex 2.01 the language has to be built into the SWF - you can't change it at runtime. In Flex 3 you can switch language at runtime. http://labs.adobe.com/wiki/index.php/Flex_3:Feature_Introductions:_Runtime_Localization A: An important step left out above is to run the command: copylocale.exe en_US sv_SE from the bin folder of the sdk. This is in the article though.
{ "language": "en", "url": "https://stackoverflow.com/questions/156610", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to setup JNDI for Sun App Server 8.2 http://localhost:8080/rtsclient/loginform.faces Url jnp://localhost:1099 Application Server Type jboss40 Datasource jdbc/ilogDataSource User rtsAdmin Password rtsAdmin The above is for jboss. Now i have deployed RTS onto Sun Application Server. And i want to configure the jndi such that. My RTS client can actually access it. How do i go about this? I asked this question here http://forums.ilog.com/brms/index.php?topic=803.0 i know it is quite specific. But how to do it generally in sun application server? A: I think creating a jndi.properties file in your project root with the following should be enough. org.omg.CORBA.ORBInitialHost=localhost org.omg.CORBA.ORBInitialPort=1099 java.naming.security.principal=rtsAdmin java.naming.security.credentials=rtsAdmin There are also a few other things configurable if you need to java.naming.provider.url=... java.naming.factory.initial=... java.naming.factory.initial=com.sun.enterprise.naming.SerialInitContextFactory java.naming.factory.url.pkgs=com.sun.enterprise.naming java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl A less flexible method is also available. On startup provide the needed values to the InitialContext()-constructor as a Hashmap Properties prop = new Properties(); prop.put(Context. ...., "..."); e.g. prop.put(Context.SECURITY_PRINCIPAL, "rtsAdmin"); prop.put(Context.SECURITY_CREDENTIALS, "rtsAdmin"); InitialContext context = new InitialContext(prop); Check here what you can set via the constructor
{ "language": "en", "url": "https://stackoverflow.com/questions/156634", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MySQL query to prepend character to each entry I have a table of users which has a username column consisting of a six digit number e.g 675381, I need to prepend a zero to each of these usernames e.g. 0675381 would be the final output of the previous example, is there a query that could handle this? A: what type is the column of? if it's string type, try something like this: UPDATE your_table SET column_name=concat('0',column_name); A: UPDATE Tablename SET Username = Concat('0', Username); A: You mean "prepend" ? i.e. add it on the front? Is the column numeric? Do you always want 7 characters output? Assuming that, something like this would work for a query: select LPAD(CONVERT(username, CHAR), 7, '0') If the column is characters, the CONVERT() part is unnecessary, just LPAD the username. If you want to permanently modify the value in the table, you'll need to ensure the column is a character type and UPDATE using the above. A: You might want to use CONCAT_WS('', '0', Username) because if there is a null value, then you'll end up with NULL instead of '0'. This probably isn't a problem, but something I've learnt the hard way.
{ "language": "en", "url": "https://stackoverflow.com/questions/156641", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "18" }
Q: Does the last element in a loop deserve a separate treatment? When reviewing, I sometimes encounter this kind of loop: i = begin while ( i != end ) { // ... do stuff if ( i == end-1 (the one-but-last element) ) { ... do other stuff } increment i } Then I ask the question: would you write this? i = begin mid = ( end - begin ) / 2 // (the middle element) while ( i != end ) { // ... do stuff if ( i > mid ) { ... do other stuff } increment i } In my opinion, this beats the intention of writing a loop: you loop because there is something common to be done for each of the elements. Using this construct, for some of the elements you do something different. So, I conclude, you need a separate loop for those elements: i = begin mid = ( end - begin ) / 2 //(the middle element) while ( i != mid ) { // ... do stuff increment i } while ( i != end ) { // ... do stuff // ... do other stuff increment i } Now I even saw a question on SO on how to write the if-clause in a nice way... And I got sad: something isn't right here. Am I wrong? If so, what's so good about cluttering the loop body with special cases, which you are aware of upfront, at coding time? A: @xtofl, I agree with your concern. Million times I encountered similar problem. Either developer adds special handling for first or for last element. In most cases it is worth to just loop from startIdx + 1 or to endIdx - 1 element or even split one long loop into multiple shorter loops. In a very rare cases it's not possible to split loop. In my opinion uncommon things should be handled outside of the loop whenever possible. A: I came to a realization that when I put special cases in a for loop, I'm usually being too clever for my own good. A: In the last snippet you posted, you are repeating code for // .... do stuff. It makes sense of keeping 2 loops when you have completely different set of operations on a different set of indices. i = begin mid = ( end - begin ) / 2 //(the middle element) while ( i != mid ) { // ... do stuff increment i } while ( i != end ) { // ... do other stuff increment i } This not being the case, you would still want to keep one single loop. However fact remains that you still save ( end - begin ) / 2 number of comparisons. So it boils down to whether you want your code to look neat or you want to save some CPU cycles. Call is yours. A: I think you have it entirely nailed. Most people fall into the trap of including conditional branches in loops, when they could do them outside: which is simply faster. For example: if(items == null) return null; StringBuilder result = new StringBuilder(); if(items.Length != 0) { result.Append(items[0]); // Special case outside loop. for(int i = 1; i < items.Length; i++) // Note: we start at element one. { result.Append(";"); result.Append(items[i]); } } return result.ToString(); And the middle case you described is just plain nasty. Imagine if that code grows and needs to be refactored into different methods. Unless you are parsing XML <grin> loops should be kept as simple and concise as possible. A: I think you are right about the loop being meant to deal with all elements equally. Unfortunately sometimes there are special cases though and these should be dealt with inside the loop construct via if statements. If there are lots of special cases though you should probably think about coming up with some way to deal with the two different sets of elements in separate constructs. A: I prefer to simply, exclude the element from the loop and give a spearate treatment outside the loop For eg: Lets consider the case of EOF i = begin while ( i != end -1 ) { // ... do stuff for element from begn to second last element increment i } if(given_array(end -1) != ''){ // do stuff for the EOF element in the array } A: I don't think this question should be answered by a principle (e.g. "in a loop, treat every element equally"). Instead, you can look at two factors to evaluate if an implementation is good or bad: * *Runtime effectivity - does the compiled code run fast, or would it be faster doing it differently? *Code maintainability - Is it easy (for another developer) to understand what is happening here? If it is faster and the code is more readable by doing everything in one loop, do it that way. If it is slower and less readable, do it another way. If it is faster and less readably, or slower but more readable, find out which of the factors matters more in your specific case, and then decide how to loop (or not to loop). A: Of course, special-casing things in a loop which can be pulled out is silly. I wouldn't duplicate the do_stuff either though; I'd either put it in a function or a macro so I don't copy-paste code. A: Which one performs better? If the number of items is very large then I would always loop once, especially if you are going to perform some operation on every item. The cost of evaluating the conditional is likely to be less than looping twice. Oops, of course you are not looping twice... In which case two loops is preferable. However, I maintain that the primary consideration should be performance. There's no need to incur the conditional in the loop (N times) if you can partition the work by a simple manipulation of the loop bounds (once). A: Another thing I hate to see is the for-case pattern: for (i=0; i<5; i++) { switch(i) { case 0: // something break; case 1: // something else break; // etc... } } I've seen this in real code. A: I know I've seen this when people tried to join elements of an array into a comma-seperated string: for(i=0;i<elements.size;i++) { if (i>0) { string += ',' } string += elements[i] } You either have that if clause in there, or you have to duplicate the string += line again at the end. The obvious solution in this case is string = elements.join(',') But the join method does the same loop internally. And there isn't always a method to do what you want. A: The special case should be done outside the loop if it is only to be performed once. However, there may be an index or some other variable(s) that are just easier to keep inside the loop due to scoping. There may also be a contextual reason for keeping all the operations on the datastructure together inside the loop control structure, though I think that is a weak argument on its own. A: Its just about using it as per need and convenience. There is as such no mentions to treat elements equally and there is certainly no harm clubbing the features which language provides.
{ "language": "en", "url": "https://stackoverflow.com/questions/156650", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "20" }
Q: What is the best XSLT engine for Perl? I would like to know what of the many XSLT engines out there works well with Perl. I will use Apache (2.0) and Perl, and I want to obtain PDFs and XHTMLs. I'm new to this kind of projects so any comment or suggestion will be welcome. Thanks. Doing a simple search on Google I found a lot and I suppose that there are to many more. * *http://www.mod-xslt2.com/ *http://xml.apache.org/xalan-j/ *http://saxon.sourceforge.net/ *http://www.dopscripts.com/xslt_parser.html Any comment on your experiences will be welcome. A: So far I'm very satisfied with XML::LibXML for non-xslt tasks, and its documentation points to XML::LibXSLT, which looks quite nice, but I have no experience with it so far A: Can't really say which is the best solution because I didn't have a chance to try them all. But I can recommend you to try Perl module LibXSLT. It's an interface to the gnome libxslt library. I used it on one of my recent project was satisfied with it. A: First mistake - search on CPAN, not Google :) This throws up a bunch of results, but does rather highlight the problem of CPAN, that there's more than one solution, and it's not always clear which ones work, have been abandoned, are broken, slow or whatever. And disturbingly, the best answer (or at least, one of the best) comes up on page four of the results :( As other folks have suggested, XML::LibXSLT is robust and does the job: use XML::LibXSLT; use XML::LibXML; my $parser = XML::LibXML->new(); my $xslt = XML::LibXSLT->new(); my $source = $parser->parse_file('foo.xml'); my $style_doc = $parser->parse_file('bar.xsl'); my $stylesheet = $xslt->parse_stylesheet($style_doc); my $results = $stylesheet->transform($source); print $stylesheet->output_string($results); If you want to output results to a file then add this #create output file open(my $output_xml_file_name, '>', 'test.xml'); print $output_xml_file_name "$results"; If you don't want to do anything fancy, though, there's XML::LibXSLT::Easy, which essentially just wraps the above in one method call (and does a bunch of clever stuff behind the scenes using Moose. Check the source for an education!). use XML::LibXSLT::Easy; my $p = XML::LibXSLT::Easy->new; my $output = $p->process( xml => "foo.xml", xsl => "foo.xsl" ); A: You don't say what OS but for most *nix platforms, XML::LibXML is going to be the easiest to use and install. A: Here are a few Perl libraries intended to replace XSLT: * *XPathScript *XSLTish *XSH2
{ "language": "en", "url": "https://stackoverflow.com/questions/156683", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Creating a REST webserver with security I am very new to creating webservers - and I have had several goes at trying to understand them and write a quick webserver, but it's never quite 'clicked'. At the moment I am under the impression that REST would be most suitable for my purposes (I will explain later). Can anyone either show me a basic code example in Java (using Tomcat Apache) or a tutorial resource to show how a webserver: * *Can be used for security - i.e. pass in some kind of value to identify the client - from their the webserver will either deny or grant access to the client dependant on some criteria - maybe a lookup list. *Once the client is successfully accepted they will be allowed to pass in some more values to the webserver that will be used to write a row in a database table. Many thanks. PS - I would have thought there might have been soemthing that comes with Eclipse Ganymede? If someone can confirm? A: The best way to write restful resources in Java is via the JAX-RS standard. So I'd recommend you download Jersey which is the JAX-RS reference implementation and check out its examples; its got lots of them. Take an example for a spin then try hacking it to do what you like. BTW JAX-RS can be run inside any Servlet engine - you just build a WAR and deploy it (there are examples in the Jersery samples) - though Jersey also comes with a small lightweight web server you can use too which is a little easier to use - again there are examples in the distro of this. A: I would also suggest that you look at Restlet
{ "language": "en", "url": "https://stackoverflow.com/questions/156684", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How to start automatic download of a file in Internet Explorer? How do I initialize an automatic download of a file in Internet Explorer? For example, in the download page, I want the download link to appear and a message: "If you download doesn't start automatically .... etc". The download should begin shortly after the page loads. In Firefox this is easy, you just need to include a meta tag in the header, <meta http-equiv="Refresh" content="n;url"> where n is the number of seconds and url is the download URL. This does not work in Internet Explorer. How do I make this work in Internet Explorer browsers? A: A simple bit of jQuery solved this problem for me. $(function() { $(window).bind('load', function() { $("div.downloadProject").delay(1500).append('<iframe width="0" height="0" frameborder="0" src="[YOUR FILE SRC]"></iframe>'); }); }); In my HTML, I simply have <div class="downloadProject"></div> All this does is wait a second and a half, then append the div with the iframe referring to the file that you want to download. When the iframe is updated onto the page, your browser downloads the file. Simple as that. :D A: I used this, seems working and is just simple JS, no framework: Your file should start downloading in a few seconds. If downloading doesn't start automatically <a id="downloadLink" href="[link to your file]">click here to get your file</a>. <script> var downloadTimeout = setTimeout(function () { window.location = document.getElementById('downloadLink').href; }, 2000); </script> NOTE: this starts the timeout in the moment the page is loaded. A: Works on Chrome, firefox and IE8 and above: var link = document.createElement('a'); document.body.appendChild(link); link.href = url; link.click(); A: I hate when sites complicate download so much and use hacks instead of a good old link. Dead simple version: <a href="file.zip">Start automatic download!</a> It works! In every browser! If you want to download a file that is usually displayed inline (such as an image) then HTML5 has a download attribute that forces download of the file. It also allows you to override filename (although there is a better way to do it): <a href="report-generator.php" download="result.xls">Download</a> Version with a "thanks" page: If you want to display "thanks" after download, then use: <a href="file.zip" onclick="if (event.button==0) setTimeout(function(){document.body.innerHTML='thanks!'},500)"> Start automatic download! </a> Function in that setTimeout might be more advanced and e.g. download full page via AJAX (but don't navigate away from the page — don't touch window.location or activate other links). The point is that link to download is real, can be copied, dragged, intercepted by download accelerators, gets :visited color, doesn't re-download if page is left open after browser restart, etc. That's what I use for ImageOptim A: This is what I'm using in some sites (requires jQuery).: $(document).ready(function() { var downloadUrl = "your_file_url"; setTimeout("window.location.assign('" + downloadUrl + "');", 1000); }); The file is downloaded automatically after 1 second. A: I checked and found, it will work on button click via writing onclick event to Anchor tag or Input button onclick='javascript:setTimeout(window.location=[File location], 1000);' A: Back to the roots, i use this: <meta http-equiv="refresh" content="0; url=YOURFILEURL"/> Maybe not WC3 conform but works perfect on all browsers, no HTML5/JQUERY/Javascript. Greetings Tom :) A: I hope this will works all the browsers. You can also set the auto download timing. <html> <head> <title>Start Auto Download file</title> <script src="http://code.jquery.com/jquery-3.2.1.min.js"></script> <script> $(function() { $('a[data-auto-download]').each(function(){ var $this = $(this); setTimeout(function() { window.location = $this.attr('href'); }, 2000); }); }); </script> </head> <body> <div class="wrapper"> <p>The download should start shortly. If it doesn't, click <a data-auto-download href="auto-download.zip">here</a>.</p> </div> </body> </html> A: One more : var a = document.createElement('a'); a.setAttribute('href', dataUri); a.setAttribute('download', filename); var aj = $(a); aj.appendTo('body'); aj[0].click(); aj.remove(); A: I recently solved it by placing the following script on the page. setTimeout(function () { window.location = 'my download url'; }, 5000) I agree that a meta-refresh would be nicer but if it doesn't work what do you do... A: I had a similar issue and none of the above solutions worked for me. Here's my try (requires jquery): $(function() { $('a[data-auto-download]').each(function(){ var $this = $(this); setTimeout(function() { window.location = $this.attr('href'); }, 2000); }); }); Usage: Just add an attribute called data-auto-download to the link pointing to the download in question: <p>The download should start shortly. If it doesn't, click <a data-auto-download href="/your/file/url">here</a>.</p> It should work in all cases. A: Be sure to serve up the file without a no-cache header! IE has issues with this, if user tries to "open" the download without saving first. A: SourceForge uses an <iframe> element with the src="" attribute pointing to the file to download. <iframe width="1" height="1" frameborder="0" src="[File location]"></iframe> (Side effect: no redirect, no JavaScript, original URL remains unchanged.) A: This seemed to work for me - across all browsers. <script type="text/javascript"> window.onload = function(){ document.location = 'somefile.zip'; } </script> A: I think this will work for you. But visitors are easy if they got something in seconds without spending more time and hence they will also again visit your site. <a href="file.zip" onclick="if (event.button==0) setTimeout(function(){document.body.innerHTML='thanks!'},500)"> Start automatic download! </a> A: For those trying to trigger the download using a dynamic link it's tricky to get it working consistently across browsers. I had trouble in IE10+ downloading a PDF and used @dandavis' download function (https://github.com/rndme/download). IE10+ needs msSaveBlob. A: Nice jquery solution: jQuery('a.auto-start').get(0).click(); You can even set different file name for download inside <a> tag: Your download should start shortly. If not - you can use <a href="/attachments-31-3d4c8970.zip" download="attachments-31.zip" class="download auto-start">direct link</a>. A: <meta http-equiv="Refresh" content="n;url"> That's It. Easy, Right? <meta http-equiv="Refresh" content="n;url"> A: This is an old question but in case anyone wants to use automatic download of files with Flask, Python. You can do this: from flask import Flask, make_response, send_from_directory file_path = "Path containing the file" #e.g Uploads/images @app.route("/download/<file_name>") def download_file(file_name): resp = make_response(send_from_directory(file_path, file_name) resp.headers['Content-Disposition'] = f"attachment; filename={file_name}" return resp Inside a template or html page, index for example <div> <a class="btn btn-outline-warning" href={{url_for( 'download_file', name='image.png' )}} ">Download Image</a> </div> Clicking on the link will download the file without opening another page. For more info on: * *Content-Disposition *Setting request headers in Flask
{ "language": "en", "url": "https://stackoverflow.com/questions/156686", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "76" }
Q: Community server Username issue - User Username not found in membership store does not exist I have an error occuring frequently from our community server installation whenever the googlesitemap.ashx is traversed on a specific sectionID. I suspect that a username has been amended but the posts havn't recached to reflect this. Is there a way a can check the data integruity by performing a select statement on the database, alternatively is there a way to force the database to recache? A: Not so much an answer, but you can find the affected data entries by running the following query... Select * FROM cs_Posts Where UserID Not In (Select UserID From cs_Users Where UserAccountStatus = 2) A: This error could be thrown by community server if it finds users that aren't in the instance of MemberRoleProfileProvider. See CommunityServer.Users AddMembershipDataToUser() as an example UPDATE: I Solved this problem for my case by noticing that the usernames are stored in two tables - cs_Users and aspnet_Users. Turns out somehow the username was DIFFERENT in each table. Manually updating so the names were the same fixed this problem. Also, the user would left out of membership in the following line of the stored procedure cs_Membership_GetUsersByName: INSERT INTO @tbUsers SELECT UserId FROM dbo.aspnet_Users ar, @tbNames t WHERE LOWER(t.Name) = ar.LoweredUserName AND ar.ApplicationId = @ApplicationId The @tbNames is a table of names comes from cs_Users(?) at some point and therefore the usernames didn't match and user was not inserted in to the result later on. See also: http://dev.communityserver.com/forums/t/490899.aspx?PageIndex=2
{ "language": "en", "url": "https://stackoverflow.com/questions/156688", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Do you have a common base class for Hibernate entities? Do you have a common base class for Hibernate entities, i.e. a MappedSuperclass with id, version and other common properties? Are there any drawbacks? Example: @MappedSuperclass() public class BaseEntity { private Long id; private Long version; ... @Id @GeneratedValue(strategy = GenerationType.AUTO) public Long getId() {return id;} public void setId(Long id) {this.id = id;} @Version public Long getVersion() {return version;} ... // Common properties @Temporal(TemporalType.TIMESTAMP) public Date creationDate() {return creationDate;} ... } @Entity public class Customer extends BaseEntity { private String customerName; ... } A: This works fine for us. As well as the ID and creation date, we also have a modified date. We also have an intermediate TaggedBaseEntity that implements a Taggable interface, because some of our web application's entities have tags, like questions on Stack Overflow. A: The one that I use is primarily to implement hashCode() and equals(). I also added a method to pretty print the entity. In response to DR above, most of this can be overridden, but in my implementation you are stuck with an ID of type Long. public abstract class BaseEntity implements Serializable { public abstract Long getId(); public abstract void setId(Long id); /** * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((getId() == null) ? 0 : getId().hashCode()); return result; } /** * @see java.lang.Object#equals(Object) */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; BaseEntity other = (BaseEntity) obj; if (getId() == null) { if (other.getId() != null) return false; } else if (!getId().equals(other.getId())) return false; return true; } /** * @see java.lang.Object#toString() */ @Override public String toString() { return new StringBuilder(getClass().getSimpleName()).append(":").append(getId()).toString(); } /** * Prints complete information by calling all public getters on the entity. */ public String print() { final String EQUALS = "="; final String DELIMITER = ", "; final String ENTITY_FORMAT = "(id={0})"; StringBuffer sb = new StringBuffer("{"); PropertyDescriptor[] properties = PropertyUtils.getPropertyDescriptors(this); PropertyDescriptor property = null; int i = 0; while ( i < properties.length) { property = properties[i]; sb.append(property.getName()); sb.append(EQUALS); try { Object value = PropertyUtils.getProperty(this, property.getName()); if (value instanceof BaseEntity) { BaseEntity entityValue = (BaseEntity) value; String objectValueString = MessageFormat.format(ENTITY_FORMAT, entityValue.getId()); sb.append(objectValueString); } else { sb.append(value); } } catch (IllegalAccessException e) { // do nothing } catch (InvocationTargetException e) { // do nothing } catch (NoSuchMethodException e) { // do nothing } i++; if (i < properties.length) { sb.append(DELIMITER); } } sb.append("}"); return sb.toString(); } } A: I wouldn't hesitate to use a common base class, after all that's the point of O/R mapping. I use common base classes, too, but only if the entities share at least some common properties. I won't use it, if the ID is the only common property. Until now I did not encounter any problems. A: It works well for me too. Notice that you can also in this entity add some event listeners / interceptors like the Hibernate Envers one or any custom one according to your need so that you can: - Track all modifications - Know which user made the last modification - Update automatically the last modification - Set automatically the first insertion date And ther stuff like that... A: You can find some samples here http://blogsprajeesh.blogspot.com/2010/01/nhibernate-defining-mappings-part-4.html
{ "language": "en", "url": "https://stackoverflow.com/questions/156689", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "20" }
Q: Is it safe to run Access 2003 and 2007 at the same time? My question about the reconfiguration delay when switching between Access 2003 and 2007 the comment was made: Btw, you can't avoid the reconfiguration between Access 2007 and earlier versions. Access 2007 uses some of the same registry keys as earlier versions and they have to be rewritten when opening Access 2007. If this is so then is it actually safe to be running/developing databases in both versions at the same time? Do the registry changes affect the operation of Access once it has started up. For example recompiling/saving changes to objects? A: It works most of the time but it's not perfectly safe, which is why Microsft refuses to support multiple installations of Microsoft Office on the same pc. The recommended solution is to install a virtual machine and install the second Microsoft Office version on the virtual machine. Then you can switch from one version of Access to the other without them interfering with one another (and no switching time wait!) Microsoft offers a free download of Virtual PC 2007 in both 32 bit and 64 bit versions: http://www.microsoft.com/downloads/details.aspx?FamilyID=04d26402-3199-48a3-afa2-2dc0b40a73b6&DisplayLang=en Here's the service pack: http://www.microsoft.com/downloads/details.aspx?FamilyID=28c97d22-6eb8-4a09-a7f7-f6c7a1f000b5&DisplayLang=en A: It is perfectly safe, I have done it very often (both running and developing). As soon as you open a database in Access 2007, some extra properties will be added to the database. However, this is done in such a way that you can still open the database safely in Access 2003 at a later time. We also have databases installed in a multi-version environment were different people use the same backend, with the front end opened in Access 2003 or 2007. A: It seems to me that the instance of Access you open will inherit the registry settings at the time it is open. So, if you open A2K7, you'll get the registry settings that it writes in its "configuring Office" procedures. If while A2K7 is still open, you open A2K3, it will reconfigure the registry settings and inherit those for its session. This will have no effect on the already-running instance of A2K7. The only possible exception would be if there are some registry keys that the "configuring..." process changes that Access doesn't read upon opening, but later in the session. I have strong doubts that MS would ever design things that way. Professional Access developers been dealing with this kind of thing since MS introduced the MS Installer (first seen by most people with Office 2000), and the A2K7 issues are only slightly worse than with previous versions (though on Vista, it's more complex because of the way Vista handles registry changes). The fact that MS gets the vapors over contemplating multiple versions of Access on a single PC does not mean that it's actually dangerous -- it shows only that they don't want to devote resources to supporting that scenario.
{ "language": "en", "url": "https://stackoverflow.com/questions/156694", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Which web browsers natively support Array.forEach() Which browsers other than Firefox support Array.forEach()? Mozilla say it's an extension to the standard and I realise it's trivial to add to the array prototype, I'm just wondering what other browsers support it? A: All modern browsers but IE. A: I just checked this for another question: JavaScript for...in vs for. On kangax's ECMAScript 5 compatibility table, Array.forEach gets a 'yes' for all browsers except IE8. As of September 2011, IE browser share on desktop devices is less than 40%, and at least 8% of browsers are IE 9. In other words, Array.forEach is now supported by around 70% of desktop browsers. Obviously, this figure varies considerably, depending on territory and other factors -- some regions or countries (such as Brasil) have a higher proportion of Chrome users, for example, and some (such as China) have far more users on IE6 and IE8. I haven't checked, but mobile support (on WebKit and Opera browsers) may be even higher. A: The JavaScript article of Wikipedia lists the JS versions by browser. forEach is part of JavaScript 1.6. So it is supported indeed by most browsers, except Opera 9.02 (which I just tested). Opera 9.5 (which I just installed!) supports it, along with indexOf for Array. Surprisingly, it is not official. I don't see its support in the page ECMAScript support in Opera 9.5. Perhaps it is an overlook or perhaps only a partial support they don't want to advertise. A: Since IE doesn't support it (not even v8), I use jQuery.each() -- http://docs.jquery.com/Utilities/jQuery.each A: The Microsoft AJAX client library adds this to the Array prototype so if you have that client library in your site then you'll have it for sure. A: If you need all browsers to support this and other JavaScript 1.6 to 1.8 functions, I would suggest using the customizable jPaq library. The functions are implemented in the way that was suggested by Mozilla. A: I have checked on caniuse.com and it looks like all browsers support foreach except Opera Mini which has support info as ?Support unknow. If you're interested you can use this link to check the browser support for any features. https://caniuse.com/?search=foreach
{ "language": "en", "url": "https://stackoverflow.com/questions/156696", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "41" }
Q: How to encode characters from Oracle to XML? In my environment here I use Java to serialize the result set to XML. It happens basically like this: //foreach column of each row xmlHandler.startElement(uri, lname, "column", attributes); String chars = rs.getString(i); xmlHandler.characters(chars.toCharArray(), 0, chars.length()); xmlHandler.endElement(uri, lname, "column"); The XML looks like this in Firefox: <row num="69004"> <column num="1">10069</column> <column num="2">sd&#26;</column> <column num="3">FCVolume </column> </row> But when I parse the XML I get the a org.xml.sax.SAXParseException: Character reference "&#26" is an invalid XML character. My question now is: Which charactes do I have to replace or how do I have to encode my characters, that they will be valid XML? A: I found an interesting list in the Xml Spec: According to that List its discouraged to use the Character #26 (Hex: #x1A). The characters defined in the following ranges are also discouraged. They are either control characters or permanently undefined Unicode characters See the complete ranges. This code replaces all non-valid Xml Utf8 from a String: public String stripNonValidXMLCharacters(String in) { StringBuffer out = new StringBuffer(); // Used to hold the output. char current; // Used to reference the current character. if (in == null || ("".equals(in))) return ""; // vacancy test. for (int i = 0; i < in.length(); i++) { current = in.charAt(i); if ((current == 0x9) || (current == 0xA) || (current == 0xD) || ((current >= 0x20) && (current <= 0xD7FF)) || ((current >= 0xE000) && (current <= 0xFFFD)) || ((current >= 0x10000) && (current <= 0x10FFFF))) out.append(current); } return out.toString(); } its taken from Invalid XML Characters: when valid UTF8 does not mean valid XML But with that I had the still UTF-8 compatility issue: org.xml.sax.SAXParseException: Invalid byte 1 of 1-byte UTF-8 sequence After reading XML - returning XML as UTF-8 from a servlet I just tried out what happens if I set the Contenttype like this: response.setContentType("text/xml;charset=utf-8"); And it worked .... A: Extensible Markup Language (XML) 1.0 says: The ampersand character (&) and the left angle bracket (<) must not appear in their literal form, except when used as markup delimiters, or within a comment, a processing instruction, or a CDATA section. If they are needed elsewhere, they must be escaped using either numeric character references or the strings "&" and "<" respectively. The right angle bracket (>) may be represented using the string ">", and must, for compatibility, be escaped using either ">" or a character reference when it appears in the string "]]>" in content, when that string is not marking the end of a CDATA section. You can skip the encoding if you use CDATA: <column num="1"><![CDATA[10069]]></column> <column num="2"><![CDATA[sd&]]></column> A: Which version of JRE are you running? Sax Project says: J2SE 1.4 bundles an old version of SAX2. How do I make SAX2 r2 or later available?
{ "language": "en", "url": "https://stackoverflow.com/questions/156697", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Dealing with "global" data structures in an object-oriented world This is a question with many answers - I am interested in knowing what others consider to be "best practice". Consider the following situation: you have an object-oriented program that contains one or more data structures that are needed by many different classes. How do you make these data structures accessible? * *You can explicitly pass references around, for example, in the constructors. This is the "proper" solution, but it means duplicating parameters and instance variables all over the program. This makes changes or additions to the global data difficult. *You can put all of the data structures inside of a single object, and pass around references to this object. This can either be an object created just for this purpose, or it could be the "main" object of your program. This simplifies the problems of (1), but the data structures may or may not have anything to do with one another, and collecting them together in a single object is pretty arbitrary. *You can make the data structures "static". This lets you reference them directly from other classes, without having to pass around references. This entirely avoids the disadvantages of (1), but is clearly not OO. This also means that there can only ever be a single instance of the program. When there are a lot of data structures, all required by a lot of classes, I tend to use (2). This is a compromise between OO-purity and practicality. What do other folks do? (For what it's worth, I mostly come from the Java world, but this discussion is applicable to any OO language.) A: Global data isn't as bad as many OO purists claim! After all, when implementing OO classes you've usually using an API to your OS. What the heck is this if it isn't a huge pile of global data and services! If you use some global stuff in your program, you're merely extending this huge environment your class implementation can already see of the OS with a bit of data that is domain specific to your app. Passing pointers/references everywhere is often taught in OO courses and books, academically it sounds nice. Pragmatically, it is often the thing to do, but it is misguided to follow this rule blindly and absolutely. For a decent sized program, you can end up with a pile of references being passed all over the place and it can result in completely unnecessary drudgery work. Globally accessible services/data providers (abstracted away behind a nice interface obviously) are pretty much a must in a decent sized app. A: I must really really discourage you from using option 3 - making the data static. I've worked on several projects where the early developers made some core data static, only to later realise they did need to run two copies of the program - and incurred a huge amount of work making the data non-static and carefully putting in references into everything. So in my experience, if you do 3), you will eventually end up doing 1) at twice the cost. Go for 1, and be fine-grained about what data structures you reference from each object. Don't use "context objects", just pass in precisely the data needed. Yes, it makes the code more complicated, but on the plus side, it makes it clearer - the fact that a FwurzleDigestionListener is holding a reference to both a Fwurzle and a DigestionTract immediately gives the reader an idea about its purpose. And by definition, if the data format changes, so will the classes that operate on it, so you have to change them anyway. A: You might want to think about altering the requirement that lots of objects need to know about the same data structures. One reason there does not seem to be a clean OO way of sharing data is that sharing data is not very object-oriented. You will need to look at the specifics of your application but the general idea is to have one object responsible for the shared data which provides services to the other objects based on the data encapsulated in it. However these services should not involve giving other objects the data structures - merely giving other objects the pieces of information they need to meet their responsibilites and performing mutations on the data structures internally. A: I tend to use 3) and be very careful about the synchronisation and locking across threads. I agree it is less OO, but then you confess to having global data, which is very un-OO in the first place. Don't get too hung up on whether you are sticking purely to one programming methodology or another, find a solution which fits your problem. I think there are perfectly valid contexts for singletons (Logging for instance). A: I use a combination of having one global object and passing interfaces in via constructors. From the one main global object (usually named after what your program is called or does) you can start up other globals (maybe that have their own threads). This lets you control the setting up of program objects in the main objects constructor and tearing them down again in the right order when the application stops in this main objects destructor. Using static classes directly makes it tricky to initialize/uninitialize any resources these classes use in a controlled manner. This main global object also has properties for getting at the interfaces of different sub-systems of your application that various objects may want to get hold of to do their work. I also pass references to relevant data-structures into constructors of some objects where I feel it is useful to isolate those objects from the rest of the world within the program when they only need to be concerned with a small part of it. Whether an object grabs the global object and navigates its properties to get the interfaces it wants or gets passed the interfaces it uses via its constructor is a matter of taste and intuition. Any object you're implementing that you think might be reused in some other project should definately be passed data structures it should use via its constructor. Objects that grab the global object should be more to do with the infrastructure of your application. Objects that receive interfaces they use via the constructor are probably easier to unit-test because you can feed them a mock interface, and tickle their methods to make sure they return the right arguments or interact with mock interfaces correctly. To test objects that access the main global object, you have to mock up the main global object so that when they request interfaces (I often call these services) from it they get appropriate mock objects and can be tested against them. A: I prefer using the singleton pattern as described in the GoF book for these situations. A singleton is not the same as either of the three options described in the question. The constructor is private (or protected) so that it cannot be used just anywhere. You use a get() function (or whatever you prefer to call it) to obtain an instance. However, the architecture of the singleton class guarantees that each call to get() returns the same instance. A: We should take care not to confuse Object Oriented Design with Object Oriented Implementation. Al too often, the term OO Design is used to judge an implementation, just as, imho, it is here. Design If in your design you see a lot of objects having a reference to exactly the same object, that means a lot of arrows. The designer should feel an itch here. He should verify whether this object is just commonly used, or if it is really a utility (e.g. a COM factory, a registry of some kind, ...). From the project's requirements, he can see if it really needs to be a singleton (e.g. 'The Internet'), or if the object is shared because it's too general or too expensive or whatsoever. Implementation When you are asked to implement an OO Design in an OO language, you face a lot of decisions, like the one you mentioned: how should I implement all the arrows to the oft used object in the design? That's the point where questions are addressed about 'static member', 'global variable' , 'god class' and 'a-lot-of-function-arguments'. The Design phase should have clarified if the object needs to be a singleton or not. The implementation phase will decide on how this singleness will be represented in the program. A: Option 3) while not purist OO, tends to be the most reasonable solution. But I would not make your class a singleton; and use some other object as a static 'dictionary' to manage those shared resources. A: I don't like any of your proposed solutions: * *You are passing around a bunch of "context" objects - the things that use them don't specify what fields or pieces of data they are really interested in *See here for a description of the God Object pattern. This is the worst of all worlds *Simply do not ever use Singleton objects for anything. You seem to have identified a few of the potential problems yourself
{ "language": "en", "url": "https://stackoverflow.com/questions/156701", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: In Eclipse, how do I replace a character by a new line? In Eclipse 3.3.2, I would like to replace a character (say ',') by a new line in a file. What should I write in the "Replace with" box in order to do so ? EDIT : Many answers seems to be for Eclipse 3.4. Is there a solution for Eclipse 3.3.X ? A: Check box 'Regular Expressions' and use '\n' in the 'Replace with' box A: Like the others said, just use regular expression, but instead of just \r, put \r\n A: Check box 'Regular Expressions' and use '\R' in the 'Replace with' box It's a new feature introduced with Eclipse 3.4, See What's New in 3.4 A: if the file search is performed with Regular Expressions checkbox checked, then replace all / replace selected will also allow regular expression and will transform \n to a newline in the file(s) A: I've just found an article about that problem. It seems to be a bug. There's a workaround which is to copy a new line in clipboard and then paste it inside the "replace" box. A: I'm using Helios and it works, however I had some issues with replacement... I wanted to place a line break between any of these brackets "><" (to make each new XML tag go to a new line)... first I had to place a chacter between the 2 brackets, for instance /r, after this i checked the "regular expressions" box and replaced the /r with \R, which resulted in the correct linebreak. otherwise, the replace seemed to be greyed out.
{ "language": "en", "url": "https://stackoverflow.com/questions/156707", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "89" }
Q: What is the default lifetime of a session? If I hit a page which calls session_start(), how long would I have to wait before I get a new session ID when I refresh the page? A: Check out php.ini the value set for session.gc_maxlifetime is the ID lifetime in seconds. I believe the default is 1440 seconds (24 mins) http://www.php.net/manual/en/session.configuration.php Edit: As some comments point out, the above is not entirely accurate. A wonderful explanation of why, and how to implement session lifetimes is available here: How do I expire a PHP session after 30 minutes? A: it depends on your php settings... use phpinfo() and take a look at the session chapter. There are values like session.gc_maxlifetime and session.cache_expire and session.cookie_lifetime which affects the sessions lifetime EDIT: it's like Martin write before A: According to a user on PHP.net site, his efforts to keep session alive failed, so he had to make a workaround. <?php $Lifetime = 3600; $separator = (strstr(strtoupper(substr(PHP_OS, 0, 3)), "WIN")) ? "\\" : "/"; $DirectoryPath = dirname(__FILE__) . "{$separator}SessionData"; //in Wamp for Windows the result for $DirectoryPath //would be C:\wamp\www\your_site\SessionData is_dir($DirectoryPath) or mkdir($DirectoryPath, 0777); if (ini_get("session.use_trans_sid") == true) { ini_set("url_rewriter.tags", ""); ini_set("session.use_trans_sid", false); } ini_set("session.gc_maxlifetime", $Lifetime); ini_set("session.gc_divisor", "1"); ini_set("session.gc_probability", "1"); ini_set("session.cookie_lifetime", "0"); ini_set("session.save_path", $DirectoryPath); session_start(); ?> In SessionData folder it will be stored text files for holding session information, each file would be have a name similar to "sess_a_big_hash_here". A: The default in the php.ini for the session.gc_maxlifetime directive (the "gc" is for garbage collection) is 1440 seconds or 24 minutes. See the Session Runtime Configuation page in the manual: http://www.php.net/manual/en/session.configuration.php You can change this constant in the php.ini or .httpd.conf files if you have access to them, or in the local .htaccess file on your web site. To set the timeout to one hour using the .htaccess method, add this line to the .htaccess file in the root directory of the site: php_value session.gc_maxlifetime "3600" Be careful if you are on a shared host or if you host more than one site where you have not changed the default. The default session location is the /tmp directory, and the garbage collection routine will run every 24 minutes for these other sites (and wipe out your sessions in the process, regardless of how long they should be kept). See the note on the manual page or this site for a better explanation. The answer to this is to move your sessions to another directory using session.save_path. This also helps prevent bad guys from hijacking your visitors' sessions from the default /tmp directory. A: You can use something like ini_set('session.gc_maxlifetime', 28800); // 8 * 60 * 60 too. A: But watch out, on most xampp/ampp/...-setups and some linux destributions it's 0, which means the file will never get deleted until you do it within your script (or dirty via shell) PHP.INI: ; Lifetime in seconds of cookie or, if 0, until browser is restarted. ; http://php.net/session.cookie-lifetime session.cookie_lifetime = 0
{ "language": "en", "url": "https://stackoverflow.com/questions/156712", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "69" }
Q: Seam Problem: Could not set field value by reflection I'm having a problem with my Seam code and I can't seem to figure out what I'm doing wrong. It's doing my head in :) Here's an excerpt of the stack trace: Caused by: java.lang.IllegalArgumentException: Can not set java.lang.Long field com.oobjects.sso.manager.home.PresenceHome.customerId to java.lang.String I'm trying to get a parameter set on my URL passed into one of my beans. To do this, I've got the following set up in my pages.xml: <page view-id="/customer/presences.xhtml"> <begin-conversation flush-mode="MANUAL" join="true" /> <param name="customerId" value="#{presenceHome.customerId}" /> <raise-event type="PresenceHome.init" /> <navigation> <rule if-outcome="persisted"> <end-conversation /> <redirect view-id="/customer/presences.xhtml" /> </rule> </navigation> </page> My bean starts like this: @Name("presenceHome") @Scope(ScopeType.CONVERSATION) public class PresenceHome extends EntityHome<Presence> implements Serializable { @In private CustomerDao customerDao; @In(required = false) private Long presenceId; @In(required = false) private Long customerId; private Customer customer; // Getters, setters and other methods follow. They return the correct types defined above } Finally the link I use to link one one page to the next looks like this: <s:link styleClass="#{selected == 'presences' ? 'selected' : ''}" view="/customer/presences.xhtml" title="Presences" propagation="none"> <f:param name="customerId" value="#{customerId}" /> Presences </s:link> All this seems to work fine. When I hover over the link above in my page, I get a URL ending in something like "?customerId=123". So the parameter is being passed over and it's something that can be easily converted into a Long type. But for some reason, it's not. I've done similar things to this before in other projects and it's worked then. I just can't see what it isn't working now. If I remove the element from my page declaration, I get through to the page fine. So, does anyone have any thoughts? A: You want to add a converter to your pages.xml file. Like this: <param name="customerId" value="#{presenceHome.customerId}" converterId="javax.faces.Long" /> See the seampay example provided with seam for more details. A: try: ... <f:param name="customerId" value="#{customerId.toString()}" /> ... A: Our code does something similar, but with the customerId property in the Java class as a String: private String customerId; public String getCustomerId() { return customerId; } public void setCustomerId(final String customerId) { this.customerId = customerId; } A: You could try using a property editor. Put this into the same package as your bean: import java.beans.PropertyEditorSupport; public class PresenceHomeEditor extends PropertyEditorSupport { public void setAsText(final String text) throws IllegalArgumentException { try { final Long value = Long.decode(text); setValue(value); } catch (final NumberFormatException e) { super.setAsText(text); } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/156724", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Hooking up Reporting Services 2005SP2 to SQL Server 2008 I am trying to configure Reporting Services 2005SP2 on a machine with SQL 2008 on another hosting the ReportServer DB. When I create the ReportServerDB the DB is created as version C.0.9.45: When, afterwards, I try to initialise Reporting Services, I get an error about an incorrect version number. Reporting Services created a ReportServer DB version C.0.9.45 but now expects a version C.0.8.54. Changing compatibility settings of the DB doesn’t have an effect. And changing the version number sproc in the DB to return what Reporting Services wants to hear only delays the crash until initialisation has started. Any ideas? A: I got a reply from microsoft support saying that it is impossible on the same box. http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=4153333&SiteID=1 A: You must have created the reportServerDB using the SQL 2008 configuration tool. If you want to use the 2005 version of the server you need to create the configuration database using the configuration tool that came with SQL 2005. The 2005 SP2 tool will create a database with version C.0.8.54
{ "language": "en", "url": "https://stackoverflow.com/questions/156740", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Best Practices for Eclipse's Problems View I am using Eclipse for quite some time and I still haven't found how to configure the Problems View to display only the Errors and Warnings of interest. Is there an easy way to filter out warnings from a specific resource or from a specific path? For example, when I generate javadoc I get tons of irrelevant html warnings. Also, is there a way to change the maximum number of appearing warnings/errors? I am aware of the filters concept, but I am looking for some real life examples. What kind of filters or practices do other people use? Edit: I found the advice to filter on "On selected element and its children" to be the best one. I have one other issue however. If I have "a lot" of warnings or errors, only the first 100 appear. In the rare case I want to see all of them, how do I do it? A: I feel that filtering "On selected element and its children" is the best mode of Problems view filter, because it allows you to very quickly narrow down the scope of reported problems: click on Working Set (in Package Explorer), and it shows all problems in all projects in the set; click on a project - and only problems in the selected project appear. Click on individual class (or package) - only problems in the selected class (or package) are shown. So you don't get distracted with problems unrelated to your task at hand. A: An updated link for Ganymede (Eclipse 3.4): http://help.eclipse.org/ganymede/topic/org.eclipse.platform.doc.user/concepts/cprbview.htm But I agree with the fundamental problem: the Problems view needs filtering by Resource, not just Description. In my case, I include generated jsp code in my source path, and there are all kinds of warning that occur in the *_jsp.java files (like unused application, page, out, config, page_context variables). So it would be nice to exclude them by the Resource pattern. (Or for jspc to not write unused code...but that's a different issue altogether). A: Re: your edit In the drop down button by the filter button, there is a preferences option. Uncheck "Use Marker Limits" and you will be shown all errors + warnings. A: In the top right hand corner of the problems pane is a filter button (it looks like three arrows pointing to the right), clicking that will let you configure the view. You can filter by element, such as the class you're editing or working set, the type of problem (e.g. java problems, buildfile problems etc..) and by severity. It's actually very configurable. See http://help.eclipse.org/help32/index.jsp?topic=/org.eclipse.platform.doc.user/concepts/cprbview.htm for details and screenshots. A: To view more than 100 warnings, go to the problem view's drop down menu (use the little arrow next to the minimize button on the view), select Preferences, and you will have the option to change this limit from 100 to another number. This information is for Ganymede; things have changed since Europa and I'm not sure of all the differences. A: In order to view more than 100 warnings, go to the problem view's drop down menu (use the little arrow next to the minimize button on the view), select Configure Contents. Uncheck the Use item limitsat the bottom left of the Configure Contents window or set a limit in the Number of items visible per group:. A: Open problems view. Click corner triangle. Select preferences Uncross: [ ] Use marker limits A: Make sure you don't forget to uncheck "Show all items" on top left corner of Filters window. I was applying all these filters such as 'On selected elements and its children' but it doesn't seem to work out. Finally I unchecked the aforementioned checkbox, selected the required 'Configurations' and then it started working.
{ "language": "en", "url": "https://stackoverflow.com/questions/156745", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "64" }
Q: SSL pages under ASP.NET MVC How do I go about using HTTPS for some of the pages in my ASP.NET MVC based site? Steve Sanderson has a pretty good tutorial on how to do this in a DRY way on Preview 4 at: http://blog.codeville.net/2008/08/05/adding-httpsssl-support-to-aspnet-mvc-routing/ Is there a better / updated way with Preview 5?, A: If you are using ASP.NET MVC 2 Preview 2 or higher, you can now simply use: [RequireHttps] public ActionResult Login() { return View(); } Though, the order parameter is worth noting, as mentioned here. A: As Amadiere wrote, [RequireHttps] works great in MVC 2 for entering HTTPS. But if you only want to use HTTPS for some pages as you said, MVC 2 doesn't give you any love - once it switches a user to HTTPS they're stuck there until you manually redirect them. The approach I used is to use another custom attribute, [ExitHttpsIfNotRequired]. When attached to a controller or action this will redirect to HTTP if: * *The request was HTTPS *The [RequireHttps] attribute wasn't applied to the action (or controller) *The request was a GET (redirecting a POST would lead to all sorts of trouble). It's a bit too big to post here, but you can see the code here plus some additional details. A: Here's a recent post from Dan Wahlin on this: http://weblogs.asp.net/dwahlin/archive/2009/08/25/requiring-ssl-for-asp-net-mvc-controllers.aspx He uses an ActionFilter Attribute. A: Some ActionLink extensions: http://www.squaredroot.com/post/2008/06/11/MVC-and-SSL.aspx Or an controller action attribute that redirects to https:// http://forums.asp.net/p/1260198/2358380.aspx#2358380 A: For those who are not a fan of attribute-oriented development approaches, here is a piece of code that could help: public static readonly string[] SecurePages = new[] { "login", "join" }; protected void Application_AuthorizeRequest(object sender, EventArgs e) { var pageName = RequestHelper.GetPageNameOrDefault(); if (!HttpContext.Current.Request.IsSecureConnection && (HttpContext.Current.Request.IsAuthenticated || SecurePages.Contains(pageName))) { Response.Redirect("https://" + Request.ServerVariables["HTTP_HOST"] + HttpContext.Current.Request.RawUrl); } if (HttpContext.Current.Request.IsSecureConnection && !HttpContext.Current.Request.IsAuthenticated && !SecurePages.Contains(pageName)) { Response.Redirect("http://" + Request.ServerVariables["HTTP_HOST"] + HttpContext.Current.Request.RawUrl); } } There are several reasons to avoid attributes and one of them is if you want to look at the list of all secured pages you will have to jump over all controllers in solution. A: I went accross this question and hope my solution can helps someone. We got few problems: - We need to secure specific actions, for instance "LogOn" in "Account". We can use the build in RequireHttps attribute, which is great - but it'll redirect us back with https://. - We should make our links, forms and such "SSL aware". Generally, my solution allows to specify routes that will use absolute url, in addition to the ability to specify the protocol. You can use this approch to specify the "https" protocol. So, firstly I've created an ConnectionProtocol enum: /// <summary> /// Enum representing the available secure connection requirements /// </summary> public enum ConnectionProtocol { /// <summary> /// No secure connection requirement /// </summary> Ignore, /// <summary> /// No secure connection should be used, use standard http request. /// </summary> Http, /// <summary> /// The connection should be secured using SSL (https protocol). /// </summary> Https } Now, I've created hand-rolled version of RequireSsl. I've modified the original RequireSsl source code to allow redirection back to http:// urls. In addition, I've put a field that allows us to determine if we should require SSL or not (I'm using it with the DEBUG pre-processor). /* Note: * This is hand-rolled version of the original System.Web.Mvc.RequireHttpsAttribute. * This version contains three improvements: * - Allows to redirect back into http:// addresses, based on the <see cref="SecureConnectionRequirement" /> Requirement property. * - Allows to turn the protocol scheme redirection off based on given condition. * - Using Request.IsCurrentConnectionSecured() extension method, which contains fix for load-balanced servers. */ [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)] public sealed class RequireHttpsAttribute : FilterAttribute, IAuthorizationFilter { public RequireHttpsAttribute() { Protocol = ConnectionProtocol.Ignore; } /// <summary> /// Gets or sets the secure connection required protocol scheme level /// </summary> public ConnectionProtocol Protocol { get; set; } /// <summary> /// Gets the value that indicates if secure connections are been allowed /// </summary> public bool SecureConnectionsAllowed { get { #if DEBUG return false; #else return true; #endif } } public void OnAuthorization(System.Web.Mvc.AuthorizationContext filterContext) { if (filterContext == null) { throw new ArgumentNullException("filterContext"); } /* Are we allowed to use secure connections? */ if (!SecureConnectionsAllowed) return; switch (Protocol) { case ConnectionProtocol.Https: if (!filterContext.HttpContext.Request.IsCurrentConnectionSecured()) { HandleNonHttpsRequest(filterContext); } break; case ConnectionProtocol.Http: if (filterContext.HttpContext.Request.IsCurrentConnectionSecured()) { HandleNonHttpRequest(filterContext); } break; } } private void HandleNonHttpsRequest(AuthorizationContext filterContext) { // only redirect for GET requests, otherwise the browser might not propagate the verb and request // body correctly. if (!String.Equals(filterContext.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase)) { throw new InvalidOperationException("The requested resource can only be accessed via SSL."); } // redirect to HTTPS version of page string url = "https://" + filterContext.HttpContext.Request.Url.Host + filterContext.HttpContext.Request.RawUrl; filterContext.Result = new RedirectResult(url); } private void HandleNonHttpRequest(AuthorizationContext filterContext) { if (!String.Equals(filterContext.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase)) { throw new InvalidOperationException("The requested resource can only be accessed without SSL."); } // redirect to HTTP version of page string url = "http://" + filterContext.HttpContext.Request.Url.Host + filterContext.HttpContext.Request.RawUrl; filterContext.Result = new RedirectResult(url); } } Now, this RequireSsl will do the following base on your Requirements attribute value: - Ignore: Won't do nothing. - Http: Will force redirection to http protocol. - Https: Will force redirection to https protocol. You should create your own base controller and set this attribute to Http. [RequireSsl(Requirement = ConnectionProtocol.Http)] public class MyController : Controller { public MyController() { } } Now, in each cpntroller/action you'd like to require SSL - just set this attribute with ConnectionProtocol.Https. Now lets move to URLs: We got few problems with the url routing engine. You can read more about them at http://blog.stevensanderson.com/2008/08/05/adding-httpsssl-support-to-aspnet-mvc-routing/. The solution suggested in this post is theoreticly good, but old and I don't like the approch. My solutions is the following: Create a subclass of the basic "Route" class: public class AbsoluteUrlRoute : Route { #region ctor /// <summary> /// Initializes a new instance of the System.Web.Routing.Route class, by using /// the specified URL pattern and handler class. /// </summary> /// <param name="url">The URL pattern for the route.</param> /// <param name="routeHandler">The object that processes requests for the route.</param> public AbsoluteUrlRoute(string url, IRouteHandler routeHandler) : base(url, routeHandler) { } /// <summary> /// Initializes a new instance of the System.Web.Routing.Route class, by using /// the specified URL pattern and handler class. /// </summary> /// <param name="url">The URL pattern for the route.</param> /// <param name="defaults">The values to use for any parameters that are missing in the URL.</param> /// <param name="routeHandler">The object that processes requests for the route.</param> public AbsoluteUrlRoute(string url, RouteValueDictionary defaults, IRouteHandler routeHandler) : base(url, defaults, routeHandler) { } /// <summary> /// Initializes a new instance of the System.Web.Routing.Route class, by using /// the specified URL pattern and handler class. /// </summary> /// <param name="url">The URL pattern for the route.</param> /// <param name="defaults">The values to use for any parameters that are missing in the URL.</param> /// <param name="constraints">A regular expression that specifies valid values for a URL parameter.</param> /// <param name="routeHandler">The object that processes requests for the route.</param> public AbsoluteUrlRoute(string url, RouteValueDictionary defaults, RouteValueDictionary constraints, IRouteHandler routeHandler) : base(url, defaults, constraints, routeHandler) { } /// <summary> /// Initializes a new instance of the System.Web.Routing.Route class, by using /// the specified URL pattern and handler class. /// </summary> /// <param name="url">The URL pattern for the route.</param> /// <param name="defaults">The values to use for any parameters that are missing in the URL.</param> /// <param name="constraints">A regular expression that specifies valid values for a URL parameter.</param> /// <param name="dataTokens">Custom values that are passed to the route handler, but which are not used /// to determine whether the route matches a specific URL pattern. These values /// are passed to the route handler, where they can be used for processing the /// request.</param> /// <param name="routeHandler">The object that processes requests for the route.</param> public AbsoluteUrlRoute(string url, RouteValueDictionary defaults, RouteValueDictionary constraints, RouteValueDictionary dataTokens, IRouteHandler routeHandler) : base(url, defaults, constraints, dataTokens, routeHandler) { } #endregion public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values) { var virtualPath = base.GetVirtualPath(requestContext, values); if (virtualPath != null) { var scheme = "http"; if (this.DataTokens != null && (string)this.DataTokens["scheme"] != string.Empty) { scheme = (string) this.DataTokens["scheme"]; } virtualPath.VirtualPath = MakeAbsoluteUrl(requestContext, virtualPath.VirtualPath, scheme); return virtualPath; } return null; } #region Helpers /// <summary> /// Creates an absolute url /// </summary> /// <param name="requestContext">The request context</param> /// <param name="virtualPath">The initial virtual relative path</param> /// <param name="scheme">The protocol scheme</param> /// <returns>The absolute URL</returns> private string MakeAbsoluteUrl(RequestContext requestContext, string virtualPath, string scheme) { return string.Format("{0}://{1}{2}{3}{4}", scheme, requestContext.HttpContext.Request.Url.Host, requestContext.HttpContext.Request.ApplicationPath, requestContext.HttpContext.Request.ApplicationPath.EndsWith("/") ? "" : "/", virtualPath); } #endregion } This version of "Route" class will create absolute url. The trick here, followed by the blog post author suggestion, is to use the DataToken to specify the scheme (example at the end :) ). Now, if we'll generate an url, for example for the route "Account/LogOn" we'll get "/http://example.com/Account/LogOn" - that's since the UrlRoutingModule sees all the urls as relative. We can fix that using custom HttpModule: public class AbsoluteUrlRoutingModule : UrlRoutingModule { protected override void Init(System.Web.HttpApplication application) { application.PostMapRequestHandler += application_PostMapRequestHandler; base.Init(application); } protected void application_PostMapRequestHandler(object sender, EventArgs e) { var wrapper = new AbsoluteUrlAwareHttpContextWrapper(((HttpApplication)sender).Context); } public override void PostResolveRequestCache(HttpContextBase context) { base.PostResolveRequestCache(new AbsoluteUrlAwareHttpContextWrapper(HttpContext.Current)); } private class AbsoluteUrlAwareHttpContextWrapper : HttpContextWrapper { private readonly HttpContext _context; private HttpResponseBase _response = null; public AbsoluteUrlAwareHttpContextWrapper(HttpContext context) : base(context) { this._context = context; } public override HttpResponseBase Response { get { return _response ?? (_response = new AbsoluteUrlAwareHttpResponseWrapper(_context.Response)); } } private class AbsoluteUrlAwareHttpResponseWrapper : HttpResponseWrapper { public AbsoluteUrlAwareHttpResponseWrapper(HttpResponse response) : base(response) { } public override string ApplyAppPathModifier(string virtualPath) { int length = virtualPath.Length; if (length > 7 && virtualPath.Substring(0, 7) == "/http:/") return virtualPath.Substring(1); else if (length > 8 && virtualPath.Substring(0, 8) == "/https:/") return virtualPath.Substring(1); return base.ApplyAppPathModifier(virtualPath); } } } } Since this module is overriding the base implementation of UrlRoutingModule, we should remove the base httpModule and register ours in web.config. So, under "system.web" set: <httpModules> <!-- Removing the default UrlRoutingModule and inserting our own absolute url routing module --> <remove name="UrlRoutingModule-4.0" /> <add name="UrlRoutingModule-4.0" type="MyApp.Web.Mvc.Routing.AbsoluteUrlRoutingModule" /> </httpModules> Thats it :). In order to register an absolute / protocol followed route, you should do: routes.Add(new AbsoluteUrlRoute("Account/LogOn", new MvcRouteHandler()) { Defaults = new RouteValueDictionary(new {controller = "Account", action = "LogOn", area = ""}), DataTokens = new RouteValueDictionary(new {scheme = "https"}) }); Will love to hear your feedback + improvements. Hope it can help! :) Edit: I forgot to include the IsCurrentConnectionSecured() extension method (too many snippets :P). This is an extension method that generally uses Request.IsSecuredConnection. However, this approch will not work when using load-balancing - so this method can bypass this (took from nopCommerce). /// <summary> /// Gets a value indicating whether current connection is secured /// </summary> /// <param name="request">The base request context</param> /// <returns>true - secured, false - not secured</returns> /// <remarks><![CDATA[ This method checks whether or not the connection is secured. /// There's a standard Request.IsSecureConnection attribute, but it won't be loaded correctly in case of load-balancer. /// See: <a href="http://nopcommerce.codeplex.com/SourceControl/changeset/view/16de4a113aa9#src/Libraries/Nop.Core/WebHelper.cs">nopCommerce WebHelper IsCurrentConnectionSecured()</a>]]></remarks> public static bool IsCurrentConnectionSecured(this HttpRequestBase request) { return request != null && request.IsSecureConnection; // when your hosting uses a load balancer on their server then the Request.IsSecureConnection is never got set to true, use the statement below // just uncomment it //return request != null && request.ServerVariables["HTTP_CLUSTER_HTTPS"] == "on"; } A: MVCFutures has a 'RequireSSL' attribute. (thanks Adam for pointing that out in your updated blogpost) Just apply it to your action method, with 'Redirect=true' if you want an http:// request to automatically become https:// : [RequireSsl(Redirect = true)] See also: ASP.NET MVC RequireHttps in Production Only A: Here's a blog post by Pablo M. Cibrano from January 2009 that gathers up a couple of techniques including a HttpModule and extension methods. A: Here's a blog post by Adam Salvo that uses an ActionFilter. A: This isn't necessarily MVC specific, but this solution does work for both ASP.NET WebForms and MVC: http://www.codeproject.com/KB/web-security/WebPageSecurity_v2.aspx I've used this for several years and like the separation of concerns and management via the web.config file. A: MVC 6 (ASP.NET Core 1.0) is working slightly different with Startup.cs. To use RequireHttpsAttribute (as mentioned in answer by Amadiere) on all pages, you could add this in Startup.cs instead of using attribute style on each controller (or instead of creating a BaseController for all your controllers to inherit from). Startup.cs - register filter: public void ConfigureServices(IServiceCollection services) { // TODO: Register other services services.AddMvc(options => { options.Filters.Add(typeof(RequireHttpsAttribute)); }); } For more info about design decisions for above approach, see my answer on similar question about how to exclude localhost requests from being handled by the RequireHttpsAttribute. A: Alternately add a filter to Global.asax.cs GlobalFilters.Filters.Add(new RequireHttpsAttribute()); RequireHttpsAttribute Class using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; namespace xxxxxxxx { public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); GlobalFilters.Filters.Add(new RequireHttpsAttribute()); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/156748", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "81" }
Q: What's the difference between an argument and a parameter? When verbally talking about methods, I'm never sure whether to use the word argument or parameter or something else. Either way the other people know what I mean, but what's correct, and what's the history of the terms? I'm a C# programmer, but I also wonder whether people use different terms in different languages. For the record I'm self-taught without a background in Computer Science. (Please don't tell me to read Code Complete because I'm asking this for the benefit of other people who don't already have a copy of Steve McConnell's marvellous book.) Summary The general consensus seems to be that it's OK to use these terms interchangeably in a team environment. Except perhaps when you're defining the precise terminology; then you can also use "formal argument/parameter" and "actual argument/parameter" to disambiguate. A: There is already a Wikipedia entry on the subject (see Parameter) that defines and distinguishes the terms parameter and argument. In short, a parameter is part of the function/procedure/method signature and an argument is the actual value supplied at run-time and/or call-site for the parameter. The Wikipedia article also states that the two terms are often used synonymously (especially when reasoning about code informally): Although parameters are also commonly referred to as arguments, arguments are more properly thought of as the actual values or references assigned to the parameter variables when the subroutine is called at runtime. Given the following example function in C that adds two integers, x and y would be referred to as its parameters: int add(int x, int y) { return x + y; } At a call-site using add, such as the example shown below, 123 and 456 would be referred to as the arguments of the call. int result = add(123, 456); Also, some language specifications (or formal documentation) choose to use parameter or argument exclusively and use adjectives like formal and actual instead to disambiguate between the two cases. For example, C/C++ documentation often refers to function parameters as formal arguments and function call arguments as actual arguments. For an example, see “Formal and Actual Arguments” in the Visual C++ Language Reference. A: Parameters and Arguments All the different terms that have to do with parameters and arguments can be confusing. However, if you keep a few simple points in mind, you will be able to easily handle these terms. * *The formal parameters for a function are listed in the function declaration and are used in the body of the function definition. A formal parameter (of any sort) is a kind of blank or placeholder that is filled in with something when the function is called. *An argument is something that is used to fill in a formal parameter. When you write down a function call, the arguments are listed in parentheses after the function name. When the function call is executed, the arguments are plugged in for the formal parameters. *The terms call-by-value and call-by-reference refer to the mechanism that is used in the plugging-in process. In the call-by-value method only the value of the argument is used. In this call-by-value mechanism, the formal parameter is a local variable that is initialized to the value of the corresponding argument. In the call-by-reference mechanism the argument is a variable and the entire variable is used. In the call- by-reference mechanism the argument variable is substituted for the formal parameter so that any change that is made to the formal parameter is actually made to the argument variable. Source: Absolute C++, Walter Savitch That is, A: The terms are somewhat interchangeable. The distinction described in other answers is more properly expressed with the terms formal parameter for the name used inside the body of the function and parameter for the value supplied at the call site (formal argument and argument are also common). Also note that, in mathematics, the term argument is far more common and parameter usually means something quite different (though the parameter in a parametric equation is essentially the argument to two or more functions). A: An argument is an instantiation of a parameter. A: Simple Explanations without code A "parameter" is a very general, broad thing, but an "argument: is a very specific, concrete thing. This is best illustrated via everyday examples: Example 1: Vending Machines - Money is the parameter, $2.00 is the argument Most machines take an input and return an output. For example a vending machine takes as an input: money, and returns: fizzy drinks as the output. In that particular case, it accepts as a parameter: money. What then is the argument? Well if I put $2.00 into the machine, then the argument is: $2.00 - it is the very specific input used. Example 2: Cars - Petrol is the parameter Let's consider a car: they accept petrol (unleaded gasoline) as an input. It can be said that these machines accept parameters of type: petrol. The argument would be the exact and concrete input I put into my car. e.g. In my case, the argument would be: 40 litres of unleaded petrol/gasoline. Example 3 - Elaboration on Arguments An argument is a particular and specific example of an input. Suppose my machine takes a person as an input and turns them into someone who isn't a liar. What then is an argument? The argument will be the particular person who is actually put into the machine. e.g. if Colin Powell is put into the machine then the argument would be Colin Powell. So the parameter would be a person as an abstract concept, but the argument would always be a particular person with a particular name who is put into the machine. The argument is specific and concrete. That's the difference. Simple. Confused? Post a comment and I'll fix up the explanation. A: Yes! Parameters and Arguments have different meanings, which can be easily explained as follows: Function Parameters are the names listed in the function definition. Function Arguments are the real values passed to (and received by) the function. A: Parameter is the variable in the declaration of the function. Argument is the actual value of this variable that gets passed to the function. A: They both dont have much difference in usage in C, both the terms are used in practice. Mostly arguments are often used with functions. The value passed with the function calling statement is called the argument, And the parameter would be the variable which copies the value in the function definition (called as formal parameter). int main () { /* local variable definition */ int a = 100; int b = 200; int ret; /* calling a function to get max value */ ret = max(a, b); printf( "Max value is : %d\n", ret ); return 0; } /* function returning the max between two numbers */ int max(int num1, int num2) { /* local variable declaration */ int result; if (num1 > num2) result = num1; else result = num2; return result; } In the above code num1 and num2 are formal parameters and a and b are actual arguments. A: Oracle's Java tutorials define this distinction thusly: "Parameters refers to the list of variables in a method declaration. Arguments are the actual values that are passed in when the method is invoked. When you invoke a method, the arguments used must match the declaration's parameters in type and order." A more detailed discussion of parameters and arguments: https://docs.oracle.com/javase/tutorial/java/javaOO/arguments.html A: Logically speaking,we're actually talking about the same thing. But I think a simple metaphor would be helpful to solve this dilemma. If the metaphors can be called various connection point we can equate them to plug points on a wall. In this case we can consider parameters and arguments as follows; Parameters are the sockets of the plug-point which may take various different shapes. But only certain types of plugs fit them. Arguments will be the actual plugs that would be plugged into the plug points/sockets to activate certain equipments. A: I'm still not happy with all these answers. They all start talking about "function declarations" and my monkey brain has already wandered off and started thinking about unicorns. That doesn't help me remember at all, it's just the definition. I want something that I can immediately and forever hold in my head. The only answer here that I quickly understand is: "Arguments are actual values that are passed in". Arguments are easier to define and as long as you know what they are then you know parameters are the other. The other way I can think of it is: * *Arguments are the variables outside the function *Parameters are the variables inside the function Simplified down to: Arguments outside, parameters inside If any one wants to disagree with me, you can leave your arguments outside ;) A: A parameter is something you have to fill in when you call a function. What you put in it is the argument. Simply set: the argument goes into the parameter, an argument is the value of the parameter. A bit more info on: http://en.wikipedia.org/wiki/Parameter_(computer_science)#Parameters_and_arguments A: When we create the method (function) in Java, the method like this.. data-type name of the method (data-type variable-name) In the parenthesis, these are the parameters, and when we call the method (function) we pass the value of this parameter, which are called the arguments. A: According to Joseph's Alabahari book "C# in a Nutshell" (C# 7.0, p. 49) : static void Foo (int x) { x = x + 1; // When you're talking in context of this method x is parameter Console.WriteLine (x); } static void Main() { Foo (8); // an argument of 8. // When you're talking from the outer scope point of view } In some human languages (afaik Italian, Russian) synonyms are widely used for these terms. * *parameter = formal parameter *argument = actual parameter In my university professors use both kind of names. A: It's explained perfectly in Parameter (computer programming) - Wikipedia Loosely, a parameter is a type, and an argument is an instance. In the function definition f(x) = x*x the variable x is a parameter; in the function call f(2) the value ``2 is the argument of the function. And Parameter - Wikipedia In computer programming, two notions of parameter are commonly used, and are referred to as parameters and arguments—or more formally as a formal parameter and an actual parameter. For example, in the definition of a function such as y = f(x) = x + 2, x is the formal parameter (the parameter) of the defined function. When the function is evaluated for a given value, as in f(3): or, y = f(3) = 3 + 2 = 5, is the actual parameter (the argument) for evaluation by the defined function; it is a given value (actual value) that is substituted for the formal parameter of the defined function. (In casual usage the terms parameter and argument might inadvertently be interchanged, and thereby used incorrectly.) A: Parameter is a variable in a function definition Argument is a value of parameter <?php /* define function */ function myFunction($parameter1, $parameter2) { echo "This is value of paramater 1: {$parameter1} <br />"; echo "This is value of paramater 2: {$parameter2} <br />"; } /* call function with arguments*/ myFunction(1, 2); ?> A: Let's say you're an airline. You build an airplane. You install seats in it. Then, you fill the plane up with passengers and send it somewhere. The passengers disembark. Next day, you re-use the same plane, and same seats, but with different passengers this time. The plane is your function. The parameters are the seats. The arguments are the passengers that go in those seats. function fly(seat1, seat2) { seat1.sayMyName(); // Estraven seat2.sayMyName(); etc. } var passenger1 = "Estraven"; var passenger2 = "Genly Ai"; fly(passenger1, passenger2); A: The use of the terms parameters and arguments have been misused somewhat among programmers and even authors. When dealing with methods, the term parameter is used to identify the placeholders in the method signature, whereas the term arguments are the actual values that you pass in to the method. MCSD Cerfification Toolkit (Exam 70-483) Programming in C#, 1st edition, Wrox, 2013 Real-world case scenario // Define a method with two parameters int Sum(int num1, int num2) { return num1 + num2; } // Call the method using two arguments var ret = Sum(2, 3); A: Or even simpler... Arguments in ! Parameters out ! A: I thought it through and realized my previous answer was wrong. Here's a much better definition {Imagine a carton of eggs: A pack of sausage links: And a maid } These represent elements of a Function needed for preparation called : (use any name: Lets say Cooking is the name of my function). A Maid is a method . ( You must __call_ or ask this method to make breakfast)(The act of making breakfast is a Function called Cooking)_ Eggs and sausages are Parameters : (because the number of eggs and the number of sausages you want to eat is __variable_ .)_ Your decision is an Argument : It represents the __Value_ of the chosen number of eggs and/or sausages you are Cooking ._ {Mnemonic} _" When you call the maid and ask her to make breakfast, she __argues_ with you about how many eggs and sausages you should eating. She's concerned about your cholesterol" __ ( Arguments , then, are the values for the combination of Parameters you have declared and decided to pass to your Function ) A: Simple: * *PARAMETER → PLACEHOLDER (This means a placeholder belongs to the function naming and be used in the function body) *ARGUMENT → ACTUAL VALUE (This means an actual value which is passed by the function calling) A: Always Remember that: Arguments are passed while parameters are received. A: Generally speaking, the terms parameter and argument are used interchangeably to mean information that is passed into a function. Yet, from a function's perspective: * *A parameter is the variable listed inside the parentheses in the function definition. *An argument is the value that is sent to the function when it is called. A: Or maybe it's even simpler to remember like this, in case of optional arguments for a method: public void Method(string parameter = "argument") { } parameter is the parameter, its value, "argument" is the argument :) A: In editing, I'm often put off at how people forget: structure languages are based on natural languages. In English A "parameter" is a placeholder. They set the response format, in spoken language. By definition, it's party to the call, limiting the response. An "argument" is a position that is being considered. You argue your opinion: you consider an argument. Main difference The thematic role of an argument is agent. The thematic role of parameter is recipient. Interactions Think of the argument as the male part, making the parameter the female part. The argument goes into the parameter. Usage A parameter is usually used in definitions. An argument is usually used in invocations. Questions Finish the sentence to make it less dissonant. (A) Speaking of a definition: * *What argument will be used []? *What [] will this parameter []? (B) Speaking of an invocation: * *What parameter will you use, []? *What [] will be [] this parameter? Answers (A) * *on/in/against/with this parameter *argument(s) ... take (B) * *and what are some example arguments *argument(s) ... used on/in/against/with Overlaps As you can imagine, after answering: in spoken language, these words will sometimes produce identical responses! So, as a rule: * *Usually if someone wants parameter information, they want to know more about the type, the variable name, etc. They may become confused if you only give example arguments. * *Usually if someone wants argument information, they want to know what value you passed to a function or its parameter(s). A: A parameter is a variable in the declaration of the function. An argument is the actual value of the variable that gets passed to the function. A: A parameter is a variable in a method definition. When a method is called, the arguments are the data you pass into the method's parameters. public void MyMethod(string myParam) { } ... string myArg1 = "this is my argument"; myClass.MyMethod(myArg1); A: The parameters of a function/method describe to you the values that it uses to calculate its result. The arguments of a function are the values assigned to these parameters during a particular call of the function/method. A: This example might help. int main () { int x = 5; int y = 4; sum(x, y); // **x and y are arguments** } int sum(int one, int two) { // **one and two are parameters** return one + two; } A: Parameters are the variables received by a function.Hence they are visible in function declaration.They contain the variable name with their data type. Arguments are actual values which are passed to another function. thats why we can see them in function call. They are just values without their datatype A: The formal parameters for a function are listed in the function declaration and are used in the body of the function definition. A formal parameter (of any sort) is a kind of blank or placeholder that is filled in with something when the function is called. An argument is something that is used to fill in a formal parameter. When you write down a function call, the arguments are listed in parentheses after the function name. When the function call is executed, the arguments are plugged in for the formal parameters. The terms call-by-value and call-by-reference refer to the mechanism that is used in the plugging-in process. In the call-by-value method only the value of the argument is used. In this call-by-value mechanism, the formal parameter is a local variable that is initialized to the value of the corresponding argument. In the call-by-reference mechanism the argument is a variable and the entire variable is used. In the call- by-reference mechanism the argument variable is substituted for the formal parameter so that any change that is made to the formal parameter is actually made to the argument variable. A: Parameters are variables that are used to store the data that's passed into a function for the function to use. Arguments are the actual data that's passed into a function when it is invoked: // x and y are parameters in this function declaration function add(x, y) { // function body var sum = x + y; return sum; // return statement } // 1 and 2 are passed into the function as arguments var sum = add(1, 2); A: You need to get back to basics.Both constructors and methods have parameters and arguments.Many people even call constructors special kind of methods.This is how a method is declared parameters are used: type name(parameters){ //body of method } And this is how a constructor is declared parameters are used: classname(parameters){ //body } Now lets see an example code using which we calculate the volume of a cube: public class cuboid { double width; double height; double depth; cuboid(double w,double h,double d) { //Here w,h and d are parameters of constructor this.width=w; this.height=h; this.depth=d; } public double volume() { double v; v=width*height*depth; return v; } public static void main(String args[]){ cuboid c1=new cuboid(10,20,30); //Here 10,20 and 30 are arguments of a constructor double vol; vol=c1.volume(); System.out.println("Volume is:"+vol); } } So now you understand that when we call a constructor/method on an object at some place later in the code we pass arguments and not parameters.Hence parameters are limited to the place where the logical object is defined but arguments come into play when a physical object gets actually created. A: As my background and main environment is C, I will provide some statements/citations to that topic from the actual C standard and an important reference book, from also one of the developers of C, which is often cited and common treated as the first unofficial standard of C: The C Programming Language (2nd Edition) by Brian W. Kernighan and Dennis M. Ritchie (April 1988): Page 25, Section 1.7 - Functions We will generally use parameter for a variable named in the parenthesized list in a function definition, and argument for the value used in the call of the function. The terms formal argument and actual argument are sometimes used for the same distinction. ISO/IEC 9899:2018 (C18): 3.3 argument actual argument DEPRECATED: actual parameter expression in the comma-separated list bounded by the parentheses in a function call expression, or a sequence of preprocessing tokens in the comma-separated list bounded by the parentheses in a function-like macro invocation. 3.16 parameter formal parameter DEPRECATED: formal argument object declared as part of a function declaration or definition that acquires a value on entry to the function, or an identifier from the comma-separated list bounded by the parentheses immediately following the macro name in a function-like macro definition. A: Arguments are actual values passed to parameters. A: * *Parameter: * *A value that is already "built in" to a function. *Parameters can be changed so that the function can be used for other things. *Argument: * *An input to a function *A variable that affects a functions result. Source A: Consider the below java code. public class Test{ public String hello(String name){ return "Hello Mr."+name; } public static void main(String args[]){ Test test = new Test(); String myName = "James Bond"; test.hello(myName); } } The method definition of hello(String name) declares a String parameter called name. In the main method we are calling the hello method by passing the argument myName. So parameter is the placeholder where as argument is the actual value for a method. A: This is a key:value issue... The parameter is the key The argument is the value /****************************************/ Example: name: "Peter" /********/ let printName = (name) => console.log(name) printName("Peter") /********/ In this case, the parameter is "name", the argument is "Peter"
{ "language": "en", "url": "https://stackoverflow.com/questions/156767", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "978" }
Q: How can I find similar address records? The workflow is like this: * *I receive a scan of a coupon with data (firstname, lastname, zip, city + misc information) on it. *Before I create a new customer, I have to search the database if the customer might exist already. Now my question: What's the best way to find an existing customer, when there is no unique ID available? PS: I do have a unique ID in the database, just not on the coupons we receive ;) A: We are using the Levenshtein distance algorithm to check users for duplication. However we have quite strict rules to enter the data itself, so we have to check only for misstyping, case differences and such. A: See this previous question: Parse usable Street Address, City, State, Zip from a string. Soundex would help you if you require similiar matches. A: If you really want to do this the right way, the easy way, the complete way you'll buy Netrics. http://www.netrics.com/ We bought it, and wrapped an application around it that lets our employees match anything they want. The can configure confidence intervals for each column, build thesauri where you can map Robert to Bob, and John to Jack. It's amazing and used by some of the larger institutions in the country for scrubing various lists. A: If you have SQL Server 2005, you can bring your data in through SSIS and use a fuzzy lookup to check for sameness. A: You query the database for all customers that match the given data, e.g. SELECT ID FROM tbl_customers WHERE first_name LIKE 'JOHN' AND last_name LIKE 'Doe' AND zip_code=12345 AND city LIKE 'Ducktown' If the number of rows returned is 0, create a new entry in the database. If it is 1, the query will give you the ID. If it is > 1 you may have several customers of the same name living in the same area, need to find a way to deal with this situation. But that would justify a new question here ;-) p.s.: If you have no unique ID at all, redesign your database.
{ "language": "en", "url": "https://stackoverflow.com/questions/156769", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is there any website which showcase nice / comprehensive build.xml? What i mean exactly is that build.xml that actually included those plugins like findbugs etc. Or nicely done build.xml A: A great resource for sample Ant build files is Google code search. Search Google Code for build.xml. Once you search, narrow it down to "Project Hosting" to get the real meat. You will find dozens of examples of real, working, usable build.xml files. For example, here's the build file for Firebug, the build file for the Clojure language, the build file for GWT and the build file for Google Guice. Of course, there are other fine repositories of source code, here is a build.xml file search on GitHub, a Google search of SourceForge.net for build.xml files and a Google search of RIAForge.org for build.xml files Another good way to find quality build files is a Google search for build.xml in the URL, which will result with a good variety. Add to that query an aspect or programming language of choice, and you will have what you need in no time. A: I created the project Antiplate to create a build-template for typical Java-projects. You can look into it's template-dir for some solutions for typical problems. Findbugs isn't included (yet), but PMD, Checkstyle, Emma and some other stuff. It's splitted over different files, so the ant-code should be understandable. The main stuff can be found in the .xml-files in this directory. This is a link directly in the SVN of Antiplate, that shows the content of the imported .xml-files, that contain all the tasks. The file doc.xml contains the generation of the reports with emma, cpd, checkstyle etc. I hope the links directly in the source help to understand how to implement such task yourself. A: I know this is not exactly what you asked for. But if you want to use ant, you'll need to read this piece: Ant in anger. Yes: I know you just want some hack'n'slash examples; read the piece Yes: I know you just want your problem solved; read the piece Once an ant file reach beyond a certain threshold, it'll cease being nice. And nice examples will ever be to small to get you anywhere interesting. So just stop trying to copy paste eleven lines of arbitrary xml and;... yeah, I think you got it by now ;) A: You could use maven 2, because it has built-in plugin support.And all the stuff like: PMD, Findbugs, Checkstyle etc , could be integrated automatically . If you have some existing code it could be called from maven you could use maven-antrun-plugin.
{ "language": "en", "url": "https://stackoverflow.com/questions/156770", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Distributed corporate collaboration tools I'm looking for a corporate collaboration tool to help bring together my team, who are geographically and organisationally distributed. Some team members operate on client sites, behind corporate firewalls and similar. The restrictions I have are: * *Must allow creation of persistent 'channels' (i.e. not just one-to-one or one-to-many chats). *Must be free (or very close to it). *Must be commonly available through corporate firewalls (i.e. operate on port 80 or similar). I'm aware no solution will be guaranteed to work through every firewall, but one that allows us to avoid the common restrictions is important. *Must have a desktop/alert agent, to allow users to be alerted if/when new messages arrive in channels they are listening to. *If at all possible, should have a feature to allow the app to start at login/boot time, so developers don't have to remember to activate it, or manually sign in. Does anyone have any recommendations which meet these criteria? I have so far considered: * *Google Talk: Fails the 'channels' test - group chats are also only available via the web interface. *CampFire: Fails the desktop alert and auto-start function. Requires users to open web browser, navigate, log in, etc. Also fails the 'free' test, but only just. Price wouldn't be an object if these other failures could be overcome. *www.24im.com: Fails the 'common corporate firewalls' test - this communicates on ports 10880-10889, which are blocked on all corporate firewalls we tested. A: Skype meets all your requirements. A: Just use Skype. It's free, it has excellent chatting capabilities, works over firewalls, supports lots of collaboration features out of box and plenty more as plugins. P.S. It is also supported natively on Windows Mobile and has good clients on other mobile platforms (like Fring on S60) A: OpenFire + Spark are good, very good. There is a beta plugin to integrate both with red5 and enable video and audio stream. AFAIK, Spark already have support for SIP. Kind Regards A: IIRC google talk uses the jabber protocol internally. You should be able to connect to it with any client and some of them should offer the channels functionality. Alternatively, you could set up your own jabber server if you want to keep your data away from google's eyes. A: Sadly, Skype is blocked on our own corporate network, though I'm not sure by what mechanism or logic. I'm going to pursue Jabber/XMPP clients. A: IRC? If you host it on your own server you can run it on port 80 if you damn well please. Just make sure it doesn't crash and burn when it gets stray web requests. :P
{ "language": "en", "url": "https://stackoverflow.com/questions/156774", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to output a CDATA section from a Sax XmlHandler This is a followup question of How to encode characters from Oracle to Xml? In my environment here I use Java to serialize the result set to xml. I have no access to the output stream itself, only to a org.xml.sax.ContentHandler. When I try to output characters in a CDATA Section: It happens basically like this: xmlHandler.startElement(uri, lname, "column", attributes); String chars = "<![CDATA["+rs.getString(i)+"]]>"; xmlHandler.characters(chars.toCharArray(), 0, chars.length()); xmlHandler.endElement(uri, lname, "column"); I get this: <column>&lt;![CDATA[33665]]&gt;</column> But I want this: <column><![CDATA[33665]]></column> So how can I output a CDATA section with a Sax ContentHandler? A: It is getting escaped because the handler.characters function is designed to escape and the <![CDATA[ part isn't considered part of the value. You need to use the newly exposed methods in DefaultHandler2 or use the TransformerHandler approach where you can set the output key CDATA_SECTION_ELEMENTS, which takes a whitespace delimited list of tag names that should output sub text sections enclosed in CDATA. StreamResult streamResult = new StreamResult(out); SAXTransformerFactory tf = (SAXTransformerFactory) SAXTransformerFactory.newInstance(); TransformerHandler hd = tf.newTransformerHandler(); Transformer serializer = hd.getTransformer(); serializer.setOutputProperty(OutputKeys.CDATA_SECTION_ELEMENTS, "column"); hd.setResult(streamResult); hd.startDocument(); hd.startElement("","","column",atts); hd.characters(asdf,0, asdf.length()); hd.endElement("","","column"); hd.endDocument(); A: You should use startCDATA() and endCData() as delimiters, i.e. xmlHandler.startElement(uri, lname, "column", attributes); xmlHandler.startCDATA(); String chars = rs.getString(i); xmlHandler.characters(chars.toCharArray(), 0, chars.length()); xmlHandler.endCDATA(); xmlHandler.endElement(uri, lname, "column");
{ "language": "en", "url": "https://stackoverflow.com/questions/156777", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: C# - How do I define an inline method Func as a parameter? I've written a simple SessionItem management class to handle all those pesky null checks and insert a default value if none exists. Here is my GetItem method: public static T GetItem<T>(string key, Func<T> defaultValue) { if (HttpContext.Current.Session[key] == null) { HttpContext.Current.Session[key] = defaultValue.Invoke(); } return (T)HttpContext.Current.Session[key]; } Now, how do I actually use this, passing in the Func<T> as an inline method parameter? A: Why don't you pass the default value directly? What use is the functor? By the way, defaultValue.Invoke() is quite verbose. It's also possible to just write defaultValue(). A: Since that is a func, a lambda would be the simplest way: Foo foo = GetItem<Foo>("abc", () => new Foo("blah")); Where [new Foo("blah")] is the func that is invoked as a default. You could also simplify to: return ((T)HttpContext.Current.Session[key]) ?? defaultValue(); Where ?? is the null-coalescing operator - if the first arg is non-null, it is returned; otherwise the right hand is evaluated and returned (so defaultValue() isn't invoked unless the item is null). Finally, if you just want to use the default constructor, then you could add a "new()" constraint: public static T GetItem<T>(string key) where T : new() { return ((T)HttpContext.Current.Session[key]) ?? new T(); } This is still lazy - the new() is only used if the item was null. A: var log = SessionItem.GetItem("logger", () => NullLog.Instance) Note, than normally you can skip {T} specification in the GetItem{T} call (if Func{T} returns object of the same type)
{ "language": "en", "url": "https://stackoverflow.com/questions/156779", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Does .NET Reporting Services support vectorial graphics? After diving into the www, I don't have a clue about the support of vectorial grahics/image by reporting services. It seems to be impossible. We are using Reporting Services with a PDF rendering and we are forced to use raw bitmap into reports. That leads to huge sized reports. We know that dealing with vectorial graphics will help but such feature seems to be not supported by reporting services. A: No, there are no known ways to insert vector graphics within SQL Reporting Services. Now since RDL 2.0 some support for HTML is supported but I'm not sure if that would include VML or anything adequate for showing graphics. I have the same need and have been communicating as much as possible with those involved in SQL Reporting Services and other RDL based alternatives such as DataDynamic Reports and FYI Reporting to see if I can get this type of support. So far DataDynamics Reports support people claim to have "better EMF and CRI support" but the others have no such capabilities nor do they have any publicly known plans to implement them. For more information see my post on the MSDN forums regarding whether OLE object or EMF image support would be introduced in any future versions of SQL Server Reporting Services. As for those who may be willing to implement a solution themselves I think balaweblog is right in that a custom report item could be created to render vector graphic in your preferred format, but that requires that you basically write the control that isn't supplied by Microsoft and write a rendering engine if your format isn't directly supported on the system or in the .NET Framework for example (SVG comes to mind). Update: It appears somebody else also is looking to implement vector graphics in FYI Reporting however they seem to be running into the same roadblock that many have when trying to export to PDF. A: There have been problems in the past with SQL Reporting Services and PDF compression. If you are creating serverreports in a version prior to 2005 or localreports in a version prior to 2008 the hugh pdf files could be caused by the compression issue. http://forums.asp.net/t/1066296.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/156782", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: IE6 crashes while displaying simple site I have a really strange problem with an quite simple ASP.NET (.NET 3.5) Site and the IE6. It seems sometimes and on certain machines, the IE6 crashes while displaying the site. CSS was already eliminated as a reason for the crashes. After a while of research, I was not able to find a reason for the crashes and could not reproduce it properly. The site works on all browsers, except IE6 and it crashes only on certain machines, not everywhere. Any idea what this could be? [Edit] When IE crashes, I get the Windows-Exception Dialog and have to close IE6: not just a warning or something. A: A couple of things you could try: * *Check if any IE plug-ins (toolbars, etc) are installed on the machines in question, and try disabling all of them. *Check the Windows Event Log to see if the crash has left any clues. If you want to get really hardcore, you could follow Mark Russinovich's Guide to analyzing the process crash data to determine what if anything could be causing the issue. In his case it turned out to be an Nvidia component that caused IE to randomly crash. A: How exactly does IE 6 crash? If you are getting the infamous Operation Aborted error try moving any JavaScript to the foot of the page just above the closing tag to see if that helps. A: I get the Windows-Exception Dialog and have to close IE6 A: Try looking at the event log (control panel/admin tools/event viewer) and then double click on application. That might give you some clues. A: IE 6 has multiple versions - Service Pack 1, Service Pack 2, Service Pack 3 and of course, no service pack. Try looking at the version information for the browser's on which it crashes and see if you can narrow down the problem there. To try and see what the problem is, I suggest stripping down the page as much as possible, and adding elements to it until you can reproduce the problem. IE 6 is bizarre. Check out this link: http://immike.net/blog/2007/08/06/single-line-of-html-crashes-ie-6/ Where the author points out that it is possible to crash IE6 with a single line of valid HTML. A: As you've already eliminated CSS as being the cause I would try checking that your HTML validates against your DOCTYPE, then try visiting the page with JavaScript disabled to see if either of these can be eliminated as well. A: I assume this has already been solved (at least I hope by now) but I just had a very similar question asked. The answer for my problem was that input tags were not being closed and the page's DTD was XHTML which has OMITTAG NO as the default. So you may want to ensure that all tags are either self-closed (Which will validate XHTML transitional, not Strict) or with Good luck, Jeremy
{ "language": "en", "url": "https://stackoverflow.com/questions/156798", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What is data area? In C++ the storage class specifier static allocates memory from the data area. What does "data area" mean? A: I'm not familiar with the term “data area” but memory is often divided into “code section” and “data section”. Code resides in the former, data in the latter. I presume this is what's meant here. Classically, there's no distinction between the two. However, many modern operating systems can prohibit the execution of code int he data segment (provided the CPU supports this distinction). This sometimes goes by the catch phrase of “NX flag”, as in “no execution” and can effectively prevent some cases of malicious code injection. /EDIT: Notice that the C++ standard doesn't mention a “data area”. A: The names of the areas vary by platform, compiler and linker. In general, there are: * *program text: The executable code space. *constants: Non-executable constants. *stack: The stack. *bss: Broadly "statics" in C/C++ terms. "Block Started by Symbol" *data: Uninitialised globals *heap: Storage allocated at runtime. In this case the documentation in question is using the name "data area" for what is traditionally called the bss segment. In C terms, the storage class specifier "static" means memory that exists for the lifetime of the program and is initialised to zero or value of the initialiser. In the example: static int s_value_one; static int s_value_two = 123; The value of s_value_one is guaranteed to be zero and the value of s_value_type is 123 at the point of the first statement in main(). How this comes to be true is an implementation issue. A: In addition to what Konrad said, declaring a variable as static basically means that the memory for it gets allocated with the program as it is loaded, as opposed to on the heap or the stack. Historically, using only static variables in a critical applications meant that the memory footprint of the application would not change at run-time and hence it was less likely to fail due to resource limitations. Don't know if this is still true of modern operating systems. If you get your compiler to generate a mapfile as part of its output, you can have a look see at what is in all the various sections, including data. A: What Konrad said. I'd like to add that there are still CPUs out there that can't read data if it's placed in the code section and vice versa. These have been more common decades ago, but they are still alive in the embedded world. In a nutshell the linker just groups symbols of equal kind together. On the PC you often have even more than simple code and data areas. You will find areas for uninitialized data, read only data and other OS dependent stuff as well. A: With little googling I found more information on these subjects here: * *http://www.informit.com/articles/article.aspx?p=31783&seqNum=4 *http://www.codeguru.com/cpp/tic/tic0111.shtml A: There are many places that data might end up. Usually, local variables are allocated on the stack, and you can allocate things on the heap using malloc (or de default version of 'new'). Static data, however, is usually allocated when your program starts, and might end up anywhere -- where exactly is up to the compiler, OS, and executable format. A: Executable has lots of information in it. An executable, has many types / classes of data stored inside its physical file. eg's are * *Executable code instructions *Resources *Dependency information (which dlls this binary depends on) *The symbols that are exported from this binary etc There needs to be some way to organize all this information inside the .exe file format such that the OS can easily find all the information and load the executable and get things working. For this purpose a common binary format (created by M$ of-course) called PE (portable Executable) is used in the windows world. All the information i just listed (and many more) are described in detail in different sections of the binary. .data section One such section is the .data section. The .data section contains all the initialized global and static data, while the .bss section contains the uninitialized global data. Why do you require a separate section for globals ? Well, a global behaves like a global because it is created in an area of memory that exists for the lifetime of a program and is not a temporary data structure like a stack which might be overwritten / reused. (like normal auto variables). Compiler Therefore these variables need to be allocated in some permanent address in the heap, which unfortunately cannot be known at the time of compilation. So the compiler places all the global and static variables in this .data / .bss section, and the instructions that refer to these variables refer to these relatively permanent addresses in the .data / .bss. Linker When the linker loads the executable in the real world, it decides where these sections have to be placed and creates FIX UPs for these temp addresses such that the instructions that refers to the globals refer to the now real virtual addresses in the programs memory. Now you know what the .data section / area is and why the globals needs to be allocated some space in that area and how that helps the program in real time. Googling PE format and linker and .data section etc would get you the links. A: I think 'data area' is referring to the heap, whereas local variables would usually be located on the stack. Or it means that the memory allocated for this variable is located in the .data section of the executable, but that would be specific to Windows and the PE format.
{ "language": "en", "url": "https://stackoverflow.com/questions/156799", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Silverlight display problem I have created a nice silverlight control doing exactly what I want it to do, and it looks great :) When I host it in the test projects ASPX sample file or the HTML sample file it shows up nicely. I now have to use the control in my existing ASP.NET 2.0 project, which has a fancy design. The problem I'm having is that the control don't show up exactly how it should: * *The loading progress don't show *The control usually don't become visible before I move my mouse over the aria where it's contained Obviously it's something with my HTML/CSS design causing this, but it will be extremely time consuming to find the issue - so does anyone have knowledge in this area? What are the rules around how to make sure the control is displayed properly? What CSS properties should be used? PS: Since I have a 2.0 app, I'm using the object tag approach to Silverlight, and it's contained in a DIV with height and width set in style. Code snippet was requested. It's something like this (basically a copy of the HTML test page from the silverlight test project (which work perfectly)): <div id="silverlightControlHost" style="height: 300px; width: 750px;"> <object data="data:application/x-silverlight," type="application/x-silverlight-2-b2" width="100%" height="100%"> <param name="source" value="Contiki.SilverLight.FileUploader.xap" /> <param name="onerror" value="onSilverlightError" /> <param name="background" value="white" /> <a href="http://go.microsoft.com/fwlink/?LinkID=115261" style="text-decoration: none;"> <img src="http://go.microsoft.com/fwlink/?LinkId=108181" alt="Get Microsoft Silverlight" style="border-style: none" /> </a> </object> <iframe style='visibility: hidden; height: 0; width: 0; border: 0px'></iframe> </div> This DIV is contained in a cell in a table, which again is part of a larger design. There's a lot of CSS as mentioned. Don't know if this helps... A: Found the cause myself... It turns out Silverlight has a display problem when the control is placed in a html table. Found information about this on the silverlight forum. It was about the beta 2, but I have upgraded to the release version, and it's still a problem. Try this. Add a height and a width to the table containing the Silverlight control. You may also want to add a single character of white space inside the TD containing the control. Basically when the table was rendered it couldn't 'see' the size of the contents so it either didn't render at all or only rendered to the size of a single white-space character. -- John Stockton My design is quite complex with nested tables, so I haven't actually been able to make it work yet. UPDATE: The actual fix I ended up implementing was a small JavaScript that "refreshes" the containing <DIV>. Here it is: <script type="text/javascript"> function refreshSL() { var div = document.getElementById('silverlightControlHost'); div.style.display = 'block'; } refreshSL(); </script> I placed this in my HTML below the actual SL markup, and then it worked (I guess calling it on the page loaded event would be the proper thing to do. A: CSS issues can be difficult to debug sometimes. Is the behavior the same in different browsers? Is your CSS using "float"s anywhere? Does the app work properly on the same page outside of the table and then outside of the div? A: As Adam says, CSS issues are a real PITA. Typically when I run into something like this I start by pointing to a blank CSS instead of the "fancy" one and then start adding the styles back in until I'm able to reproduce the issue. A: LOL I had the same exact problem and it was driving me mad. The problem was isolated to Internet Explorer. Works fine in all other browsers (even Opera). Your solution is a hack for sure. Since this is really a work around for a bug in IE you can officially get away with it. Technically we should not be using tables for layout but in the real world it is the only way to get things to work consistantly cross browsers.
{ "language": "en", "url": "https://stackoverflow.com/questions/156800", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Download files to local drive when sshed What is the best way to download files to local hard drive when logged in to another computer using ssh in bash. I'm aware of sftp, but it is not convienent, e.g. it lacks tab completion of directory names. I'm using Ubuntu 8.04.1 . I don't have a public IP and would not like to setup dynamic Dynamic DNS solution. A: I'm also running Ubuntu 8.04.1, and if I type $ scp me@myserver.mydomain.com:.bashr<TAB> I do indeed get tab completion (i.e. bash is sshing to my server and getting completion results from the filesystem there). Then $ scp me@myserver.mydomain.com:.bashrc . copies my .bashrc from my server to the current directory on my local machine. If you don't get this, try sudo apt-get install bash-completion, and check that your .bashrc contains the following lines (mine did by default): # enable programmable completion features (you don't need to enable # this, if it's already enabled in /etc/bash.bashrc and /etc/profile # sources /etc/bash.bashrc). if [ -f /etc/bash_completion ]; then . /etc/bash_completion fi A: How about FISH? ***Fi***le transfer over ***Sh***ell - You can use Midnight Commander in your console: $ sudo apt-get install mc $ mc Then hit F9; Right (for the Right panel) -> Shell link Type in the ssh link of the remote host. At the prompt enter machine name specify: user@host The system will prompt for the password (or auto login if your SSH keys are setup for that) Now you can browse the remote filesystem, select and copy over (F5) as you wish. A: I don't know. I'd $ scp host:file locallocation A: As far as I know there is no simply scp-on-steroids that lets you autocomplete on remote folder-structures. If you just want to basically mount a remote folder, take a look at sshfs. Or just try mounting a remote directory with ssh://... within Nautilus. A: I actually like to use the command line SCP client. :) I do not know how it does this, but my SCP on Ubuntu (from openssh-client 1:4.7p1-8ubuntu1.2) actually does tab-completion of remote directories and files on hosts where I usually auth via public key. A: ssh-xfer is what you are looking for. Once you have it set up, you can type (from within the ssh session on the remote machine): $ ssh-xfer foo.txt and foo.txt will magically show up on your local machine.
{ "language": "en", "url": "https://stackoverflow.com/questions/156810", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Explain x => x.ToString() //simplify so many calls In a question answer I find the following coding tip:- 2) simple lambdas with one parameter: x => x.ToString() //simplify so many calls As someone who has not yet used 3.0 I don't really understand this tip but it looks interesting so I would appreciate an expantion on how this simplifies calls with a few examples. I've researched lambdas so I think I know what they do, however I may not fully understand so a little unpacking might also be in order. A: When you need to create an instance of a delegate which has a single parameter, lambda expressions allow you to create that delegate "inline" in a very concise manner. For instance, here's code to find a particular person in a list, by their name: List<Person> list = new List<Person>(); // [..] Populate list here Person jon = list.Find(p => p.Name == "Jon"); In C# 2.0 you could use an anonymous method which was a little bit more longwinded, but not too bad: List<Person> list = new List<Person>(); // [..] Populate list here Person jon = list.Find(delegate(Person p) { return p.Name == "Jon"; }); In C# 1.0 you'd have to create a whole extra method. In addition, if you wanted to parameterise it, you'd have to create a different type, whereas anonymous methods and lambda expressions capture their executing environment (local variables etc) so they act like closures: public Person FindByName(List<Person> list, String name) { return list.Find(p => p.Name == name); // The "name" variable is captured } There's more about this in my article about closures. While passing delegates into methods isn't terribly common in C# 2.0 and .NET 2.0, it's a large part of the basis of LINQ - so you tend to use it a lot in C# 3.0 with .NET 3.5. A: This basically expands to: private string Lambda(object x) { return x.ToString(); } A: Are you familiar with C# 2.0 anonymous methods? These two calls are equivalent (assuming SomeMethod accepts a delegate etc): SomeMethod(x => x.ToString()); SomeMethod(delegate (SomeType x) { return x.ToString();}); I know which I'd rather type... A: string delegate(TypeOfX x) { return x.ToString(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/156815", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Online viewing of server logs? Is this encouraged? I understand that this could be a big security issue if people manage to hack it and able to view the server logs. Is there any application that can actually grab logs and display via web interface with the necessary security imposed? I am talking about java enterprise application A: Take a look at Splunk. http://www.splunk.com/ This tool is likely overkill for what you are looking for, but should do the job. A: I haven't tried any of the products available, but often thought about it trying. I even implemented some log analysis tools myself. Maybe have a look at this "commercial" A: I have recently worked with a large web-based application which would have a separate menu entry for debugging, available to selected users -- and provided it was first activated in the first place. Even though the solution implemented was kind of short on features -- it just showed the .log file as is onscreen --, it usually did the job. Since we as developers had full access to the server (usually in a VM), we'd often use a tool such as BareTail for convenient features such as line highlighting and following tail, but if you can't always access the server and your time allows it, you should consider implementing the best of both worlds, which may not be very complex.
{ "language": "en", "url": "https://stackoverflow.com/questions/156817", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Redirect ILog Messages I'm currently developing a RCP Eclipse Application. For logging purposes I use SFL4J over log4j. For my own code this works well since I can specify the correct logger ( LoggerFactory.getLogger ... logger.debug...). But how can I redirect all the plugin logs to the same location, so that I can see all exceptions from other rcp plugins also in my log4j-LogFile. How can I log uncaught exceptions in my log-file? I heard something about ILog but I'm not aware how to redirect this to my log4j/slf4j implementation. So what is the best way to log all plugin messages in one log file? A: To capture log events for the entire platform, create an ILogListener instance and register it using Platform.addLogListener(ILogListener). As for logging uncaught exceptions, one way to do it is to create a new ThreadGroup and override uncaughtException(Thread t, Throwable e) to log the exception. You then have to start a new thread in that thread group and do everything else inside it. I take care of this in the run method of my implementation of IPlatformRunnable.
{ "language": "en", "url": "https://stackoverflow.com/questions/156821", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: database synchronization - SFTP / RMAN / By codes? Which method you all will recommend and why? A: Since you mention RMAN, may I assume that you are talking in particular about an Oracle database? Or are you talking about a more generic problem? What is the business purpose of synchronizing the databases? That is going to strongly influence the choice of technology. In the Oracle world, you would have DataGuard if you wanted to have a hot standby, RAC if you wanted to have a single database with load spread across multiple physical nodes of a cluster, Streams and multi-master replication if you wanted to have load spread across multiple geographically distributed databases, RMAN if you wanted to periodically clone a test database from production, etc.
{ "language": "en", "url": "https://stackoverflow.com/questions/156830", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to consume a wcf service when i only know its URL I need to consume a wcf service dynamically when all i know is its URL. I do not have the option of creating a service reference or web reference as my client side code picks up the URL from a config file. What classes and methods can i use from the System.ServiceModel namespace for doing so. A: If you don't have the service interface, you must, at the very least, have an idea as to what the messages the server expects look like; otherwise it be pretty hard to do :) But there is certainly a way to do that. You can start by creating the raw message the server expects as input, and create it in a Message object (I mean System.ServiceModel.Channels.Message). Make sure that you set all the necessary headers to it, depending on what binding you expect to use to call the client (like setting the right credentials, the right MessageVersion and so on). Then you can simply create a channel factory using one of the standard, generic channel shapes like IRequestChannel or IInputChannel (for one-way services), and use the channel factory to create a new channel and invoke the service. I.e. something like: Message input = Message.CreateMessage( .... ); ChannelFactory<IRequestChannel> factory = new ChannelFactory<IRequestChannel>(binding, endpoint); IRequestChannel channel - factory.CreateChannel(); Message output = channel.Send(input); A: If you know the contract then you can do something like: using (WebChannelFactory<IService> wcf = new WebChannelFactory<IService>(new Uri("http://localhost:8000/Web"))) More here
{ "language": "en", "url": "https://stackoverflow.com/questions/156833", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Undefined Variable in php I have inherited some code for a custom CMS that is a little out of my league and keep stumbling over the same errors, Notice: Undefined variable: media in /Applications/MAMP/htdocs/Chapman/Chapman_cms/admin/team-2.php on line 48. This is supposed to create new users and edit old users. However, it does not work when I try and add a new user. Below is the pertinant code: $db = new database("mysql",$dbHost,$dbName,$dbUser,$dbPass); $target = 'add'; if ($_GET['task'] == 'edit') { $media = $db->get_row(edit_media_item($db, $_GET['team_id'])); $target = 'update'; <p><label for="copy">Full Name:</label> <input type="text" name="title" value="<?=$media['title']?>" /> <textarea name="media" id="media" cols="30" rows="5" style="width: 100%"><?=$media['copy']?></textarea></p> <input type="hidden" name="process" value="<?=$target.",copy,4,team-1,".$media['id'].""?>"> <p><input type="submit" name="save" value="Submit" /> <input type="reset" name="reset" value="Reset" /></p> </form> Any help would be much appreciated. A: To remove the notice in the right way is to do this with the code <?php if(isset($media['copy'])){ echo $media['copy']; } ?> A: It may be hard to help you like this, but, I would see where this $db->get_row() call goes and what it returns (using var_dump() or something...) As general tip, I would recommend setting up debugger in your system, so you can trace calls. On windows platform I use xdebug with WinCacheGrind to trace call when I am unsure about call hierarchy. On Linux, setup is similar (xdebug,kcachegrind...). A: The notice is irrelevant, but this code doesn't create anything. That happens on the page it is submitted to. Look at the if statement on the first few lines. I guess you need to call it with task=edit in the URL. A: you can also use the at symbol like this: if($_GET['undefined_key']) { // blah... } if(@$_GET['undefined_key']) { // blah... } it suppresses warnings, however some will argue that the best time to use the at symbol is to avoid warnings you couldn't do otherwise. A: The code you posted does not do any creating, so that problem does not stemfrom this bit of code. The undefined notice is from the <?=$media['copy']?> bit. $media was never defined. If this is not an issue, ignore it and tell PHP to not output notices. This isn't exactly good practice, but if you're not getting paid to fix every little thing, I'd say it's a feasible alternative. To suppress notices add this code anywhere before the notices occur or better yet into a global include: error_reporting(E_ERROR | E_WARNING | E_PARSE); For more info: http://www.php.net/error_reporting A: That error message is not from this code. $media is assigned in line 6 of the code you provided ($media = $db->get_row(..)). I'm guessing that you either have stripped out the relevant code (Which is line 48, give/take), or it's the wrong file (Is this from /Applications/MAMP/htdocs/Chapman/Chapman_cms/admin/team-2.php?).
{ "language": "en", "url": "https://stackoverflow.com/questions/156835", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Dynamicaly populating a combobox with values from a Map based on what's selected in another combobox Ok, here's one for the Java/JavaScript gurus: In my app, one of the controllers passes a TreeMap to it's JSP. This map has car manufacturer's names as keys and Lists of Car objects as values. These Car objects are simple beans containing the car's name, id, year of production etc. So, the map looks something like this (this is just an example, to clarify things a bit): Key: Porsche Value: List containing three Car objects(for example 911,Carrera,Boxter with their respectable years of production and ids) Key: Fiat Value: List containing two Car objects(for example, Punto and Uno) etc... Now, in my JSP i have two comboboxes. One should receive a list of car manufacturers(keys from the map - this part I know how to do), and the other one should dynamicaly change to display the names of the cars when the user selects a certain manufacturer from the first combobox. So, for example, user selects a "Porsche" in the first combobox, and the second immediately displays "911, Carrera, Boxter"... After spending a couple of days trying to find out how to do this, I'm ready to admit defeat. I tried out a lot of different things but every time I hit a wall somewehere along the way. Can anybody suggest how I should approach this one? Yes, I'm a JavaScript newbie, if anybody was wondering... EDIT: I've retagged this as a code-challenge. Kudos to anybody who solves this one without using any JavaScript framework (like JQuery). A: I just love a challenge. No jQuery, just plain javascript, tested on Safari. I'd like to add the following remarks in advance: * *It's faily long due to the error checking. *Two parts are generated; the first script node with the Map and the contents of the manufacterer SELECT *Works on My Machine (TM) (Safari/OS X) *There is no (css) styling applied. I have bad taste so it's no use anyway. . <body> <script> // DYNAMIC // Generate in JSP // You can put the script tag in the body var modelsPerManufacturer = { 'porsche' : [ 'boxter', '911', 'carrera' ], 'fiat': [ 'punto', 'uno' ] }; </script> <script> // STATIC function setSelectOptionsForModels(modelArray) { var selectBox = document.myForm.models; for (i = selectBox.length - 1; i>= 0; i--) { // Bottom-up for less flicker selectBox.remove(i); } for (i = 0; i< modelArray.length; i++) { var text = modelArray[i]; var opt = new Option(text,text, false, false); selectBox.add(opt); } } function setModels() { var index = document.myForm.manufacturer.selectedIndex; if (index == -1) { return; } var manufacturerOption = document.myForm.manufacturer.options[index]; if (!manufacturerOption) { // Strange, the form does not have an option with given index. return; } manufacturer = manufacturerOption.value; var modelsForManufacturer = modelsPerManufacturer[manufacturer]; if (!modelsForManufacturer) { // This modelsForManufacturer is not in the modelsPerManufacturer map return; // or alert } setSelectOptionsForModels(modelsForManufacturer); } function modelSelected() { var index = document.myForm.models.selectedIndex; if (index == -1) { return; } alert("You selected " + document.myForm.models.options[index].value); } </script> <form name="myForm"> <select onchange="setModels()" id="manufacturer" size="5"> <!-- Options generated by the JSP --> <!-- value is index of the modelsPerManufacturer map --> <option value="porsche">Porsche</option> <option value="fiat">Fiat</option> </select> <select onChange="modelSelected()" id="models" size="5"> <!-- Filled dynamically by setModels --> </select> </form> </body> A: Well anyway, as i said, i finally managed to do it by myself, so here's my answer... I receive the map from my controller like this (I'm using Spring, don't know how this works with other frameworks): <c:set var="manufacturersAndModels" scope="page" value="${MANUFACTURERS_AND_MODELS_MAP}"/> These are my combos: <select id="manufacturersList" name="manufacturersList" onchange="populateModelsCombo(this.options[this.selectedIndex].index);" > <c:forEach var="manufacturersItem" items="<%= manufacturers%>"> <option value='<c:out value="${manufacturersItem}" />'><c:out value="${manufacturersItem}" /></option> </c:forEach> </select> select id="modelsList" name="modelsList" <c:forEach var="model" items="<%= models %>" > <option value='<c:out value="${model}" />'><c:out value="${model}" /></option> </c:forEach> </select> I imported the following classes (some names have, of course, been changed): <%@ page import="org.mycompany.Car,java.util.Map,java.util.TreeMap,java.util.List,java.util.ArrayList,java.util.Set,java.util.Iterator;" %> And here's the code that does all the hard work: <script type="text/javascript"> <% Map mansAndModels = new TreeMap(); mansAndModels = (TreeMap) pageContext.getAttribute("manufacturersAndModels"); Set manufacturers = mansAndModels.keySet(); //We'll use this one to populate the first combo Object[] manufacturersArray = manufacturers.toArray(); List cars; List models = new ArrayList(); //We'll populate the second combo the first time the page is displayed with this list //initial second combo population cars = (List) mansAndModels.get(manufacturersArray[0]); for(Iterator iter = cars.iterator(); iter.hasNext();) { Car car = (Car) iter.next(); models.add(car.getModel()); } %> function populateModelsCombo(key) { var modelsArray = new Array(); //Here goes the tricky part, we populate a two-dimensional javascript array with values from the map <% for(int i = 0; i < manufacturersArray.length; i++) { cars = (List) mansAndModels.get(manufacturersArray[i]); Iterator carsIterator = cars.iterator(); %> singleManufacturerModelsArray = new Array(); <% for(int j = 0; carsIterator.hasNext(); j++) { Car car = (Car) carsIterator.next(); %> singleManufacturerModelsArray[<%= j%>] = "<%= car.getModel()%>"; <% } %> modelsArray[<%= i%>] = singleManufacturerModelsArray; <% } %> var modelsList = document.getElementById("modelsList"); //Empty the second combo while(modelsList.hasChildNodes()) { modelsList.removeChild(modelsList.childNodes[0]); } //Populate the second combo with new values for (i = 0; i < modelsArray[key].length; i++) { modelsList.options[i] = new Option(modelsArray[key][i], modelsArray[key][i]); } } A: Are you using Struts? You will need some JavaScript trickery (or AJAX) to accomplish this. What you'd need to do is, somewhere in your JavaScript code (leaving aside how you generate it for the minute): var map = { 'porsche': [ 'boxter', '911', 'carrera' ], 'fiat': ['punto', 'uno'] }; This is basically a copy of your server-side data structure, i.e. a map keyed by manufacturer, each value having an array of car types. Then, in your onchange event for the manufacturers, you'd need to get the array from the map defined above, and then create a list of options from that. (Check out devguru.com - it has a lot of helpful information about standard JavaScript objects). Depending on how big your list of cars is, though, it might be best to go the AJAX route. You'd need to create a new controller which looked up the list of cars types given a manufacturer, and then forward on to a JSP which returned JSON (it doesn't have to be JSON, but it works quite well for me). Then, use a library such as jQuery to retrieve the list of cars in your onchange event for the list of manufacturers. (jQuery is an excellent JavaScript framework to know - it does make development with JavaScript much easier. The documentation is very good). I hope some of that makes sense? A: Here is a working, cut-and-paste answer in jsp without any tag libraries or external dependencies whatsoever. The map with models is hardcoded but shouldn't pose any problems. I separated this answer from my previous answer as the added JSP does not improve readability. And in 'real life' I would not burden my JSP with all the embedded logic but put it in a class somewhere. Or use tags. All that "first" stuff is to prevent superfluos "," in the generated code. Using a foreach dosn't give you any knowledge about the amount of elements, so you check for last. You can also skip the first-element handling and strip the last "," afterwards by decreasing the builder length by 1. <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <%@page import="java.util.Map"%> <%@page import="java.util.TreeMap"%> <%@page import="java.util.Arrays"%> <%@page import="java.util.Collection"%> <%@page import="java.util.List"%> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Challenge</title> </head> <body onload="setModels()"> <% // You would get your map some other way. Map<String,List<String>> map = new TreeMap<String,List<String>>(); map.put("porsche", Arrays.asList(new String[]{"911", "Carrera"})); map.put("mercedes", Arrays.asList(new String[]{"foo", "bar"})); %> <%! // You may wish to put this in a class public String modelsToJavascriptList(Collection<String> items) { StringBuilder builder = new StringBuilder(); builder.append('['); boolean first = true; for (String item : items) { if (!first) { builder.append(','); } else { first = false; } builder.append('\'').append(item).append('\''); } builder.append(']'); return builder.toString(); } public String mfMapToString(Map<String,List<String>> mfmap) { StringBuilder builder = new StringBuilder(); builder.append('{'); boolean first = true; for (String mf : mfmap.keySet()) { if (!first) { builder.append(','); } else { first = false; } builder.append('\'').append(mf).append('\''); builder.append(" : "); builder.append( modelsToJavascriptList(mfmap.get(mf)) ); } builder.append("};"); return builder.toString(); } %> <script> var modelsPerManufacturer =<%= mfMapToString(map) %> function setSelectOptionsForModels(modelArray) { var selectBox = document.myForm.models; for (i = selectBox.length - 1; i>= 0; i--) { // Bottom-up for less flicker selectBox.remove(i); } for (i = 0; i< modelArray.length; i++) { var text = modelArray[i]; var opt = new Option(text,text, false, false); selectBox.add(opt); } } function setModels() { var index = document.myForm.manufacturer.selectedIndex; if (index == -1) { return; } var manufacturerOption = document.myForm.manufacturer.options[index]; if (!manufacturerOption) { // Strange, the form does not have an option with given index. return; } manufacturer = manufacturerOption.value; var modelsForManufacturer = modelsPerManufacturer[manufacturer]; if (!modelsForManufacturer) { // This modelsForManufacturer is not in the modelsPerManufacturer map return; // or alert } setSelectOptionsForModels(modelsForManufacturer); } function modelSelected() { var index = document.myForm.models.selectedIndex; if (index == -1) { return; } alert("You selected " + document.myForm.models.options[index].value); } </script> <form name="myForm"> <select onchange="setModels()" id="manufacturer" size="5"> <% boolean first = true; for (String mf : map.keySet()) { %> <option value="<%= mf %>" <%= first ? "SELECTED" : "" %>><%= mf %></option> <% first = false; } %> </select> <select onChange="modelSelected()" id="models" size="5"> <!-- Filled dynamically by setModels --> </select> </form> </body> </html> A: How about something like this, using prototype? First, your select box of categories: <SELECT onchange="changeCategory(this.options[this.selectedIndex].value); return false;"> <OPTION value="#categoryID#">#category#</OPTION> ... Then, you output N different select boxes, one for each of the sub-categories: <SELECT name="myFormVar" class="categorySelect"> ... Your changeCategory javascript function disables all selects with class categorySelect, and then enables just the one for your current categoryID. // Hide all category select boxes except the new one function changeCategory(categoryID) { $$("select.categorySelect").each(function (select) { select.hide(); select.disable(); }); $(categoryID).show(); $(categoryID).enable(); } When you hide/disable like this in prototype, it not only hides it on the page, but it will keep that FORM variable from posting. So even though you have N selects with the same FORM variable name (myFormVar), only the active one posts. A: Not that long ago I thought about something similar. Using jQuery and the TexoTela add-on it wasn't all that difficult. First, you have a data structure like the map mentioned above: var map = { 'porsche': [ 'boxter', '911', 'carrera' ], 'fiat': ['punto', 'uno'] }; Your HTML should look comparable to: <select size="4" id="manufacturers"> </select> <select size="4" id="models"> </select> Then, you fill the first combo with jQuery code like: $(document).ready( function() { $("#bronsysteem").change( manufacturerSelected() ); } ); ); where manufacturerSelected is the callback registered on the onChange event function manufacturerSelected() { newSelection = $("#manufacturers").selectedValues(); if (newSelection.length != 1) { alert("Expected a selection!"); return; } newSelection = newSelection[0]; fillModels(newSelection); } function fillModels(manufacterer) { var models = map[manufacturer]; $("models").removeOption(/./); // Empty combo for(modelId in models) { model = models[modelId]; $("models").addOption(model,model); // Value, Text } } This should do the trick. Please note that there may be syntax errors in there; I have edited my code to reflect your use case and had to strip quite a lot out. If this helps I would appreciate a comment. A: As an add-on on my previous post; You can put a script tag in your JSP where you iterate over your map. An example about iterating over maps can be found in Maps in Struts. What you would like to achieve (if you don't care about form submission) is I think something like: <script> var map = { <logic:iterate id="entry" name="myForm" property="myMap"> '<bean:write name=" user" property="key"/>' : [ <logic:iterate id="model" name="entry" property="value"> '<bean:write name=" model" property="name"/>' , </logic:iterate> ] , </logic:iterate> }; </script> You still have some superfuous "," which you might wish to prevent, but I think this should do the trick.
{ "language": "en", "url": "https://stackoverflow.com/questions/156852", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to communicate between CE 6.0 device (as server) and PC (as client) We're in the process of developing a measurement device that will be running CE 6.0 with CF 3.5 on x86 embedded hardware, a PC is used to control the device and is connected with it using ethernet. We would like to communicate using interfaces (using DCOM (we know it is not supported by default on CE6), .NET Remoting or Web services) instead of using some sort of (custom) protocol. Calling methods defined in an interface is so much easier and elegant then parsing raw data. What would be the best solution in this case? A: If you're using CE 6 and .NET Compact Framework 3.5, have you considered using the Windows Communication Foundation (WCF)? You'd have to write your own transport, but when that is done, you will be able to consume your service interfaces with relative ease. A: I've had some experience setting up comms between CE devices and a PC, and have used custom interfaces using winsock (thwacking some bytes back and forwards) and have tried SOAP. In Windows CE 5.0, the Microsoft provided SOAP server took our device down somehow every couple of hours or so. I spent many weeks trying to work out what was wrong, thinking it was something I'd done wrong. So, I prefer to stick to winsock now because at least I've got a chance of knowing what's going on and can fix it. Also, CE devices aren't always the quickest performers depending on what hardware you've got. Web-services take up some overhead and time converting data to XML, and this may be a performance hit you are or are not able to afford. A: As with Scott, we went down the road of using socket based communications, for performance and stability reasons. The code works well across all devices from Windows CE 2.1 up to mobile 6.0. I found the Windows CE developers handbook, ISBN 0-7821-2414-3, to be very useful in developing this functionality, albeit in C++ rather than C#.
{ "language": "en", "url": "https://stackoverflow.com/questions/156860", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to optimize PostgreSQL Configuration? (Is there a tool available?) In postgresql you have a wealth of optimizations at hand to configure it for your performance needs. The settings for memory usage are still easy enough, but with other options like the cost factors for CPU and IO which are used for the query optimizer are quite a mystery for me. I wonder if there is a program available which would do lets say a benchmark of your hardware (CPU speed, memory performance, harddisk speed), analyze your database and come up with the optimal configuration for this specific environment? EDIT: Let me clarify this, I know how to tune my database with indexes and the basic memory settings. I also could find out which settings are to be tweaked to get better performance, but: I don't have the time, so I want to have a tool which finds this out for me. A: Start here. A: Not that I know of, but the next best thing is the GUCs: A Three Hour Tour presentation. You can download a PDF from there which gives the recommended values for the settings depending on your system resources. A: Understanding indexes is the where most people should start when trying to improve any databases performance.
{ "language": "en", "url": "https://stackoverflow.com/questions/156866", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Good simulation software for mobile devices Can anyone recommend good simulation software for mobile devices? I am most interested in Nokia smart phones. A: Are you looking for Emulator for Nokia phones? You can find those here.. Otherwise explain clearly what kind of simulation software you are looking for! A: The Nokia S60 SDKs have an emulator which will run on the pc. http://www.forum.nokia.com/main/resources/tools_and_sdks/ Symbian phones can be programmed in a variety of languages, not just Symbian C++. There's OpenC, Ruby, Py60 (Python), web programming and of course the various flavours of Java. A: OK, I am showing my newb-ness with mobile development. I am talking about emulation rather than simulation. I am contemplating porting an application to a phone platform and like the look (and ubiquity in my market) of Nokia smart phone, which I think run Symbian. What I would like to do is experiment by creating a development environment locally but I am a little lost and need some pointers to get started. A: You are right! The Nokia phones runs on Symbian Platform. There are quite some variants out there, But S60 is better. UIQ is not doing that well lately. Have a read at Developing with S60 You can download the SDK from forum.nokia.com. So the Emulator comes with the Developer Kit. You can try to build and run the samples on Emulator to get first hand feeling. Unfortunately Developing for Symbian is not walk-in-the-park. You can get some developer feelings here: * *Symbian OS Alternatively you can look for Windows Mobile. Which has pretty easy learning curve if you have prior knowledge in any of the areas [Win32, or MFC or .NET C#] Getting Started with Windows Mobile or If you are comfortable with Java, check out J2ME. It has a wireless toolkit with decent emulator. A: A relevant shameless plug. A recent book from Symbian Press is targeted at developers new to mobile development. It guides you step by step through a 2 weeks learning curve and can greatly help porting efforts. http://developer.symbian.com/quick A: Just to be clear, not all Nokia phones run Symbian. Only the Series 60 smart phones devices run Symbian, the lower end Series 40 devices run a proprietary OS. Your best bet is to use WURFL to determine what the capabilities of each device are. The nice thing about the Nokia S60 emulators is how well they are integrated with Eclipse and Netbeans. I am personally using Eclispe and the S60 emulator to develop a J2ME application and it was all quite straight forward to set up.
{ "language": "en", "url": "https://stackoverflow.com/questions/156871", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }