text
stringlengths
8
267k
meta
dict
Q: Where is the benefit in using the Strategy Pattern? I've looked at this explanation on Wikipedia, specifically the C++ sample, and fail to recognize the difference between just defining 3 classes, creating instances and calling them, and that example. What I saw was just placing two other classes into the process and cannot see where there would be a benefit. Now I'm sure I'm missing something obvious (wood for the trees) - could someone please explain it using a definitive real-world example? What I can make from the answers so far, it seems to me to be just a more complex way of doing this: have an abstract class: MoveAlong with a virtual method: DoIt() have class Car inherit from MoveAlong, implementing DoIt() { ..start-car-and-drive..} have class HorseCart inherit from MoveAlong, implementing DoIt() { ..hit-horse..} have class Bicycle inherit from MoveAlong, implementing DoIt() { ..pedal..} now I can call any function taking MoveAlong as parm passing any of the three classes and call DoIt Isn't this what Strategy intents? (just simpler?) [Edit-update] The function I refer to above is replaced with another class in which MoveAlong would be attribute which is set according to need based on the algorithm implemented in this new class. (Similar to what is demonstrated in the accepted answer.) [Edit-update] Conclusion The Strategy Pattern has it's uses, but I am a strong believer in KISS, and would tend to more straightforward and less obfuscatory techniques. Mostly since I want to pass on easily maintainable code (and 'cos I'll most likely be the one who have to make the changes!). A: There is a difference between strategy and decision/choice. Most of the time a we would be handling decisions/choices in our code, and realise them using if()/switch() constructs. Strategy pattern is useful when there is a need to decouple the logic/algorithm from usage. As an example, Think of a polling mechanism, where different users would check for resources/updates. Now we may want some of the priveliged users to be notified with a quicker turnaround time or with more details. Essentailly the logic being used changes based on user roles. Strategy makes sense from a design/architecture view point, at lower levels of granularity it should always be questioned. A: The strategy pattern allows you to exploit polimorphism without extending your main class. In essence, you are putting all variable parts in the strategy interface and implementations and the main class delegates to them. If your main object uses only one strategy, it's almost the same as having an abstract (pure virtual) method and different implementations in each subclass. The strategy approach offers some benefits: * *you can change strategy at runtime - compare this to changing the class type at runtime, which is much more difficult, compiler specific and impossible for non-virtual methods *one main class can use more than one strategies which allows you to recombine them in multiple ways. Consider a class that walks a tree and evaluates a function based on each node and the current result. You can have a walking strategy (depth-first or breadth-first) and calculation strategy (some functor - i.e. 'count positive numbers' or 'sum'). If you do not use strategies, you will need to implement subclass for each combination of walking/calculation. *code is easier to maintain as modifying or understanding strategy does not require you to understand the whole main object The drawback is that in many cases, the strategy pattern is an overkill - the switch/case operator is there for a reason. Consider starting with simple control flow statements (switch/case or if) then only if necessary move to class hierarchy and if you have more than one dimensions of variability, extract strategies out of it. Function pointers fall somewhere in the middle of this continuum. Recommended reading: * *http://www.industriallogic.com/xp/refactoring/ *http://www.refactoring.com/ A: The point is to separate algorithms into classes that can be plugged in at runtime. For instance, let's say you have an application that includes a clock. There are many different ways that you can draw a clock, but for the most part the underlying functionality is the same. So you can create a clock display interface: class IClockDisplay { public: virtual void Display( int hour, int minute, int second ) = 0; }; Then you have your Clock class that is hooked up to a timer and updates the clock display once per second. So you would have something like: class Clock { protected: IClockDisplay* mDisplay; int mHour; int mMinute; int mSecond; public: Clock( IClockDisplay* display ) { mDisplay = display; } void Start(); // initiate the timer void OnTimer() { mDisplay->Display( mHour, mMinute, mSecond ); } void ChangeDisplay( IClockDisplay* display ) { mDisplay = display; } }; Then at runtime you instantiate your clock with the proper display class. i.e. you could have ClockDisplayDigital, ClockDisplayAnalog, ClockDisplayMartian all implementing the IClockDisplay interface. So you can later add any type of new clock display by creating a new class without having to mess with your Clock class, and without having to override methods which can be messy to maintain and debug. A: This design pattern allows to encapsulate algorithms in classes. The class that uses the strategy, the client class, is decoupled from the algorithm implementation. You can change the algorithms implementation, or add new algorithm without having to modify the client. This can also be done dynamically: the client can choose the algorithm he will use. For an example, imagine an application that needs to save an image to a file ; the image can be saved in different formats (PNG, JPG ...). The encoding algorithms will all be implemented in different classes sharing the same interface. The client class will choose one depending on the user preference. A: One way to look at this is when you have a variety of actions you want to execute and those actions are determined at runtime. If you create a hashtable or dictionary of strategies, you could retrieve those strategies that correspond to command values or parameters. Once your subset is selected, you can simply iterate the list of strategies and execute in succession. One concrete example would be calculation the total of an order. Your parameters or commands would be base price, local tax, city tax, state tax, ground shipping and coupon discount. The flexibility come into play when you handle the variation of orders - some states will not have sales tax, while other orders will need to apply a coupon. You can dynamically assign the order of calculations. As long as you have accounted for all your calculations, you can accommodate all combinations without re-compiling. A: In Java you use a cipher input stream to decrypt like so: String path = ... ; InputStream = new CipherInputStream(new FileInputStream(path), ???); But the cipher stream has no knowledge of what encryption algorithm you intend to use or the block size, padding strategy etc... New algorithms will be added all the time so hardcoding them is not practical. Instead we pass in a Cipher strategy object to tell it how to perform the decryption... String path = ... ; Cipher strategy = ... ; InputStream = new CipherInputStream(new FileInputStream(path), strategy); In general you use the strategy pattern any time you have any object that knows what it needs to do but not how to do it. Another good example is layout managers in Swing, although in that case it didnt work out quite as well, see Totally GridBag for an amusing illustration. NB: There are two patterns at work here, as the wrapping of streams in streams is an example of Decorator. A: In the Wikipedia example, those instances can be passed into a function that doesn't have to care which class those instances belong to. The function just calls execute on the object passed, and know that the Right Thing will happen. A typical example of the Strategy Pattern is how files work in Unix. Given a file descriptor, you can read from it, write to it, poll it, seek on it, send ioctls to it, etc., without having to know whether you're dealing with a file, directory, pipe, socket, device, etc. (Of course some operations, like seek, don't work on pipes and sockets. But reads and writes will work just fine in these cases.) That means you can write generic code to handle all these different types of "files", without having to write separate code to deal with files versus directories, etc. The Unix kernel takes care of delegating the calls to the right code. Now, this is Strategy Pattern as used in kernel code, but you didn't specify that it had to be user code, just a real world example. :-) A: Strategy pattern works on simple idea i.e. "Favor Composition over Inheritance" so that strategy/algorithm can be changed at run time. To illustrate let's take an example where in we need to encrypt different messages based on its type e.g. MailMessage, ChatMessage etc. class CEncryptor { virtual void encrypt () = 0; virtual void decrypt () = 0; }; class CMessage { private: shared_ptr<CEncryptor> m_pcEncryptor; public: virtual void send() = 0; virtual void receive() = 0; void setEncryptor(cost shared_ptr<Encryptor>& arg_pcEncryptor) { m_pcEncryptor = arg_pcEncryptor; } void performEncryption() { m_pcEncryptor->encrypt(); } }; Now at runtime you can instantiate different Messages inherited from CMessage (like CMailMessage:public CMessage) with different encryptors (like CDESEncryptor:public CEncryptor) CMessage *ptr = new CMailMessage(); ptr->setEncryptor(new CDESEncrypto()); ptr->performEncryption();
{ "language": "en", "url": "https://stackoverflow.com/questions/171776", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: nhibernate - sort null at end Using NHibernate from C# and only HQL (not SQL) in a way that is compatible with MS SQL Server 2005/2008 (and preferably Oracle). Is there a way to write the order by clause so that nulls will sort at the end of the query results while the non-null results will be sorted in ascending order? Based on the answer to the question referenced by nickf the answer is: select x from MyClass x order by case when x.MyProperty is null then 1 else 0 end, x.MyProperty A: I don't know if this helps or not, but there's another question asking the same thing about how to do this with MySQL. Perhaps the same logic could be applied to HQL? edit: this got accepted, so apparently, yes it can. Here's the accepted answer from that question (by Bill Karwin): SELECT * FROM myTable WHERE ... ORDER BY CASE WHEN myDate IS NULL THEN 1 ELSE 0 END, myDate; A: At one point I just gave up and fixed the sort order in my collection class. Since I was just moving NULLs all I had to do was peel off the nulls at the beginning of the collection and append them to the end. With a bet of cleaver coding, it can even be done on an array. Nevertheless, that ORDER BY CASE is a cleaver and readable trick.
{ "language": "en", "url": "https://stackoverflow.com/questions/171778", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do you organize Python modules? When it comes to organizing python modules, my Mac OS X system is a mess. I've packages lying around everywhere on my hdd and no particular system to organize them. How do you keep everything manageable? A: In addition to PEP8 and easy_install, you should check out virtualenv. Virtualenv allows you to have multiple different python library trees. At work, we use virtualenv with a bootstrapping environment to quickly set up a development/production environment where we are all in sync w.r.t library versions etc. We generally coordinate library upgrades. A: There are several families of Python componentry. * *The stuff that comes with Python. This takes care of itself. *The stuff that you got with easy_install. This, also, takes care of itself. *The packages that you had to get some other way, either as TARballs or SVN checkouts. Create a Components folder. Put the downloads or the SVN's in there first. Every Single Time. Do installs from there. *The packages that you wrote that are reusable. I have a Projects folder with each project in that folder. If the project is a highly reusable thing, it has a setup.py and I actually run the install as if I downloaded it. I don't have many of these, but a few. Some of them might become open source projects. *The final applications you write. I have a folder in Projects with each of these top-level applications. These are usually big, rambling things (like Django sites) and don't have setup.py. Why? They're often pretty complex with only a few server installations to manage, and each of those server installations is unique. These generally rely on PYTHONPATH to identify their parts. Notice the common theme. Either they're Components you downloaded or they're Projects you're working on. Also, I keep this separate (to an extent) from the client. I have a master directory of Client folders, each of which has Projects and each project has Sales and Delivery. Not all projects have both sales and delivery. A: Maybe PEP8 and easy_install can help you? A: I keep all the source for my packages inside ~/Packages/ , and then I do a standard install with "python2.5 setup.py install" on them. This tosses into (for me) /Library/Frameworks/Python/Versions/current/lib/python2.5/site-packages/ . For the development of my own software, I have aliases set up to switch between trunk/ branches/1.0, etc, by pre-prending onto PYTHONPATH. (I have to run 'setup.py build_ext --inplace' in each of these directories before they will import properly.) It's worth noting that Python2.6 has a per-user site-packages directory, which you may find more convenient. A: My advice: * *Read Installing Python Modules. *Read Distributing Python Modules. *Start using easy_install from setuptools. Read the documentation for setuptools. *Always use virtualenv. My site-packages directory contains setuptools and virtualenv only. *Check out Ian Bicking's new project pyinstall. *Follow everything Ian Bicking is working on. It is always goodness. *When creating your own packages, use distutils/setuptools. Consider using paster create (see http://pythonpaste.org) to create your initial directory layout. A: The "Modules" Python documentation page is a useful guide on organising code, specifically the "packages" sections A: My advice is to try to put everything into your site-packages directory(ies) unless you have a good reason not to. And I try to avoid easy_install because I find that it tends to cruft up my sys.path with egg locations, but that's just me. Some people find it useful. If you have lots of programs that use different libraries that may conflict with each other, you may also want to check out virtualenv. A: Just ran across this site from another StackOverflow question: http://infinitemonkeycorps.net/docs/pph/ This addresses more than just module placement, but once you place it write how you can easily handle documentation, testing, and distribution.
{ "language": "en", "url": "https://stackoverflow.com/questions/171785", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: TSVN DNS error: The requested name is valid, but no data of the requested type was found I've updated my TortoiseSVN client and now I'm getting the error when trying to update or commit to different repositories: The requested name is valid, but no data of the requested type was found Any ideas on how I can solve this? Internet Explorer shows up appropriate URL just fine. TortoiseSVN 1.5.3, Build 13783. A: I was struggling to resolve this problom..atlast i found a solution... in the URL provided, give IP Address instead of ServerName eg: 'http://xxx.xxx.x.x:8080/svn/RepositoryName' i got the problom fixed by doing this... hope this piece of information will help A: This error being reported is a winsock one, rather than being particular to TSVN. From Windows Sockets Error Codes: The requested name is valid and was found in the database, but it does not have the correct associated data being resolved for, e.g. an MX record is returned but no A record - indicating the host itself exists, but is not directly reachable. It is strange that you can access the host via IE however. Is it possible that in TSVN you've specified a port number that isn't available on the remote host, and IE is accessing the host on port 80? A: Did you change the connection protocol (eg. from svn to http or from http to https)? Or did any firewall configuration between your PC and the SVN server change? SVN over HTTP uses DAV verbs to perform actions, so it might be that these are blocked in a firewall. A: I realise this is an old thread but I've just experienced the same problem and found a solution so no harm in sharing. The solution for me involved setting the appropriate proxy settings within TortoiseSVN | Settings | Network (which were already setup in my browser, hence being able to view the repository fine there). So if you are behind a proxy server, make sure you setup TortoiseSVN appropriately. A: Guys, thanks for your answers. Everything was fixed by yet another reboot (2 reboots after TSVN update). Still I can't explain what happened. :) A: I got this error when trying to run both TeamCity and Visual SVN Server on the same virtual pc. Turning of the TeamCity services solved the problem for me. It is possible that the two web servers was having a little struggle with each other. A: I have tried all solutions, but the mixture of them worked. * *Erase all valid lines under C:\Users\%USERNAME%\AppData\Subversion\servers *Erase all valid lines under C:\ProgramData\Subversion\servers *Open TortoiseSvn -> network then uncheck "enable proxy server" worked for me. Good luck :) A: I had a static IP resulting in no DNS server. Set your IP to DHCP and it will help.
{ "language": "en", "url": "https://stackoverflow.com/questions/171805", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Is there any LaTeX package for drawing Gantt diagrams? Are there LaTeX packages for (more or less) easily drawing Gantt diagrams? Thanks. A: I have not used myself, but it looks like PSTricks offers some Gantt chart drawing capabilities. Main PSTricks site: http://tug.org/PSTricks/main.cgi Example of Gantt chart using PSTricks: http://tug.org/PSTricks/main.cgi?file=Examples/Charts/gantt A: There is the pst-gantt package. The bad news is, that you have to draw dependencies between the tasks yourself. So you need to use the \psline macro to draw lines and arrows. A: The pgfgantt package is quite easy to use and does linking.
{ "language": "en", "url": "https://stackoverflow.com/questions/171809", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "22" }
Q: VC9 and VC8 lib compatibility (The original question was asked there : http://www.ogre3d.org/phpBB2/viewtopic.php?t=44832 ) Someone asked : "While I would like to build everything in vs2008 (VC9), the PhysX SDK is built with vs2005 (VC8). Would this cause any problems, using all vc9 compiled libs and used in combination with this vc8 lib?" I answered that the day before i tried to use a .lib file (and a .dll) generated with VC8 and include it in a vc9 compiled exe, the compiler couldn't open the .lib file. Now, other answered they did this with no problems.... I can't find the information about lib compatibility between vc9 and vc8. so... Help? A: It works, but you get problems when sharing CRT/STL objects. So when you do a 'new' in a vc8 library and return this to a vc9 function, which in turn deletes this object, you get an assert from delete. T* funcInVc8Lib() { return new T(); } void funcInVC9Program() { T* p = funcInVc8Lib(); // ... delete p; // it should at least assert here (in _CrtIsValidHeapPtr() ) } A: The lib format is COFF (http://msdn.microsoft.com/en-us/library/7ykb2k5f(VS.71).aspx), also COFF is used in the PE format. Thus I would expect that most if not all libraries built with vc8 to be linkable with vc9. However I found a thread on msdn where MS seems not to guarantee that the libs compiled with VC8 will link nicely with VC9. http://social.msdn.microsoft.com/Forums/en-US/vcgeneral/thread/8042a534-aa8b-4f99-81ee-e5ff39ae6e69/) Taking into account this 2 bits of info I would conclude: Although MS does not guarantee the complete 100% compatibility I would expect that in most cases linking a vc8 lib with vc9 to work. Hope this helps. P.S. You write "the compiler couldn't open the .lib file.". The linker is the one that tries to open the libraries to be linked, not the compiler.
{ "language": "en", "url": "https://stackoverflow.com/questions/171816", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Programmatically showing a View from an Eclipse Plug-in I have a plug-in to an Eclipse RCP application that has a view. After an event occurs in the RCP application, the plug-in is instantiated, its methods are called to populate the plug-in's model, but I cannot find how to make the view appear without going to the "Show View..." menu. I would think that there would be something in the workbench singleton that could handle this, but I have not found out how anywhere. A: You are probably looking for this: PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().showView("viewId"); A: I found the need to bring the view to the front after it had been opened and pushed to the background. The activate method does the trick. PlatformUI.getWorkbench() .getActiveWorkbenchWindow() .getActivePage() .activate(workbenchPartToActivate); NOTE: The workbenchPartToActivate is an instance of IWorkbenchPart. A: If called from handler of a command HandlerUtil.getActiveWorkbenchWindow(event).getActivePage().showView(viewId); would be better, as I know. A: In e4, the EPartService is responsible for opening Parts. This can also be used to open e3 ViewParts. Instantiate the following class through your IEclipseContext, call the openPart-Method, and you should see the Eclipse internal browser view. public class Opener { @Inject EPartService partService; public void openPart() { MPart part = partService.createPart("org.eclipse.ui.browser.view"); part.setLabel("Browser"); partService.showPart(part, PartState.ACTIVATE); } } Here you can find an example of how this works together with your Application.e4xmi.
{ "language": "en", "url": "https://stackoverflow.com/questions/171824", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "32" }
Q: Looking for a Complete Delphi (object pascal) syntax I need a complete Object Pascal syntax (preferably Delphi 2009). Some of the syntax is given by the help files, but not all information is provided. So I started collecting loose bits of information. Recently I added these to a more or less complete syntax description (EBNF like). Although it looks extensive, there are still bugs and I'm sure parts are missing (specially in the .NET syntax). So I'm asking the SO Delphi community. Do you have any information or can you correct the errors? In return I provide the complete syntax to the community. It probably saves you some time ;-). In the future, I like to do the same for other languages (Like C#/C++/Java). The syntax description I already have is given: My Syntax sofar. Or if you like a Text version. (The XHTML is generated from the text version). Please note that the syntax focusses on the syntactical part, because the lexical part is not really a problem. Update I have a new version of the Delphi Syntax. html version. It includes al versions including 2009. Prism extentions are still on the todo list. And I'm not sure if I'm going to keep them together. For the real purists, it also contains the full assembler code (which does not support the full 100% of the intel set but only a few instructions are missed.). A: There is no complete, published syntax for Delphi. Bear in mind that .net and win32 delphi have different syntaxes. This project has hand-build Delphi parser in it. And lots of test cases of code that compiles but pushes the limits of the syntax. A: Delphi 7's grammar is in the back of the Object Pascal book. You mean for a few thousand dollars they don't even send you that? Do they even send you a 6' x 6' poster? A: This might be a good help. It is the parser used in TwoDesk's Castalia. A: Try this: DGrok - Delphi grammar A: What exactly are the bugs and functionality you're missing? From scanning over your document, it seems you mingle syntax and semantics. I do not understand why to distinguish between SimpleTypeFloat and SimpleTypeOrdinal on a syntactic level, or code operator precedence as syntactic feature in AddOp and MulOp. true, false, nil are identifiers just as any variable name you choose. A: You could always read the source to the Free Pascal Compiler. It supports Object Pascal.
{ "language": "en", "url": "https://stackoverflow.com/questions/171827", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "29" }
Q: How best to store Subversion version information in EAR's? When receiving a bug report or an it-doesnt-work message one of my initials questions is always what version? With a different builds being at many stages of testing, planning and deploying this is often a non-trivial question. I the case of releasing Java JAR (ear, jar, rar, war) files I would like to be able to look in/at the JAR and switch to the same branch, version or tag that was the source of the released JAR. How can I best adjust the ant build process so that the version information in the svn checkout remains in the created build? I was thinking along the lines of: * *adding a VERSION file, but with what content? *storing information in the META-INF file, but under what property with which content? *copying sources into the result archive *added svn:properties to all sources with keywords in places the compiler leaves them be I ended up using the svnversion approach (the accepted anwser), because it scans the entire subtree as opposed to svn info which just looks at the current file / directory. For this I defined the SVN task in the ant file to make it more portable. <taskdef name="svn" classname="org.tigris.subversion.svnant.SvnTask"> <classpath> <pathelement location="${dir.lib}/ant/svnant.jar"/> <pathelement location="${dir.lib}/ant/svnClientAdapter.jar"/> <pathelement location="${dir.lib}/ant/svnkit.jar"/> <pathelement location="${dir.lib}/ant/svnjavahl.jar"/> </classpath> </taskdef> Not all builds result in webservices. The ear file before deployment must remain the same name because of updating in the application server. Making the file executable is still an option, but until then I just include a version information file. <target name="version"> <svn><wcVersion path="${dir.source}"/></svn> <echo file="${dir.build}/VERSION">${revision.range}</echo> </target> Refs: svnrevision: http://svnbook.red-bean.com/en/1.1/re57.html svn info http://svnbook.red-bean.com/en/1.1/re13.html subclipse svn task: http://subclipse.tigris.org/svnant/svn.html svn client: http://svnkit.com/ A: Use the svnversion command in your Ant script to get the revision number: <exec executable="svnversion" outputproperty="svnversion" failonerror="true"> <env key="path" value="/usr/bin"/> <arg value="--no-newline" /> </exec> Then use the ${svnversion} property somewhere in your EAR. We put it in the EAR file name, but you could also put it in a readme or version file inside the EAR, or specify the version in the EAR's META-INF/manifest.mf: <!-- myapp-r1234.ear --> <property name="ear" value="myapp-r${svnrevision}.ear" /> A: You'd want to provide the Subversion branch and repository number. As discussed in How to access the current Subversion build number?, the svn info command will give you this information, which you can then use to build a VERSION file or place in any of the other files that you're building into your *AR files. If you've nothing else in mind, you could consider using the XmlProperty Ant task to extract the relevant information from the output of your svn info --xml command A: Check out the jreleaseinfo project. Contains a ANT task that can generate a java class that can be called at runtime to display the release info for your project. I like its simplicity. A: See also this question: Build and Version Numbering for Java Projects (ant, cvs, hudson) It includes several helpful code snippets. A: From the top of my mind. A tag for each jar build? A: We have the first part of our build create a version.txt file in the root of the package and dump the tag used to check the code out from (in our case) CVS... Additionally, the final part of our build process checks the fully built EAR back into CVS for future reference. That way, if we have an issue with a webapp - it's just a case of asking the reporter to hit /app/version.txt - from there we can drill down the particular build history in CVS to locate the relevant components (handles different versions of libraries in apps) to locate the error. Not sure how much help this is to our support folk - but it's definitely something they complain about not being there! A: Do automatic builds, and place a tag (with a date stamp) on the codebase when the build is succesful (with unittest ofcourse). In your delivery process, only deliver tagged builds to the customer. This way you are in control, and can place the tag name in a readme.txt somewhere, or have the filename of the ear file reflect the tagname. I personally switched back to CVS, and this is one of the reasons. In CVS, I can have a class report it's tag. All my jar files contain a "main" which makes them runnable. With support questions, I ask the customer to do a "java -jar somejar.jar" and send the output to me alongside the question. This way I'm sure of the build they-re using, and I can even have information like java version, OS type and version. Without the customer having to answer strange questions. It's simple but very effective. A: Why not put the build number into a properties file... this can then be easily read by the java and output to a Help | About dialog (applet/application), web-page footer or whatever other GUI you might have. (See the footer on every SOF page.... has the SVN version number there.) Seems a load easier than looking in the WAR/EAR/JAR etc easy time? A: I store the absolute repository revision as a part of my full version number. This gives people a quick glance to see if a given change is in a given version or not. We also store the version number / build date / etc in the manifest file of the ear as custom properties, these are mostly informational only. We also store it in a properties file that is built into our jar, so the application can read it.
{ "language": "en", "url": "https://stackoverflow.com/questions/171828", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Double buffer child controls in custom control (C#) I want to double buffer a custom control which contains buttons. I have tried various ways to double buffer the control; SetStyle, BufferedGraphicsContext, and drawing to a bitmap. These all work fine for the custom drawing of the control, but none of them handle drawing the button to a back buffer. How do I achieve this? A: Technically you can't, and you really shouldn't need to if they're standard .NET WinForms buttons. The buttons themselves control that through the protected DoubleBuffered property. The only way to access this would be to derive a new class from S.W.F.Button, and implement code to enable the DoubleBuffered property on instances of that class (I'd probably do that in the constructor). Finally, use objects of that new class on your form instead of S.W.F.Buttons. However, as I recall, buttons are purely drawn from WinAPI; they are not GDI+. As a result, you shouldn't need to double-buffer their drawing. That said, I don't know your usage scenario and I don't know what symptoms your app is displaying, so I could be wrong. :) You might consider checking out the book Pro .NET 2.0 Windows Forms and Custom Controls in C#. All of this was summarized from information in that book.
{ "language": "en", "url": "https://stackoverflow.com/questions/171830", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Which Python book would you recommend for a Linux Sysadmin? Python for Unix and Linux System Administration is aimed at sysadmins. Any other favorites besides this. A: First, you can start off the learn the basics of Python at Python documentation Index. Also of interest there would be the tutorial, library references. For sysadmin, some of the libraries you can use are , to name a few * *shutil (moving/copying files) *os eg os.walk() -> recursive directories looking for files os.path.join() -> join file paths os.getmtime(), os.getatime() -> file timestamp os.remove(), os.removedirs() -> remove files os.rename() -> rename files .. and many more... please see help(os) for more operating system stuffs... *sys *ftplib, telnetlib --> for file transfer and telnetting... *glob() -> file globbing, wildcards *re -> regular expression, if you ever need to use it.(but its not necessary) *paramiko -> SSH, if you want to use Secure shell *socket -> socket library if you need to do networking.... *most often times as a sysadmin, you will need to read/write files so learn about doing that *a) using for loop for line in open("file"): print line *b) with a file handle f=open("file") for line in f: print line f.close() *c) using while loop f=open("file") while 1: line=f.readline() if not line: break print line f.close() *datetime, time -> handle date and time , such as calculating how many days old or differences between 2 dates etc *fileinput -> for editing files in place. *md5 or hashlib -> calculating hash digest/md5 eg to find duplicate files ... Of course, there are many more but i leave it to you to explore. A: Mark Pilgrim's http://www.diveintopython.net/ is very good and clear. A: +1 for Dive into Python and Python in a Nutshell. I also highly recommend effbot's Guide to the Standard Library. You'll probably also want to check out the Python Cookbook for some good examples of idiomatic Python code. Check out Foundations of Python Networking to pick up where the SysAdmin book leaves off in terms of network protocols (fyi: all APress books are available as PDFs, which I love) A: If you don't know Python, you can start from here: Dive into Python (if you know a bit of coding). It's a free download. The Python tutorial at Python.org is also very good, I learned mostly from here and Dive into Python. You can also start by watching this Google Tech Talk Video. The title says Python for programmers, but it's still helpful. Once you know this, from what I heard, Python for Unix and Linux System Administration you mentioned is a very good and sufficient one. I highly recommend that you learn the basics of it before going into the specifics of system administration using Python. Happy Python. A: I think you'd want to include Python in a Nutshell on your bookshelf. Excellent, thorough reference, by Alex Martelli. A: Beginning Python: From Novice to Professional is an excellent book. I can recommend it. A: I also started from the Python tutorial on python.org and it got me started rather quick, after this i'm reading O'Reilly's Programming Python. A: I started with Mark Lutz's Programming Python (O'Reilly).
{ "language": "en", "url": "https://stackoverflow.com/questions/171835", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Problem using the ASP.NET FileUpload control in an UpdatePanel? I'm running into an issue where I have a FileUpload control in an UpdatePanel. When I attempt to save changes and upload the file, no file is found. If I remove the UpdatePanel everything seems to work fine. Any ideas why this might be happening? And is there a work-around? A: To upload a file you need to perform a full ASP.NET page postback, it does not operate over the partial postback method. You'll need to register the button which "uploads" your file as a PostBackTrigger of the UpdatePanel's triggers. There are lots of free (and non-free) AJAX file upload solutions, or you can easily create one, it's just a matter of putting your file upload control within an iframe and submitting the iframe page back to the server. It isn't really ajax, but it gives a visual impression of AJAX.
{ "language": "en", "url": "https://stackoverflow.com/questions/171840", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Excel 2003 XML format - AutoFitWidth not working I have a program that spits out an Excel workbook in Excel 2003 XML format. It works fine with one problem, I cannot get the column widths to set automatically. A snippet of what I produce: <Table > <Column ss:AutoFitWidth="1" ss:Width="2"/> <Row ss:AutoFitHeight="0" ss:Height="14.55"> <Cell ss:StyleID="s62"><Data ss:Type="String">Database</Data></Cell> This does not set the column to autofit. I have tried not setting width, I have tried many things and I am stuck. Thanks. A: Only date and number values are autofitted :-( quote: "... We do not autofit textual values" http://msdn.microsoft.com/en-us/library/aa140066.aspx#odc_xmlss_ss:column A: Take your string length before passing to XML and construct the ss:Width="length". A: Autofit does not work on cells with strings. Try to replace the Column-line in your example by the following code: <xsl:for-each select="/*/*[1]/*"> <Column> <xsl:variable name="columnNum" select="position()"/> <xsl:for-each select="/*/*/*[position()=$columnNum]"> <xsl:sort select="concat(string-length(string-length(.)),string-length(.))" order="descending"/> <xsl:if test="position()=1"> <xsl:if test="string-length(.) &lt; 201"> <xsl:attribute name="ss:Width"> <xsl:value-of select="5.25 * (string-length(.)+2)"/> </xsl:attribute> </xsl:if> <xsl:if test="string-length(.) &gt; 200"> <xsl:attribute name="ss:Width"> <xsl:value-of select="1000"/> </xsl:attribute> </xsl:if> </xsl:if> <xsl:if test = "local-name() = 'Sorteer'"> <xsl:attribute name="ss:Width"> <xsl:value-of select="0"/> </xsl:attribute> </xsl:if> </xsl:for-each> </Column> </xsl:for-each> Explanation: It sorts on string-length (longest string first), take first line of sorted strings, take length of that string * 5.25 and you will have a reasonable autofit. Sorting line: <xsl:sort select="concat(string-length(string-length(.)),string-length(.))" order="descending"/> explanation: if you just sort on length, like <xsl:sort select="string-length(.)" order="descending"/> because the lengths are handled as strings, 2 comes after 10, which you don't want. So you should left-pad the lengths in order to get it sorted right (because 002 comes before 010). However, as I couldn't find that padding function, I solved it by concattenating the length of the length with the length. A string with length of 100 will be translated to 3100 (first digit is length of length), you will see that the solution will always get string-sorted right. for example: 2 will be "12" and 10 will be "210", so this wil be string-sorted correctly. Only when the length of the length > 9 will cause problems, but strings of length 100000000 cannot be handled by Excel. Explantion of <xsl:if test="string-length(.) &lt; 201"> <xsl:attribute name="ss:Width"> <xsl:value-of select="5.25 * (string-length(.)+2)"/> </xsl:attribute> </xsl:if> <xsl:if test="string-length(.) &gt; 200"> <xsl:attribute name="ss:Width"> <xsl:value-of select="1000"/> </xsl:attribute> </xsl:if> I wanted to maximize length of string to about 200, but I could not get the Min function to work, like <xsl:value-of select="5.25 * Min((string-length(.)+2),200)"/> So I had to do it the dirty way. I hope you can autofit now! A: I know this post is old, but I'm updating it with a solution I coded if anyone still use openXml. It works fine with big files and small files. The algorithm is in vb, it takes an arraylist of arraylist of string (can be changed according to needs) to materialise a excel array. I used a Windows form to find width of rendered text, and links to select only the biggest cells (for big files efficiency) There: Dim colsTmp as ArrayList '(of Arraylist(of String)) Dim cols as Arraylist '(of Integer) Max size of cols 'Whe populate the Arraylist Dim width As Integer 'For each column For i As Integer = 0 To colsTmp.Count - 1 'Whe sort cells by the length of their String colsTmp(i) = (From f In CType(colsTmp(i), String()) Order By f.Length).ToArray Dim deb As Integer = 0 'If they are more than a 100 cells whe only take the biggest 10% If colsTmp(i).length > 100 Then deb = colsTmp(i).length * 0.9 End If 'For each cell taken For j As Integer = deb To colsTmp(i).length - 1 'Whe messure the lenght with the good font and size width = Windows.Forms.TextRenderer.MeasureText(colsTmp(i)(j), font).Width 'Whe convert it to "excel lenght" width = (width / 1.42) + 10 'Whe update the max Width If width > cols(i) Then cols(i) = width Next Next
{ "language": "en", "url": "https://stackoverflow.com/questions/171849", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Detecting appearance/disappearance of volumes on osx I want to update a list of storage devices as the user inserts USB keys, adds external disks and mounts disk images. IOKit's IOServiceAddInterestNotification looks like the way to go, but the obvious use of registering general interest in kIOMediaClass only gives you notifications for unmounting of volumes and then only sometimes. What's the right way to do this? A: The following calls in DiskArbitration.h do exactly what I want: * *DARegisterDiskAppearedCallback *DARegisterDiskDisappearedCallback *DARegisterDiskDescriptionChangedCallback These cover insertion, removal (even of unmountable volumes) metadata change events. P.S. Don't forget to add your DASession to a runloop or you won't get any callbacks. A: I want to update a list of storage devices as the user inserts USB keys, adds external disks and mounts disk images. I can get you two out of three with this piece of code, which I imagine wouldn't require a lot more work to give you the third. File: USBNotificationExample.c Description: This sample demonstrates how to use IOKitLib and IOUSBLib to set up asynchronous callbacks when a USB device is attached to or removed from the system. It also shows how to associate arbitrary data with each device instance. http://opensource.apple.com/source/IOUSBFamily/IOUSBFamily-385.4.1/Examples/Another%20USB%20Notification%20Example/USBNotificationExample.c I've personally used (a slightly modified copy of this code) for a long time, to monitor the connection of USB HDDs. As you can see from this small sample, it may easily prove adaptable to monitor mounted drives. Or it may not. YMMV. matchingDict = IOServiceMatching(kIOUSBDeviceClassName); // Interested in instances of class // IOUSBDevice and its subclasses and when it matches void DeviceAdded(void *refCon, io_iterator_t iterator) { kern_return_t kr; io_service_t usbDevice; IOCFPlugInInterface **plugInInterface=NULL; SInt32 score; HRESULT res; while ( (usbDevice = IOIteratorNext(iterator)) ) { io_name_t deviceName; CFStringRef deviceNameAsCFString; MyPrivateData *privateDataRef = NULL; UInt32 locationID; printf("Device 0x%08x added.\n", usbDevice); and so forth, and so on. A: Would watching /Volumes for changes do what you need? A: If you happen to be working at the Cocoa level, you can also register to receive the following notifications from NSWorkspace: * *NSWorkspaceDidMountNotification *NSWorkspaceDidRenameVolumeNotification *NSWorkspaceWillUnmountNotification *NSWorkspaceDidUnmountNotification
{ "language": "en", "url": "https://stackoverflow.com/questions/171855", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Namespaces and Operator Overloading in C++ When authoring a library in a particular namespace, it's often convenient to provide overloaded operators for the classes in that namespace. It seems (at least with g++) that the overloaded operators can be implemented either in the library's namespace: namespace Lib { class A { }; A operator+(const A&, const A&); } // namespace Lib or the global namespace namespace Lib { class A { }; } // namespace Lib Lib::A operator+(const Lib::A&, const Lib::A&); From my testing, they both seem to work fine. Is there any practical difference between these two options? Is either approach better? A: You should define them in the library namespace. The compiler will find them anyway through argument dependant lookup. No need to pollute the global namespace. A: You should define it in the namespace, both because the syntax will be less verbose and not to clutter the global namespace. Actually, if you define your overloads in your class definition, this becomes a moot question: namespace Lib { class A { public: A operator+(const A&); }; } // namespace Lib A: Putting it into the library namespace works because of Koenig lookup.
{ "language": "en", "url": "https://stackoverflow.com/questions/171862", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "42" }
Q: How to find and tail the Oracle alert log When you take your first look at an Oracle database, one of the first questions is often "where's the alert log?". Grid Control can tell you, but its often not available in the environment. I posted some bash and Perl scripts to find and tail the alert log on my blog some time back, and I'm surprised to see that post still getting lots of hits. The technique used is to lookup background_dump_dest from v$parameter. But I only tested this on Oracle Database 10g. Is there a better approach than this? And does anyone know if this still works in 11g? A: Am sure it will work in 11g, that parameter has been around for a long time. Seems like the correct way to find it to me. If the background_dump_dest parameter isn't set, the alert.log will be put in $ORACLE_HOME/RDBMS/trace A: Once you've got the log open, I would consider using File::Tail or File::Tail::App to display it as it's being written, rather than sleeping and reading. File::Tail::App is particularly clever, because it will detect the file being rotated and switch, and will remember where you were up to between invocations of your program. I'd also consider locking your cache file before using it. The race condition may not bother you, but having multiple people try to start your program at once could result in nasty fights over who gets to write to the cache file. However both of these are nit-picks. My brief glance over your code doesn't reveal any glaring mistakes.
{ "language": "en", "url": "https://stackoverflow.com/questions/171868", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: KSH scripting: how to split on ',' when values have escaped commas? I try to write KSH script for processing a file consisting of name-value pairs, several of them on each line. Format is: NAME1 VALUE1,NAME2 VALUE2,NAME3 VALUE3, etc Suppose I write: read l IFS="," set -A nvls $l echo "$nvls[2]" This will give me second name-value pair, nice and easy. Now, suppose that the task is extended so that values could include commas. They should be escaped, like this: NAME1 VALUE1,NAME2 VALUE2_1\,VALUE2_2,NAME3 VALUE3, etc Obviously, my code no longer works, since "read" strips all quoting and second element of array will be just "NAME2 VALUE2_1". I'm stuck with older ksh that does not have "read -A array". I tried various tricks with "read -r" and "eval set -A ....", to no avail. I can't use "read nvl1 nvl2 nvl3" to do unescaping and splitting inside read, since I dont know beforehand how many name-value pairs are in each line. Does anyone have a useful trick up their sleeve for me? PS I know that I have do this in a nick of time in Perl, Python, even in awk. However, I have to do it in ksh (... or die trying ;) A: As it often happens, I deviced an answer minutes after asking the question in public forum :( I worked around the quoting/unquoting issue by piping the input file through the following sed script: sed -e 's/\([^\]\),/\1\ /g;s/$/\ / It converted the input into: NAME1.1 VALUE1.1 NAME1.2 VALUE1.2_1\,VALUE1.2_2 NAME1.3 VALUE1.3 <empty line> NAME2.1 VALUE2.1 <second record continues> Now, I can parse this input like this: while read name value ; do echo "$name => $value" done Value will have its commas unquoted by "read", and I can stuff "name" and "value" in some associative array, if I like. PS Since I cant accept my own answer, should I delete the question, or ...? A: You can also change the \, pattern to something else that is known not to appear in any of your strings, and then change it back after you've split the input into an array. You can use the ksh builtin pattern-substitution syntax to do this, you don't need to use sed or awk or anything. read l l=${l//\\,/!!} IFS="," set -A nvls $l unset IFS echo ${nvls[2]/!!/,}
{ "language": "en", "url": "https://stackoverflow.com/questions/171873", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How do two-phase commits prevent last-second failure? I am studying how two-phase commit works across a distributed transaction. It is my understanding that in the last part of the phase the transaction coordinator asks each node whether it is ready to commit. If everyone agreed, then it tells them to go ahead and commit. What prevents the following failure? * *All nodes respond that they are ready to commit *The transaction coordinator tells them to "go ahead and commit" but one of the nodes crashes before receiving this message *All other nodes commit successfully, but now the distributed transaction is corrupt *It is my understanding that when the crashed node comes back, its transaction will have been rolled back (since it never got the commit message) I am assuming each node is running a normal database that doesn't know anything about distributed transactions. What did I miss? A: There are many ways to attack the problems with two-phase commit. Almost all of them wind up as some variant of the Paxos three-phase commit algorithm. Mike Burrows, who designed the Chubby lock service at Google which is based on Paxos, said that there are two types of distributed commit algorithms - "Paxos, and incorrect ones" - in a lecture I saw. One thing the crashed node could do, when it reawakes, is say "I never heard about this transaction, should it have been committed?" to the coordinator, which will tell it what the vote was. Bear in mind that this is an example of a more general problem: the crashed node could miss many transactions before it recovers. Therefore it's terribly important that upon recovery it should talk either to the coordinator or another replica before making itself available. If the node itself can't tell whether or not it has crashed, then things get more involved but still tractable. If you use a quorum system for database reads, the inconsistency will be masked (and made known to the database itself). A: No, they are not instructed to roll back because in the original poster's scenario, some of the nodes have already committed. What happens is when the crashed node becomes available, the transaction coordinator tells it to commit again. Because the node responded positively in the "prepare" phase, it is required to be able to "commit", even when it comes back from a crash. A: Summarizing everyone's answers: * *One cannot use normal databases with distributed transactions. The database must explicitly support a transaction coordinator. *The nodes are not instructed to roll back because some of the nodes have already committed. What happens is that when the crashed node comes back, the transaction coordinator tells it to finish the commit. A: No. Point 4 is incorrect. Each node records in stable storage that it was able to commit or rollback the transaction, so that it will be able to do as commanded even across crashes. When the crashed node comes back up, it must realize that it has a transaction in pre-commit state, reinstate any relevant locks or other controls, and then attempt to contact the coordinator site to collect the status of the transaction. The problems only occur if the crashed node never comes back up (then everything else thinks the transaction was OK, or will be when the crashed node comes back). A: Two phase commit isn't foolproof and is just designed to work in the 99% of the time cases. "The protocol assumes that there is stable storage at each node with a write-ahead log, that no node crashes forever, that the data in the write-ahead log is never lost or corrupted in a crash, and that any two nodes can communicate with each other." http://en.wikipedia.org/wiki/Two-phase_commit_protocol
{ "language": "en", "url": "https://stackoverflow.com/questions/171876", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "90" }
Q: Browsing directory without using mapped drive Is there an app or way to browse a directory that requires different login credentials without using a mapped drive? The issue is given one login credential Windows Explorer only allows you to map it to one drive and disallows using the same login credential to map to a different drive. A: As far as I know, you cant map a drive to a shared folder with one username/password on the same server as another mapped drive with a different username and password. If you are doing it programmatically you can add multiple credentials to the credential cache, that would allow you to authorise yourself with multiple permission sets. I've always been able to map drives using the same username and password to two different servers. For example net use x: \\server1\shareFolder /user:domain\username net use y: \\server2\shareFolder /user:domain\username You can omit the /user section if you want the network share to be mapped as the current user. You can have as many network drives as you want on different machines as long as you have enough drive letters. alternatively you can use the unc path \server1\share1 and \server2\share1, if your username and password which you are not currently logged in as do not have access windows will prompt you for a username and password. A: That's simply not true...you can authenticate with the same login credentials to multiple servers. What you can't do is: * *Be automatically authenticated to the 2nd server *Connect to the same server with different credentials My understanding is that the reason for both problems is that Windows stores the credentials by server name.
{ "language": "en", "url": "https://stackoverflow.com/questions/171878", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Example websites using db4o I'm very impressed with my initial tests with db4o. However, i'm wondering just how many enterprise class websites are out there powered by db4o, i couldn't see any on the main website? I can't see any reason why db4o should not be used. There appears to be decent enough support for transactions and ways to handle concurrency for example. Anyone got a list of websites i could look at? A: A particular search engine used to be powered by db4o (I say "used to" because I haven't talked to the author about this since a long time). http://www.rel8r.com/ The author is Travis Reeder. A: See: http://developer.db4o.com/Projects/html/projectspaces/gaabormarkt.html A: Although I cannot see websites specifically, here is a list of Open Source Projects from the db4o website: http://developer.db4o.com/ProjectSpaces/view.aspx/Open_Source_Products
{ "language": "en", "url": "https://stackoverflow.com/questions/171892", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Best generic strategy to group items using multiple criteria I have a simple, real life problem I want to solve using an OO approach. My harddrive is a mess. I have 1.500.000 files, duplicates, complete duplicate folders, and so on... The first step, of course, is parsing all the files into my database. No problems so far, now I got a lot of nice entries which are kind of "naturaly grouped". Examples for this simple grouping can be obtained using simple queries like: * *Give me all files bigger than 100MB *Show all files older than 3 days *Get me all files ending with docx But now assume I want to find groups with a little more natural meaning. There are different strategies for this, depending on the "use case". Assume I have a bad habit of putting all my downloaded files first on the desktop. Then I extract them to the appropriate folder, without deleting the ZIP file always. The I move them into a "attic" folder. For the system, to find this group of files a time oriented search approach, perhaps combined with a "check if ZIP is same then folder X" would be suitable. Assume another bad habit of duplicating files, having some folder where "the clean files" are located in a nice structure, and another messy folders. Now my clean folder has 20 picture galleries, my messy folder has 5 duplicated and 1 new gallery. A human user could easily identify this logic by seeing "Oh, thats all just duplicates, thats a new one, so I put the new one in the clean folder and trash all the duplicates". So, now to get to the point: Which combination of strategies or patterns would you use to tackle such a situation. If I chain filters the "hardest" would win, and I have no idea how to let the system "test" for suitable combination. And it seemes to me it is more then just filtering. Its dynamic grouping by combining multiple criteria to find the "best" groups. One very rough approach would be this: * *In the beginning, all files are equal *The first, not so "good" group is the directory *If you are a big, clean directory, you earn points (evenly distributed names) *If all files have the same creation date, you may be "autocreated" *If you are a child of Program-Files, I don't care for you at all *If I move you, group A, into group C, would this improve the "entropy" What are the best patterns fitting this situation. Strategy, Filters and Pipes, "Grouping".. Any comments welcome! Edit in reacation to answers: The tagging approach: Of course, tagging crossed my mind. But where do I draw the line. I could create different tag types, like InDirTag, CreatedOnDayXTag, TopicZTag, AuthorPTag. These tags could be structured in a hirarchy, but the question how to group would remain. But I will give this some thought and add my insights here.. The procrastination comment: Yes, it sounds like that. But the files are only the simplest example I could come up with (and the most relevant at the moment). Its actually part of the bigger picture of grouping related data in dynamic ways. Perhaps I should have kept it more abstract, to stress this: I am NOT searching for a file tagging tool or a search engine, but an algorithm or pattern to approach this problem... (or better, ideas, like tagging) Chris A: You're procrastinating. Stop that, and clean up your mess. If it's really big, I recommend the following tactic: * *Make a copy of all the stuff on your drive on an external disk (USB or whatever) *Do a clean install of your system *As soon as you find you need something, get it from your copy, and place it in a well defined location *After 6 months, throw away your external drive. Anything that's on there can't be that important. You can also install Google Desktop, which does not clean your mess, but at least lets you search it efficiently. If you want to prevent this from happening in the future, you have to change the way you're organizing things on your computer. Hope this helps. A: I don't have a solution (and would love to see one), but I might suggest extracting metadata from your files besides the obvious name, size and timestamps. * *in-band metadata such as MP3 ID3 tags, version information for EXEs / DLLs, HTML title and keywords, Summary information for Office documents etc. Even image files can have interesting metadata. A hash of the entire contents helps if looking for duplicates. *out-of-band metadata such as can be stored in NTFS alternate data streams - eg. what you can edit in the Summary tab for non-Office files *your browsers keep information on where you have downloaded files from (though Opera doesn't keep it for long), if you can read it. A: You've got a fever, and the only prescription is Tag Cloud! You're still going to have to clean things up, but with tools like TaggCloud or Tag2Find you can organize your files by meta data as opposed to location on the drive. Tag2Find will watch a share, and when anything is saved to the share a popup appears and asks you to tag the file. You should also get Google Desktop too.
{ "language": "en", "url": "https://stackoverflow.com/questions/171899", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: State of "memset" functionality in C++ with modern compilers Context: A while ago, I stumbled upon this 2001 DDJ article by Alexandrescu: http://www.ddj.com/cpp/184403799 It's about comparing various ways to initialized a buffer to some value. Like what "memset" does for single-byte values. He compared various implementations (memcpy, explicit "for" loop, duff's device) and did not really find the best candidate across all dataset sizes and all compilers. Quote: There is a very deep, and sad, realization underlying all this. We are in 2001, the year of the Spatial Odyssey. (...) Just step out of the box and look at us — after 50 years, we're still not terribly good at filling and copying memory. Question: * *does anyone have more recent information about this problem ? Do recent GCC and Visual C++ implementations perform significantly better than 7 years ago ? *I'm writing code that has a lifetime of 5+ (probably 10+) years and that will process arrays' sizes from a few bytes to hundred of megabytes. I can't assume that my choices now will still be optimal in 5 years. What should I do: * *a) use the system's memset (or equivalent) and forget about optimal performance or assume the runtime and compiler will handle this for me. *b) benchmark once and for all on various array sizes and compilers and switch at runtime between several routines. *c) run the benchmark at program initialization and switch at runtime based on accurate (?) data. Edit: I'm working on image processing software. My array items are PODs and every millisecond counts ! Edit 2: Thanks for the first answers, here are some additional informations: * *Buffer initialization may represent 20%-40% of total runtime of some algorithms. *The platform may vary in the next 5+ years, although it will stay in the "fastest CPU money can buy from DELL" category. Compilers will be some form of GCC and Visual C++. No embedded stuff or exotic architectures on the radar *I'd like to hear from people who had to update their software when MMX and SSE appeared, since I'll have to do the same when "SSE2015" becomes available... :) A: The MASM Forum has a lot of incredible assembly language programmers/hobbyists who have beaten this issue completely to death (have a look through The Laboratory). The results were much like Christopher's response: SSE is incredible for large, aligned, buffers, but going down you will eventually reach such a small size that a basic for loop is just as quick. A: Memset/memcpy are mostly written with a basic instruction set in mind, and so can be outperformed by specialized SSE routines, which on the other hand enforce certain alignment constraints. But to reduce it to a list : * *For data-sets <= several hundred kilobytes memcpy/memset perform faster than anything you could mock up. *For data-sets > megabytes use a combination of memcpy/memset to get the alignment and then use your own SSE optimized routines/fallback to optimized routines from Intel etc. *Enforce the alignment at the start up and use your own SSE-routines. This list only comes into play for things where you need the performance. Too small/or once initialized data-sets are not worth the hassle. Here is an implementation of memcpy from AMD, I can't find the article which described the concept behind the code. A: d) Accept that trying to play "jedi mind tricks" with the initialization will lead to more lost programmer hours than the cumulative milliseconds difference between some obscure but fast method versus something obvious and clear. A: It depends what you're doing. If you have a very specific case, you can often vastly outperform the system libc (and/or compiler inlining) of memset and memcpy. For example, for the program I work on, I wrote a 16-byte-aligned memcpy and memset designed for small data sizes. The memcpy was made for multiple-of-16 sizes greater than or equal to 64 only (with data aligned to 16), and memset was made for multiple-of-128 sizes only. These restrictions allowed me to get enormous speed, and since I controlled the application, I could tailor the functions specifically to what was needed, and also tailor the application to align all necessary data. The memcpy performed at about 8-9x the speed of the Windows native memcpy, knocing a 460-byte copy down to a mere 50 clock cycles. The memset was about 2.5x faster, filling a stack array of zeros extremely quickly. If you're interested in these functions, they can be found here; drop down to around line 600 for the memcpy and memset. They're rather trivial. Note they're designed for small buffers that are supposed to be in cache; if you want to initialize enormous amounts of data in memory while bypassing cache, your issue may be more complex. A: You can take a look on liboil, they (try to) provide different implementation of the same function and choosing the fastest on initialization. Liboil has a pretty liberal licence, so you can take it also for proprietary software. http://liboil.freedesktop.org/ A: The DDJ article acknowledges that memset is the best answer, and much faster than what he was trying to achieve: There is something sacrosanct about C's memory manipulation functions memset, memcpy, and memcmp. They are likely to be highly optimized by the compiler vendor, to the extent that the compiler might detect calls to these functions and replace them with inline assembler instructions — this is the case with MSVC. So, if memset works for you (ie. you are initializing with a single byte) then use it. Whilst every millisecond may count, you should establish what percentage of your execution time is lost to setting memory. It is likely very low (1 or 2%??) given that you have useful work to do as well. Given that the optimization effort would likely have a much better rate of return elsewhere. A: Well this all depends on your problem domain and your specifications, have you ran into performance issues, failed to meet timing deadline and pinpointed memset as being the root of all evil ? If it this you're in the one and only case where you could consider some memset tuning. Then you should also keep in mind that the memset anyhow will vary on the hardware the platform it is ran on, during those five years, will the software run on the same platform ? On the same architecture ? One you come to that conclusion you can try to 'roll your own' memset, typically playing with the alignment of buffers, making sure you zero 32 bit values at once depending on what is most performant on your architecture. I once ran into the same for memcmpt where the alignment overhead caused some problems, bit typically this will not result in miracles, only a small improvement, if any. If you're missing your requirements by an order of mangnitude than this won't get you any further. A: If memory is not a problem, then precreate a static buffer of the size you need, initialized to your value(s). As far as I know, both these compilers are optimizing compilers, so if you use a simple for-loop, the compiler should generate the optimum assembler-commands to copy the buffer across. If memory is a problem, use a smaller buffer & copy that accross at sizeof(..) offsets into the new buffer. HTH A: I would always choose an initialization method that is part of the runtime or OS (memset) I am using (worse case pick one that is part of a library that I am using). Why: If you are implementing your own initialization, you might end up with a marginally better solution now, but it is likely that in a couple of years the runtime has improved. And you don't want to do the same work that the guys maintaining the runtime do. All this stands if the improvement in runtime is marginal. If you have a difference of an order of magnitude between memset and your own initialization, then it makes sense to have your code running, but I really doubt this case. A: If you have to allocate your memory as well as initialize it, I would: * *Use calloc instead of malloc *Change as much of my default values to be zero as possible (ex: let my default enumeration value be zero; or if a boolean variable's default value is 'true', store it's inverse value in the structure) The reason for this is that calloc zero-initializes memory for you. While this will involve the overhead for zeroing memory, most compilers are likely to have this routine highly-optimized -- more optimized that malloc/new with a call to memcpy. A: As always with these types of questions, the problem is constrained by factors outside of your control, namely, the bandwidth of the memory. And if the host OS decides to start paging the memory then things get far worse. On Win32 platforms, the memory is paged and pages are only allocated on first use which will generate a big pause every page boundary whilst the OS finds a page to use (this may require another process' page to be paged to disk). This, however, is the absolute fastest memset ever written: void memset (void *memory, size_t size, byte value) { } Not doing something is always the fastest way. Is there any way the algorithms can be written to avoid the initial memset? What are the algorithms you're using? A: The year isn't 2001 anymore. Since then, new versions of Visual Studio have appeared. I've taken the time to study the memset in those. They will use SSE for memset (if available, of course). If your old code was correct, statistically if will now be faster. But you might hit an unfortunate cornercase. I expect the same from GCC, although I haven't studied the code. It's a fairly obvious improvement, and an Open-Source compiler. Someone will have created the patch.
{ "language": "en", "url": "https://stackoverflow.com/questions/171917", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "19" }
Q: How do I syntax check a Bash script without running it? Is it possible to check a bash script syntax without executing it? Using Perl, I can run perl -c 'script name'. Is there any equivalent command for bash scripts? A: I actually check all bash scripts in current dir for syntax errors WITHOUT running them using find tool: Example: find . -name '*.sh' -print0 | xargs -0 -P"$(nproc)" -I{} bash -n "{}" If you want to use it for a single file, just edit the wildcard with the name of the file. A: bash -n scriptname Perhaps an obvious caveat: this validates syntax but won't check if your bash script tries to execute a command that isn't in your path, like ech hello instead of echo hello. A: I also enable the 'u' option on every bash script I write in order to do some extra checking: set -u This will report the usage of uninitialized variables, like in the following script 'check_init.sh' #!/bin/sh set -u message=hello echo $mesage Running the script : $ check_init.sh Will report the following : ./check_init.sh[4]: mesage: Parameter not set. Very useful to catch typos A: null command [colon] also useful when debugging to see variable's value set -x for i in {1..10}; do let i=i+1 : i=$i done set - A: For only validating syntax: shellcheck [programPath] For running the program only if syntax passes, so debugging both syntax and execution: shellproof [programPath] A: Bash shell scripts will run a syntax check if you enable syntax checking with set -o noexec if you want to turn off syntax checking set +o noexec A: sh -n script-name Run this. If there are any syntax errors in the script, then it returns the same error message. If there are no errors, then it comes out without giving any message. You can check immediately by using echo $?, which will return 0 confirming successful without any mistake. It worked for me well. I ran on Linux OS, Bash Shell. A: There is BashSupport plugin for IntelliJ IDEA which checks the syntax. A: Time changes everything. Here is a web site which provide online syntax checking for shell script. I found it is very powerful detecting common errors. About ShellCheck ShellCheck is a static analysis and linting tool for sh/bash scripts. It's mainly focused on handling typical beginner and intermediate level syntax errors and pitfalls where the shell just gives a cryptic error message or strange behavior, but it also reports on a few more advanced issues where corner cases can cause delayed failures. Haskell source code is available on GitHub! A: If you need in a variable the validity of all the files in a directory (git pre-commit hook, build lint script), you can catch the stderr output of the "sh -n" or "bash -n" commands (see other answers) in a variable, and have a "if/else" based on that bashErrLines=$(find bin/ -type f -name '*.sh' -exec sh -n {} \; 2>&1 > /dev/null) if [ "$bashErrLines" != "" ]; then # at least one sh file in the bin dir has a syntax error echo $bashErrLines; exit; fi Change "sh" with "bash" depending on your needs
{ "language": "en", "url": "https://stackoverflow.com/questions/171924", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "316" }
Q: jquery-ui-dialog - How to hook into dialog close event I am using the jquery-ui-dialog plugin I am looking for way to refresh the page when in some circumstances when the dialog is closed. Is there a way to capture a close event from the dialog? I know I can run code when the close button is clicked but that doesn't cover the user closing with escape or the x in the top right corner. A: As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document. Because no one actually created an answer with using .on() instead of bind() i decided to create one. $('div#dialog').on('dialogclose', function(event) { //custom logic fired after dialog is closed. }); A: add option 'close' like under sample and do what you want inline function close: function(e){ //do something } A: If I'm understanding the type of window you're talking about, wouldn't $(window).unload() (for the dialog window) give you the hook you need? (And if I misunderstood, and you're talking about a dialog box made via CSS rather than a pop-up browser window, then all the ways of closing that window are elements you could register click handers for.) Edit: Ah, I see now you're talking about jquery-ui dialogs, which are made via CSS. You can hook the X which closes the window by registering a click handler for the element with the class ui-dialog-titlebar-close. More useful, perhaps, is you tell you how to figure that out quickly. While displaying the dialog, just pop open FireBug and Inspect the elements that can close the window. You'll instantly see how they are defined and that gives you what you need to register the click handlers. So to directly answer your question, I believe the answer is really "no" -- there's isn't a close event you can hook, but "yes" -- you can hook all the ways to close the dialog box fairly easily and get what you want. A: $("#dialog").dialog({ autoOpen: false, resizable: false, width: 400, height: 140, modal: true, buttons: { "SUBMIT": function() { $("form").submit(); }, "CANCEL": function() { $(this).dialog("close"); } }, close: function() { alert('close'); } }); A: I have found it! You can catch the close event using the following code: $('div#popup_content').on('dialogclose', function(event) { alert('closed'); }); Obviously I can replace the alert with whatever I need to do. Edit: As of Jquery 1.7, the bind() has become on() A: $( "#dialogueForm" ).dialog({ autoOpen: false, height: "auto", width: "auto", modal: true, my: "center", at: "center", of: window, close : function(){ // functionality goes here } }); "close" property of dialog gives the close event for the same. A: I believe you can also do it while creating the dialog (copied from a project I did): dialog = $('#dialog').dialog({ modal: true, autoOpen: false, width: 700, height: 500, minWidth: 700, minHeight: 500, position: ["center", 200], close: CloseFunction, overlay: { opacity: 0.5, background: "black" } }); Note close: CloseFunction A: You may try the following code for capturing the closing event for any item : page, dialog etc. $("#dialog").live('pagehide', function(event, ui) { $(this).hide(); }); A: U can also try this $("#dialog").dialog({ autoOpen: false, resizable: true, height: 400, width: 150, position: 'center', title: 'Term Sheet', beforeClose: function(event, ui) { console.log('Event Fire'); }, modal: true, buttons: { "Submit": function () { $(this).dialog("close"); }, "Cancel": function () { $(this).dialog("close"); } } }); A: This is what worked for me... $('#dialog').live("dialogclose", function(){ //code to run on dialog close });
{ "language": "en", "url": "https://stackoverflow.com/questions/171928", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "192" }
Q: What does it mean to run a virtual OS in "headless mode"? I've been hearing a lot about about how the new version of VMWare Fusion can run virtual operating systems in "headless mode". A Google search makes it clear that other virtualisation products also have similar features, however, I have not been able to find a good description of what this actually means? What is happening when you do this? A: For anyone that is interested, you can activate headless mode in VMWare Fusion by running the following command in Terminal.app defaults write com.vmware.fusion fluxCapacitor -bool YES A: Headless mode means that the virtual machine is running in the background without any foreground elements visible (like the Vmware Fusion application) You would have no screen to see running the front end; i.e. the screen/console would not be visible, even though the operating system is running, and would typically have to access the machine via SSH.
{ "language": "en", "url": "https://stackoverflow.com/questions/171948", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "28" }
Q: Is there a destructor for Java? Is there a destructor for Java? I don't seem to be able to find any documentation on this. If there isn't, how can I achieve the same effect? To make my question more specific, I am writing an application that deals with data and the specification say that there should be a 'reset' button that brings the application back to its original just launched state. However, all data have to be 'live' unless the application is closed or reset button is pressed. Being usually a C/C++ programmer, I thought this would be trivial to implement. (And hence I planned to implement it last.) I structured my program such that all the 'reset-able' objects would be in the same class so that I can just destroy all 'live' objects when a reset button is pressed. I was thinking if all I did was just to dereference the data and wait for the garbage collector to collect them, wouldn't there be a memory leak if my user repeatedly entered data and pressed the reset button? I was also thinking since Java is quite mature as a language, there should be a way to prevent this from happening or gracefully tackle this. A: I agree with most of the answers. You should not depend fully on either finalize or ShutdownHook finalize * *The JVM does not guarantee when this finalize() method will be invoked. *finalize() gets called only once by GC thread. If an object revives itself from finalizing method, then finalize will not be called again. *In your application, you may have some live objects, on which garbage collection is never invoked. *Any Exception that is thrown by the finalizing method is ignored by the GC thread *System.runFinalization(true) and Runtime.getRuntime().runFinalization(true) methods increase the probability of invoking finalize() method but now these two methods have been deprecated. These methods are very dangerous due to lack of thread safety and possible deadlock creation. shutdownHooks public void addShutdownHook(Thread hook) Registers a new virtual-machine shutdown hook. The Java virtual machine shuts down in response to two kinds of events: * *The program exits normally, when the last non-daemon thread exits or when the exit (equivalently, System.exit) method is invoked, or *The virtual machine is terminated in response to a user interrupt, such as typing ^C, or a system-wide event, such as user logoff or system shutdown. *A shutdown hook is simply an initialized but non-started thread. When the virtual machine begins its shutdown sequence it will start all registered shutdown hooks in some unspecified order and let them run concurrently. When all the hooks have finished it will then run all uninvoked finalizers if finalization-on-exit has been enabled. *Finally, the virtual machine will halt. Note that daemon threads will continue to run during the shutdown sequence, as will non-daemon threads if the shutdown was initiated by invoking the exit method. *Shutdown hooks should also finish their work quickly. When a program invokes exit the expectation is that the virtual machine will promptly shut down and exit. But even Oracle documentation quoted that In rare circumstances the virtual machine may abort, that is, stop running without shutting down cleanly This occurs when the virtual machine is terminated externally, for example with the SIGKILL signal on Unix or the TerminateProcess call on Microsoft Windows. The virtual machine may also abort if a native method goes awry by, for example, corrupting internal data structures or attempting to access nonexistent memory. If the virtual machine aborts then no guarantee can be made about whether or not any shutdown hooks will be run. Conclusion : use try{} catch{} finally{} blocks appropriately and release critical resources in finally(} block. During release of resources in finally{} block, catch Exception and Throwable. A: First, note that since Java is garbage-collected, it is rare to need to do anything about object destruction. Firstly because you don't usually have any managed resources to free, and secondly because you can't predict when or if it will happen, so it's inappropriate for things that you need to occur "as soon as nobody is using my object any more". You can be notified after an object has been destroyed using java.lang.ref.PhantomReference (actually, saying it has been destroyed may be slightly inaccurate, but if a phantom reference to it is queued then it's no longer recoverable, which usually amounts to the same thing). A common use is: * *Separate out the resource(s) in your class that need to be destructed into another helper object (note that if all you're doing is closing a connection, which is a common case, you don't need to write a new class: the connection to be closed would be the "helper object" in that case). *When you create your main object, create also a PhantomReference to it. Either have this refer to the new helper object, or set up a map from PhantomReference objects to their corresponding helper objects. *After the main object is collected, the PhantomReference is queued (or rather it may be queued - like finalizers there is no guarantee it ever will be, for example if the VM exits then it won't wait). Make sure you're processing its queue (either in a special thread or from time to time). Because of the hard reference to the helper object, the helper object has not yet been collected. So do whatever cleanup you like on the helper object, then discard the PhantomReference and the helper will eventually be collected too. There is also finalize(), which looks like a destructor but doesn't behave like one. It's usually not a good option. A: The finalize() function is the destructor. However, it should not be normally used because it is invoked after the GC and you can't tell when that will happen (if ever). Moreover, it takes more than one GC to deallocate objects that have finalize(). You should try to clean up in the logical places in your code using the try{...} finally{...} statements! A: Because Java is a garbage collected language you cannot predict when (or even if) an object will be destroyed. Hence there is no direct equivalent of a destructor. There is an inherited method called finalize, but this is called entirely at the discretion of the garbage collector. So for classes that need to explicitly tidy up, the convention is to define a close method and use finalize only for sanity checking (i.e. if close has not been called do it now and log an error). There was a question that spawned in-depth discussion of finalize recently, so that should provide more depth if required... A: If it's just memory you are worried about, don't. Just trust the GC it does a decent job. I actually saw something about it being so efficient that it could be better for performance to create heaps of tiny objects than to utilize large arrays in some instances. A: Use of finalize() methods should be avoided. They are not a reliable mechanism for resource clean up and it is possible to cause problems in the garbage collector by abusing them. If you require a deallocation call in your object, say to release resources, use an explicit method call. This convention can be seen in existing APIs (e.g. Closeable, Graphics.dispose(), Widget.dispose()) and is usually called via try/finally. Resource r = new Resource(); try { //work } finally { r.dispose(); } Attempts to use a disposed object should throw a runtime exception (see IllegalStateException). EDIT: I was thinking, if all I did was just to dereference the data and wait for the garbage collector to collect them, wouldn't there be a memory leak if my user repeatedly entered data and pressed the reset button? Generally, all you need to do is dereference the objects - at least, this is the way it is supposed to work. If you are worried about garbage collection, check out Java SE 6 HotSpot[tm] Virtual Machine Garbage Collection Tuning (or the equivalent document for your JVM version). A: Perhaps you can use a try ... finally block to finalize the object in the control flow at which you are using the object. Of course it doesn't happen automatically, but neither does destruction in C++. You often see closing of resources in the finally block. A: There is a @Cleanup annotation in Lombok that mostly resembles C++ destructors: @Cleanup ResourceClass resource = new ResourceClass(); When processing it (at compilation time), Lombok inserts appropriate try-finally block so that resource.close() is invoked, when execution leaves the scope of the variable. You can also specify explicitly another method for releasing the resource, e.g. resource.dispose(): @Cleanup("dispose") ResourceClass resource = new ResourceClass(); A: With Java 1.7 released, you now have the additional option of using the try-with-resources block. For example, public class Closeable implements AutoCloseable { @Override public void close() { System.out.println("closing..."); } public static void main(String[] args) { try (Closeable c = new Closeable()) { System.out.println("trying..."); throw new Exception("throwing..."); } catch (Exception e) { System.out.println("catching..."); } finally { System.out.println("finalizing..."); } } } If you execute this class, c.close() will be executed when the try block is left, and before the catch and finally blocks are executed. Unlike in the case of the finalize() method, close() is guaranteed to be executed. However, there is no need of executing it explicitly in the finally clause. A: The closest equivalent to a destructor in Java is the finalize() method. The big difference to a traditional destructor is that you can't be sure when it'll be called, since that's the responsibility of the garbage collector. I'd strongly recommend carefully reading up on this before using it, since your typical RAIA patterns for file handles and so on won't work reliably with finalize(). A: Just thinking about the original question... which, I think we can conclude from all the other learned answers, and also from Bloch's essential Effective Java, item 7, "Avoid finalizers", seeks the solution to a legitimate question in a manner which is inappropriate to the Java language...: ... wouldn't a pretty obvious solution to do what the OP actually wants be to keep all your objects which need to be reset in a sort of "playpen", to which all other non-resettable objects have references only through some sort of accessor object... And then when you need to "reset" you disconnect the existing playpen and make a new one: all the web of objects in the playpen is cast adrift, never to return, and one day to be collected by the GC. If any of these objects are Closeable (or not, but have a close method) you could put them in a Bag in the playpen as they are created (and possibly opened), and the last act of the accessor before cutting off the playpen would be to go through all the Closeables closing them... ? The code would probably look something like this: accessor.getPlaypen().closeCloseables(); accessor.setPlaypen( new Playpen() ); closeCloseables would probably be a blocking method, probably involving a latch (e.g. CountdownLatch), to deal with (and wait as appropriate for) any Runnables/Callables in any threads specific to the Playpen to be ended as appropriate, in particular in the JavaFX thread. A: Many great answers here, but there is some additional information about why you should avoid using finalize(). If the JVM exits due to System.exit() or Runtime.getRuntime().exit(), finalizers will not be run by default. From Javadoc for Runtime.exit(): The virtual machine's shutdown sequence consists of two phases. In the first phase all registered shutdown hooks, if any, are started in some unspecified order and allowed to run concurrently until they finish. In the second phase all uninvoked finalizers are run if finalization-on-exit has been enabled. Once this is done the virtual machine halts. You can call System.runFinalization() but it only makes "a best effort to complete all outstanding finalizations" – not a guarantee. There is a System.runFinalizersOnExit() method, but don't use it – it's unsafe, deprecated long ago. A: If you got the chance of using a Contexts and Dependency Injection (CDI) framework such as Weld you can use the Java annotation @Predestroy for doing cleanup jobs etc. @javax.enterprise.context.ApplicationScoped public class Foo { @javax.annotation.PreDestroy public void cleanup() { // do your cleanup } } A: I fully agree to other answers, saying not to rely on the execution of finalize. In addition to try-catch-finally blocks, you may use Runtime#addShutdownHook (introduced in Java 1.3) to perform final cleanups in your program. That isn't the same as destructors are, but one may implement a shutdown hook having listener objects registered on which cleanup methods (close persistent database connections, remove file locks, and so on) can be invoked - things that would normally be done in destructors. Again - this is not a replacement for destructors but in some cases, you can approach the wanted functionality with this. The advantage of this is having deconstruction behavior loosely coupled from the rest of your program. A: Have a look at the try-with-resources statement. For example: try (BufferedReader br = new BufferedReader(new FileReader(path))) { System.out.println(br.readLine()); } catch (Exception e) { ... } finally { ... } Here the resource that is no longer needed is freed in the BufferedReader.close() method. You can create your own class that implements AutoCloseable and use it in a similar fashion. This statement is more limited than finalize in terms of code structuring, but at the same time it makes the code simpler to understand and maintain. Also, there is no guarantee that a finalize method is called at all during the livetime of the application. A: No, java.lang.Object#finalize is the closest you can get. However, when (and if) it is called, is not guaranteed. See: java.lang.Runtime#runFinalizersOnExit(boolean) A: Nope, no destructors here. The reason is that all Java objects are heap allocated and garbage collected. Without explicit deallocation (i.e. C++'s delete operator) there is no sensible way to implement real destructors. Java does support finalizers, but they are meant to be used only as a safeguard for objects holding a handle to native resources like sockets, file handles, window handles, etc. When the garbage collector collects an object without a finalizer it simply marks the memory region as free and that's it. When the object has a finalizer, it's first copied into a temporary location (remember, we're garbage collecting here), then it's enqueued into a waiting-to-be-finalized queue and then a Finalizer thread polls the queue with very low priority and runs the finalizer. When the application exits, the JVM stops without waiting for the pending objects to be finalized, so there practically no guarantees that your finalizers will ever run. A: Though there have been considerable advancements in Java's GC technology, you still need to be mindful of your references. Numerous cases of seemingly trivial reference patterns that are actually rats nests under the hood come to mind. From your post it doesn't sound like you're trying to implement a reset method for the purpose of object reuse (true?). Are your objects holding any other type of resources that need to be cleaned up (i.e., streams that must be closed, any pooled or borrowed objects that must be returned)? If the only thing you're worried about is memory dealloc then I would reconsider my object structure and attempt to verify that my objects are self contained structures that will be cleaned up at GC time. A: If you're writing a Java Applet, you can override the Applet "destroy()" method. It is... * Called by the browser or applet viewer to inform * this applet that it is being reclaimed and that it should destroy * any resources that it has allocated. The stop() method * will always be called before destroy(). Obviously not what you want, but might be what other people are looking for. A: No Java doesn't have any destructors .The main reason behind it in Java is the Garbage Collectors that passively works in the background always and all the objects are made in the heap memory , that is the place where GC works .In c++ there we have to explicitly call the delete function since there is no Garbage collector like thing. A: In Java, the garbage collector automatically deletes the unused objects to free up the memory. So it’s sensible Java has no destructors available. A: Try calling the onDestroy() method when it comes to android programming. This is the last method that executed just before the Activity/Service class is killed. A: Missing form all the answers I just scanned is the safer replacement for finalizers. All of the other answers are correct about using try-with-resources and avoiding finalizers as they are unreliable and are now deprecated... However they haven't mentioned Cleaners. Cleaners were added in Java 9 to explicitly handle the job of cleanup in a better way than finalizers. https://docs.oracle.com/javase/9/docs/api/java/lang/ref/Cleaner.html A: I used to mainly deal with C++ and that is what lead me to the search of a destructor as well. I am using JAVA a lot now. What I did, and it may not be the best case for everyone, but I implemented my own destructor by reseting all the values to either 0 or there default through a function. Example: public myDestructor() { variableA = 0; //INT variableB = 0.0; //DOUBLE & FLOAT variableC = "NO NAME ENTERED"; //TEXT & STRING variableD = false; //BOOL } Ideally this won't work for all situations, but where there are global variables it will work as long as you don't have a ton of them. I know I am not the best Java programmer, but it seems to be working for me.
{ "language": "en", "url": "https://stackoverflow.com/questions/171952", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "656" }
Q: AG_E_PARSER_BAD_PROPERTY_VALUE for StaticResource in Silverlight I'm storing all localizable strings in a ResourceDictionary (in App.xaml) and assign those via the StaticResource markup extension to TextBlock.Text, Button.Content etc. In Beta 2 and RC0, sometimes parsing the XAML in InitializeComponent() will fail with an AG_E_PARSER_BAD_PROPERTY_VALUE on the line and position where I set the attribute value to the StaticResource. It only happens sometimes: When restarting the app, it parses and displays without any problems. The same interface code works for days or weeks, then it happens again. Any ideas? A: Parser, at least in beta 2, didnt like whitespace... For instance: Text="{StaticResource bleh}" worked however this: Text = "{StaticResource bleh}" bombed A: Basically it means bad xaml somewhere in the code you can see the Line number and Position and see something is wrong .. I got the same error in my xaml Once corrected everything seems working
{ "language": "en", "url": "https://stackoverflow.com/questions/171962", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I find the method that called the current method? When logging in C#, how can I learn the name of the method that called the current method? I know all about System.Reflection.MethodBase.GetCurrentMethod(), but I want to go one step beneath this in the stack trace. I've considered parsing the stack trace, but I am hoping to find a cleaner more explicit way, something like Assembly.GetCallingAssembly() but for methods. A: A quick recap of the 2 approaches with speed comparison being the important part. http://geekswithblogs.net/BlackRabbitCoder/archive/2013/07/25/c.net-little-wonders-getting-caller-information.aspx Determining the caller at compile-time static void Log(object message, [CallerMemberName] string memberName = "", [CallerFilePath] string fileName = "", [CallerLineNumber] int lineNumber = 0) { // we'll just use a simple Console write for now Console.WriteLine("{0}({1}):{2} - {3}", fileName, lineNumber, memberName, message); } Determining the caller using the stack static void Log(object message) { // frame 1, true for source info StackFrame frame = new StackFrame(1, true); var method = frame.GetMethod(); var fileName = frame.GetFileName(); var lineNumber = frame.GetFileLineNumber(); // we'll just use a simple Console write for now Console.WriteLine("{0}({1}):{2} - {3}", fileName, lineNumber, method.Name, message); } Comparison of the 2 approaches Time for 1,000,000 iterations with Attributes: 196 ms Time for 1,000,000 iterations with StackTrace: 5096 ms So you see, using the attributes is much, much faster! Nearly 25x faster in fact. A: /// <summary> /// Returns the call that occurred just before the "GetCallingMethod". /// </summary> public static string GetCallingMethod() { return GetCallingMethod("GetCallingMethod"); } /// <summary> /// Returns the call that occurred just before the the method specified. /// </summary> /// <param name="MethodAfter">The named method to see what happened just before it was called. (case sensitive)</param> /// <returns>The method name.</returns> public static string GetCallingMethod(string MethodAfter) { string str = ""; try { StackTrace st = new StackTrace(); StackFrame[] frames = st.GetFrames(); for (int i = 0; i < st.FrameCount - 1; i++) { if (frames[i].GetMethod().Name.Equals(MethodAfter)) { if (!frames[i + 1].GetMethod().Name.Equals(MethodAfter)) // ignores overloaded methods. { str = frames[i + 1].GetMethod().ReflectedType.FullName + "." + frames[i + 1].GetMethod().Name; break; } } } } catch (Exception) { ; } return str; } A: We can improve on Mr Assad's code (the current accepted answer) just a little bit by instantiating only the frame we actually need rather than the entire stack: new StackFrame(1).GetMethod().Name; This might perform a little better, though in all likelihood it still has to use the full stack to create that single frame. Also, it still has the same caveats that Alex Lyman pointed out (optimizer/native code might corrupt the results). Finally, you might want to check to be sure that new StackFrame(1) or .GetFrame(1) don't return null, as unlikely as that possibility might seem. See this related question: Can you use reflection to find the name of the currently executing method? A: Maybe you are looking for something like this: StackFrame frame = new StackFrame(1); frame.GetMethod().Name; //Gets the current method name MethodBase method = frame.GetMethod(); method.DeclaringType.Name //Gets the current class name A: Try this: using System.Diagnostics; // Get call stack StackTrace stackTrace = new StackTrace(); // Get calling method name Console.WriteLine(stackTrace.GetFrame(1).GetMethod().Name); one-liner: (new System.Diagnostics.StackTrace()).GetFrame(1).GetMethod().Name It is from Get Calling Method using Reflection [C#]. A: In general, you can use the System.Diagnostics.StackTrace class to get a System.Diagnostics.StackFrame, and then use the GetMethod() method to get a System.Reflection.MethodBase object. However, there are some caveats to this approach: * *It represents the runtime stack -- optimizations could inline a method, and you will not see that method in the stack trace. *It will not show any native frames, so if there's even a chance your method is being called by a native method, this will not work, and there is in-fact no currently available way to do it. (NOTE: I am just expanding on the answer provided by Firas Assad.) A: As of .NET 4.5 you can use Caller Information Attributes: * *CallerFilePath - The source file that called the function; *CallerLineNumber - Line of code that called the function; *CallerMemberName - Member that called the function. public void WriteLine( [CallerFilePath] string callerFilePath = "", [CallerLineNumber] long callerLineNumber = 0, [CallerMemberName] string callerMember= "") { Debug.WriteLine( "Caller File Path: {0}, Caller Line Number: {1}, Caller Member: {2}", callerFilePath, callerLineNumber, callerMember); }   This facility is also present in ".NET Core" and ".NET Standard". References * *Microsoft - Caller Information (C#) *Microsoft - CallerFilePathAttribute Class *Microsoft - CallerLineNumberAttribute Class *Microsoft - CallerMemberNameAttribute Class A: In C# 5, you can get that information using caller info: //using System.Runtime.CompilerServices; public void SendError(string Message, [CallerMemberName] string callerName = "") { Console.WriteLine(callerName + "called me."); } You can also get the [CallerFilePath] and [CallerLineNumber]. A: private static MethodBase GetCallingMethod() { return new StackFrame(2, false).GetMethod(); } private static Type GetCallingType() { return new StackFrame(2, false).GetMethod().DeclaringType; } A fantastic class is here: http://www.csharp411.com/c-get-calling-method/ A: Another approach I have used is to add a parameter to the method in question. For example, instead of void Foo(), use void Foo(string context). Then pass in some unique string that indicates the calling context. If you only need the caller/context for development, you can remove the param before shipping. A: For getting Method Name and Class Name try this: public static void Call() { StackTrace stackTrace = new StackTrace(); var methodName = stackTrace.GetFrame(1).GetMethod(); var className = methodName.DeclaringType.Name.ToString(); Console.WriteLine(methodName.Name + "*****" + className ); } A: Extra information to Firas Assaad answer. I have used new StackFrame(1).GetMethod().Name; in .net core 2.1 with dependency injection and I am getting calling method as 'Start'. I tried with [System.Runtime.CompilerServices.CallerMemberName] string callerName = "" and it gives me correct calling method A: Obviously this is a late answer, but I have a better option if you can use .NET 4.5 or newer: internal static void WriteInformation<T>(string text, [CallerMemberName]string method = "") { Console.WriteLine(DateTime.Now.ToString() + " => " + typeof(T).FullName + "." + method + ": " + text); } This will print the current Date and Time, followed by "Namespace.ClassName.MethodName" and ending with ": text". Sample output: 6/17/2016 12:41:49 PM => WpfApplication.MainWindow..ctor: MainWindow initialized Sample use: Logger.WriteInformation<MainWindow>("MainWindow initialized"); A: Note that doing so will be unreliable in release code, due to optimization. Additionally, running the application in sandbox mode (network share) won't allow you to grab the stack frame at all. Consider aspect-oriented programming (AOP), like PostSharp, which instead of being called from your code, modifies your code, and thus knows where it is at all times. A: You can use Caller Information and optional parameters: public static string WhoseThere([CallerMemberName] string memberName = "") { return memberName; } This test illustrates this: [Test] public void Should_get_name_of_calling_method() { var methodName = CachingHelpers.WhoseThere(); Assert.That(methodName, Is.EqualTo("Should_get_name_of_calling_method")); } While the StackTrace works quite fast above and would not be a performance issue in most cases the Caller Information is much faster still. In a sample of 1000 iterations, I clocked it as 40 times faster. A: We can also use lambda's in order to find the caller. Suppose you have a method defined by you: public void MethodA() { /* * Method code here */ } and you want to find it's caller. 1. Change the method signature so we have a parameter of type Action (Func will also work): public void MethodA(Action helperAction) { /* * Method code here */ } 2. Lambda names are not generated randomly. The rule seems to be: > <CallerMethodName>__X where CallerMethodName is replaced by the previous function and X is an index. private MethodInfo GetCallingMethodInfo(string funcName) { return GetType().GetMethod( funcName.Substring(1, funcName.IndexOf("&gt;", 1, StringComparison.Ordinal) - 1) ); } 3. When we call MethodA the Action/Func parameter has to be generated by the caller method. Example: MethodA(() => {}); 4. Inside MethodA we can now call the helper function defined above and find the MethodInfo of the caller method. Example: MethodInfo callingMethodInfo = GetCallingMethodInfo(serverCall.Method.Name); A: StackFrame caller = (new System.Diagnostics.StackTrace()).GetFrame(1); string methodName = caller.GetMethod().Name; will be enough, I think.
{ "language": "en", "url": "https://stackoverflow.com/questions/171970", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "613" }
Q: How can I extract a line or row? How can I extract the whole line in a row, for example, row 3. These data are saved in my text editor in linux. Here's my data: 1,julz,kath,shiela,angel 2,may,ann,janice,aika 3,christal,justine,kim 4,kris,allan,jc,mine I want output like: 3,christal,justine,kim A: $ perl -ne'print if $. == 3' your_file.txt Below is a script version of @ysth's answer: $ perl -mTie::File -e'tie @lines, q(Tie::File), q(your_file.txt); > print $lines[2]' A: If it's always the third line: perl -ne 'print if 3..3' <infile >outfile If it's always the one that has a numeric value of "3" as the first column: perl -F, -nae 'print if $F[0] == 3' <infile >outfile # thanks for the comment doh! Since you didn't say how you were identifying that line, I am providing alternatives. A: Um, the -n answers are assuming the question is "what is a script that...". In which case, perl isn't even the best answer. But I don't read that into the question. In general, if the lines are not of fixed length, you have to read through a file line by line until you get to the line you want. Tie::File automates this process for you (though since the code it would replace is so trivial, I rarely bother with it, myself). use Tie::File; use Fcntl "O_RDONLY"; tie my @line, "Tie::File", "yourfilename", mode => O_RDONLY or die "Couldn't open file: $!"; print "The third line is ", $line[2]; A: For a more general solution: open my $fh, '<', 'infile.txt'; while (my $line = <$fh>) { print $line if i_want_this_line($line); } where i_want_this_line implements the criteria defining which line(s) you want. A: You can assign the diamond operator on your filehandle to a list, each element will be a line or row. open $fh, "myfile.txt"; my @lines = <$fh>; EDIT: This solution grabs all the lines so that you can access any one you want, e.g. row 3 would be $lines[2] ... If you really only want one specific line, that'd be a different solution, like the other answerers'. A: The following snippet reads in the first three lines, prints only the third then exits to ensure that no unnecessary processing takes place. Without the exit, the script would continue to process the input file despite you knowing that you have no use for it. perl -ne 'if ($. == 3) {print;exit}' infile.txt As perlvar points out, $. is the current line number for the last file handle accessed.
{ "language": "en", "url": "https://stackoverflow.com/questions/171999", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: when updating a whole project's root, how to exclude svn externals from being updated? Is there a way to exclude all svn externals when doing a recursive update? Is there a way to exclude only 1 of all of the svn externals when doing a recursive update? Basically I'd like to cut down the svn update time, and a couple of the SVN externals that I have will just about never get updated. A: If you are using TortoiseSVN, you can do the same thing as "svn update --ignore-externals". Use the "Update to revision..." menu item instead of the normal "Update". On that dialog you have a "Omit Externals" checkbox. A: Yes, there is an option for this (to ignore all): > svn update --ignore-externals I don't know of any option to specifically ignore one or some externals while updating the rest. A: I'd recommend changing the default context menu items to have Update to Revision on the main context menu. In the TortoiseSVN settings, go to 'Look and Feel', then uncheck items you want main folder context menu and check items you want in the submenu. I have the following unchecked. * *Checkout *Commit *Show Log *Check for modifications *Update to Revision The great thing about having all these items is that they only show up when relevant, ie, when the directory is a working copy. So for a non SVN folder you will just get Checkout.
{ "language": "en", "url": "https://stackoverflow.com/questions/172018", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: How do you develop against OpenID locally I'm developing a website (in Django) that uses OpenID to authenticate users. As I'm currently only running on my local machine I can't authenticate using one of the OpenID providers on the web. So I figure I need to run a local OpenID server that simply lets me type in a username and then passes that back to my main app. Does such an OpenID dev server exist? Is this the best way to go about it? A: I have no problems testing with myopenid.com. I thought there would be a problem testing on my local machine but it just worked. (I'm using ASP.NET with DotNetOpenId library). The 'realm' and return url must contain the port number like 'http://localhost:93359'. I assume it works OK because the provider does a client side redirect. A: I'm also looking into this. I too am working on a Django project that might utilize Open Id. For references, check out: * *PHPMyId *OpenId's page Hopefully someone here has tackled this issue. A: I'm using phpMyID to authenticate at StackOverflow right now. Generates a standard HTTP auth realm and works perfectly. It should be exactly what you need. A: You could probably use the django OpenID library to write a provider to test against. Have one that always authenticates and one that always fails. A: The libraries at OpenID Enabled ship with examples that are sufficient to run a local test provider. Look in the examples/djopenid/ directory of the python-openid source distribution. Running that will give you an instance of this test provider. A: Why not run an OpenID provider from your local machine? If you are a .Net developer there is an OpenID provider library for .Net at Google Code. This uses the standard .Net profile provider mechanism and wraps it with an OpenID layer. We are using it to add OpenID to our custom authentication engine. If you are working in another language/platform there are a number of OpenID implementation avalaiable from the OpenID community site here. A: You shouldn't be having trouble developing against your own machine. What error are you getting? An OpenID provider will ask you to give your site (in this case http://localhost:8000 or similar) access to your identity. If you click ok then it will redirect you that url. I've never had problems with livejournal and I expect that myopenid.com will work too. If you're having problems developing locally I suggest that the problem you're having is unrelated to the url being localhost, but something else. Without an error message or problem description it's impossible to say more. Edit: It turns out that Yahoo do things differently to other OpenID providers that I've come across and disallow redirections to ip address, sites without a correct tld in their domain name and those that run on ports other than 80 or 443. See here for a post from a Yahoo developer on this subject. This post offers a work around, but I would suggest that for development myopenid.com would be far simpler than working around Yahoo, or running your own provider.
{ "language": "en", "url": "https://stackoverflow.com/questions/172040", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "41" }
Q: GPSID - Poll Driver V2.0 On the page http://msdn.microsoft.com/en-us/library/bb202066.aspx If references something called "POLL Driver V2" however this is the only place I can see that talks about this. I'm extermely interested in the GPSSetDeviceParam: GPS_QUERY_FIX call but after searching for about 2 hours on this, I couldn't find any information. Can someone point me in the right direction on this? A: According to MS, GPSID - Poll Driver v2.0 are not made available to ISV's in WM6.1. They are evaluating including this in a future version of the OS. My solution along the same lines was to create a Windows CE notification that fires at a predetermined interval. Then when my app receives the notification, I set the power mode to "Unattended". To make this work however you will need to set the power requirements in the registry for the GPDO to D0 when in the "Unattended" power mode. HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Power\State\Unattended gpd0: = 0 Using the SetPowerRequirement or SetDevicePower = D0 does not accomplish the same thing.
{ "language": "en", "url": "https://stackoverflow.com/questions/172050", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Why does FileSystemWatcher create multiple change events when I copy a file to the directory I've written a small test application using the .Net FileSystemWatcher to keep an eye on a directory. When I copy a large-ish (a few Mb) file into that directory I get the following events listed (see screenshot - and ignore the Delete event to begin with). alt text http://robinwilson.homelinux.com/FSW.png I get a created event (as expected), but then two changed events (about 0.7 seconds apart). Why is this? This would cause major problems in the application I am planning to develop - as I'd try and do things with the file twice (presumably once before it has finished being written to!). Is there anything I can do to stop this happening? From what I've read on StackOverflow and elsewhere, you should just get one changed event once the file has been changed and then closed. Why am I getting two? A: Usually the copying program is doing it in blocks, not entire file at once. I don't think you can do anything to avoid this, you will have to adopt your algorithms to deal with this. You can perform an attempt to open file with exclusive read rights, which should be granted to your program only when other program finished copying and closed file. Otherwise you will get IOException and you can wait for next change. But this doesn't mean you shouldn't deal with multiply change events. Opening text file in Notepad and saving it once in a while will generate change events, but file will not be locked all the time. Another approach would be to collect touched files for a period of time, and when FileSystemWatcher stops generating events, process all files at once. A: According to the documentation (see the first bullet point under Events and Buffer Sizes): Common file system operations might raise more than one event. For example, when a file is moved from one directory to another, several OnChanged and some OnCreated and OnDeleted events might be raised. Moving a file is a complex operation that consists of multiple simple operations, therefore raising multiple events. Likewise, some applications (for example, antivirus software) might cause additional file system events that are detected by FileSystemWatcher.
{ "language": "en", "url": "https://stackoverflow.com/questions/172060", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Migrate from ClearCase to SVN/Mercurial At work, we're using ClearCase right now. However, there's a lot of overhead required, especially when someone does something stupid (like erase a view with multiple reserved check-outs on the trunk...). Since we're trying to lower our overhead and be as lightweight as possible, we've through about the possibility of ditching CC and going for something lighter (Subversion or Mercurial), seeing as how we don't use 90% of CC's features anyway. Does this sound reasonable or will we be trading our Ferrari in for a station wagon? A: I agree with the previous posters. Ditching the IBM product and moving to an open source source control product won't be a downgrade at all. You'll probably be happier with these lighter and easier to use tools. In our shop we're in the process of moving from CVS to SVN and have been quite pleased with the result. A: I'd definitely consider a move from clearcase to subversion an upgrade! A: We went from ClearCase LT to SVN and love it. We're saving a lot of cash in maintenance fees and everything is working just as well as before. I just wish I had investigated Git or something like that before I recommended SVN. A: Fourthing the recommendation that you switch. If you're not using the features, it's a poor business choice to go with the commercially-priced solution. Now, there's an associated cost with the "free" solution, too. Neither SVN nor Mercurial are going to provide you commercial-grade support. If this is an issue, and it certainly can be for some situations, you might not want to do it. Of the two that you mention, SVN is the one you should choose if you're currently using a centralized VC repository. Not only is SVN's operational model a simple and intuitive one, but SVN has simply the best documentation and developer community I've ever seen in an open source project. The user mailing list is magnificent, the developers are responsive and responsible to their users, and the Red Bean book is the single best piece of open source manual writing out there. A: I have no problem with your "switch". It will be an upgrade if you do not have many inter-dependent projects using UCM. I manage both SCM (ClearCase and Subversion) and do recommend Subversion for small to medium independent projects. However, make sure your developers are not used to the dynamic views of ClearCase: it is an encapsulation of the file system allowing the user to access files from the network. To my knowledge, ClearCase is the only one with that kind of access. And take into consideration the paradigm-shift: * *ClearCase is file-centric (every file you get is read-only, and you checkout only the files on which you do work) *Subversion is repository-centric (every file you get is read-write, you checkin all modified/added/removed files in one atomic commit) A: From my experience, ClearCase has indeed a lot of overhead and we managed greatly with SVN. I vote, "downgrade" (actually its an UPGRADE). ;) A: Things I liked about ClearCase that I haven't been able to do as well or at all in other SCM tools: * *Working with developer branches was painless. In CC (UCM), you work in your stream (a.k.a. branch), and "deliver" a bunch of work to the integration stream. Meanwhile, other developers do the same. The integrator (maybe one of the developers) then does some testing on the integration stream, and makes sure everything builds and maybe smoke tests things, then recommends a new baseline, which includes the work from all developers. Meanwhile, you keep working in your branch. Next time you want to deliver (or before if you like), you see a new baseline is available, so you merge into your stream. In fact, you are forced to rebase if a newer baseline is available. I tried doing this in Microsoft Team Foundation Server, and SVN. First, I couldn't find a way to enforce a policy like the enforced rebase of CC, so I had to go and figure out which of my revisions I did since the last merge, and what was done in the trunk since then, and then merge from the trunk into my branch. Then when I wanted to merge my new work into the trunk, I had to re-merge all the stuff I just merged into my branch, plus my new work. *Developer branches were conducive to effective code reviews. When I was using CC, we reviewed everything. Practically, though, reviews took time, and we needed to keep working. Each piece of work corresponded to an activity in CC. Only when the review was complete did we deliver the activity to the integration stream. If the review required changes, I could decide to either make the change in the activity I did the original work (as long as no subsequent changes were made to files changed in that activity), create a new activity to address the review changes, or possibly blow away the entire activity and start over (again, as long as no subsequent changes were made). In TFS and SVN, once you commit something, you can't go back easily without blowing away subsequent work. So we had to find some other way to show our changes to other developers. This ended up being diffs converted to web pages, but still, we couldn't go on with more work without it getting blended with the work pending review. *Cross-platform development is made easier with dynamic views. I only have SVN to compare here, so maybe Mercurial or others are better. My goal was to make changes, build, test, debug on both Linux and PowerPC platforms (and Windows for another project), and commit a single changeset once I was happy it works on all platforms. For the PowerPC builds, we had a sun workstation (accessing the dynamic view) that we used to build and test for a target. It was slow, so we did most of our coding and debugging on Linux, and then build and test on the PowerPC before final testing on the (PowerPC) target, and finally a check-in. One way around this is network file shares. One issue I've seen here is version incompatibilities between Linux svn and TortoiseSVN on Windows. If you let Tortoise into a Linux repo copy, it changes the .svn files, and Linux svn then complains the version is too new. (We weren't able to upgrade our Linux boxes to a new enough svn because of the platform we chose for a target.) So I can't use my Windows diff tool in a Linux svn repo. If I go the other way, using a Windows check-out and Linux mounting the Windows repo, the symlinks are not preserved (which are needed on the Linux build). I do not disagree, maintaining ClearCase is a nightmare, and will cost you money. But once it's setup, it can provide for a very good development environment. Especially when you start integrating with ClearQuest (defect tracking, which we also used for tracking code reviews). As another responder stated, the answer for you is highly dependent on your process needs. A: In my previous company (CMMi process), about 100 developers/testers/integrators work with ClearCase (CC) with 3 full-time administrators (add 2 voluntary part-time ). Unless you use the configuration management part ( baseline ), you should move on modern SCM. The baseline feature is powerful : in traditional SCM , when you update/rebase you get the lastest revisions by default. A baseline is a set of software component at certain 'compatible' revision to make sure the build is ok. In some way, it's like dependency build (ie Maven, Ant Ivy) . When developers rebase (update) on baseline, they get what should be "buildable". Now looking back from my new company (Agile shop), we use SVN and Mercurial and I think CC was daily pain. With CC to work on a project (repository), you have a create a view , create an activity, then check out a file . Some colleagues were afraid to make branches :) . With SVN and Mercurial, we don't have such some problems with their GUI clients. Developers commit 10 times on a daily basis. Versus on CC people would check in once a day. Indeed CC has a lot of overhead and slow network latency, high licence cost and need full time administrator. So what's the benefits except the configuration management. On Mercurial, the workflow is lighter. For our current project, one messed up by committing non source files. The Hg history is immutable. We have no administrator. One developer re cloned a new project in half day. In Clearcase , you would need to ask an expert just to back up a deleted file :). To create a new repo, you ask your admin :) After moving away from ClearCase, now I'm really happy with SVN and especially Mercurial. So moving from ClearCase to Mercurial will be really lightweight in terms process, €€ and you get more productivity. Now the choice between SVN and Mercurial ? You should ask yourself whether centralized or decentralized repository. You can do a quick search on stackoverflow. I came to dislike IBM Rational products in favor elegant open source solutions. If you read this and understood it, you should title "Upgrading from clearcase to svn-mercurial". Added : Clearcase is behind the recommendability threshold , while Mercurial, Subversion & Git are clearly recommended. http://martinfowler.com/bliki/VersionControlTools.html You can also to combine Mercurial & Clearcase. Read the paragraph "Multiple VCS" A: The major thing I've learned is that, more important than the product is the process. If you've implemented ClearCase (CC) using an SVN-type model, then SVN will work just fine and be a lot cheaper. On the other hand, if you use deferred branching, build-by-label, and dynamic views (or can), which we use to great advantage in saving time and effort, and improving reliability, you will seriously regret losing these features. (Not to mention build management, UCM, etc.) I find most people use the first choice, which is like using a Ferrari in rush hour traffic... Example? Define labels GA, SP1, SP2 (you can have as many releases between GA and SP1 as you like, not relevant, and remember, CC labels are NOT the same as SVN). GA was your base release, SP1 is your current release. SP2 is your next release. The current release is based on GA and SP1. The next release is based on GA, SP1, and SP2 (see CC config specs) Begin QA. Development is doing ongoing work for the "next release", and users can reference (not change) GA and SP1, and can apply SP2. Maintenance is doing work to repair defects found by QA and can reference GA, and apply SP1. Case 1: In ClearCase, the mere act of applying the SP1 label makes the fix automatically available to the Dev SP2 release team. No work. Nada, Zero. In Subversion, you would be making the change on a QA branch, and then (hopefully, remember to) migrate the change to SP2. Case 2: Before you ask, certainly, if you add an SP2 change, you will have to branch to add a subsequent change for SP1, as it would be in most systems. In my world, real world numbers: Case 1 happened 122 times for my last SP (8 SPs per year). Over 800 changes per year I didn't have to make in ClearCase I would have had to make if I used the Subversion model. Case 2 has happened 6 times since early 2002 when we installed CC. Look at the process, not just the product. (Sorry for length, it didn't start that long :-) A: I have just been spending the past few weeks at my new job looking into SCM (Software Configuration Management) and ALM (Application Lifecycle Management) tools to adopt to replace CVS and support the adoption of Agile. If you are looking for something that will support true SCM with parallel development and branching then there are probably more alternatives out there than you realise. For a simple SCM solution look into the following: * *Accurev: This is an SCM tool that has native support for stream/parallel based development. It provides a very good stream browser giving you a graphical view of your streams and allowing you to graphically promote changes as issues or as changeset (enforces atomic promotes of a set of source files). It has a built in issue tracker to give you change management and let you work in a task based manner. With AccuFlow you can have even more control of your changes with workflow and Accubridge gives you IDE integration. *Seapine Surround: This is a nice looking tool which works well for branching but not quite as advanced as Accurev. What is nice about Seapine is the integration with their issue tracking tool, TestTrack Pro and also their test case management solution TestTrack TCM (which combine into TestTrack Stuido). Finally they also have QA Wizard Pro which is a web and winforms automated testing tool. *PureCM: This is another alternative which is quite popular but i have not looked at it in great detail *Perforce: Another alternative in this space which i wasn't so impressed with but it does have some interesting niche features like the ability to compare and merge images. *Plastic SCM: An imature product but very interesting to look at. All of these solutions offer much better branching support than ClearCase have natively suppert concepts such as developer sandboxes (instead of using those crazy views in ClearCase), and verions snapshots. Esentially a readonly branch, a bit like a baseline. If you have an extensive Rational deployment you might want to look into these alternatives: * *MKS Integrity: A nice well put together product which has excellent portfolio management tools with a nice built in test run view. All of its tools fall into one IDE and is very customisable. *Serena CM: Again a nice enough suite with extensive tools around the core ALM solution. Very big portfolio management piece and there is a lot of buiness process support with their Mashups components and also support for prototyping. *Telelogic: Ironically is now part of IBM and soon to be IBM rational. Its SCM solution (Telelogic Change and Synergy) is easily the best i've seen with the ability to promote code changes explicitly by task into a release build branch. All of the above solutions support the same SCM concepts as Accurev etc but are obviously more end to end products and are enterprise scale. We have at this point narrowed our choice down to either MKS or Telelogic. My biggest point on this is that there are many, many solutions out there in between ClearCase and CVS/Subversion which are commercial but relitvely cheap. Hope this was of use. A: I recommend reading HG Init - a guide by Joel Spolsky on how to switch from SVN to Mercurial. As some previous answers have mentioned, SVN and ClearCase basically work under the same paradigm, so when you read the article, you can pretty much substitute every occurrence of the word "Subversion" for "ClearCase" and apply it to your situation. This is the writeup that finally convinced me to start using Mercurial at work. A: I'd be interested to hear about how your branch structure is set up. Why are users working on the 'trunk' of your product? (I assume this means your main branch). Wouldn't development branches prevent your developers from affecting the main trunk? Why couldn't you introduce a trigger on the rmview script preventing users from removing a view whilst still having checkouts? This is quite a trivial exercise, and there are plenty of sources online (and I'm sure StackOverflow would provide you with answers if you ask!). Another suggestion would be, if you have the cash already invested in IBM products (thus willing to spend money on a commercially supported SCM environment) you might want to have a look at Team Concert, and Jazz. A: Sounds to me like you'll be happy in git/mercurial and probably not in SVN. OTOH, all my clearcase experience was tedious and unloving, so I would consider any "escape" action to be a very good thing indeed. The distributed systems sound like they match your workflow better.
{ "language": "en", "url": "https://stackoverflow.com/questions/172065", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: Django UserProfile... without a password I'd like to create a subset of Users that don't have a login... basically as a way to add a photographer field to photos without having a full blown account associated with that person (since in many cases, they'll never actually log in to the site). A caveat is that I'd also like to be able to enable an account for them later. So, I think the question becomes what's the best way to set up a "People" table that ties to the User table without actually extending the User table with UserProfile. A: A user profile (as returned by django.contrib.auth.models.User.get_profile) doesn't extend the User table - the model you specify as the profile model with the AUTH_PROFILE_MODULE setting is just a model which has a ForeignKey to User. get_profile and the setting are really just a convenience API for accessing an instance of a specific model which has a ForeignKey to a specific User instance. As such, one option is to create a profile model in which the ForeignKey to User can be null and associate your Photo model with this profile model instead of the User model. This would allow you to create a profile for a non-existent user and attach a registered User to the profile at a later date. A: Users that can't login? Just given them a totally random password. import random user.set_password( str(random.random()) ) They'll never be able to log on. A: Supply your own authentication routine, then you can check (or not check) anything you like. We do this so if they fail on normal username, we can also let them in on email/password (although that's not what I'm showing below). in settings.py: AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'userprofile.my_authenticate.MyLoginBackend', # if they fail the normal test ) in userprofile/my_authenticate.py: from django.contrib.auth.backends import ModelBackend from django.contrib.auth.models import User class MyLoginBackend(ModelBackend): """Return User record if username + (some test) is valid. Return None if no match. """ def authenticate(self, username=None, password=None, request=None): try: user = User.objects.get(username=username) # plus any other test of User/UserProfile, etc. return user # indicates success except User.DoesNotExist: return None # authenticate # class MyLoginBackend A: From the documentation on django auth, if you want to use the User model, it's mandatory to have a username and password, there are no "anonymous accounts". I guess you could create accounts with a default password and then give the opportunity for people to enable a "real" account (by setting a password themselves). To set up a "People" table that ties to the User table you just have to use a ForeignKey field (that's actually the recommended way of adding additional info to the User model, and not inheritance) A: Using a model with a ForeignKey field linking to User might not work as you want because you need anonymous access. I'm not sure if that's going to work, but you might try what happens if you let it have a ForeignKey to AnonymousUser (whose id is always None!) instead. If you try it, post your results here, I'd be curious. A: The django.contrib.auth.models.User exists solely for the purpose of using default authentication backend (database-based). If you write your own backend, you can make some accounts passwordless, while keeping normal accounts with passwords. Django documentation has a chapter on this. A: Another upvote for insin's answer: handle this through a UserProfile. James Bennett has a great article about extending django.contrib.auth.models.User. He walks through a couple methods, explains their pros/cons and lands on the UserProfile way as ideal.
{ "language": "en", "url": "https://stackoverflow.com/questions/172066", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Is it possible to generate a database from the Entity Data Model (edmx) file? In Linq to SQL it is possible to generate the database from the dbml file. Is it possible to generate a database from the Entity Data Model ? I wish to accomplish the same thing using the edmx file. A: Not until the next version, as you can read on the Entity Framework Design blog: http://blogs.msdn.com/efdesign/archive/2008/09/10/model-first.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/172084", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Slow SoapHttpClientProtocol constructor I'm doing some experiments with Microsoft Dynamics CRM. You interact with it through web services and I have added a Web Reference to my project. The web service interface is very rich, and the generated "Reference.cs" is some 90k loc. I'm using the web reference in a console application. I often change something, recompile and run. Compilation is fast, but newing up the web service reference is very slow, taking some 15-20 seconds: CrmService service = new CrmService(); Profiling reveals that all time is spent in the SoapHttpClientProtocol constructor. The culprit is apparently the fact that the XML serialization code (not included in the 90k loc mentioned above) is generated at run time, before being JIT'ed. This happens during the constructor call. The wait is rather frustrating when playing around and trying things out. I've tried various combinations of sgen.exe, ngen and XGenPlus (which takes several hours and generates 500MB of additional code) but to no avail. I've considered implementing a Windows service that have few CrmService instances ready to dish out when needed but that seems excessive. Any ideas? A: The following is ripped from this thread on the VMWare forums: Hi folks, We've found that sgen.exe does work. It'just that there is a couple of additional steps beyond pre-generating the serializer dll's that we missed in this thread. Here is the detailed instruction PROBLEM When using the VIM 2.0 SDK from .NET requires long time to instantiate the VimService class. (The VimService class is the proxy class generated by running 'wsdl.exe vim.wsdl vimService.wsdl') In other words, the following line of code: _service = new VimService(); Could take about 50 seconds to execute. CAUSE Apparently, the .NET XmlSerializer uses the System.Xml.Serialization.* attributes annotating the proxy classes to generate serialization code in run time. When the proxy classes are many and large, as is the code in VimService.cs, the generation of the serialization code can take a long time. SOLUTION This is a known problem with how the Microsoft .NET serializer works. Here are some references that MSDN provides about solving this problem: http://msdn2.microsoft.com/en-us/library/bk3w6240.aspx http://msdn2.microsoft.com/en-us/library/system.xml.serialization.xmlserializerassemblyattribute.aspx Unfortunately, none of the above references describe the complete solution to the problem. Instead they focus on how to pre-generate the XML serialization code. The complete fix involves the following steps: * *Create an assembly (a DLL) with the pre-generated XML serializer code *Remove all references to System.Xml.Serialization.* attributes from the proxy code (i.e. from the VimService.cs file) *Annotate the main proxy class with the XmlSerializerAssemblyAttribute to point it to where the XML serializer assembly is. Skipping step 2 leads to only 20% improvement in the instantiation time for the VimService class. Skipping either step 1 or 3 leads to incorrect code. With all three steps 98% improvement is achieved. Here are step-by-step instructions: Before you begin, makes sure you are using .NET verison 2.0 tools. This solution will not work with version 1.1 of .NET because the sgen tool and the XmlSerializationAssemblyAttribute are only available in version 2.0 of .NET * *Generate the VimService.cs file from the WSDL, using wsdl.exe: wsdl.exe vim.wsdl vimService.wsdl This will output the VimService.cs file in the current directory *Compile VimService.cs into a library csc /t:library /out:VimService.dll VimService.cs *Use the sgen tool to pre-generate and compile the XML serializers: sgen /p VimService.dll This will output the VimService.XmlSerializers.dll in the current directory *Go back to the VimService.cs file and remove all System.Xml.Serialization.* attributes. Because the code code is large, the best way to achieve that is by using some regular expression substitution tool. Be careful as you do this because not all attributes appear on a line by themselves. Some are in-lined as part of a method declaration. If you find this step difficult, here is a simplified way of doing it: Assuming you are writing C#, do a global replace on the following string: [System.Xml.Serialization.XmlIncludeAttribute and replace it with: // [System.Xml.Serialization.XmlIncludeAttribute This will get rid of the Xml.Serialization attributes that are the biggest culprits for the slowdown by commenting them out. If you are using some other .NET language, just modify the replaced string to be prefix-commented according to the syntax of that language. This simplified approach will get you most of the speedup that you can get. Removing the rest of the Xml.Serialization attributes only achieves an extra 0.2 sec speedup. *Add the following attribute to the VimService class in VimService.cs: [System.Xml.Serialization.XmlSerializerAssemblyAttribute(AssemblyName = "VimService.XmlSerializers")] You should end up with something like this: // ... Some code here ... [System.Xml.Serialization.XmlSerializerAssemblyAttribute(AssemblyName = "VimService.XmlSerializers")] public partial class VimService : System.Web.Services.Protocols.SoapHttpClientProtocol { // ... More code here *Regenerate VimSerice.dll library by csc /t:library /out:VimService.dll VimService.cs *Now, from your application, you can add a reference to VimSerice.dll library. *Run your application and verify that VimService object instanciation time is reduced. ADDITIONAL NOTES The sgen tool is a bit of a black box and its behavior varies depending on what you have in your Machine.config file. For example, by default it is supposed to ouptut optimized non-debug code, but that is not always the case. To get some visibility into the tool, use the /k flag in step 3, which will cause it to keep all its temporary generated files, including the source files and command line option files it generated. Even after the above fix the time it takes to instantiate the VimService class for the first time is not instantaneous (1.5 sec). Based on empirical observation, it appears that the majority of the remaining time is due to processing the SoapDocumentMethodAttribute attributes. At this point it is unclear how this time can be reduced. The pre-generated XmlSerializer assembly does not account for the SOAP-related attributes, so these attributes need to remain in the code. The good news is that only the first instantiation of the VimService class for that app takes long. So if the extra 1.5 seconds are a problem, one could try to do a dummy instantiation of this class at the beginning of the application as a means to improve user experience of login time. A: You might wish to look into the Sgen.exe tool that comes with .NET. There's also a handy little thing in Visual Studio's C# project properties "Build" page, at the very bottom, called "Build serialization assembly" that automatically runs Sgen for you. A: I believe that this is not an SGEN issue. I have looked at the constructor code, and I see that it is doing a lot of reflection (based on the XmlIncludeAttribute on the class). It reflects on all of them, and can take a really long time. A: There is a pre-generated XmlSerializer assembly that comes with CRM. Check to see whether you have SdkTypeProxy.XmlSerializers.dll and SdkProxy.XmlSerializers.dll in the GAC. If you don't then that means that when you create the CrmService, .net will generate the XmlSerializer assembly which can take some time. Hope this helps A: I came across this thread when trying to find out why my initial SoapHttpClientProtocol calls were taking so long. I found that setting the Proxy to null/Empty stopped the Proxy AutoDetect from occurring - This was taking up to 7 seconds on the initial call: this.Proxy = GlobalProxySelection.GetEmptyWebProxy(); A: I have used above detailed answer as guide, and went a few steps forward, making a script to automate process. Script is made out of two files : generateproxy.bat : REM if your path for wsdl, csc or sgen is missing, please add it here (it varies from machine to machine) set PATH=%PATH%;C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6.1 Tools;C:\Program Files (x86)\MSBuild\14.0\Bin wsdl http://localhost:57237/VIM_WS.asmx?wsdl REM create source code out of WSDL PowerShell.exe -ExecutionPolicy Bypass -Command "& '%~dpn0.ps1'" REM proces source code (remove annotations, add other annotation, put class into namespace) csc /t:library /out:references\VIM_Service.dll VIM_WS.cs REM compile source into dll sgen /p references\VIM_Service.dll /force REM generate serializtion dll generateproxy.ps1 (Get-Content VIM.cs) | ForEach-Object { $_ -replace "(?<attr>\[global::System.Xml.Serialization.[^\]]*\])", "/*${attr}*/" ` -replace "public partial class VIM", "[System.Xml.Serialization.XmlSerializerAssemblyAttribute(AssemblyName = ""VIM_Service.XmlSerializers"")] `npublic partial class VIM" ` -replace "using System;", "namespace Classes.WS_VIM { `n`nusing System;" } | Set-Content VIM.cs Add-Content VIM.cs "`n}" I have added those two files to client project, and in the pre-build event I have added lines cd..\.. generateproxy So, before every build, proxy classes are regenerated, and developer has (almost) no need to think about it. While building, WS must be up and running, and its URL must be in bat file. As a result of prebuild, two dll files will regenerate in client project's subfolder references. After first execution of scripts, you should add reference to new dll.
{ "language": "en", "url": "https://stackoverflow.com/questions/172095", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "30" }
Q: Deserialize jSON Google AJAX Translation API I've got the JSON coming back like this: { "responseData": [{ "responseData": { "translatedText": "elefante" }, "responseDetails": null, "responseStatus": 200 }, { "responseData": { "translatedText": "Burro" }, "responseDetails": null, "responseStatus": 200 }], "responseDetails": null, "responseStatus": 200 } And I need to parse it into a ResponseData object I have set-up: public class ResponseData { public string translatedText = string.Empty; public object responseDetails = null; public HttpStatusCode responseStatus = HttpStatusCode.OK; public List <ResponseData> responseData { get;set; } } I Deserialize it like this: JavaScriptSerializer serializer = new JavaScriptSerializer(); ResponseData translation = serializer.Deserialize<ResponseData>(responseJson); But no matter what the translated text is always empty. A: you should think about the JSON object graph represented in that string. You can nest types for deserializating objects with different properties/fields using generics like so: class Response < T > { public ResponseData < T > [] responseData = new ResponseData < T > [0]; public HttpStatusCode responseStatus; public object responseDetails; } public class ResponseData < TInternal > { public TInternal responseData; public HttpStatusCode responseStatus; public object responseDetails; } public class TranslatedText { public string translatedText; } [Test] public void Sample() { var input = @ " { "" responseData "": [{ "" responseData "": { "" translatedText "": "" elefante "" }, "" responseDetails "": null, "" responseStatus "": 200 }, { "" responseData "": { "" translatedText "": "" Burro "" }, "" responseDetails "": null, "" responseStatus "": 200 }], "" responseDetails "": null, "" responseStatus "": 200 } "; var json = new JavaScriptSerializer(); var response = json.Deserialize < Response < TranslatedText >> (input); Assert.AreEqual(response.responseData[0].responseData.translatedText, "elefante"); Assert.AreEqual(response.responseStatus, HttpStatusCode.OK); }
{ "language": "en", "url": "https://stackoverflow.com/questions/172102", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How do I elegantly print the date in RFC822 format in Perl? How can I elegantly print the date in RFC822 format in Perl? A: It can be done with strftime, but its %a (day) and %b (month) are expressed in the language of the current locale. From man strftime: %a The abbreviated weekday name according to the current locale. %b The abbreviated month name according to the current locale. The Date field in mail must use only these names (from rfc2822 DATE AND TIME SPECIFICATION): day = "Mon" / "Tue" / "Wed" / "Thu" / "Fri" / "Sat" / "Sun" month = "Jan" / "Feb" / "Mar" / "Apr" / "May" / "Jun" / "Jul" / "Aug" / "Sep" / "Oct" / "Nov" / "Dec" Therefore portable code should switch to the C locale: use POSIX qw(strftime locale_h); my $old_locale = setlocale(LC_TIME, "C"); my $date_rfc822 = strftime("%a, %d %b %Y %H:%M:%S %z", localtime(time())); setlocale(LC_TIME, $old_locale); print "$date_rfc822\n"; A: use POSIX qw(strftime); print strftime("%a, %d %b %Y %H:%M:%S %z", localtime(time())) . "\n"; A: The DateTime suite gives you a number of different ways, e.g.: use DateTime; print DateTime->now()->strftime("%a, %d %b %Y %H:%M:%S %z"); use DateTime::Format::Mail; print DateTime::Format::Mail->format_datetime( DateTime->now() ); print DateTime->now( formatter => DateTime::Format::Mail->new() ); Update: to give time for some particular timezone, add a time_zone argument to now(): DateTime->now( time_zone => $ENV{'TZ'}, ... ) A: Just using POSIX::strftime() has issues that have already been pointed out in other answers and comments on them: * *It will not work with MS-DOS aka Windows which produces strings like "W. Europe Standard Time" instead of "+0200" as required by RFC822 for the %z conversion specification. *It will print the abbreviated month and day names in the current locale instead of English, again required by RFC822. Switching the locale to "POSIX" resp. "C" fixes the latter problem but is potentially expensive, even more for well-behaving code that later switches back to the previous locale. But it's also not completely thread-safe. While temporarily switching locale will work without issues inside Perl interpreter threads, there are races when the Perl interpreter itself runs inside a kernel thread. This can be the case, when the Perl interpreter is embedded into a server (for example mod_perl running in a threaded Apache MPM). The following version doesn't suffer from any such limitations because it doesn't use any locale dependent functions: sub rfc822_local { my ($epoch) = @_; my @time = localtime $epoch; use integer; my $tz_offset = (Time::Local::timegm(@time) - $now) / 60; my $tz = sprintf('%s%02u%02u', $tz_offset < 0 ? '-' : '+', $tz_offset / 60, $tz_offset % 60); my @month_names = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec); my @day_names = qw(Sun Mon Tue Wed Thu Fri Sat Sun); return sprintf('%s, %02u %s %04u %02u:%02u:%02u %s', $day_names[$time[6]], $time[3], $month_names[$time[4]], $time[5] + 1900, $time[2], $time[1], $time[0], $tz); } But it should be noted that converting from seconds since the epoch to a broken down time and vice versa are quite complex and expensive operations, even more when not dealing with GMT/UTC but local time. The latter requires the inspection of zoneinfo data that contains the current and historical DST and time zone settings for the current time zone. It's also error-prone because these parameters are subject to political decisions that may be reverted in the future. Because of that, code relying on the zoneinfo data is brittle and may break, when the system is not regulary updated. However, the purpose of RFC822 compliant date and time specifications is not to inform other servers about the timezone settings of "your" server but to give its notion of the current date and time in a timezone indepent manner. You can save a lot of CPU cycles (they can be measured in CO2 emission) on both the sending and receiving end by simply using UTC instead of localtime: sub rfc822_gm { my ($epoch) = @_; my @time = gmtime $epoch; my @month_names = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec); my @day_names = qw(Sun Mon Tue Wed Thu Fri Sat Sun); return sprintf('%s, %02u %s %04u %02u:%02u:%02u +0000', $day_names[$time[6]], $time[3], $month_names[$time[4]], $time[5] + 1900, $time[2], $time[1], $time[0]); } By hard-coding the timezone to +0000 you avoid all of the above mentioned problems, while still being perfectly standards compliant, leave alone faster. Go with that solution, when performance could be an issue for you. Go with the first solution, when your users complain about the software reporting the "wrong" timezone.
{ "language": "en", "url": "https://stackoverflow.com/questions/172110", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "18" }
Q: How to get notified when a drive letter becomes available Is it possible to get notified (without polling, but via an event) when a drive letter becomes accessible. For example if you have an external hard drive that always appears as drive F - is it possible to have an event raised when that is connected and F becomes accessible? A: Okay.. found what I was looking for :) Take a look at this VBScript: (source): strComputer = "." Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2") Set colEvents = objWMIService.ExecNotificationQuery _ ("Select * From __InstanceOperationEvent Within 10 Where " _ & "TargetInstance isa 'Win32_LogicalDisk'") Do While True Set objEvent = colEvents.NextEvent If objEvent.TargetInstance.DriveType = 2 Then Select Case objEvent.Path_.Class Case "__InstanceCreationEvent" Wscript.Echo "Drive " & objEvent.TargetInstance.DeviceId & _ " has been added." Case "__InstanceDeletionEvent" Wscript.Echo "Drive " & objEvent.TargetInstance.DeviceId & _ " has been removed." End Select End If Loop I leave it to your exercise to port it to C#. Instead of polling all the time you can use a WMI event sink. A: You can wait for the WM_DEVICECHANGE message, all the details are at: http://msdn.microsoft.com/en-us/library/aa363215(VS.85).aspx You're going to have to create a window to receive this message, the window can be hidden if you need, to get this message in WinForms just override the Form.WndProc method
{ "language": "en", "url": "https://stackoverflow.com/questions/172111", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Avoiding, finding and removing memory leaks in Cocoa Memory (and resource) leaks happen. How do you make sure they don't? What tips & techniques would you suggest to help avoid creating memory leaks in first place? Once you have an application that is leaking how do you track down the source of leaks? (Oh and please avoid the "just use GC" answer. Until the iPhone supports GC this isn't a valid answer, and even then - it is possible to leak resources and memory on GC) A: The Instruments Leaks tool is pretty good at finding a certain class of memory leak. Just use "Start with Performance Tool" / "Leaks" menu item to automatically run your application through this tool. Works for Mac OS X and iPhone (simulator or device). The Leaks tool helps you find sources of leaks, but doesn't help so much tracking down the where the leaked memory is being retained. A: * *Follow the rules for retaining and releasing (or use Garbage Collection). They're summarized here. *Use Instruments to track down leaks. You can run an application under Instruments by using Build > Start With Performance Tool in Xcode. A: In XCode 4.5, use the built in Static Analyzer. In versions of XCode prior to 3.3, you might have to download the static analyzer. These links show you how: Use the LLVM/Clang Static Analyzer To avoid creating memory leaks in the first place, use the Clang Static Analyzer to -- unsurprisingly -- analyse your C and Objective-C code (no C++ yet) on Mac OS X 10.5. It's trivial to install and use: * *Download the latest version from this page. *From the command-line, cd to your project directory. *Execute scan-build -k -V xcodebuild. (There are some additional constraints etc., in particular you should analyze a project in its "Debug" configuration -- see http://clang.llvm.org/StaticAnalysisUsage.html for details -- the but that's more-or-less what it boils down to.) The analyser then produces a set of web pages for you that shows likely memory management and other basic problems that the compiler is unable to detect. If your project does not target Mac OS X desktop, there are a couple of other details: * *Set the Base SDK for All Configurations to an SDK that uses the Mac OS X desktop frameworks... *Set the Command Line Build to use the Debug configuration. (This is largely the same answer as to this question.) A: I remember using a tool by Omni a while back when I was trying to track down some memory leaks that would show all retain/release/autorelease calls on an object. I think it showed stack traces for the allocation as well as all retains and releases on the object. http://www.omnigroup.com/developer/omniobjectmeter/ A: Don't overthink memory management For some reason, many developers (especially early on) make memory management more difficult for themselves than it ever need be, frequently by overthinking the problem or imagining it to be more complicated than it is. The fundamental rules are very simple. You should concentrate just on following those. Don't worry about what other objects might do, or what the retain count is of your object. Trust that everyone else is abiding by the same contract and it will all Just Work. In particular, I'll reiterate the point about not worrying about the retain count of your objects. The retain count itself may be misleading for various reasons. If you find yourself logging the retain count of an object, you're almost certainly heading down the wrong path. Step back and ask yourself, are you following the fundamental rules? A: Always use accessor methods; declare accessors using properties You make life much simpler for yourself if you always use accessor methods to assign values to instance variables (except in init* and dealloc methods). Apart from ensuring that any side-effects (such as KVO change notifications) are properly triggered, it makes it much less likely that you'll suffer a copy-and-paste or some other logic error than if you sprinkle your code with retains and releases. When declaring accessors, you should always use the Objective-C 2 properties feature. The property declarations make the memory management semantics of the accessors explicit. They also provide an easy way for you to cross-check with your dealloc method to make sure that you have released all the properties you declared as retain or copy. A: First of all, it's vitally important that your use of [ ] and { } brackets and braces match the universal standard. OK, just kiddin'. When looking at leaks, you can assume that the leak is due to a problem in your code but that's not 100% of the fault. In some cases, there may be something happening in Apple's (gasp!) code that is at fault. And it may be something that's hard to find, because it doesn't show up as cocoa objects being allocated. I've reported leak bugs to Apple in the past. Leaks are sometimes hard to find because the clues you find (e.g. hundreds of strings leaked) may happen not because those objects directly responsible for the strings are leaking, but because something is leaking that object. Often you have to dig through the leaves and branches of a leaking 'tree' in order to find the 'root' of the problem. Prevention: One of my main rules is to really, really, really avoid ever allocating an object without just autoreleasing it right there on the spot. Anywhere that you alloc/init an object and then release it later on down in the block of code is an opportunity for you to make a mistake. Either you forget to release it, or you throw an exception so that the release never gets called, or you put a 'return' statement for early exit somewhere in the method (something I try to avoid also). A: You can build the beta port of Valgrind from here: http://www.sealiesoftware.com/valgrind/ It's far more useful than any static analysis, but doesn't have any special Cocoa support yet that I know of. A: Obviously you need to understand the basic memory management concepts to begin with. But in terms of chasing down leaks, I highly recommend reading this tutorial on using the Leaks mode in Instruments.
{ "language": "en", "url": "https://stackoverflow.com/questions/172125", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "19" }
Q: How to remove paths from tabs in Visual Studio 2008? Is there a way to stop the path showing in a source code tab in Visual Studio 2008? Currently when developing an ASP.NET site, I get the path from the root plus the filename - truncated when it gets too long. So something like: MyDir/MyPage.aspx for a short path and filename, or: MyDir/MyLong...yPage.aspx for a longer path and filename. I'd prefer to see just the filename (ie just MyPage.aspx), allowing more tabs to show at once and making it easier to see which files I have open without using the drop-down list or Crtl-Tab to show the full set. In VS2005, I just get the filename - no path however long it is. Oddly in VS2003 I get the path and filename. I've scoured the options and I can't find a setting that lets me change what appears in the tabs. Searching suggests that other people have similar issues (although which version it occurs in appears to differ) but no-one could identify an option to change what appears. Can anyone point me in the right direction to get rid of the paths in the tabs (or confirm that it can't be changed to save me wasting more time searching)? A: In my copy of VS 2008 I just get the filename, not the path. I wonder whether it's a "web site" vs "web application" thing. Which one are you working in? Can you create a project of the other type and see if it still happens? (I'm working in a web application where I get filename-only.) A: It looks like Microsoft does not allow to do it using the standard method. I'm know ReSharper allows this, but installing a big plugin for this is a bad idea. I think I have sinse found a small plugin which allows show or hide the full path. I am sure this should exist. A: Tabs Studio add-in can remove path from tab in Visual Studio 2008. See Removing path from tab name blog post for the example screenshots.
{ "language": "en", "url": "https://stackoverflow.com/questions/172130", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: UTF8 vs. UTF16 vs. char* vs. what? Someone explain this mess to me! I've managed to mostly ignore all this multi-byte character stuff, but now I need to do some UI work and I know my ignorance in this area is going to catch up with me! Can anyone explain in a few paragraphs or less just what I need to know so that I can localize my applications? What types should I be using (I use both .Net and C/C++, and I need this answer for both Unix and Windows). A: Check out Joel Spolsky's The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!) EDIT 20140523: Also, watch Characters, Symbols and the Unicode Miracle by Tom Scott on YouTube - it's just under ten minutes, and a wonderful explanation of the brilliant 'hack' that is UTF-8 A: The various UTF standards are ways to encode "code points". A codepoint is the index into the Unicode charater set. Another encoding is UCS2 which is allways 16bit, and thus doesn't support the full Unicode range. Good to know is also that one codepoint isn't equal to one character. For example a character such as å can be represented both as a code point or as two code points one for the a and one for the ring. Comparing two unicode strings thus requires normalization to get the canonical representation before comparison. A: A character encoding consists of a sequence of codes that each look up a symbol from a given character set. Please see this good article on Wikipedia on character encoding. UTF8 (UCS) uses 1 to 4 bytes for each symbol. Wikipedia gives a good rundown of how the multi-byte rundown works: * *The most significant bit of a single-byte character is always 0. *The most significant bits of the first byte of a multi-byte sequence determine the length of the sequence. These most significant bits are 110 for two-byte sequences; 1110 for three-byte sequences, and so on. *The remaining bytes in a multi-byte sequence have 10 as their two most significant bits. *A UTF-8 stream contains neither the byte FE nor FF. This makes sure that a UTF-8 stream never looks like a UTF-16 stream starting with U+FEFF (Byte-order mark) The page also shows you a great comparison between the advantages and disadvantages of each character encoding type. UTF16 (UCS2) Uses 2 bytes to 4 bytes for each symbol. UTF32 (UCS4) uses 4 bytes always for each symbol. char just means a byte of data and is not an actual encoding. It is not analogous to UTF8/UTF16/ascii. A char* pointer can refer to any type of data and any encoding. STL: Both stl's std::wstring and std::string are not designed for variable-length character encodings like UTF-8 and UTF-16. How to implement: Take a look at the iconv library. iconv is a powerful character encoding conversion library used by such projects as libxml (XML C parser of Gnome) Other great resources on character encoding: * *tbray.org's Characters vs. Bytes *IANA character sets *www.cs.tut.fi's A tutorial on code issues *The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!) (first mentioned by @Dylan Beattie) A: Received wisdom suggests that Spolsky's article misses a couple of important points. This article is recommended as being more complete: The Unicode® Standard: A Technical Introduction This article is also a good introduction: Unicode Basics The latter in particular gives an overview of the character encoding forms and schemes for Unicode. A: There is also the issue with fonts. There are two ways to handle fonts. Either you use a gigantic font with glyphs for all the Unicode characters you need (I think recent versions of Windows comes with one or two such fonts). Or you use som library capable of combining glyphs from various fonts dedicated to subsets of the Unicode standard.
{ "language": "en", "url": "https://stackoverflow.com/questions/172133", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "33" }
Q: Setup multi languages wordpress I need to setup a blog using wordpress engine but i need it support multi languages (3 languages), currently i am thinking of using custom field to identify the language of current post though i knew thats not a best practices, does anyone has better suggestions? A: I've tested 2 plugins that both looked very promising: qTranslate and Gengo qTranslate works by adding inputs for all used languages for each post, Gengo used separate posts and links them in a "post Y is a translation of post X" way, which I preferred much (because it allowed me to not translate everything) and it worked fine for me. A: I have used the xlanguage plugin and I am happy with it. xlanguage site A: I fi i remember well, wordpress uses a gettext "customization" library to translate itself. I think you can make some options based on a session variable, about the translation files you're going to read. A: Try using plugin wordpress WPML.
{ "language": "en", "url": "https://stackoverflow.com/questions/172138", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Which data structure for linking text with audio in Java I want to write a program in which plays an audio file that reads a text. I want to highlite the current syllable that the audiofile plays in green and the rest of the current word in red. What kind of datastructure should I use to store the audio file and the information that tells the program when to switch to the next word/syllable? A: This is a slightly left-field suggestion, but have you looked at Karaoke software? It may not be seen as "serious" enough, but it sounds very similar to what you're doing. For example, Aegisub is a subtitling program that lets you create subtitles in the SSA/ASS format. It has karaoke tools for hilighting the chosen word or part. It's most commonly used for subtitling anime, but it also works for audio provided you have a suitable player. These are sadly quite rare on the Mac. The format looks similar to the one proposed by Yuval A: {\K132}Unmei {\K34}no {\K54}tobira {\K60}{\K132}yukkuri {\K36}to {\K142}hirakareta The lengths are durations rather than absolute offsets. This makes it easier to shift the start of the line without recalculating all the offsets. The double entry indicates a pause. Is there a good reason this needs to be part of your Java program, or is an off the shelf solution possible? A: How about a simple data structure that describes what next batch of letters consists of the next syllable and the time stamp for switching to that syllable? Just a quick example: [0:00] This [0:02] is [0:05] an [0:07] ex- [0:08] am- [0:10] ple A: To highlight part of word sounds like you're getting into phonetics which are sounds that make up words. It's going to be really difficult to turn a sound file into something that will "read" a text. Your best bet is to use the text itself to drive a phonetics based engine, like FreeTTS which is based off of the Java Speech API. To do this you're going to have to take the text to be read, split it into each phonetic syllable and play it. so "syllable" is "syl" "la" "ble". Playing would be; highlight syl, say it and move to next one. This is really "old-skool" its been done on the original Apple II the same way. A: you might want to get familiar with FreeTTS -- this open source tool : http://freetts.sourceforge.net/docs/index.php - You might want to feed only a few words to the TTS engine at a given point of time -- highlight them and once those are SPOKEN out, de-highlight them and move to the next batch of words. BR, ~A
{ "language": "en", "url": "https://stackoverflow.com/questions/172151", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: What does "Total Length of columns in constraint is too long" err mean in Informix? I get the Total length of columns in constraint is too long. erro from the following sql] Failed to execute: CREATE TABLE GTW_WORKFLOW_MON ( WORKFLOW_NAME VARCHAR(255) NOT NULL, WORKFLOW_LOADED NUMERIC(20) NOT NULL, ACTIVITY_NAME VARCHAR(255) NOT NULL, FLAGS INTEGER NOT NULL, MONITOR_NAME VARCHAR(255) NOT NULL, CLASSNAME VARCHAR(255) NOT NULL, S TR0 VARCHAR(255), STR1 VARCHAR(255), STR2 VARCHAR(255), NUM0 VARCHAR(255), NUM1 VARCHAR(255), NUM2 VARCHAR(255), DATE0 VARCHAR(255), DATE1 VARCHAR(255), DATE2 VARCHAR(255), PRIMARY KEY (WORKFLOW_NAME,WORKFLOW_LOADED,ACTIVITY_NAME,MONITOR_NAME) ) [sql] java.sql.SQLException: Total length of columns in constraint is too long. A: Your primary key constraint is 785 bytes (255+20+255+255). If you increase your database page size to 4K it should work, barely. You should also reconsider if you need your columns to be as wide as you are defining them. I found a discussion group where an engineer, Radhika Gadde, describes that the maximum index size is related to page size. He says: which error you are getting while creation of Tables. Maximum Index key length can be calculated as follows: [(PAGESIZE -93)/5] -1 like for 2k it is [( 2048-93)/5] -1 =[1955/5] -1 =391-1=390 if PAGESIZE is 4K it is [(4096-93)/5] -1 =4003/5-1=800-1 =799 A: Above answer is complete. But thought of adding some helpful links in case someone runs to this issue again. Pagesize on Informix depends on Operating System. On my recent experience, I found it's 4K on Win 2008, OSX - Lion and 2K on SUSE EL4. You can find the page size by using 'onstat -D'. I wrote http://sumedha.blogspot.com/2013/03/how-to-increase-informix-page-size.html with this experience. Following documentation link from IBM is also very helpful. http://publib.boulder.ibm.com/infocenter/idshelp/v115/index.jsp?topic=%2Fcom.ibm.admin.doc%2Fids_admin_0564.htm
{ "language": "en", "url": "https://stackoverflow.com/questions/172156", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Apache or lighttpd For development, I use a local LAMP stack, for production I'm using MediaTemple's Django Container (which I'm loving BTW). MT's container uses lighthttpd. Honestly I've never had any other experience with it. I've always used Apache. I've been doing some reading: * *Onlamp *TextDrive *Linux.com Here's are questions: * *What strengths does one have over the other? *Would it benefit me to use lighthttpd on my dev setup? *What's up with using both? The Linux.com article talks about using lighttpd with Apache. A: The benefit of both: Apache is more powerful and extensible (useless if you don't need that power, but anyway...) and lighttpd is faster at static content. The idea is of splitting your site into static content (css, js, images, etc) and dynamic code that flows through Apache. I'm not saying you can't do a lot with lighttpd on its own. You can and people do. If you're using lighttpd exclusively on your production server, I would seriously consider mirroring that on your development and staging servers so you know exactly what to expect before you deploy. A: For purely static web pages (.gif, .css, etc.) with n http requests from distinct ip addresses: 1. Apache: Runs n processes (with mod_perl, mod_php in memory) 2. lighttpd: Runs 1 process and 1 threads (You can assign m threads before launching it) For purely dynamic web pages (.php, .pl) with n http requests from distinct ip addresses: 1. Apache: Runs n processes (with mod_perl, mod_php in memory) 2. lighttpd: Runs 1 lighttpd process thanks to async I/O, and runs m fast-cgi processes for each script language. Lighttpd consumes much less memory. YouTube used to be a big user of lighttpd until it was acquired by Google. Go to its homepage for more info. P.S. At my previous company, we used both with a load balancer to distribute the http traffic according to its url suffixes. Why not fully lighttpd? For legacy reasons. A: The way you interface between the web server and Django might have even a greater impact on performance than the choice of web server software. For instance, mod_python is known to be heavy on RAM. This question and its answers discuss other web server options as well. I wouldn't be concerned on compatibility issues with client software (see MarkR's comment). I've had no such problems when serving Django using lighttpd and FastCGI. I'd like to see a diverse ecosystem of both server and client software. Having a good standard is better than a de facto product from a single vendor. A: The answer depends on your projects goals. If it's going to be a large scale site where uptime is critical and load is hight go with lighttpd; it scales amazingly. The only downside is that you have to be more hands on initially. Most hosts won't support this and it really pays to know what you're doing with lighttpd. If it's a site for your mother that'll get a few thousand visitors a month apache'll work better. She'll be able to move to a new host a lot easier and support is easier to find. A: Use a standard web server. Apache is used by 50% of web sites (Netcraft), therefore, if you use Apache, peoples' web browsers, spiders, proxies etc, are pretty much guaranteed to work with your site (its web server anyway). Lighthttpd is used by 1.5% of web sites (Netcraft), so it's far less likely that people will test their apps with it. Any performance difference is likely not to matter in production; an Apache server can probably serve static requests at a much higher bandwidth than you have, on the slowest hardware you're likely to deploy in production.
{ "language": "en", "url": "https://stackoverflow.com/questions/172164", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: How do you bind a DropDownList in a GridView in the EditItemTemplate Field? Here's my code in a gridview that is bound at runtime: ... <asp:templatefield> <edititemtemplate> <asp:dropdownlist runat="server" id="ddgvOpp" /> </edititemtemplate> <itemtemplate> <%# Eval("opponent.name") %> </itemtemplate> </asp:templatefield> ... I want to bind the dropdownlist "ddgvOpp" but i don't know how. I should, but I don't. Here's what I have, but I keep getting an "Object reference" error, which makes sense: protected void gvResults_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) //skip header row { DropDownList ddOpp = (DropDownList)e.Row.Cells[5].FindControl("ddgvOpp"); BindOpponentDD(ddOpp); } } Where BindOpponentDD() is just where the DropDownList gets populated. Am I not doing this in the right event? If not, which do I need to put it in? Thanks so much in advance... A: Ok, I guess I'm just dumb. I figured it out. In the RowDataBound event, simply add the following conditional: if (myGridView.EditIndex == e.Row.RowIndex) { //do work } A: Thanks to Saurabh Tripathi, The solution you provided worked for me. In gridView_RowDataBound() event use. if(gridView.EditIndex == e.Row.RowIndex && e.Row.RowType == DataControlRowType.DataRow) { // FindControl // And populate it } If anyone is stuck with the same issue, then try this out. Cheers. A: protected void grdDevelopment_RowDataBound(object sender, GridViewRowEventArgs e) { if (grdDevelopment.EditIndex == e.Row.RowIndex && e.Row.RowType==DataControlRowType.DataRow) { DropDownList drpBuildServers = (DropDownList)e.Row.Cells[0].FindControl("ddlBuildServers"); } } Try this one This will help u A: I had the same issue, but this fix (Jason's, which is adding the conditional to the handler) didn't work for me; the Edit row never was databound, so that condition never evaluated to true. RowDataBound was simply never called with the same RowIndex as the GridView.EditIndex. My setup is a little different, though, in that instead of binding the dropdown programmatically I have it bound to an ObjectDataSource on the page. The dropdown still has to be bound separately per row, though, because its possible values depend on other information in the row. So the ObjectDataSource has a SessionParameter, and I make sure to set the appropriate session variable when needed for binding. <asp:ObjectDataSource ID="objInfo" runat="server" SelectMethod="GetData" TypeName="MyTypeName"> <SelectParameters> <asp:SessionParameter Name="MyID" SessionField="MID" Type="Int32" /> </SelectParameters> And the dropdown in the relevant row: <asp:TemplateField HeaderText="My Info" SortExpression="MyInfo"> <EditItemTemplate> <asp:DropDownList ID="ddlEditMyInfo" runat="server" DataSourceID="objInfo" DataTextField="MyInfo" DataValueField="MyInfoID" SelectedValue='<%#Bind("ID") %>' /> </EditItemTemplate> <ItemTemplate> <span><%#Eval("MyInfo") %></span> </ItemTemplate> </asp:TemplateField> What I ended up doing was not using a CommandField in the GridView to generate my edit, delete, update and cancel buttons; I did it on my own with a TemplateField, and by setting the CommandNames appropriately, I was able to trigger the built-in edit/delete/update/cancel actions on the GridView. For the Edit button, I made the CommandArgument the information I needed to bind the dropdown, instead of the row's PK like it would usually be. This luckily did not prevent the GridView from editing the appropriate row. <asp:TemplateField> <ItemTemplate> <asp:ImageButton ID="ibtnDelete" runat="server" ImageUrl="~/images/delete.gif" AlternateText="Delete" CommandArgument='<%#Eval("UniqueID") %>' CommandName="Delete" /> <asp:ImageButton ID="ibtnEdit" runat="server" ImageUrl="~/images/edit.gif" AlternateText="Edit" CommandArgument='<%#Eval("MyID") %>' CommandName="Edit" /> </ItemTemplate> <EditItemTemplate> <asp:ImageButton ID="ibtnUpdate" runat="server" ImageUrl="~/images/update.gif" AlternateText="Update" CommandArgument='<%#Eval("UniqueID") %>' CommandName="Update" /> <asp:ImageButton ID="ibtnCancel" runat="server" ImageUrl="~/images/cancel.gif" AlternateText="Cancel" CommandName="Cancel" /> </EditItemTemplate> </asp:TemplateField> And in the RowCommand handler: void grdOverrides_RowCommand(object sender, GridViewCommandEventArgs e) { if (e.CommandName == "Edit") Session["MID"] = Int32.Parse(e.CommandArgument.ToString()); } The RowCommand, of course, happens before the row goes into edit mode and thus before the dropdown databinds. So everything works. It's a little bit of a hack, but I'd spent enough time trying to figure out why the edit row wasn't being databound already. A: This code will be do what you want: <asp:TemplateField HeaderText="garantia" SortExpression="garantia"> <EditItemTemplate> <asp:DropDownList ID="ddgvOpp" runat="server" SelectedValue='<%# Bind("opponent.name") %>'> <asp:ListItem Text="Si" Value="True"></asp:ListItem> <asp:ListItem Text="No" Value="False"></asp:ListItem> </asp:DropDownList> </EditItemTemplate> <ItemTemplate> <asp:Label ID="Label1" runat="server" Text='<%# Bind("opponent.name") %>'></asp:Label> </ItemTemplate>
{ "language": "en", "url": "https://stackoverflow.com/questions/172175", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Indexing URL's in SQL Server 2005 What is the best way to deal with storing and indexing URL's in SQL Server 2005? I have a WebPage table that stores metadata and content about Web Pages. I also have many other tables related to the WebPage table. They all use URL as a key. The problem is URL's can be very large, and using them as a key makes the indexes larger and slower. How much I don't know, but I have read many times using large fields for indexing is to be avoided. Assuming a URL is nvarchar(400), they are enormous fields to use as a primary key. What are the alternatives? How much pain would there likely to be with using URL as a key instead of a smaller field. I have looked into the WebPage table having a identity column, and then using this as the primary key for a WebPage. This keeps all the associated indexes smaller and more efficient but it makes importing data a bit of a pain. Each import for the associated tables has to first lookup what the id of a url is before inserting data in the tables. I have also played around with using a hash on the URL, to create a smaller index, but am still not sure if it is the best way of doing things. It wouldn't be a unique index, and would be subject to a small number of collisions. So I am unsure what foreign key would be used in this case... There will be millions of records about webpages stored in the database, and there will be a lot of batch updating. Also there will be a quite a lot of activity reading and aggregating the data. Any thoughts? A: I'd use a normal identity column as the primary key. You say: This keeps all the associated indexes smaller and more efficient but it makes importing data a bit of a pain. Each import for the associated tables has to first lookup what the id of a url is before inserting data in the tables. Yes, but the pain is probably worth it, and the techniques you learn in the process will be invaluable on future projects. On SQL Server 2005, you can create a user-defined function GetUrlId that looks something like CREATE FUNCTION GetUrlId (@Url nvarchar(400)) RETURNS int AS BEGIN DECLARE @UrlId int SELECT @UrlId = Id FROM Url WHERE Url = @Url RETURN @UrlId END This will return the ID for urls already in your URL table, and NULL for any URL not already recorded. You can then call this function inline your import statements - something like INSERT INTO UrlHistory(UrlId, Visited, RemoteIp) VALUES (dbo.GetUrlId('http://www.stackoverflow.com/'), @Visited, @RemoteIp) This is probably slower than a proper join statement, but for one-time or occasional import routines it might make things easier. A: Break up the URL into columns based on the bits your concerned with and use the RFC as a guide. Reverse the host and domain info so an index can group like domains (Google does this). stackoverflow.com -> com.stackoverflow blog.stackoverflow.com -> com.stackoverflow.blog Google has a paper that outlines what they do but I can't find right now. http://en.wikipedia.org/wiki/Uniform_Resource_Locator A: I would stick with the hash solution. This generates a unique key with a fairly low chance of collision. An alternative would be to create GUID and use that as the key. A: I totally agree with Dylan. Use an IDENTITY column or a GUID column as surrogate key in your WebPage table. Thats a clean solution. The lookup of the id while importing isn't that painful i think. Using a big varchar column as key column is wasting much space and affects insert and query performance. A: Not so much a solution. More another perspective. Storing the total unique URI of a page perhaps defeats part of the point of URI construction. Each forward slash is supposed to refer to a unique semantic space within the domain (whether that space is actual or logical). Unless the URIs you intend to store are something along the line of www.somedomain.com/p.aspx?id=123456789 then really it might be better to break a single URI metatable into a table representing the subdomains you have represented in your site. For example if you're going to hold a number of "News" section URIs in the same table as the "Reviews" URIs then you're missing a trick to have a "Sections" table whose content contains meta information about the section and whose own ID acts as a parent to all those URIs within it.
{ "language": "en", "url": "https://stackoverflow.com/questions/172176", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: C#/.NET Lexer Generators I'm looking for a decent lexical scanner generator for C#/.NET -- something that supports Unicode character categories, and generates somewhat readable & efficient code. Anyone know of one? EDIT: I need support for Unicode categories, not just Unicode characters. There are currently 1421 characters in just the Lu (Letter, Uppercase) category alone, and I need to match many different categories very specifically, and would rather not hand-write the character sets necessary for it. Also, actual code is a must -- this rules out things that generate a binary file that is then used with a driver (i.e. GOLD) EDIT: ANTLR does not support Unicode categories yet. There is an open issue for it, though, so it might fit my needs someday. A: GPLEX seems to support your requirements. A: The two solutions that come to mind are ANTLR and Gold. ANTLR has a GUI based grammar designer, and an excellent sample project in C# can be found here. A: I agree with @David Robbins, ANTLR is probably your best bet. However, the generated ANTLR code does need a seperate runtime library in order to use the generated code because there are some string parsing and other library commonalities that the generated code relies on. ANTLR generates a lexer AND a parser. On a side note: ANTLR is great...I wrote a 400+ line grammar to generate over 10k or C# code to efficiently parse a language. This included built in error checking for every possible thing that could go wrong in the parsing of the language. Try to do that by hand, and you'll never keep up with the bugs. A: I just found this http://www.seclab.tuwien.ac.at/projects/cuplex/lex.htm It says that it's configurable enough to support unicode ;-). Herber
{ "language": "en", "url": "https://stackoverflow.com/questions/172189", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: How can I show the result of a POST request as an image? I am working on a web-application in which dynamically-created images are used to display information. This data is currently sent to the images using a GET query-string but with more complex images and data I am worried about running into problems with the url character limit. I could simply pass the record ID to the image and have this query the database but this would obviously increase demand on the server. Is there some way I could add an image retrieved using POST into a HTML document? A: In the end, I think quering the database will probably be faster. To get a small string (say up to 2000 characters) from the database is very quick and probably faster than having the user post it all the time, especially if there is more than 1 on a page. The best option would be create the image once and cache it if it doesn't change. When the image is requested again, check to see if it's cached and just use readfile() to send it to the browser. I like to store the cached image outside the doc root so it's not accessible by others, but this may not be a factor in what you're doing (both caching and privacy). The SESSION might be an option, but this is the best option when you need to regenerate the image on multiple pages with slight changes, so you don't have query the db each time. A: Not easily - HTML doesn't include any intrinsic support for sending multiple POST requests and rendering the results as inline resources, as it does with <img /> <script /> and other tags that define a SRC attribute. Even AJAX workarounds might not help you here. Changing the SRC attribute of an image is easy, but all that'll do is cause the browser to GET the new image (from the cache or the server, depending on your configuration). Actually changing the content of the image to a binary response from an HTTP POST is much more involved - although you could look into base64-encoding the response stream and using the data: URL scheme to display the resulting image in your page. You can always have a form with "Click to view image" as the submit button, of course - you submit the form, the server responds with image/jpeg data, and your browser displays it as a standalone image. I'm pretty sure you can't do it inline, though. A: One option could be to store this data in a session variable. You should do some tests to see which way your server(s) handle it better A: To expand on Darryl Hein's comment: With this, I'd recommend removing it from the SESSION after you are done with it. If it's in there all the time, PHP will load it on every page call, not just the image "page". – Darryl Hein Yea I thought about this and agree, you don't want to clog the tubes with unneeded session data but what if you don't know when to remove the data? You can't just delete the session data after the image is created, what if the image is to be displayed twice? Unless the images themselves are cached for a certain period of time. Something like this Requesting page <? //index.php $_SESSION['imagedata']['header'] = array('name'=>'Simon','backgroundcolor'=>'red'); echo '<img src="image.php?image=header">'; // more stuff echo '<img src="image.php?image=header">'; // same image ?> Image script <? //image.php switch($_GET['image']){ case 'header': if(isSet($_SESSION['imagedata']['header'])){ // create image using $_SESSION['imagedata']['header'] data // create cached image unset($_SESSION['imagedata']['header']); else if(cache_file_exists()){ // display cached file }else{ // no data, use plan B } break; } ?> A: If the image can be identified by an id just use that. Assuming that the same id should produce the same image each time just use some proxy to serve the images using standard HTTP caching support. A: In some scenarios and under some limitations you could use an Iframe where you want your image to apear and post with a target attribute pointing to that iframe. so the main page has an iframe. the main page has a form that posts the the I frame and the server returns an image that is displayed in the iframe.
{ "language": "en", "url": "https://stackoverflow.com/questions/172192", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: good resource for socket errors? Where can I find a list of all types of bsd style socket errors? A: In the documentation? For instance, for connect(), see: % man connect ... ECONNREFUSED No-one listening on the remote address. EISCONN The socket is already connected. ENETUNREACH Network is unreachable. A: You can also find a list of error codes (and a general description of their meaning) on the Open Group's pages for each function (like connect, for example). A: Of you want to know all possible errno's or some comments on them you could take a look at the header files, on a Linux system there are located in * */usr/include/asm-generic/errno-base.h #ifndef _ASM_GENERIC_ERRNO_BASE_H #define _ASM_GENERIC_ERRNO_BASE_H #define EPERM 1 /* Operation not permitted */ #define ENOENT 2 /* No such file or directory */ #define ESRCH 3 /* No such process */ #define EINTR 4 /* Interrupted system call */ #define EIO 5 /* I/O error */ #define ENXIO 6 /* No such device or address */ #define E2BIG 7 /* Argument list too long */ #define ENOEXEC 8 /* Exec format error */ #define EBADF 9 /* Bad file number */ #define ECHILD 10 /* No child processes */ #define EAGAIN 11 /* Try again */ ... * */usr/include/asm-generic/errno.h #ifndef _ASM_GENERIC_ERRNO_H #define _ASM_GENERIC_ERRNO_H #include #define EDEADLK 35 /* Resource deadlock would occur */ #define ENAMETOOLONG 36 /* File name too long */ #define ENOLCK 37 /* No record locks available */ #define ENOSYS 38 /* Function not implemented */ #define ENOTEMPTY 39 /* Directory not empty */ #define ELOOP 40 /* Too many symbolic links encountered */ #define EWOULDBLOCK EAGAIN /* Operation would block */ ... If you want to know what errno a call, e.g. socket() or connect() can return, when install the development manpages and try man socket or man connect A: Many functions will set errno on failure, and instead of going through errno.h yourself and converting the error number to strings, you are much better off calling perror. perror will print the current errno's corresponding message to stderr with an optional prefix. Example usage: if (connect()) { perror("connect() failed in function foo"); ... } perror has friends called strerror and strerror_r who might prove useful if you want to capture the string for use in places other than stderr.
{ "language": "en", "url": "https://stackoverflow.com/questions/172199", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Why does System.Net.Mail fail where System.Web.Mail works I can get both System.Net.Mail and System.Web.Mail to work with GMail, but I can't get them both to work with smtp.att.yahoo.com. I get the SMTP settings from my own Web.config keys. These settings work when I send using System.Web.Mail, but fail with System.Net.Mail. <add key="SmtpServer" value="smtp.att.yahoo.com"/> <add key="SmtpServerAuthenticateUser" value="ctrager@sbcglobal.net"/> <add key="SmtpServerPort" value="465"/> <add key="SmtpUseSSL" value="1"/> <add key="SmtpServerAuthenticatePassword" value="MY PASSWORD"/> Here is the code that grabs my settings, and works with GMail, fails with att.yahoo: SmtpClient smtp; if (!string.IsNullOrEmpty(Util.get_setting("SmtpServer", ""))) { smtp = new SmtpClient(Util.get_setting("SmtpServer", "")); } else { smtp = new SmtpClient(); } if (!string.IsNullOrEmpty(Util.get_setting("SmtpServerAuthenticatePassword", ""))) smtp.Credentials = new System.Net.NetworkCredential( Util.get_setting("SmtpServerAuthenticateUser", ""), Util.get_setting("SmtpServerAuthenticatePassword", "")); if (!string.IsNullOrEmpty(Util.get_setting("SmtpServerPort", ""))) smtp.Port = int.Parse(Util.get_setting("SmtpServerPort", "")); if (Util.get_setting("SmtpUseSSL", "0") == "1") smtp.EnableSsl = true; smtp.Send(message); Is this my problem? http://blogs.msdn.com/webdav_101/archive/2008/06/02/system-net-mail-with-ssl-to-authenticate-against-port-465.aspx A: The previous answers concerning implicit and explicit SSL connections via System.Net.Mail is absolutely correct. The way I was able to get through this obstacle, and without having to use the now obsolete System.Web.Mail, was to use the CDO (Collaborative Data Objects). I detailed and gave an example on another stack overflow post (GMail SMTP via C# .Net errors on all ports) if curious. Otherwise, you can go directly to the KB article at http://support.microsoft.com/kb/310212. Hope this helps! A: I've learned the answer. The answer is: Because System.Net.Mail does not support "implicit" SSL, only "explicit" SSL. A: Gimel's answer is back to front. He says use the new System.Net.Mail library, but the problem is that System.Net.Mail does not work for SSL on port 465 like System.Web.Mail did/does work! I've beaten my head against this all day and for identical settings System.Web.Mail WORKS, and System.Net.Mail DOES NOT work (at least for the SMTP server I have been testing with), and here I was thinking that I should always upgrade to Microsoft's latest offering to get the best in life. :-( That link to the M$ blog seems to state it all; "System.Net.Mail only supports “Explicit SSL”." and I assume the SMTP server I have been testing with wants Implicit SSL. (It's a Yahoo server btw). Since "upgrading" to the new API will no doubt break functionality for users who have servers that require implicit SSL it seems like a step backwards to "upgrade" in this case. If you can still compile only with warnings, simply disable those warnings (0618 if I recall) and keep on trucking. Oh, and you may want to consider ensuring your application always runs against the .NET framework version you built and tested with by way of config file, just so in future if M$ rips out the old API your application is safe.
{ "language": "en", "url": "https://stackoverflow.com/questions/172203", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Should one use Tapestry 5 for a production release? We're starting a large web project, mostly green field. I like the Tapestry framework for java/web solutions. I have concerns about starting a Tapestry 5 project since T5 is still in beta. However, if I understand the documentation correctly, T4 development will not be supported by T5 and up. My question: Should I begin a large project for a large company with T5? If not, with the imminent release of T5, should I ignore T4 altogether? A: This question is moot now; Tapestry 5.0.18 was released on Dec.12 and it's the stable production-ready release, so nobody has to worry about using Tap5 before production anymore... just upgrade from whatever 5.0.x you're using to 5.0.18. WARNING: If you're still using 5.0.15 then maybe you will have to modify some stuff around. I had 2 problems upgrading from 5.0.15 to 5.0.17: one is that any fields marked as @Property must not have any accessors; if you have an accessor for a @Property field you must remove the @Property tag and implement both accessors if you need them. The other one was that the page classes are no longer packed in their own jar file (this only applies to newly created projects), so if you need your pages to be in their own jar file (for whatever reason), you must modify your pom.xml to add the archiveClasses to the maven-war-plugin plugin. A: T5 is in the last beta, the next release is RC, and then the full release. according to howard, things should be done by the end of october. so, if you're starting the project, i believe the framework will catch you with its release. another thing, the betas are pretty quality products, howard does the great job with his framework. at my now previous company, there is a project started in september based on tapestry 5, a colleague managed to get a working example pretty quickly and it seems okay. we worked with tapestry 4 on a previous project, and when the question raised about which version to choose, the fact that T4 will be abandoned in favor of T5, and much changes in the framework concept itself, the counclusion was it's much better for a developer new in tapestry to learn new version immidiately (also, if i were to stay, i was interested in switching to T5 also as soon as possible, because i see a quality improvement in the T5 concepts compared to T4 which i worked with). of course, you have your deadlines and project limitations which you have to take into account. if it's rather flexibile, or long-lasting project, maybe get a quick start of T5 for a week, and then decide based on your experience with it. A: You should take a very good look at the development history of Tapestry before committing to use it. Tapestry has done a lot of non-compatible upgrades, with no continuation of support of older versions. Patches to 4.1 are not processed anymore within a reasonable timeframe. That is in my point of view not acceptable for the official stable version. Committing to use Tapestry 5 means: * *you should become a committer; *you need to keep up with all new development, abandon old versions as fast as possible; *maintain stable versions yourself. A: As zappan said, you should consider T5 if your project delivery (LIVE/RELEASE) date is several months ahead. Especially since T5 is not released yet -- which leads to the expectation that there will NOT be too many people who will have experience with it. Then again, if your project is NOT mission critical and can suffer some delays to the LIVE date, it should NOT hurt. A: Reading through Tapestry user mailing list, there still appear to many rough edges. T5 is impressive when you run through the demo, but I'd wait a while before considering using it for production. http://www.nabble.com/Tapestry---User-f340.html A: I don't think I can recommend a beta solution to a high profile app like this, but I'm also leaning against T4 because the upgrade path will be slammed shut upon the release of T5. Do you agree? A: I'm currently using T5 in a project that is about to go live with the beta version, which is not exactly what we intended - we thought the first release would be out by now. T5, IMHO, is stable and mature, apart from a few rough edges and a rather small community. If you're only getting started, I wouldn't bother using T4. I found T5 quite elegant and fun to work with, so if you have some time before the planned release, go for it! A: Tapestry 5 is awful. Productivity plummets, there are memory leaks. It profiles very badly for heap size and the older object generations in GC. It does not scale for large numbers of users due to use of sessions everywhere. It is very badly documented, poorly suppurted with a tiny number of commiters. The code base quality is very low with non standard looking code. I woudl avoid it like the plague. I worked with it for 6 months on a very high profile project that was eventually canned at the expense of multi million pounds. T5 was not responsible for that but had its part to play by bringing developer productivity to zero. With wicket and grails and Spring MVC and Struts2 why on earth woudl you risk anything on this also ran framework?
{ "language": "en", "url": "https://stackoverflow.com/questions/172208", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Is it possible to get perforce to behave like subversion? Can perforce be adjusted so I don't need to "open files for edit"? Someone told me that this was a "feature", and that s/he guessed it could be turned off. A: Although that's not a direct answer to your request, I though I could share a little trick. In my editor (SciTE), I can define keyboard shortcuts, with a macro expanding to the path of the currently edited file, running an application. If your favorite editor can do that, you can adapt this trick. command.name.0.*=P4 edit command.0.*=p4 edit -c default $(FileNameExt) command.save.before.0.*=2 You can change the "default" to your current changelist number, too. Of course, if your editor/IDE has Perforce support, so much the better... A: See http://www.perforce.com/perforce/doc.081/manuals/p4guide/02_config.html (section Configuring workspace options). You can set the allwrite option, but even then you would have to do the offline synchronization or something like checking out all files and doing p4 revert -a (revert unchanged files) to find out which files you changed. A: One approach you can use is edit the readonly files on your synch'd branch. When you're ready to submit use the 'check consistency' File | More option to create a changelist on the basis of the modified files. There's probably a command-line way of doing this but I don't know what it is. A: According to the Wikipedia page on Perforce, they expect you to "open files for edit" so the server can maintain a list of files that are expected to get changed. If you want to edit files without doing this, you have to manually change your local copy from read-only to read-write. A: I will resist trying to reason with you as to why you wish to do this. Probably teh simples way to do this is the following. Check out the entire directory tree you are interested in eg //depot/Projects/MyProj/... All you files are now writeable and in editing (or checked out) mode. When you choose to submit your changes, simply do one of two things. Either right click the pending changelist and select Revert unchanged files to get rid of unchanged files before submitting or when submitting select the 'Dont Submit Unchanged Files' options under On Submit. This has the effect of only submitting the files you have changed. If you also check the box beside 'Check out submitted files after Submit' it will even reopen those files so that you can continue working until the next time you wish to submit. This is essentially what you are looking for.
{ "language": "en", "url": "https://stackoverflow.com/questions/172209", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Probability of hardware related disk or memory corruption? I've got a few hundred computers running an app. On one computer, I've seen two instances of a single bit being incorrectly set on some strings that I pull out of SQLite. If this was my dev computer I would assume I have a bug somewhere, but there is certainly some number of installations at which point I'll start seeing rare hardware based errors. This is certainly dependent on how much IO I do, but are there any rules of thumbs for when there is a decent chance of seeing this kind of thing? For example, for TCP packets, this paper determined that silent, undetected corruption will occur in "roughly 1 in 16 million to 10 billion packets". Unfortunately, running a mem/disk checker on the machine in question is not likely to happen. A: When I notice strange things happening, my strategy is: * *check if there is a bug in the code *check if there is a bug in the used library/tool (SQLite, here) *check if there is a bug in the compiler *then, and only then, check for hardware faults In my 10 years-long career, 99,99% of bugs were software related. Hope this helps. A: Bit errors will happen. Consider protecting your data with CRC's or some other kind of error detection/correction mechanism. The odds of it happening are dependant on what kind of hardware you have. If you have memory with ECC, then it's going to be less likely than if you don't for instance, but even ECC memory goes bad and may fail to correct errors. With several hundred computers I would say the odd hardware error is going to be very likely, probably certain, to happen daily. A: "Wikipedia: ECC memory" says "Recent DRAM tests give widely varying error rates with over 7 orders of magnitude difference, ranging from 10^−10 to 10^−17 error/bit·h, roughly one bit error, per hour, per gigabyte of memory to one bit error, per century, per gigabyte of memory.[7][11][12]" Even if we use the most optimistic estimate of one bit error per century per gigabyte, if you have a cluster of 100 computers with 2 GB of RAM each, that implies that you'll see a bit error twice a year. (This only includes RAM bit error. You mentioned TCP packet undetected corruption, and you might also consider disk drive failures, accidental power cord unplugging, cooling fan failures, etc). The more pessimistic estimates imply you'll see bit errors far more often -- as Steve Baker said, bit errors are inevitable. A: with subtle errors, it can happen anytime, and from several source, even the most unlikely. As you can see errors occurring on a single machine, your best option is to handle the damage instead of relying on statistics to tell you when something might go wrong. Whilst the errors might be due to external factors, if you've seen more than one it would be prudent to get that memchecker running on the machine to check that its not faulty hardware. The alternative is trusting to luck that you won't see a total failure. A: Switch that machine out. In my current position (~7 years) I've seen a bluescreen caused by a hardware memory error once. If you are seeing bit error failures on the same machine twice, good chance you've found the culprit. In the same period of time I've seen dozens of disk controller failure/disk failure/registry corruption bluescreens. So they are rare, but they do happen. On the network side, we had one case where a 3d party vendor's WAN compression device was compressing our apps TCP packets together, incorrectly, and then putting a good CRC on it. That wreaked havoc to say the least.
{ "language": "en", "url": "https://stackoverflow.com/questions/172219", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How do I set cookies from outside domains inside iframes in Safari? From the Apple developer faq Safari ships with a conservative cookie policy which limits cookie writes to only the pages chosen ("navigated to") by the user. By default Safari only allows cookies from sites you navigate to directly. (i.e. if you click on links with the url of that domainname). This means that if you load a page from your own site with an iFrame with a page from another site, that the other site is not able to set cookies. (for instance, a ticketshop). As soon as you have visited the other domain directly, the other site is able to access and change its own cookies. Without having access to code on the other site, how can i make the user-experience as inobtrusive as possible? Is there a (javascript?) way to check if the other site's cookies are already set, and accordingly, show a direct link to the other site first, if needed? Update: The HTML5 feature 'window.postmessage' seems to be a nice solution. There are some jQuery libraries that might help, and compatible with most recent browsers. In essence, the iFrame document sends messages, with Json, thru the window element. The very nice Postmessage-plugin, by daepark, which i got working. and another jQuery postMessage, by Ben Alman i found, but haven't tested. A: This is an issue known as Same Origin Policy. Essentially it is a security measure against creating security loopholes. When you have an iframe that points to a page on your own domain, JavaScript can access both the page you're on and the page within the Iframe. This is an acceptable parent to child and child to parent relationship. (parent doc) (iframe doc) HTML --> IFRAME <-- HTML ^--------|---------^ However, once you have a file pointing to an external page, SOP comes into play and haults any information passing between the parent page and the iframe page. (parent doc) (iframe doc) HTML --> IFRAME <-- HTML X Check out this post about iframe communication, it makes a lot of sense! Stackoverflow post These links really help too! 1) Secure Cross-Domain Communication in the Browser 2) wiki SOP or Same Origin Policy Good luck! A: This page suggests that you place some javascript in your pages which detects the absence of an always-there cookie. When it finds that the cookie has not been set, it posts the required session data to a page which sets the cookie, and redirects you back to the originating page. Apparently the POST is enough to satisfy Safari's 'have I navigated to this domain' test, so from then on it accepts cookies from that domain. Of course, it's not the nicest of code, but may well solve your problem. A: One solution (a bit messy) might be to have the parent page check for the presence of the cookie and if the cookie is not present run an AJAX call to a script on the iframe page's domain which sets the cookie. A: This is a common issue with facebook apps displayed in Safari. The way many (including myself) have dealt with this is to have the iframed page POST to itself. When a page has posted form data, it is then allowed to set cookies. In the end, it works with a 1 page refresh, which could even be your user login POST. A: localStorage, supported by safari and all modern browsers, permits read/write operations even on pages loaded into iframes. if you don't mind dropping support for ie6 and ie7, try using localStorage instead of cookies in your framed site. i know your question specifically says you don't have access to code on the framed site, but for those who do, localStorage definitely solves the "no cookies in a safari iframe" problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/172223", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "22" }
Q: What is the max length of an Informix column and can it be increased? I am trying to create a table with the following: CREATE TABLE GTW_WORKFLOW_MON ( WORKFLOW_NAME VARCHAR(255) NOT NULL, WORKFLOW_LOADED NUMERIC(20) NOT NULL, ACTIVITY_NAME VARCHAR(255) NOT NULL, FLAGS INTEGER NOT NULL, MONITOR_NAME VARCHAR(255) NOT NULL, CLASSNAME VARCHAR(255) NOT NULL, STR0 VARCHAR(255), STR1 VARCHAR(255), STR2 VARCHAR(255), NUM0 VARCHAR(255), NUM1 VARCHAR(255), NUM2 VARCHAR(255), DATE0 VARCHAR(255), DATE1 VARCHAR(255), DATE2 VARCHAR(255), PRIMARY KEY (WORKFLOW_NAME, WORKFLOW_LOADED, ACTIVITY_NAME, MONITOR_NAME) ) It fails due to column length not being large enough. A: It would help if the SQL statement was syntactically valid and if you provided the exact error message. When reformatted and syntax corrected, the statement looks like: CREATE TABLE gtw_workflow_mon ( workflow_name VARCHAR(255) NOT NULL, workflow_loaded NUMERIC(20) NOT NULL, activity_name VARCHAR(255) NOT NULL, flags INTEGER NOT NULL, monitor_name VARCHAR(255) NOT NULL, classname VARCHAR(255) NOT NULL, str0 VARCHAR(255), str1 VARCHAR(255), str2 VARCHAR(255), num0 VARCHAR(255), num1 VARCHAR(255), num2 VARCHAR(255), date0 VARCHAR(255), date1 VARCHAR(255), date2 VARCHAR(255), PRIMARY KEY(workflow_name, workflow_loaded, activity_name, monitor_name) ); And, when that is run on a system with 2KB pages, the error message is: SQL -550: Total length of columns in constraint is too long. The standard way of getting a brief explanation of an error message is finderr; it says: $ finderr -550 -550 Total length of columns in constraint is too long. The total size of all the columns listed in a UNIQUE, PRIMARY KEY, or FOREIGN KEY clause is limited. The limit depends on the database server in use, but all servers support a total of 120 bytes. The limit is the same as the restriction on the total size of all columns in a composite index. For additional information, see the CREATE TABLE statement in the IBM Informix Guide to SQL: Syntax. $ The 'a total of 120 bytes' should be 'a total of at least 120 bytes'; that lower-bound applies to Informix SE. In IDS (Informix Dynamic Server), the lower-bound is 255 bytes, but it is bigger in more recent systems, and also bigger when the page size is bigger. You have a variety of options. * *You can consider why your names need to be 255 characters each - is that sensible (would, say, 64 be sufficient)? *If your server version is recent enough (10.00 or later, I believe), you could create the table in a dbspace with a larger page size. Since the key is a maximum of 3*255+(20/2+1) = 776 bytes, and the rule of thumb is you need to be able to store 5 maximum-length key values + ROWID/FRAGID overhead (8 bytes) per page, you would need a 4 KB page size. (Had you been running on AIX, you probably wouldn't have noticed the issue.) Also, you should not be storing date values in VARCHAR(255); you should use DATE or perhaps DATETIME YEAR TO DAY (a weird way of spelling DATE - though the underlying format is different, using 5 bytes on disk instead of 4 for a plain DATE), or perhaps DATETIME YEAR TO SECOND (a funny way of spelling TIMESTAMP), or ... The 'num0, num1, num2' fields are also dubious, too; if they are meant to store numbers, use NUMERIC or DECIMAL -- DECIMAL(20) in most IDS databases means a 20-digit floating point decimal number. Edited to add: And, to answer the direct question, VARCHAR columns can only be up to 255 bytes long; LVARCHAR columns can be up to about 32 KB; CHAR columns can be up to 32 KB; TEXT columns can be up to 2 GB, and CLOB columns can be even larger. The total length of a row is limited to about 32 KB (but BYTE, TEXT, BLOB and CLOB columns count as a fixed size descriptor towards that 32 KB total - the actual data is stored outside the row). There are some version dependencies that I'm not bringing out - if you are using IDS 10.00 or later, this is accurate.
{ "language": "en", "url": "https://stackoverflow.com/questions/172227", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How do I programmatically zoom a UIScrollView? I'd like to zoom and unzoom in ways the base class doesn't support. For instance, upon receiving a double tap. A: I think I figured out what documentation Darron was referring to. In the document "iPhone OS Programming Guide" there's a section "Handling Multi-Touch Events". That contains listing 7-1: - (void) touchesEnded:(NSSet*)touches withEvent:(UIEvent*)event { UIScrollView *scrollView = (UIScrollView*)[self superview]; UITouch *touch = [touches anyObject]; CGSize size; CGPoint point; if([touch tapCount] == 2) { if(![_viewController _isZoomed]) { point = [touch locationInView:self]; size = [self bounds].size; point.x /= size.width; point.y /= size.height; [_viewController _setZoomed:YES]; size = [scrollView contentSize]; point.x *= size.width; point.y *= size.height; size = [scrollView bounds].size; point.x -= size.width / 2; point.y -= size.height / 2; [scrollView setContentOffset:point animated:NO]; } else [_viewController _setZoomed:NO]; } } } A: I'm answering my own question, after playing with things and getting it working. Apple has a very-simple example of this in their documentation on how to handle double taps. The basic approach to doing programmatic zooms is to do it yourself, and then tell the UIScrollView that you did it. * *Adjust the internal view's frame and bounds. *Mark the internal view as needing display. *Tell the UIScrollView about the new content size. *Calculate the portion of your internal view that should be displayed after the zoom, and have the UIScrollView pan to that location. Also key: once you tell the UIScrollView about your new contents size it seems to reset its concept of the current zoom level. You are now at the new 1.0 zoom factor. So you'll almost certainly want to reset the minimum and maximum zoom factors. A: NOTE: this is horribly outdated. It's around from iOS 2.x times, and has actually been fixed around iOS 3.x. Keeping it here for historical purposes only. I think I found a clean solution to this, and I made an UIScrollView subclass to encapsulate it. The sample code that illustrates both programmatic zooming (+ double-tap handling) and Photo Library-style paging+zooming+scrolling, together with ZoomScrollView class, is available at github.com/andreyvit/ScrollingMadness. In a few words, my solution is to return a new dummy view from viewForZoomingInScrollView:, temporarily making your content view (UIImageView, whatever) its child. In scrollViewDidEndZooming: we reverse that, disposing the dummy view and moving your content view back into the scroll view. Why does it help? It is a way of defeating the persistent view scale that we cannot change programmatically. UIScrollView does not keep the current view scale itself. Instead, each UIView is capable of keeping its current view scale (inside UIGestureInfo object pointed to by the _gestureInfo field). By providing a new UIView for each zooming operation, we always start with zoom scale 1.00. And how does that help? We store the current zoom scale ourself, and apply it manually to our content view, e.g. contentView.transform = CGAffineTransformMakeScale(zoomScale, zoomScale). This however conflicts with UIScrollView wanting to reset the transform when the user pinches the view. By giving UIScrollView another view with identity transform to zoom, we no longer fight for transforming the same view. UIScrollView can happily believe it starts with zoom 1.00 each time and scales a view starting with an identity transform, and its inner view has a transform applied corresponding to our actual current zoom scale. Now, ZoomScrollView encapsulates all this stuff. Here's its code for the sake of completeness, however I really recommend to download the sample project from GitHub (you don't need to use Git, there's a Download button there). If you want to be notified about sample code updates (and you should — I'm planning to maintain and update this class!), either follow the project on GitHub or drop me an e-mail at andreyvit@gmail.com. Interface: /* ZoomScrollView makes UIScrollView easier to use: - ZoomScrollView is a drop-in replacement subclass of UIScrollView - ZoomScrollView adds programmatic zooming (see `setZoomScale:centeredAt:animated:`) - ZoomScrollView allows you to get the current zoom scale (see `zoomScale` property) - ZoomScrollView handles double-tap zooming for you (see `zoomInOnDoubleTap`, `zoomOutOnDoubleTap`) - ZoomScrollView forwards touch events to its delegate, allowing to handle custom gestures easily (triple-tap? two-finger scrolling?) Drop-in replacement: You can replace `[UIScrollView alloc]` with `[ZoomScrollView alloc]` or change class in Interface Builder, and everything should continue to work. The only catch is that you should not *read* the 'delegate' property; to get your delegate, please use zoomScrollViewDelegate property instead. (You can set the delegate via either of these properties, but reading 'delegate' does not work.) Zoom scale: Reading zoomScale property returns the scale of the last scaling operation. If your viewForZoomingInScrollView can return different views over time, please keep in mind that any view you return is instantly scaled to zoomScale. Delegate: The delegate accepted by ZoomScrollView is a regular UIScrollViewDelegate, however additional methods from `NSObject(ZoomScrollViewDelegateMethods)` category will be called on your delegate if defined. Method `scrollViewDidEndZooming:withView:atScale:` is called after any 'bounce' animations really finish. UIScrollView often calls it earlier, violating the documented contract of UIScrollViewDelegate. Instead of reading 'delegate' property (which currently returns the scroll view itself), you should read 'zoomScrollViewDelegate' property which correctly returns your delegate. Setting works with either of them (so you can still set your delegate in the Interface Builder). */ @interface ZoomScrollView : UIScrollView { @private BOOL _zoomInOnDoubleTap; BOOL _zoomOutOnDoubleTap; BOOL _zoomingDidEnd; BOOL _ignoreSubsequentTouches; // after one of delegate touch methods returns YES, subsequent touch events are not forwarded to UIScrollView float _zoomScale; float _realMinimumZoomScale, _realMaximumZoomScale; // as set by the user (UIScrollView's min/maxZoomScale == our min/maxZoomScale divided by _zoomScale) id _realDelegate; // as set by the user (UIScrollView's delegate is set to self) UIView *_realZoomView; // the view for zooming returned by the delegate UIView *_zoomWrapperView; // the disposable wrapper view actually used for zooming } // if both are enabled, zoom-in takes precedence unless the view is at maximum zoom scale @property(nonatomic, assign) BOOL zoomInOnDoubleTap; @property(nonatomic, assign) BOOL zoomOutOnDoubleTap; @property(nonatomic, assign) id<UIScrollViewDelegate> zoomScrollViewDelegate; @end @interface ZoomScrollView (Zooming) @property(nonatomic, assign) float zoomScale; // from minimumZoomScale to maximumZoomScale - (void)setZoomScale:(float)zoomScale animated:(BOOL)animated; // centerPoint == center of the scroll view - (void)setZoomScale:(float)zoomScale centeredAt:(CGPoint)centerPoint animated:(BOOL)animated; @end @interface NSObject (ZoomScrollViewDelegateMethods) // return YES to stop processing, NO to pass the event to UIScrollView (mnemonic: default is to pass, and default return value in Obj-C is NO) - (BOOL)zoomScrollView:(ZoomScrollView *)zoomScrollView touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event; - (BOOL)zoomScrollView:(ZoomScrollView *)zoomScrollView touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event; - (BOOL)zoomScrollView:(ZoomScrollView *)zoomScrollView touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event; - (BOOL)zoomScrollView:(ZoomScrollView *)zoomScrollView touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event; @end Implementation: @interface ZoomScrollView (DelegateMethods) <UIScrollViewDelegate> @end @interface ZoomScrollView (ZoomingPrivate) - (void)_setZoomScaleAndUpdateVirtualScales:(float)zoomScale; // set UIScrollView's minimumZoomScale/maximumZoomScale - (BOOL)_handleDoubleTapWith:(UITouch *)touch; - (UIView *)_createWrapperViewForZoomingInsteadOfView:(UIView *)view; // create a disposable wrapper view for zooming - (void)_zoomDidEndBouncing; - (void)_programmaticZoomAnimationDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(UIView *)context; - (void)_setTransformOn:(UIView *)view; @end @implementation ZoomScrollView @synthesize zoomInOnDoubleTap=_zoomInOnDoubleTap, zoomOutOnDoubleTap=_zoomOutOnDoubleTap; @synthesize zoomScrollViewDelegate=_realDelegate; - (id)initWithFrame:(CGRect)frame { if (self = [super initWithFrame:frame]) { _zoomScale = 1.0f; _realMinimumZoomScale = super.minimumZoomScale; _realMaximumZoomScale = super.maximumZoomScale; super.delegate = self; } return self; } - (id)initWithCoder:(NSCoder *)aDecoder { if (self = [super initWithCoder:aDecoder]) { _zoomScale = 1.0f; _realMinimumZoomScale = super.minimumZoomScale; _realMaximumZoomScale = super.maximumZoomScale; super.delegate = self; } return self; } - (id<UIScrollViewDelegate>)realDelegate { return _realDelegate; } - (void)setDelegate:(id<UIScrollViewDelegate>)delegate { _realDelegate = delegate; } - (float)minimumZoomScale { return _realMinimumZoomScale; } - (void)setMinimumZoomScale:(float)value { _realMinimumZoomScale = value; [self _setZoomScaleAndUpdateVirtualScales:_zoomScale]; } - (float)maximumZoomScale { return _realMaximumZoomScale; } - (void)setMaximumZoomScale:(float)value { _realMaximumZoomScale = value; [self _setZoomScaleAndUpdateVirtualScales:_zoomScale]; } @end @implementation ZoomScrollView (Zooming) - (void)_setZoomScaleAndUpdateVirtualScales:(float)zoomScale { _zoomScale = zoomScale; // prevent accumulation of error, and prevent a common bug in the user's code (comparing floats with '==') if (ABS(_zoomScale - _realMinimumZoomScale) < 1e-5) _zoomScale = _realMinimumZoomScale; else if (ABS(_zoomScale - _realMaximumZoomScale) < 1e-5) _zoomScale = _realMaximumZoomScale; super.minimumZoomScale = _realMinimumZoomScale / _zoomScale; super.maximumZoomScale = _realMaximumZoomScale / _zoomScale; } - (void)_setTransformOn:(UIView *)view { if (ABS(_zoomScale - 1.0f) < 1e-5) view.transform = CGAffineTransformIdentity; else view.transform = CGAffineTransformMakeScale(_zoomScale, _zoomScale); } - (float)zoomScale { return _zoomScale; } - (void)setZoomScale:(float)zoomScale { [self setZoomScale:zoomScale animated:NO]; } - (void)setZoomScale:(float)zoomScale animated:(BOOL)animated { [self setZoomScale:zoomScale centeredAt:CGPointMake(self.frame.size.width / 2, self.frame.size.height / 2) animated:animated]; } - (void)setZoomScale:(float)zoomScale centeredAt:(CGPoint)centerPoint animated:(BOOL)animated { if (![_realDelegate respondsToSelector:@selector(viewForZoomingInScrollView:)]) { NSLog(@"setZoomScale called on ZoomScrollView, however delegate does not implement viewForZoomingInScrollView"); return; } // viewForZoomingInScrollView may change contentOffset, and centerPoint is relative to the current one CGPoint origin = self.contentOffset; centerPoint = CGPointMake(centerPoint.x - origin.x, centerPoint.y - origin.y); UIView *viewForZooming = [_realDelegate viewForZoomingInScrollView:self]; if (viewForZooming == nil) return; if (animated) { [UIView beginAnimations:nil context:viewForZooming]; [UIView setAnimationDuration: 0.2]; [UIView setAnimationDelegate: self]; [UIView setAnimationDidStopSelector: @selector(_programmaticZoomAnimationDidStop:finished:context:)]; } [self _setZoomScaleAndUpdateVirtualScales:zoomScale]; [self _setTransformOn:viewForZooming]; CGSize zoomViewSize = viewForZooming.frame.size; CGSize scrollViewSize = self.frame.size; viewForZooming.frame = CGRectMake(0, 0, zoomViewSize.width, zoomViewSize.height); self.contentSize = zoomViewSize; self.contentOffset = CGPointMake(MAX(MIN(zoomViewSize.width*centerPoint.x/scrollViewSize.width - scrollViewSize.width/2, zoomViewSize.width - scrollViewSize.width), 0), MAX(MIN(zoomViewSize.height*centerPoint.y/scrollViewSize.height - scrollViewSize.height/2, zoomViewSize.height - scrollViewSize.height), 0)); if (animated) { [UIView commitAnimations]; } else { [self _programmaticZoomAnimationDidStop:nil finished:nil context:viewForZooming]; } } - (void)_programmaticZoomAnimationDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(UIView *)context { if ([_realDelegate respondsToSelector:@selector(scrollViewDidEndZooming:withView:atScale:)]) [_realDelegate scrollViewDidEndZooming:self withView:context atScale:_zoomScale]; } - (BOOL)_handleDoubleTapWith:(UITouch *)touch { if (!_zoomInOnDoubleTap && !_zoomOutOnDoubleTap) return NO; if (_zoomInOnDoubleTap && ABS(_zoomScale - _realMaximumZoomScale) > 1e-5) [self setZoomScale:_realMaximumZoomScale centeredAt:[touch locationInView:self] animated:YES]; else if (_zoomOutOnDoubleTap && ABS(_zoomScale - _realMinimumZoomScale) > 1e-5) [self setZoomScale:_realMinimumZoomScale animated:YES]; return YES; } // the heart of the zooming technique: zooming starts here - (UIView *)_createWrapperViewForZoomingInsteadOfView:(UIView *)view { if (_zoomWrapperView != nil) // not sure this is really possible [self _zoomDidEndBouncing]; // ...but just in case cleanup the previous zoom op _realZoomView = [view retain]; [view removeFromSuperview]; [self _setTransformOn:_realZoomView]; // should be already set, except if this is a different view _realZoomView.frame = CGRectMake(0, 0, _realZoomView.frame.size.width, _realZoomView.frame.size.height); _zoomWrapperView = [[UIView alloc] initWithFrame:view.frame]; [_zoomWrapperView addSubview:view]; [self addSubview:_zoomWrapperView]; return _zoomWrapperView; } // the heart of the zooming technique: zooming ends here - (void)_zoomDidEndBouncing { _zoomingDidEnd = NO; [_realZoomView removeFromSuperview]; [self _setTransformOn:_realZoomView]; _realZoomView.frame = _zoomWrapperView.frame; [self addSubview:_realZoomView]; [_zoomWrapperView release]; _zoomWrapperView = nil; if ([_realDelegate respondsToSelector:@selector(scrollViewDidEndZooming:withView:atScale:)]) [_realDelegate scrollViewDidEndZooming:self withView:_realZoomView atScale:_zoomScale]; [_realZoomView release]; _realZoomView = nil; } @end @implementation ZoomScrollView (DelegateMethods) - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView { if ([_realDelegate respondsToSelector:@selector(scrollViewWillBeginDragging:)]) [_realDelegate scrollViewWillBeginDragging:self]; } - (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate { if ([_realDelegate respondsToSelector:@selector(scrollViewDidEndDragging:willDecelerate:)]) [_realDelegate scrollViewDidEndDragging:self willDecelerate:decelerate]; } - (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView { if ([_realDelegate respondsToSelector:@selector(scrollViewWillBeginDecelerating:)]) [_realDelegate scrollViewWillBeginDecelerating:self]; } - (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView { if ([_realDelegate respondsToSelector:@selector(scrollViewDidEndDecelerating:)]) [_realDelegate scrollViewDidEndDecelerating:self]; } - (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView { if ([_realDelegate respondsToSelector:@selector(scrollViewDidEndScrollingAnimation:)]) [_realDelegate scrollViewDidEndScrollingAnimation:self]; } - (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView { UIView *viewForZooming = nil; if ([_realDelegate respondsToSelector:@selector(viewForZoomingInScrollView:)]) viewForZooming = [_realDelegate viewForZoomingInScrollView:self]; if (viewForZooming != nil) viewForZooming = [self _createWrapperViewForZoomingInsteadOfView:viewForZooming]; return viewForZooming; } - (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(float)scale { [self _setZoomScaleAndUpdateVirtualScales:_zoomScale * scale]; // often UIScrollView continues bouncing even after the call to this method, so we have to use delays _zoomingDidEnd = YES; // signal scrollViewDidScroll to schedule _zoomDidEndBouncing call [self performSelector:@selector(_zoomDidEndBouncing) withObject:nil afterDelay:0.1]; } - (void)scrollViewDidScroll:(UIScrollView *)scrollView { if (_zoomWrapperView != nil && _zoomingDidEnd) { [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(_zoomDidEndBouncing) object:nil]; [self performSelector:@selector(_zoomDidEndBouncing) withObject:nil afterDelay:0.1]; } if ([_realDelegate respondsToSelector:@selector(scrollViewDidScroll:)]) [_realDelegate scrollViewDidScroll:self]; } - (BOOL)scrollViewShouldScrollToTop:(UIScrollView *)scrollView { if ([_realDelegate respondsToSelector:@selector(scrollViewShouldScrollToTop:)]) return [_realDelegate scrollViewShouldScrollToTop:self]; else return YES; } - (void)scrollViewDidScrollToTop:(UIScrollView *)scrollView { if ([_realDelegate respondsToSelector:@selector(scrollViewDidScrollToTop:)]) [_realDelegate scrollViewDidScrollToTop:self]; } @end @implementation ZoomScrollView (EventForwarding) - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { id delegate = self.delegate; if ([delegate respondsToSelector:@selector(zoomScrollView:touchesBegan:withEvent:)]) _ignoreSubsequentTouches = [delegate zoomScrollView:self touchesBegan:touches withEvent:event]; if (_ignoreSubsequentTouches) return; if ([touches count] == 1 && [[touches anyObject] tapCount] == 2) if ([self _handleDoubleTapWith:[touches anyObject]]) return; [super touchesBegan:touches withEvent:event]; } - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { id delegate = self.delegate; if ([delegate respondsToSelector:@selector(zoomScrollView:touchesMoved:withEvent:)]) if ([delegate zoomScrollView:self touchesMoved:touches withEvent:event]) { _ignoreSubsequentTouches = YES; [super touchesCancelled:touches withEvent:event]; } if (_ignoreSubsequentTouches) return; [super touchesMoved:touches withEvent:event]; } - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { id delegate = self.delegate; if ([delegate respondsToSelector:@selector(zoomScrollView:touchesEnded:withEvent:)]) if ([delegate zoomScrollView:self touchesEnded:touches withEvent:event]) { _ignoreSubsequentTouches = YES; [super touchesCancelled:touches withEvent:event]; } if (_ignoreSubsequentTouches) return; [super touchesEnded:touches withEvent:event]; } - (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event { id delegate = self.delegate; if ([delegate respondsToSelector:@selector(zoomScrollView:touchesCancelled:withEvent:)]) if ([delegate zoomScrollView:self touchesCancelled:touches withEvent:event]) _ignoreSubsequentTouches = YES; [super touchesCancelled:touches withEvent:event]; } @end A: Stop reinventing the wheel! See how apple does it! ScrollViewSuite -> Apple Documentation Page ScrollViewSuite Direct Link -> XcodeProject It's exactly what you're lookng for. Cheers! A: Darren, can you provide a link to said Apple example? Or the title so that I may find it? I see http://developer.apple.com/iphone/library/samplecode/Touches/index.html , but that doesn't cover the zooming. The problem I'm seeing after a programatic zoom is that a gesture-zoom snaps the zoom back to what it was before the programatic zoom occurred. It seems that UIScrollView keeps state internally about the zoom factor/level, but I don't have conclusive evidence. Thanks, -andrew EDIT: I just realized, you are working around the fact that you have little control over UIScrollView's internal zoom factor by resizing and changing the meaning of zoom-factor 1.0. A bit of a hack, but it seems like all Apple's left us with. Perhaps a custom class could encapsulate this trick...
{ "language": "en", "url": "https://stackoverflow.com/questions/172255", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "28" }
Q: Resetting all items in a TiddlyWiki/CheckboxPlugin checklist I've written up a weekly-review GTD checklist for myself in TiddlyWiki, using CheckboxPlugin. After I'm finished with it each week, I'd like to click one link to uncheck (reset) all of the items on it, so it's ready for the next use. I'm storing the check information as tags on a separate tiddler page. I should be able to just erase all the tags on that page and refresh the checklist page, but I haven't been able to work out how to do that yet. I generally work in C, C++, and Lisp, I'm just learning about Javascript. Can anyone offer some useful pointers? (And before anyone suggests it, I've looked at the ChecklistScript on the same site. It doesn't use the CheckboxPlugin stuff, and isn't compatible with it.) A: Try this (adapted from ChecklistScript's "resetall" code): <html><form style="display:inline"> <input type="button" value="clear all" onclick=" var tid='SomeTiddler'; var list='tag1 [[tag 2]] tag3 tag4'; var tags=list.readBracketedList(); store.suspendNotifications(); for (var t=0; t<tags.length; t++) store.setTiddlerTag(tid,false,tags[t]); store.resumeNotifications(); story.refreshTiddler(tid,null,true); "></form></html> A: It took a while, but I figured it out (thanks to ELS's answer for the inspiration): <script label="(Reset All)" title="Reset all items" key="X"> var tid='WeeklyReviewStepsChecklistItems'; store.getTiddler(tid).tags=[]; story.refreshTiddler(tid,null,true); story.refreshTiddler('Weekly Review Steps',null,true); </script> This only works because I'm storing the tags in a separate tiddler, and using the InlineJavascriptPlugin.
{ "language": "en", "url": "https://stackoverflow.com/questions/172258", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C++ #include and #import difference What is the difference between #include and #import in C++? A: Import in VC++: #import is for type libraries or .tlbs (COM stuff). The content of the type library is converted into C++ classes, mostly describing the COM interfaces for you automatically, and then it is included into your file. The #import directive was introduced by Microsoft as an extension to the C++ language. You can read about it at this MSDN article. The #import directive is also used with .NET / CLI stuff. Import in gcc: The import in gcc is different from the import in VC++. It is a simple way to include a header at most once only. (In VC++ and GCC you can do this via #pragma once as well) The #import directive was officially undeprecated by the gcc team in version 3.4 and works fine 99% of the time in all previous versions of gcc which support Include: #include is for mostly header files, but to prepend the content to your current file. #include is part of the C++ standard. You can read about it at this MSDN article. A: #import is a Microsoft-specific thing, apparently for COM or .NET stuff only. #include is a standard C/C++ preprocessor statement, used for including header (or occasionally other source code) files in your source code file. A: Should this post be updated? Now, since the C++20 standard is outta there, we can get into scope "modules" with the import statement. https://en.cppreference.com/w/cpp/language/modules In terms of compiling speed when multiple modules are called from different parts of the code, import statement seems to be quicker than the old #include preprocesor directive. A: import was also one of the keywords associated with n2073, Modules in C++, proposed to the language committee by Daveed Vandevoorde in September 2006. I'm not enough of a language geek to know if that proposal was definitively shelved or if it's awaiting an implementation (proof of concept) from the author or someone else... A: Please note that in gcc 4.1, #import is deprecated. If you use it, you will get warning: #import is a deprecated GCC extension A: #import is overall a solution to the usual #ifndef ... #define ... #include ... #endif work-around. #import includes a file only if it hasn't been included before. It might be worth noting that Apple's Objective-C also uses #import statements.
{ "language": "en", "url": "https://stackoverflow.com/questions/172262", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "109" }
Q: How can I control the name of generic WCF return types? I've got a WCF Web Service method whose prototype is: [OperationContract] Response<List<Customer>> GetCustomers(); When I add the service reference to a client, Visual Studio (2005) creates a type called "ResponseOfArrayOfCustomerrleXg3IC" that is a wrapper for "Response<List<Customer>>". Is there any way I can control the wrapper name? ResponseOfArrayOfCustomerrleXg3IC doesn't sound very appealing... A: Please try this: [OperationContract] [return: MessageParameter(Name="YOURNAME")] Response<List<Customer>> GetCustomers(); A: You can define your own name in the DataContract attribute like this: [DataContract(Name = "ResponseOf{0}")] public class Response<T> Note that in your example the {0} will be replaced and your proxy reference type will be ResponseOfArrayOfCustomer. More info here: WCF: Serialization and Generics A: Yes. The OperationContractAttribute takes a parameter called Name. You could specify it like this: [OperationContract(Name = "NameGoesHere")] Response<List<Customer>> GetCustomers();
{ "language": "en", "url": "https://stackoverflow.com/questions/172265", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: PL/SQL: How to execute an SP which preforms a DML and has a return value? I have a stored procedure with the following header: FUNCTION SaveShipment (p_user_id IN INTEGER, p_transaction_id IN INTEGER, p_vehicle_code IN VARCHAR2 DEFAULT NULL, p_seals IN VARCHAR2 DEFAULT NULL) RETURN INTEGER; And I am having trouble running it from TOAD's Editor. I cannot run it as part of a select from dual statement because it preforms DML, but if I try the following syntax which I saw recommended on some forum: var c integer; exec :c := orm_helper.orm_helper.SAVESHIPMENT (9999, 31896, NULL, ''); print c; I get: ORA-01008: not all variables bound Details: BEGIN :c := orm_helper.orm_helper.saveshipment (9999, 31896, null, ''); END; Error at line 2 ORA-01008: not all variables bound What's the proper syntax to run this sp manually? A: Are you calling the stored procedure from another SP? I think the syntax is (if I recall correctly): declare c integer; begin c:=storedProc(...parameters...); Hope this helps. A: you could probably SELECT orm_helper.orm_helper.SAVESHIPMENT (9999, 31896, NULL, '') FROM DUAL.
{ "language": "en", "url": "https://stackoverflow.com/questions/172278", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What is obj folder generated for? Possible Duplicate: What are the obj and bin folders (created by Visual Studio) used for? The default output path for any project is Visual studio is bin/Debug, but I have noticed that obj folder is also generated which again contains dll and pdb files. Can someone tell me why is this folder generated? A: "obj" folder is used to store temporary object files and other files used to create the final binary. Further reading here
{ "language": "en", "url": "https://stackoverflow.com/questions/172279", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "92" }
Q: What is the state of the art user interface for browsing complex version control system history? When using Mercurial I sometimes find that it is hard to understand the relationship between changesets when there are thousands of changesets, and sometimes ten or more active branches at any one time. Currently, I use hgview which is okay, and while it makes a reasonable attempt to represent the parent relationships it is still basically one dimensional. I imagine something making use of graph visualisation programs such as GraphViz might work nicely, or perhaps something more wacky. Currently I'm working on projects with around 30,000 revisions, and I expect that number to grow significantly; if 100 full time developers really grok distributed version control and start committing regularly and sharing their full development history then we could end up dealing with millions of revisions. A browser which doesn't have to load the entire history in to RAM every time you want to look at it therefore becomes necessary I'm interested in good history browsers for any version control systems as well, especially if there is a chance I can port them to Mercurial. A: the gitk(1) tool for git is what I use at work. Note that it takes a git rev-list constraint so you can limit what you see. You definitely want to begin doing such selective picking in the long run when the amount of commits go up. A: I use ClearCase VCS at work and its Version Tree browser could presumably suit you. But, alas, I don't know any separate ready-made tool for this.
{ "language": "en", "url": "https://stackoverflow.com/questions/172300", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: What's a good algorithm for editing a "schedule" most efficiently? This is for a small scheduling app. I need an algorithm to efficiently compare two "schedules", find differences, and update only the data rows which have been changed, as well as entries in another table having this table as a foreign key. This is a big question, so I'll say right away I'm looking for either general advice or specific solutions. EDIT: As suggested, I have significantly shortened the question. In one table, I associate resources with a span of time when they are used. I also have a second table (Table B) which uses the ID from Table A as a foreign key. The entry from Table A corresponding to Table B will have a span of time which subsumes the span of time from Table B. Not all entries in Table A will have an entry in Table B. I'm providing an interface for users to edit the resource schedule in Table A. They basically provide a new set of data for Table A that I need to treat as a diff from the version in the DB. If they completely remove an object from Table A that is pointed to by Table B, I want to remove the entry from Table B as well. So, given the following 3 sets: * *The original objects from Table A (from the DB) *The original objects from Table B (from the DB) *The edited set of objects from Table A (from the user, so no unique IDs) I need an algorithm that will: * *Leave rows in Table A and Table B untouched if no changes are needed for those objects. *Add rows to Table A as needed. *Remove rows from Table A and Table B as needed. *Modify rows in Table A and Table B as needed. Just sorting the objects into an arrangement where I can apply the appropriate database operations is more than adequate for a solution. Again, please answer as specifically or generally as you like, I'm looking for advice but if someone has a complete algorithm that would just make my day. :) EDIT: In response to lassvek, I am providing some additional detail: Table B's items are always contained entirely within Table A items, not merely overlapping. Importantly, Table B's items are quantized so they should fall either entirely within or entirely outside. If this doesn't happen, then I have a data integrity error that I'll have to handle separately. For example (to use a shorthand): Table A ID Resource Start End 01 Resource A 10/6 7:00AM 10/6 11:00AM 02 Resource A 10/6 1:00PM 10/6 3:00PM Table B ID Table_A_ID Start End 01 02 10/6 1:00PM 10/6 2:00PM So I want the following behaviours: * *If I remove ID 02 from table A, or shorten it to 2:00PM - 3:00PM, I should remove ID 01 from Table B. *If I extend Table A ID 01 to where it ends at 1:00PM, these two entries should be merged together into one row, and Table B ID 01 should now point to table A ID 01. *If I remove 8:00AM-10:00AM from Table A ID 01, that entry should be split into two entries: One for 7:00AM-8:00AM, and a new entry (ID 03) for 10:00AM-11:00AM. A: I have worked extensively with periods, but I'm afraid I don't understand entirely how table A and B work together, perhaps it's the word subsume that I don't understand. Can you give some concrete examples of what you want done? Do you mean that timespans recorded in table A contains entirely timespans in table B, like this? |---------------- A -------------------| |--- B ----| |--- B ---| or overlaps with? |---------------- A -------------------| |--- B ----| |--- B ---| or the opposite way, timespans in B contains/overlaps with A? Let's say it's the first one, where timespans in B are inside/the same as the linked timespan in table A. Does this mean that: * A removed A-timespan removes all the linked timespans from B * An added A-timespan, what about this? * A shortened A-timespan removes all the linked timespans from B that now falls outside A * A lenghtened A-timespan, will this include all matching B-timespans now inside? Here's an example: |-------------- A1 --------------| |-------- A2 --------------| |---- B1 ----| |----- B2 ---| |---- B3 ----| |-- B4 --| and then you lengthen A1 and shorten and move A2, so that: |-------------- A1 ---------------------------------| |--- A2 --| |---- B1 ----| |----- B2 ---| |---- B3 ----| |-- B4 --| this means that you want to modify the data like this: 1. Lengthen (update) A1 2. Shorten and move (update) A2 3. Re-link (update) B3 from A2 to A1 instead how about this modification, A1 is lengthened, but not enough to contain B3 entirely, and A2 is moved/shortened the same way: |-------------- A1 -----------------------------| |--- A2 --| |---- B1 ----| |----- B2 ---| |---- B3 ----| |-- B4 --| Since B3 is now not entirely within either A1 or A2, remove it? I need some concrete examples of what you want done. Edit More questions Ok, what about: |------------------ A -----------------------| |------- B1 -------| |------- B2 ------| |---| <-- I want to remove this from A What about this? Either: |------------------ A1 ----| |---- A2 -----| |------- B1 -------| |B3| |--- B2 ---| or: |------------------ A1 ----| |---- A2 -----| |------- B1 -------| To summarize how I see it, with questions, so far: * *You want to be able to do the following operations on A's * *Shorten *Lengthen *Combine when they are adjacent, combining two or more into one *Punch holes in them by removing a period, and thus splitting it *B's that are still contained within an A after the above update, relink if necessary *B's that were contained, but are now entirely outside, delete them *B's that were contained, but are now partially outside, Edit: Delete these, ref data integrity *For all the above operations, do the least minimum work necessary to bring the data in line with the operations (instead of just removing everything and inserting anew) I'll work on an implementation in C# that might work when I get home from work, I'll come back with more later tonight. Edit Here's a stab at an algorithm. * *Optimize the new list first (ie. combine adjacent periods, etc.) *"merge" this list with the master periods in the database in the following way: * *keep track of where in both lists (ie. new and existing) you are *if the current new period is entirely before the current existing period, add it, then move to the next new period *if the current new period is entirely after the current existing period, remove the existing period and all its child periods, then move to the next existing period *if the two overlap, adjust the current existing period to be equal to the new period, in the following way, then move on to the next new and existing period * *if new period starts before existing period, simply move the start *if new period starts after existing period, check if any child periods are in the difference-period, and remember them, then move the start *do the same with the other end *with any periods you "remembered", see if they needs to be relinked or deleted You should create a massive set of unit tests and make sure you cover all combinations of modifications. A: I suggest you decouple your questions into two separate ones: The first should be something like: "How do I reason about resource scheduling, when representing a schedule atom as a resource with start time and end time?" Here, ADept's suggestion to use interval algebra seems fitting. Please see The Wikipedia entry 'Interval Graph' and The SUNY algorithm repository entry on scheduling. The second question is a database question: "Given an algorithm which schedules intervals and indicate whether two intervals overlap or one is contained in another, how do I use this information to manage a database in the given schema?" I believe that once the scheduling algorithm is in place, the database question will be much easier to solve. HTH, Yuval A: You post is almost in the "too long; didnt read" category - shortening it will probably give you more feedback. Anyway, on topic: you can try lookin into a thing called "Interval Algebra" A: As I understand you, your users can only directly affect table A. Assuming you are programming in C#, you could use a simple ADO.Net DataSet to manage modifications to table A. The TableAdapter knows to leave untouched rows alone and to handle new, modified and deleted rows appropriately. In addition you should define a cascading delete in order to automatically remove corresponding objects in table B. The only case that is not handled this way is if a timespan in table A is shortened s.t. it does not subsume the corresponding record in Table B anymore. You could simply check for that case in an update stored procedure or alternatively define an update-trigger on table A. A: It seems to me like any algorithm for this will be involve a pass through NewA, matching ResourceID, StartTime, and EndTime, and keeping track of which elements from OldA get hit. Then you have two sets of non-matching data, UnmatchedNewA and UnmatchedOldA. The simplest way I can think of to proceed is to basically start over with these: Write all of UnmatchedNewA to the DB, transfer elements of B from UnmatchedOldA into New A keys (just generated) where possible, deleting when not. Then wipe out all of UnmatchedOldA. If there are a lot of changes, this is certainly not an efficient way to proceed. In cases where the size of the data is not overwhelming, though, I prefer simplicity to clever optimization. It's impossible to know whether this final suggestion makes any sense without more background, but on the off chance that you didn't think of it this way: Instead of passing the entire A collection back and forth, could you use event listeners or something similar to update the data model only where changes ARE needed? This way, the objects being altered would be able to determine which DB operations are required on the fly.
{ "language": "en", "url": "https://stackoverflow.com/questions/172302", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is there a regular expression to detect a valid regular expression? Is it possible to detect a valid regular expression with another regular expression? If so please give example code below. A: The following example by Paul McGuire, originally from the pyparsing wiki, but now available only through the Wayback Machine, gives a grammar for parsing some regexes, for the purposes of returning the set of matching strings. As such, it rejects those re's that include unbounded repetition terms, like '+' and '*'. But it should give you an idea about how to structure a parser that would process re's. # # invRegex.py # # Copyright 2008, Paul McGuire # # pyparsing script to expand a regular expression into all possible matching strings # Supports: # - {n} and {m,n} repetition, but not unbounded + or * repetition # - ? optional elements # - [] character ranges # - () grouping # - | alternation # __all__ = ["count","invert"] from pyparsing import (Literal, oneOf, printables, ParserElement, Combine, SkipTo, operatorPrecedence, ParseFatalException, Word, nums, opAssoc, Suppress, ParseResults, srange) class CharacterRangeEmitter(object): def __init__(self,chars): # remove duplicate chars in character range, but preserve original order seen = set() self.charset = "".join( seen.add(c) or c for c in chars if c not in seen ) def __str__(self): return '['+self.charset+']' def __repr__(self): return '['+self.charset+']' def makeGenerator(self): def genChars(): for s in self.charset: yield s return genChars class OptionalEmitter(object): def __init__(self,expr): self.expr = expr def makeGenerator(self): def optionalGen(): yield "" for s in self.expr.makeGenerator()(): yield s return optionalGen class DotEmitter(object): def makeGenerator(self): def dotGen(): for c in printables: yield c return dotGen class GroupEmitter(object): def __init__(self,exprs): self.exprs = ParseResults(exprs) def makeGenerator(self): def groupGen(): def recurseList(elist): if len(elist)==1: for s in elist[0].makeGenerator()(): yield s else: for s in elist[0].makeGenerator()(): for s2 in recurseList(elist[1:]): yield s + s2 if self.exprs: for s in recurseList(self.exprs): yield s return groupGen class AlternativeEmitter(object): def __init__(self,exprs): self.exprs = exprs def makeGenerator(self): def altGen(): for e in self.exprs: for s in e.makeGenerator()(): yield s return altGen class LiteralEmitter(object): def __init__(self,lit): self.lit = lit def __str__(self): return "Lit:"+self.lit def __repr__(self): return "Lit:"+self.lit def makeGenerator(self): def litGen(): yield self.lit return litGen def handleRange(toks): return CharacterRangeEmitter(srange(toks[0])) def handleRepetition(toks): toks=toks[0] if toks[1] in "*+": raise ParseFatalException("",0,"unbounded repetition operators not supported") if toks[1] == "?": return OptionalEmitter(toks[0]) if "count" in toks: return GroupEmitter([toks[0]] * int(toks.count)) if "minCount" in toks: mincount = int(toks.minCount) maxcount = int(toks.maxCount) optcount = maxcount - mincount if optcount: opt = OptionalEmitter(toks[0]) for i in range(1,optcount): opt = OptionalEmitter(GroupEmitter([toks[0],opt])) return GroupEmitter([toks[0]] * mincount + [opt]) else: return [toks[0]] * mincount def handleLiteral(toks): lit = "" for t in toks: if t[0] == "\\": if t[1] == "t": lit += '\t' else: lit += t[1] else: lit += t return LiteralEmitter(lit) def handleMacro(toks): macroChar = toks[0][1] if macroChar == "d": return CharacterRangeEmitter("0123456789") elif macroChar == "w": return CharacterRangeEmitter(srange("[A-Za-z0-9_]")) elif macroChar == "s": return LiteralEmitter(" ") else: raise ParseFatalException("",0,"unsupported macro character (" + macroChar + ")") def handleSequence(toks): return GroupEmitter(toks[0]) def handleDot(): return CharacterRangeEmitter(printables) def handleAlternative(toks): return AlternativeEmitter(toks[0]) _parser = None def parser(): global _parser if _parser is None: ParserElement.setDefaultWhitespaceChars("") lbrack,rbrack,lbrace,rbrace,lparen,rparen = map(Literal,"[]{}()") reMacro = Combine("\\" + oneOf(list("dws"))) escapedChar = ~reMacro + Combine("\\" + oneOf(list(printables))) reLiteralChar = "".join(c for c in printables if c not in r"\[]{}().*?+|") + " \t" reRange = Combine(lbrack + SkipTo(rbrack,ignore=escapedChar) + rbrack) reLiteral = ( escapedChar | oneOf(list(reLiteralChar)) ) reDot = Literal(".") repetition = ( ( lbrace + Word(nums).setResultsName("count") + rbrace ) | ( lbrace + Word(nums).setResultsName("minCount")+","+ Word(nums).setResultsName("maxCount") + rbrace ) | oneOf(list("*+?")) ) reRange.setParseAction(handleRange) reLiteral.setParseAction(handleLiteral) reMacro.setParseAction(handleMacro) reDot.setParseAction(handleDot) reTerm = ( reLiteral | reRange | reMacro | reDot ) reExpr = operatorPrecedence( reTerm, [ (repetition, 1, opAssoc.LEFT, handleRepetition), (None, 2, opAssoc.LEFT, handleSequence), (Suppress('|'), 2, opAssoc.LEFT, handleAlternative), ] ) _parser = reExpr return _parser def count(gen): """Simple function to count the number of elements returned by a generator.""" i = 0 for s in gen: i += 1 return i def invert(regex): """Call this routine as a generator to return all the strings that match the input regular expression. for s in invert("[A-Z]{3}\d{3}"): print s """ invReGenerator = GroupEmitter(parser().parseString(regex)).makeGenerator() return invReGenerator() def main(): tests = r""" [A-EA] [A-D]* [A-D]{3} X[A-C]{3}Y X[A-C]{3}\( X\d foobar\d\d foobar{2} foobar{2,9} fooba[rz]{2} (foobar){2} ([01]\d)|(2[0-5]) ([01]\d\d)|(2[0-4]\d)|(25[0-5]) [A-C]{1,2} [A-C]{0,3} [A-C]\s[A-C]\s[A-C] [A-C]\s?[A-C][A-C] [A-C]\s([A-C][A-C]) [A-C]\s([A-C][A-C])? [A-C]{2}\d{2} @|TH[12] @(@|TH[12])? @(@|TH[12]|AL[12]|SP[123]|TB(1[0-9]?|20?|[3-9]))? @(@|TH[12]|AL[12]|SP[123]|TB(1[0-9]?|20?|[3-9])|OH(1[0-9]?|2[0-9]?|30?|[4-9]))? (([ECMP]|HA|AK)[SD]|HS)T [A-CV]{2} A[cglmrstu]|B[aehikr]?|C[adeflmorsu]?|D[bsy]|E[rsu]|F[emr]?|G[ade]|H[efgos]?|I[nr]?|Kr?|L[airu]|M[dgnot]|N[abdeiop]?|Os?|P[abdmortu]?|R[abefghnu]|S[bcegimnr]?|T[abcehilm]|Uu[bhopqst]|U|V|W|Xe|Yb?|Z[nr] (a|b)|(x|y) (a|b) (x|y) """.split('\n') for t in tests: t = t.strip() if not t: continue print '-'*50 print t try: print count(invert(t)) for s in invert(t): print s except ParseFatalException,pfe: print pfe.msg print continue print if __name__ == "__main__": main() A: Good question. True regular languages can not decide arbitrarily deeply nested well-formed parenthesis. If your alphabet contains '(' and ')' the goal is to decide if a string of these has well-formed matching parenthesis. Since this is a necessary requirement for regular expressions the answer is no. However, if you loosen the requirement and add recursion you can probably do it. The reason is that the recursion can act as a stack letting you "count" the current nesting depth by pushing onto this stack. Russ Cox wrote "Regular Expression Matching Can Be Simple And Fast" which is a wonderful treatise on regex engine implementation. A: In Javascript: SyntaxError is thrown when an invalid regex is passed to evaluate. // VALID ONE > /yes[^]*day/ Out: /yes[^]*day/ // INVALID ONE > /yes[^*day/ Out: VM227:1 Uncaught SyntaxError: Invalid regular expression: missing / Here's the function to check if the regex string is valid: Step 1: Regex Parser var RegexParser = function(input) { // Parse input var m = input.match(/(\/?)(.+)\1([a-z]*)/i); // Invalid flags if (m[3] && !/^(?!.*?(.).*?\1)[gmixXsuUAJ]+$/.test(m[3])) { return RegExp(input); } // Create the regular expression return new RegExp(m[2], m[3]); }; Step 2: Use parser var RegexString = "/yes.*day/" var isRegexValid = input => { try { const regex = RegexParser(input); } catch(error) { if(error.name === "SyntaxError") { return false; } else { throw error; } } return true; } A: Unlikely. Evaluate it in a try..catch or whatever your language provides. A: No, if you are strictly speaking about regular expressions and not including some regular expression implementations that are actually context free grammars. There is one limitation of regular expressions which makes it impossible to write a regex that matches all and only regexes. You cannot match implementations such as braces which are paired. Regexes use many such constructs, let's take [] as an example. Whenever there is an [ there must be a matching ], which is simple enough for a regex "\[.*\]". What makes it impossible for regexes is that they can be nested. How can you write a regex that matches nested brackets? The answer is you can't without an infinitely long regex. You can match any number of nested parenthesis through brute force but you can't ever match an arbitrarily long set of nested brackets. This capability is often referred to as counting, because you're counting the depth of the nesting. A regex by definition does not have the capability to count. I ended up writing "Regular Expression Limitations" about this. A: No, if you use standard regular expressions. The reason is that you cannot satisfy the pumping lemma for regular languages. The pumping lemma states that a string belonging to language "L" is regular if there exists a number "N" such that, after dividing the string into three substrings x, y, z, such that |x|>=1 && |xy|<=N, you can repeat y as many times as you want and the entire string will still belong to L. A consequence of the pumping lemma is that you cannot have regular strings in the form a^Nb^Mc^N, that is, two substrings having the same length separated by another string. In any way you split such strings in x, y and z, you cannot "pump" y without obtaining a string with a different number of "a" and "c", thus leaving the original language. That's the case, for example, with parentheses in regular expressions. A: Though it is perfectly possible to use a recursive regex as MizardX has posted, for this kind of things it is much more useful a parser. Regexes were originally intended to be used with regular languages, being recursive or having balancing groups is just a patch. The language that defines valid regexes is actually a context free grammar, and you should use an appropriate parser for handling it. Here is an example for a university project for parsing simple regexes (without most constructs). It uses JavaCC. And yes, comments are in Spanish, though method names are pretty self-explanatory. SKIP : { " " | "\r" | "\t" | "\n" } TOKEN : { < DIGITO: ["0" - "9"] > | < MAYUSCULA: ["A" - "Z"] > | < MINUSCULA: ["a" - "z"] > | < LAMBDA: "LAMBDA" > | < VACIO: "VACIO" > } IRegularExpression Expression() : { IRegularExpression r; } { r=Alternation() { return r; } } // Matchea disyunciones: ER | ER IRegularExpression Alternation() : { IRegularExpression r1 = null, r2 = null; } { r1=Concatenation() ( "|" r2=Alternation() )? { if (r2 == null) { return r1; } else { return createAlternation(r1,r2); } } } // Matchea concatenaciones: ER.ER IRegularExpression Concatenation() : { IRegularExpression r1 = null, r2 = null; } { r1=Repetition() ( "." r2=Repetition() { r1 = createConcatenation(r1,r2); } )* { return r1; } } // Matchea repeticiones: ER* IRegularExpression Repetition() : { IRegularExpression r; } { r=Atom() ( "*" { r = createRepetition(r); } )* { return r; } } // Matchea regex atomicas: (ER), Terminal, Vacio, Lambda IRegularExpression Atom() : { String t; IRegularExpression r; } { ( "(" r=Expression() ")" {return r;}) | t=Terminal() { return createTerminal(t); } | <LAMBDA> { return createLambda(); } | <VACIO> { return createEmpty(); } } // Matchea un terminal (digito o minuscula) y devuelve su valor String Terminal() : { Token t; } { ( t=<DIGITO> | t=<MINUSCULA> ) { return t.image; } } A: You can submit the regex to preg_match which will return false if the regex is not valid. Don't forget to use the @ to suppress error messages: @preg_match($regexToTest, ''); * *Will return 1 if the regex is //. *Will return 0 if the regex is okay. *Will return false otherwise. A: / ^ # start of string ( # first group start (?: (?:[^?+*{}()[\]\\|]+ # literals and ^, $ | \\. # escaped characters | \[ (?: \^?\\. | \^[^\\] | [^\\^] ) # character classes (?: [^\]\\]+ | \\. )* \] | \( (?:\?[:=!]|\?<[=!]|\?>)? (?1)?? \) # parenthesis, with recursive content | \(\? (?:R|[+-]?\d+) \) # recursive matching ) (?: (?:[?+*]|\{\d+(?:,\d*)?\}) [?+]? )? # quantifiers | \| # alternative )* # repeat content ) # end first group $ # end of string / This is a recursive regex, and is not supported by many regex engines. PCRE based ones should support it. Without whitespace and comments: /^((?:(?:[^?+*{}()[\]\\|]+|\\.|\[(?:\^?\\.|\^[^\\]|[^\\^])(?:[^\]\\]+|\\.)*\]|\((?:\?[:=!]|\?<[=!]|\?>)?(?1)??\)|\(\?(?:R|[+-]?\d+)\))(?:(?:[?+*]|\{\d+(?:,\d*)?\})[?+]?)?|\|)*)$/ .NET does not support recursion directly. (The (?1) and (?R) constructs.) The recursion would have to be converted to counting balanced groups: ^ # start of string (?: (?: [^?+*{}()[\]\\|]+ # literals and ^, $ | \\. # escaped characters | \[ (?: \^?\\. | \^[^\\] | [^\\^] ) # character classes (?: [^\]\\]+ | \\. )* \] | \( (?:\?[:=!] | \?<[=!] | \?> | \?<[^\W\d]\w*> | \?'[^\W\d]\w*' )? # opening of group (?<N>) # increment counter | \) # closing of group (?<-N>) # decrement counter ) (?: (?:[?+*]|\{\d+(?:,\d*)?\}) [?+]? )? # quantifiers | \| # alternative )* # repeat content $ # end of string (?(N)(?!)) # fail if counter is non-zero. Compacted: ^(?:(?:[^?+*{}()[\]\\|]+|\\.|\[(?:\^?\\.|\^[^\\]|[^\\^])(?:[^\]\\]+|\\.)*\]|\((?:\?[:=!]|\?<[=!]|\?>|\?<[^\W\d]\w*>|\?'[^\W\d]\w*')?(?<N>)|\)(?<-N>))(?:(?:[?+*]|\{\d+(?:,\d*)?\})[?+]?)?|\|)*$(?(N)(?!)) From the comments: Will this validate substitutions and translations? It will validate just the regex part of substitutions and translations. s/<this part>/.../ It is not theoretically possible to match all valid regex grammars with a regex. It is possible if the regex engine supports recursion, such as PCRE, but that can't really be called regular expressions any more. Indeed, a "recursive regular expression" is not a regular expression. But this an often-accepted extension to regex engines... Ironically, this extended regex doesn't match extended regexes. "In theory, theory and practice are the same. In practice, they're not." Almost everyone who knows regular expressions knows that regular expressions does not support recursion. But PCRE and most other implementations support much more than basic regular expressions. using this with shell script in the grep command , it shows me some error.. grep: Invalid content of {} . I am making a script that could grep a code base to find all the files that contain regular expressions This pattern exploits an extension called recursive regular expressions. This is not supported by the POSIX flavor of regex. You could try with the -P switch, to enable the PCRE regex flavor. Regex itself "is not a regular language and hence cannot be parsed by regular expression..." This is true for classical regular expressions. Some modern implementations allow recursion, which makes it into a Context Free language, although it is somewhat verbose for this task. I see where you're matching []()/\. and other special regex characters. Where are you allowing non-special characters? It seems like this will match ^(?:[\.]+)$, but not ^abcdefg$. That's a valid regex. [^?+*{}()[\]\\|] will match any single character, not part of any of the other constructs. This includes both literal (a - z), and certain special characters (^, $, .). A: With this version you can check a string for regex with php - i took the example from above and modified a bit: $re = '/((?:(?:[^?+*{}()[\]\\\\|]+|\\\\.|\[(?:\^?\\\\.|\^[^\\\\]|[^\\\\^])(?:[^\]\\\\]+|\\\\.)*\]|\((?:\?[:=!]|\?<[=!]|\?>)??\)|\(\?(?:R|[+-]?\d+)\))(?:(?:[?+*]|\{\d*(?:,\d*)?\})[?+]?)?|\|)*)/'; $str = '[0-9]{1,}[a-z]'; preg_match($re, $str, $matches, PREG_OFFSET_CAPTURE, 0); $length = strlen($str); $length2 = strlen($matches[0][0]); if($length == $length2) { echo "is regex"; } else { echo "is no regex"; }
{ "language": "en", "url": "https://stackoverflow.com/questions/172303", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1139" }
Q: How are you planning on handling the migration to Python 3? I'm sure this is a subject that's on most python developers' minds considering that Python 3 is coming out soon. Some questions to get us going in the right direction: * *Will you have a python 2 and python 3 version to be maintained concurrently or will you simply have a python 3 version once it's finished? * *Have you already started or plan on starting soon? Or do you plan on waiting until the final version comes out to get into full swing? A: Here's the general plan for Twisted. I was originally going to blog this, but then I thought: why blog about it when I could get points for it? * *Wait until somebody cares. Right now, nobody has Python 3. We're not going to spend a bunch of effort until at least one actual user has come forth and said "I need Python 3.0 support", and has a good reason for it aside from the fact that 3.0 looks shiny. *Wait until our dependencies have migrated. A large system like Twisted has a number of dependencies. For starters, ours include: * *Zope Interface *PyCrypto *PyOpenSSL *pywin32 *PyGTK (though this dependency is sadly very light right now, by the time migration rolls around, I hope Twisted will have more GUI tools) *pyasn1 *PyPAM *gmpy Some of these projects have their own array of dependencies so we'll have to wait for those as well. *Wait until somebody cares enough to help. There are, charitably, 5 people who work on Twisted - and I say "charitably" because that's counting me, and I haven't committed in months. We have over 1000 open tickets right now, and it would be nice to actually fix some of those — fix bugs, add features, and generally make Twisted a better product in its own right — before spending time on getting it ported over to a substantially new version of the language. This potentially includes sponsors caring enough to pay for us to do it, but I hope that there will be an influx of volunteers who care about 3.0 support and want to help move the community forward. *Follow Guido's advice. This means we will not change our API incompatibly, and we will follow the transitional development guidelines that Guido posted last year. That starts with having unit tests, and running the 2to3 conversion tool over the Twisted codebase. *Report bugs against, and file patches for, the 2to3 tool. When we get to the point where we're actually using it, I anticipate that there will be a lot of problems with running 2to3 in the future. Running it over Twisted right now takes an extremely long time and (last I checked, which was quite a while ago) can't parse a few of the files in the Twisted repository, so the resulting output won't import. I think there will have to be a fair amount of success stories from small projects and a lot of hammering on the tool before it will actually work for us. However, the Python development team has been very helpful in responding to our bug reports, and early responses to these problems have been encouraging, so I expect that all of these issues will be fixed in time. *Maintain 2.x compatibility for several years. Right now, Twisted supports python 2.3 to 2.5. Currently, we're working on 2.6 support (which we'll obviously have to finish before 3.0!). Our plan is to we revise our supported versions of Python based on the long-term supported versions of Ubuntu - release 8.04, which includes Python 2.5, will be supported until 2013. According to Guido's advice we will need to drop support for 2.5 in order to support 3.0, but I am hoping we can find a way around that (we are pretty creative with version-compatibility hacks). So, we are planning to support Python 2.5 until at least 2013. In two years, Ubuntu will release another long-term supported version of Ubuntu: if they still exist, and stay on schedule, that will be 10.04. Personally I am guessing that this will ship with Python 2.x, perhaps python 2.8, as /usr/bin/python, because there is a huge amount of Python software packaged with the distribution and it will take a long time to update it all. So, five years from then, in 2015, we can start looking at dropping 2.x support. During this period, we will continue to follow Guido's advice about migration: running 2to3 over our 2.x codebase, and modifying the 2.x codebase to keep its tests passing in both versions. The upshot of this is that Python 3.x will not be a source language for Twisted until well after my 35th birthday — it will be a target runtime (and a set of guidelines and restrictions) for my python 2.x code. I expect to be writing programs in Python 2.x for the next ten years or so. So, that's the plan. I'm hoping that it ends up looking laughably conservative in a year or so; that the 3.x transition is easy as pie, and everyone rapidly upgrades. Other things could happen, too: the 2.x and 3.x branches could converge, someone might end up writing a 3to2, or another runtime (PyPy comes to mind) might allow for running 2.x and 3.x code in the same process directly, making our conversion process easier. For the time being, however, we're assuming that, for many years, we will have people with large codebases they're maintaining (or people writing new code who want to use other libraries which have not yet been migrated) who still want new features and bug fixes in Twisted. Pretty soon I expect we will also have bleeding-edge users that want to use Twisted on python 3. I'd like to provide all of those people with a positive experience for as long as possible. A: The Django project uses the library six to maintain a codebase that works simultaneously on Python 2 and Python 3 (blog post). six does this by providing a compatibility layer that intelligently redirects imports and functions to their respective locations (as well as unifying other incompatible changes). Obvious advantages: * *No need for separate branches for Python 2 and Python 3 *No conversion tools, such as 2to3. A: The main idea of 2.6 is to provide a migration path to 3.0. So you can use from __future__ import X slowly migrating one feature at a time until you get all of them nailed down and can move to 3.0. Many of the 3.0 features will flow into 2.6 as well, so you can make the language gap smaller gradually rather than having to migrate everything in one go. At work, we plan to upgrade from 2.5 to 2.6 first. Then we begin enabling 3.0 features slowly one module at a time. At some point a whole subpart of the system will probably be ready for 3.x. The only problem are libraries. If a library is never migrated, we are stuck with the old library. But I am pretty confident that we'll get a fine alternative in due time for that part. A: Speaking as a library author: I'm waiting for the final version to be released. My belief, like that of most of the Python community, is that 2.x will continue to be the dominant version for a period of weeks or months. That's plenty of time to release a nice, polished 3.x release. I'll be maintaining separate 2.x and 3.x branches. 2.x will be backwards compatible to 2.4, so I can't use a lot of the fancy syntax or new features in 2.6 / 3.0. In contrast, the 3.x branch will use every one of those features that results in a nicer experience for the user. The test suite will be modified so that 2to3 will work upon it, and I'll maintain the same tests for both branches. A: Support both I wanted to make an attempt at converting the BeautifulSoup library to 3x for a project I'm working on but I can see how it would be a pain to maintain two different branches of the code. The current model to handle this include: * *make a change to the 2x branch *run 2to3 *pray that it does the conversion properly the first time *run the code *run unit tests to verify that everything works *copy the output to the 3x branch This model works but IMHO it sucks. For every change/release you have to go through these steps ::sigh::. Plus, it discourages developers from extending the 3x branch with new features that can only be supported in py3k because you're still essentially targeting all the code to 2x. The solution... use a preprocessor Since I couldn't find a decent c-style preprocessor with #define and #ifdef directives for python I wrote one. It's called pypreprocessor and can be found in the PYPI Essentially, what you do is: * *import pypreprocessor *detect which version of python the script is running in *set a 'define' in the preprocessor for the version (ex 'python2' or 'python3') *sprinkle '#ifdef python2' and '#ifdef python3' directives where the code is version specific *run the code That's it. Now it'll work in both 2x and 3x. If you are worried about added performance hit of running a preprocessor there's also a mode that will strip out all of the metadata and output the post-processed source to a file. Best of all... you only have to do the 2to3 conversion once. Here's the a working example: #!/usr/bin/env python # py2and3.py import sys from pypreprocessor import pypreprocessor #exclude if sys.version[:3].split('.')[0] == '2': pypreprocessor.defines.append('python2') if sys.version[:3].split('.')[0] == '3': pypreprocessor.defines.append('python3') pypreprocessor.parse() #endexclude #ifdef python2 print('You are using Python 2x') #ifdef python3 print('You are using python 3x') #else print('Python version not supported') #endif These are the results in the terminal: python py2and3.py >>>You are using Python 2x python3 py2and3.py >>>You are using python 3x If you want to output to a file and make clean version-specific source file with no extra meta-data, add these two lines somewhere before the pypreprocessor.parse() statement: pypreprocessor.output = outputFileName.py pypreprocessor.removeMeta = True Then: python py2and3.py Will create a file called outputFileName.py that is python 2x specific with no extra metadata. python3 py2and3.py Will create a file called outputFileName.py that is python 3x specific with no extra metadata. For documentation and more examples see check out pypreprocessor on GoogleCode. I sincerely hope this helps. I love writing code in python and I hope to see support progress into the 3x realm asap. I hate to see the language not progress. Especially, since the 3x version resolves a lot of the featured WTFs and makes the syntax look a little more friendly to users migrating from other languages. The documentation at this point is complete but not extensive. I'll try to get the wiki up with some more extensive information soon. Update: Although I designed pypreprocessor specifically to solve this issue, it doesn't work because the lexer does syntax checking on all of the code before any code is executed. If python had real C preprocessor directive support it would allow developers to write both python2x and python3k code alongside each other in the same file but due to the bad reputation of the C preprocessor (abuse of macro replacement to change language keywords) I don't see legitimate C preprocessor support being added to python any time soon. A: The Zope Toolkit has been in a slow progress to Python 3 support. Slow mainly because many of these libraries are very complex. For most libraries I use 2to3. Some libraries make do without it because they are simple or have most of the code in a C-extension. zc.buildout, which is a related package, will run the same code without 2to3 for Python 2 and 3 support. We port the ZTK to Python 3 because many other libraries and frameworks depend on it, such as Twisted and the Pyramid framework. A: Some of my more complex 2.x code is going to stay at 2.5 or 2.6. I am moving onto 3.0 for all new development once some of the 3rd party libraries I use often have been updated for 3.
{ "language": "en", "url": "https://stackoverflow.com/questions/172306", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "52" }
Q: Solaris timezone in C (missing %z on strftime) I have an application that writes to another application and needs to provide the date + timezone of the system. I have been using strftime with the %z argument to get the timezone, and it has been working very well on Linux. However, last week we decided to merge it to solaris just to find out that %z is not present. Someone suggested to use %Z, which will give the timezone name, but I need the %z which gives the timezone with the offset format, like +0100 or -0300. Anyone has ideas? A: %z is not POSIX. You will have to calculate the offset yourself by finding the difference between localtime and gmtime. For a Perl example, see here.
{ "language": "en", "url": "https://stackoverflow.com/questions/172318", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Same class, different namespaces, a way to simplify? I'm working with a webservice that offers almost duplicated code across two namesspaces. Lets say for example PigFeet and HorseFeet, both namespaces contain a Feet class and other code that works with the Feet class requires it to be part of that same namespace. Right now In my code I'm forced to do something like this: if( _animalType == AnimalType.Pig ) { //namespace is pigfeet PigFeet.Feet feet = new Feet(); feet.WashFeet(); } if( _animalType == AnimalType.Horse ) { //namespace is horsefeet HorseFeet.Feet feet = new Feet(); feet.WashFeet(); } This is leaving me with lots of duplicated code. Is there a way to choose a namespace more dynamically? A: In your namespace imports you can assign an alias to a specific namespace or member. using PigFeet = PigFeet.Feet; using HorseFeet = HorseFeet.Feet; //now your sample code should look something like if( _animalType == AnimalType.Pig ) { //namespace is pigfeet PigFeet feet = new PigFeet(); feet.WashFeet(); } if( _animalType == AnimalType.Horse ) { //namespace is horsefeet HorseFeet feet = new HorseFeet(); feet.WashFeet(); } A: The namespace isn't the problem - it's simply that the 2 classes aren't related, so there's no inheritance chain that you can use for polymorphism. You'll need to look at something like duck typing, or an adapter pattern, or building your own proxy classes to get yourself to a common interface. For small numbers of implementations, I've gotten away with just building a single adapter class that delegates to whatever non-null instance it has: interface IFeet { void WashFeet(); } class FeetAdapter : IFeet { private PigFeet.Feet _pigFeet; private HorseFeet.Feet _horseFeet; private FeetAdapter(PigFeet.Feet pigFeet) { _pigFeet = pigFeet; } private FeetAdapter(HorseFeet.Feet horseFeet) { _horseFeet = horseFeet; } public void WashFeet() { if (_pigFeet != null) { _pigFeet.WashFeet(); } else { _horseFeet.WashFeet(); } } public static FeetAdapter Create(AnimalType animalType) { switch (animalType) { case AnimalType.Pig: return new FeetAdapter(new PigFeet.Feet()); case AnimalType.Horse: return new FeetAdapter(new HorseFeet.Feet()); } } } For larger cases, you'd be better off with a separate PigFeetAdapter and HorseFeetAdapter that both implement IFeet, along with a FeetAdapterFactory to create them - but the concept is the same as I show above. A: Namespaces are just a way to organize your types. In your case you're having 2 or more different classes that have methods with the same signature but don't have a common interface. In case you cannot change the code of the classes, the only way to avoid duplication here is to use reflection while loosing compile-time type-safety. A: Here's me making things worse before making them better. You can encapsulate all the AnimalType decision logic in a single class. Between the two types (PigsFeet and HorseFeet), there are some similiar methods... Since WashFeet has a common signature (void with no params), System.Action can be used to reference that method. Other methods with common signatures (and parameters) may require System.Func(T). Other methods without common signatures may need to be coerced into a common signature. Here's the client code: AnimalFeetFacade myFacade = new AnimalFeetFacade(_animalType); myFacade.WashFeet(); Here's the encapsulation class. public class AnimalFeetFacade { public AnimalFeetFacade(AnimalType theType) { if (theType == AnimalType.Pig) { _washFeet = WashPigFeet; //TODO reference more PigFeet methods here } else if (theType == AnimalType.Horse) { _washFeet = WashHorseFeet; //TODO reference more HorseFeet methods here } else { throw new NotImplementedException("AnimalFeetFacade only works with PigFeet and HorseFeet"); } } protected Action _washFeet; public void WashFeet() { _washFeet.Invoke(); } protected void WashPigFeet() { PigFeet.Feet = new PigFeet.Feet() feet.WashFeet() } protected void WashHorseFeet() { HorseFeet.Feet = new HorseFeet.Feet() feet.WashFeet() } }
{ "language": "en", "url": "https://stackoverflow.com/questions/172320", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How do you do ALSA in Mono? Does anyone know how to access ALSA (low-level audio API) in Linux using Mono? NOTE: I'm hoping to access ALSA using PInvoke. A: I believe there are not any bindings for Mono. You could look at the Python ALSA bindings and the Mono D-BUS bindings and try to build your own. However, it would probably be better and easier for you to just use GStreamer. The Mono GStreamer bindings are mature and work well.
{ "language": "en", "url": "https://stackoverflow.com/questions/172321", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Blackbox type data logging In a Linux embedded application I'm developing, there is the need to record some events that happen from time to time. These records are saved on a MTD flash device and once written there is no need to change them or do efficient searches, but read access is required to show the data back to the user. A big problem is that power can go away at any time, without a proper shutdown sequence. The frequency these events occur can be very slow (days/weeks), but several of them will occur at once. The data to be saved for each event is strongly typed: date, time, a couple of short text strings and several integers. Currently I inherited a solution based on jffs2 and SQLite that is far from optimal because the DB file sometimes get corrupted. When this happens the whole file gets unreadable and there is no way to understand if it was caused by a bug in jffs2, or in SQLite or if the flash sector was bad, or if the power was cut at the wrong time. Is there a library or a combination of filesystem/library that can better help me solve this kind of problem ? Or should I just use a text file with a CSV-like format ? A: I'm not expert on embeded systems, but I would think that a CSV would probably be best. It basically can't be corrupted, or if it does, then you can easily see the error and fix it manually (new line or just removing a line). I have been working on receiving the data from an embeded system where they have a lot of corruption problems (partially on the system and partially during the phone line transfer). It would be very helpful if it were in a CSV type format so we could find the errors and remove or fix them instead of corrupting the entire data set. If you aren't needing to search within the system, then a CSV works perfectly. A: There is a number of embedded file systems (not fat compatible) that designed exactly for this purpose. I can't suggest since never used one, but here something from google. I'm sure you can dig more, and hopefully somebody here can provide more info, may be there is something GPL based. Comparison of different file systems are here A: We are using plain old syslogd to a YAFFS2 partition on NAND flash, it appears to work well: when messages are sent to the logger and power is removed immediately after (<100ms) the message is there and the log never appears to corrupt. This is based on observation rather than my explicitly knowing that everything will always be consistent by design, mind. A: Two csv/text files. Start a new pair each time the system restarts. Write each event to the first file, flush the file to store, write the record to the second file, then flush again. This way, if you crash during the first write all the data in the second copy (up until that write) will still be there. Make sure the flush is a full file system flush and not just the clib buffer flush. Maybe also place the files on separate file systems. Reserving space ahead of what you need could also help speed up the process. A: What facilities are available to you? The best option is often to log to an external resource, for example via syslog, SNMP, raw socket, or serial port. This protects you logs from unpleasantries on the device itself. If you need to store logs internally, I've found plaintext, human-readable files to be the best option in embedded devices. The "write/flush" cycle is fast, no tools are needed to maintain them, and you can monitor them in real-time. If file size is a problem, you can timestamp with an integer rather than formatted text, and you can use a numeric "Event ID" to abbreviate each log (leave only the instance-specific data as text).
{ "language": "en", "url": "https://stackoverflow.com/questions/172343", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to push a key and release it using C#? I am writing a C# program which captures signals from a external device, and sends keystrokes to another application. I am using SendKeys and it works fine. SendKeys does "press" a key by holding and releasing it immediately. I would like to make it push key and release it at will. My question is : "is there a way to send a "push" signal to a key, then a "release" signal after a certain amount of time ?" I am not sure SendKeys is able to do this. Any clue ? A: I don't think it's possible from .NET directly You could try using keybd_event native call by p/invoking the function as described here: http://pinvoke.net/default.aspx/user32.keybd_event The MSDN for keybd_event is here: http://msdn.microsoft.com/en-us/library/ms646304(VS.85).aspx Hope that helps! A: The accepted answer uses keybd_event which is deprecated. The official API is now SendInput. There's also a nice wrapper for it at http://inputsimulator.codeplex.com. None of the above, however, fully caters to the "key holding" scenario. This is due to the fact that holding a key will generate multiple WM_KEYDOWN messages, followed by a single WM_KEYUP message upon release (you can check this with Spy++). The frequency of the WM_KEYDOWN messages is dependent on hardware, BIOS settings and a couple of Windows settings: KeyboardDelay and KeyboardSpeed. The latter are accessible from Windows Forms (SystemInformation.KeyboardDelay, SystemInformation.KeyboardSpeed). Using the aforementioned Input Simulator library, I've implemented a key holding method which mimics the actual behavior. It's await/async ready, and supports cancellation. static Task SimulateKeyHold(VirtualKeyCode key, int holdDurationMs, int repeatDelayMs, int repeatRateMs, CancellationToken token) { var tcs = new TaskCompletionSource<object>(); var ctr = new CancellationTokenRegistration(); var startCount = Environment.TickCount; Timer timer = null; timer = new Timer(s => { lock (timer) { if (Environment.TickCount - startCount <= holdDurationMs) InputSimulator.SimulateKeyDown(key); else if (startCount != -1) { startCount = -1; timer.Dispose(); ctr.Dispose(); InputSimulator.SimulateKeyUp(key); tcs.TrySetResult(null); } } }); timer.Change(repeatDelayMs, repeatRateMs); if (token.CanBeCanceled) ctr = token.Register(() => { timer.Dispose(); tcs.TrySetCanceled(); }); return tcs.Task; } A: You could use SendInput or keyb_event, both are native API functions. SendInput has some advantages over keybd_event, but SendInput is only available starting with XP. Here is the msdn link http://msdn.microsoft.com/en-us/library/ms646310.aspx Hope this helps A: I once was looking to do the same thing on powerpoint, to hide the cursor, and later to stop the slideshow. But it's hard and tricky as there's many top level windows appeared in powerpoint, also it's hard to figure out which part of the emulation failed if it doesn't work. After looking into the message queue using Spy++, I notice that the accelerator command was sent after the keypress, so instead, I emulated the accelerator command, and it works like charm. So you might want to look into alternative like this.
{ "language": "en", "url": "https://stackoverflow.com/questions/172353", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Is it possible to print just the canvas element? I've created a web page that lets you input some information and then draws an image in a canvas element based on that info. I have it pretty much working the way I want except for the printing. Is there a way to print out the canvas element or is creating a new window to draw in, the only way to do it? Update: The answer was so simple. I was thinking of a lot more complicated solution. I wish I could pick more than 1 answer. I wasn't able to get the canvas to print when I used * to disable display. The simplest solution was to just turn off the form that I was using for input, using form {display:none;} in the CSS inside an @media print{}. Thanks for the quick response. @media print { form { display:none; } } A: You could try something like this: @media print { * { display:none; } #SOME-CANVAS-ID { display:block; } } I'm not sure if a canvas is block by default, but you could try something along the lines of that and see if it works. The idea is that it will hide everything (*) for print media, except for some other arbitrary element as long as the rule's precedence is higher (which is why I used the ID selector). Edit: If CSS3 (specifically the negation pseudo-class) had more support, your rule could be as simple as this: *:not(canvas) { display:none; } However, this may cause the <html> and <body> tags to be hidden, effectively hiding your canvas as well... A: I'm not 100% sure of the support, but you can use CSS and put an attribute in the <link> tag for media="print". In this CSS file, just hide the elements you don't want to show while printing: display:none; A: You can try to create a canvas just for printing: this.Print = function () { var printCanvas = $('#printCanvas'); printCanvas.attr("width", mainCanvas.width); printCanvas.attr("height", mainCanvas.height); var printCanvasContext = printCanvas.get(0).getContext('2d'); window.print(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/172365", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Tracing versus Logging and how does log4net fit in? I am wondering about what the difference between logging and tracing is. Is the difference basically that tracing is more detailed log giving developers a tool to debug applications at runtime? I have been experimenting with log4net and doing logging. Now I am wondering if I should be doing tracing as well and if I could/should use log4net for that purpose. Should I be doing tracing with log4net and is there some trace level for log4net loggers? Should I use a different log level for debug and trace purposes or is it ok to use the same? Can you give a simple example on how I would do logging and tracing for a simple method? Edit: Despite a few helpful answers below I am still unsure how I should be doing tracing versus logging. I have the following method in my Business layer and I want to add logging/tracing to it. I am wondering how to do it efficiently. Is the following method acceptable in terms of logging/tracing? Should the log messages be of type Info instead of Debug? Are the Debug messages I am logging considered trace? How would you change it? IEnumerable<Car> GetCars() { try { logger.Debug("Getting cars"); IEnumerable<Car> cars = CarAccessor.GetCars().ConvertAll(DataAccessToBusinessConverter); logger.Debug("Got total of " + cars.Count + " cars"); } catch (Exception e) { logger.Error("Error when getting cars", e); throw new Exception("Unexpected error when getting cars"); } } A: Logging is not Tracing. These two should be different libraries with different performance characteristics. In fact I have written one tracing library by myself with the unique property that it can trace automatically the exception when the method with tracing enabled is left with an exception. Besides this it is possible to resolve in an elegant way the problem to trigger exceptions in specific places in your code. A: I'd say yes. Logging is the only way to determine what happened in the past - if a customer calls and says something didn't happen as expected, without a log all you can do is shrug and try and reproduce the error. Sometimes that is impossible (depending on the complexity of the software and the reliance on customer data). There is also the question of logging for auditing, a log file can be written containing information on what the user is doing - so you can use that to narrow down the possibilities to debug a problem, or even to verify the user's claims (if you get a report that the system is broken, xyz didn't happen, you can look in the logs to find out the operator failed to start the process, or didn't click the right option to make it work) Then there's logging for reporting, which is what most people think logging is for. If you can tailor the log output then put everything in logs and reduce or increase the amount of data that gets written. If you can change the output level dynamically then that's perfect. You can use any means of writing logs, subject to performance issues. I find appending to a text file is the best, most portable, easiest to view, and (very importantly) easiest to retrieve when you need it. A: Logging is the generic term for recording information - tracing is the specific form of logging used to debug. In .NET the System.Diagnostics.Trace and System.Diagnostics.Debug objects allow simple logging to a number of "event listeners" that you can configure in app.config. You can also use TraceSwitches to configure and filter (between errors and info levels, for instance). private void TestMethod(string x) { if(x.Length> 10) { Trace.Write("String was " + x.Length); throw new ArgumentException("String too long"); } } In ASP.NET, there is a special version of Trace (System.Web.TraceContext) will writes to the bottom of the ASP page or Trace.axd. In ASP.NET 2+, there is also a fuller logging framework called Health Monitoring. Log4Net is a richer and more flexible way of tracing or logging than the in-built Trace, or even ASP Health Monitoring. Like Diagnostics.Trace you configure event listeners ("appenders") in config. For simple tracing, the use is simple like the inbuilt Trace. The decision to use Log4Net is whether you have more complicated requirements. private void TestMethod(string x) { Log.Info("String length is " + x.Length); if(x.Length> 10) { Log.Error("String was " + x.Length); throw new ArgumentException("String too long"); } } A: IMO...Logging should not be designed for development debugging (but it inevitably gets used that way) Logging should be designed for operational monitoring and trouble-shooting -- this is its raison d’être. Tracing should be designed for development debugging & performance tuning. If available in the field, it can be use for really low-level operational trouble-shooting, but that is not its main purposeGiven this, the most successful approaches I've seen (and designed/implemented) in the past do not combine the two together. Better to keep the two tools separate, each doing one job as well as possible. A: log4net is well suited for both. We differentiate between logging that's useful for post-release diagnostics and "tracing" for development purposes by using the DEBUG logging level. Specifically, developers log their tracing output (things that are only of interest during development) using Debug(). Our development configuration sets the Level to DEBUG: <root> <level value="DEBUG" /> ... </root> Before the product is released, the level is changed to "INFO": <level value="INFO" /> This removes all DEBUG output from the release logging but keeps INFO/WARN/ERROR. There are other log4net tools, like filters, hierarchical (by namespace) logging, multiple targets, etc., by we've found the above simple method quite effective. A: logging != debugging Sometimes keeping log files is necessary to solve issues with the client, they prove what happened on the server side. A: Also, consider what information is logged or traced. This is especially true for senstive information. For example, while it may be generally OK to log an error stating "User 'X' attempted to access but was rejected because of a wrong password", it is not OK to log an error stating "User 'X' attempted to access but was rejected because the password 'secret' is not correct." It might be acceptable to write such senstive information to a trace file (and warn the customer/user about that fact by "some means" before you ask him to enable trace for extended troubleshooting in production). However for logging, I always have it as a policy that such senstive information is never to be written (i.e. levels INFO and above in log4net speak). This must be enforced and checked by code reviews, of course.
{ "language": "en", "url": "https://stackoverflow.com/questions/172372", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "51" }
Q: What is the difference between an nanokernel and an exokernel? I understand that they are both supposed to be small, but what are the key differences between the two? A: Exokernel is an operating system from MIT (and a class of it's variants) which handles relatively little hardware abstraction. In exokernel, the low-level responsibilities of controlling hardware (particularly memory allocation) are often left in the hands of the developer. Many developers would probably prefer to have the OS take more responsibility of such low-level tasks, because most developers are just writing applications. An exokernel just allocates physical hardware resources to programs. This allows the program to use library operating systems, which are linked in to provide some of the abstraction that the exokernel isn't providing. The developer can then choose between abstraction models, or roll their own. Given the application, this may have great performance benefits. If you don't know what you're doing, you can also write programs that will explode when they crash. Most kernels will do more to abstract physical hardware resources into some kind of theoretical model. A developer interfaces with this model, which handles the finer points of dealing with hardware internally. The term nanokernel is used to describe a specific type of kernel. The prefix "pico-", or "nano-", "micro-" is usually denoting the "size" of the kernel.. Bigger kernels are more built with more features, and handle more hardware abstraction. Nanokernels are relatively small kernels which provide hardware abstraction, but lack system services. Modern microkernels also lack system services, so the terms have become analogous. The names of kernels usually stem from a specific batch of research which yielded a new kind of kernel, for example the kernel developed at at Carnegie Mellon called "Mach", which was one of the first examples of a modern "microkernel". Sidenote: The real benefit of exokernel is choice. Most of the time, a lot of abstraction means fewer catastrophic bugs. In some applications, you might want to use a different abstraction model, or you might want to handle everything yourself. If we wanted to scrap the OS abstraction for a particular project, we'd have to cut out the operating system and commit a piece of hardware to the job. In the case of exokernel, this isn't necessary. We can program directly "to the metal", but also choose to link in an abstraction model whenever we like. It's a very powerful concept. Sidenote: Dealing with memory on such a low level is unnecessary for most application developers. There are usually several layers of operating system built on top of a kernel, and your application will run on the highest level of the OS. When writing in javascript, you're higher up still, interfacing with a model implemented in an application which runs on an operating system, etc. etc. Addressing memory, while it shouldn't be ignored, might mean something entirely different to a developer who is writing on such a high level of abstraction. A: I found one link which is really very helpful for differentiating monolithic micro and exokernels. link is--- http://www.scribd.com/doc/174682128/Difference-between-monolithic-microkernel-and-exokernel
{ "language": "en", "url": "https://stackoverflow.com/questions/172388", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: What symmetric cypher to use for encrypting messages? I haven't a clue about encryption at all. But I need it. How? Say you have a system of nodes communicating with each other on a network via asynchronous messages. The nodes do not maintain session information about other nodes (this is a design restriction). Say you want to make sure only your nodes can read the messages being sent. I believe encryption is the sollution to that. Since the nodes are not maintaining a session and communication must work in a stateless, connectionless fashion, I am guessing that asymmetric encryption is ruled out. So here is what I would like to do: * *messages are sent as UDP datagrams *each message contains a timestamp to make messages differ (counter replay attacks) *each message is encrypted with a shared secret symmetric key and sent over the network *other end can decrypt with shared secret symmetric key Keys can obviously be compromised by compromising any single node. At the same time, in this scenario, access to any single compromised node reveals all interesting information anyway, so the key is not the weakest link. What cypher should I use for this encryption? What key length? I would prefer to use something supported by ezPyCrypto. Assuming, as most point out, I go with AES. What modes should I be using? I couldn't figure out how to do it with ezPyCrypto, PyCrypto seems to be hung on a moderator swap and googles keyczar does not explain how to set this up - I fear if I don't just get it, then I run a risk of introducing insecurity. So barebones would be better. This guy claims to have a nice module for AES in python, but he also asserts that this is his first python project - Allthough he is probably loads smarter than I, maybe he got tripped up? EDIT: I moved the search for the python implementation to another question to stop clobber... A: Your first thought should be channel security - either SSL/TLS, or IPSec. Admittedly, these both have a certain amount of setup overhead, IPSec more than SSL/TLS, especially when it comes to PKI etc. - but it more than pays for itself in simplicity of development, reliability, security, and more. Just make sure you're using strong cipher suites, as appropriate to the protocol. If neither SSL/TLS or IPSec fits your scenario/environment, your next choice should be AES (aka Rijndael). Use keys at least 256 bits long, if you want you can go longer. Keys should be randomly generated, by a cryptographically secure random number generator (and not a simple rnd() call). Set the cipher mode to CBC. Use PKCS7 padding. Generate a unique, crypto-random Initialization Vector (IV). Don't forget to properly protect and manage your keys, and maybe consider periodic key rotations. Depending on your data, you may want to also implement a keyed hash, to provide for message integrity - use SHA-256 for hashing. There are also rare situations where you may want to go with a stream cipher, but thats usually more complicated and I would recommend you avoid it your first time out. Now, I'm not familiar ezpycrypto (or really python in general), and cant really state that it supports all this; but everything here is pretty standard and recommended best practice, if your crypto library doesnt support it, I would suggest finding one that does ;-). A: I haven't a clue about encryption at all. But I need it. How? DANGER! If you don't know much about cryptography, don't try to implement it yourself. Cryptography is hard to get right. There are many, many different ways to break the security of a cryptographic system beyond actually cracking the key (which is usually very hard). If you just slap a cipher on your streaming data, without careful key management and other understanding of the subtleties of cryptographic systems, you will likely open yourself up to all kinds of vulnerabilities. For example, the scheme you describe will be vulnerable to man-in-the-middle attacks without some specific plan for key distribution among the nodes, and may be vulnerable to chosen-plaintext and/or known-plaintext attacks depending on how your distributed system communicates with the outside world, and the exact choice of cipher and mode of operation. So... you will have to read up on crypto in general before you can use it securely. A: Assuming the use of symmetric crypto, then AES should be your default choice, unless you have a good very reason to select otherwise. There was a long, involved competition to select AES, and the winner was carefully chosen. Even Bruce Schneier, crypto god, has said that the AES winner is a better choice than the algorithm (TwoFish) that he submitted to the competition. A: AES 256 is generally the preferred choice, but depending on your location (or your customers' location) you may have legal constraints, and will be forced to use something weaker. Also note that you should use a random IV for each communication and pass it along with the message (this will also save the need for a timestamp). If possible, try not to depend on the algorithm, and pass the algorithm along with the message. The node will then look at the header, and decide on the algorithm that will be used for decryption. That way you can easily switch algorithms when a certain deployment calls for it. A: I'd probably go for AES. A: Asymmetric encryption would work in this scenario as well. Simply have each node publish it's public key. Any node that wants to communicate with that node need only encrypt the message with that node's public key. One advantage of using asymmetric keys is that it becomes easier to change and distribute keys -- since the public keys can be distributed openly, each node need only update it's public-private key pair and republish. You don't need some protocol for the entire network (or each node pair) to agree on a new symmetric key. A: Why not create a VPN among the nodes that must communicate securely? Then, you don't have to bother coding up your own security solution, and you're not restricted to a static, shared key (which, if compromised, will allow all captured traffic to be decrypted after the fact).
{ "language": "en", "url": "https://stackoverflow.com/questions/172392", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How do I get the max data size of every column in an IQueryable using LINQ I have a method that takes an IQueryable. Is there a LINQ query that will give me back the size of each column in the IQueryable? To be more clear: this is Linq-to-objects. I want to get the length of the ToString() of each "column". A: It depends. If you mean is there a completely generic way to make this determination the answer is no. All IQueryable will give access to is the Type of each expression. There is no way to arbitrarily map a Type to a column size. If on the other hand you have the ability to map a Type to members and member type to a column size then yes there is a way to get the size. public IEnumerable GetColumnSize(IQueryable source) { var types = MapTypeToMembers(source).Select(x => x.Type); return types.Select(x => MapTypeToSize(x)); } A: I guess you're talking about LINQ-to-SQL. It completely ignores column sizes. varchar(15), char(20) and nvarchar(max) are just strings for it. The overflow error will appear only on the SQL Server side. A: You said for each "column", that would map to each property. In Linq to Objects, this should work, although too manual: var lengths = from o in myObjectCollection select new { PropertyLength1 = o.Property1.ToString().Length, PropertyLength2 = o.Property2.ToString().Length, ... } If you meant the ToString() length of each item ("row") in the collection, then: var lengths = from o in myObjectCollection select o.ToString().Length;
{ "language": "en", "url": "https://stackoverflow.com/questions/172393", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What load-balancing system do you use in production? What do you think of it? There are a lot of different systems for balancing load and achieving redundancy in production servers (Not just web servers) * *Round-robin DNS *Linux Virtual Server *Cisco Local Director *F5 BigIP *Windows NLB *etc? If you use one of these (or another) in production, which one? How well does it work for you? Have you evaluated others? A: HAProxy is an excellent software load-balancer; easy to configure, highly customisable and extremely performant (it can saturate a 10Gb NIC). The main features which make HAProxy so suited to us: * *Easily define different traffic types, and route to the right server pool *Extreme reliability: I've not had it crash in 9 months and counting *Low resource usage: barely registers on CPU, and all the (small) I/O load is from logging *Highly flexible: various balancing, session stickiness and failover algorithms The only thing that is annoying about HAProxy is the configuration file. There is no convenient way to programmatically change a server's config, and there's a learning curve to understanding the various options. A: For our apache processes we use(d): http://www.f5.com/products/big-ip/ This seems like the industry standard. I guess it all comes down to how much you're paying, and what you're load balancing. e.g. Websphere could be done: big ip -> Apache 1 -> WebSphere 1 big ip -> Apache 2 -> WebSphere 2 or you could cross it: big ip -> Apache 1 -> WebSphere 1 & 2 (round robin) big ip -> Apache 2 -> WebSphere 2 & 1 (round robin) We used the latter and it worked perfectly. Watch out for the scenario where one host fails: in most cases you're going to lose that request if it just times out. A: I've used LVS and find it very low maintenance once setup. On a side project I tried haproxy for a site where I was just balancing 3 webservers. Worked like a charm and was very easy to configure - highly recommended. A: Add Ultramonkey to the list. We only tend to use DBs for redundancy, Oracle Dataguard works well but its complex to set up. A: Mark Imbriaco of 37signals has created a short screencast demonstrating how his company uses HAproxy for Rails load balancing: http://www.37signals.com/svn/posts/1073-nuts-bolts-haproxy A: I have used one of the low-end Coyote Point load balancers for a small website. I found the setup intuitive and the product stable and easy to use. I believe their product is a nice web GUI interface to BSD's relayd, formerly hoststated. In retrospect, I wish I had bought the middle to high end product so I could have used the load balancer as an SSL-endpoint and saved money on certificates. A: We are using a E250si by coyotepoint. Reasons why we opted for this particular loadbalancer * *We wanted a turn-key solution, which this piece of hardware is. *Price (we got it used with a year of support left on eBay). *Webbased interface - really easy to use (e.g. setup a cluster, quiesce a server, troubleshoot, statistics, ...), even if you're not a system administrator. *Semi-personal relationship with the company (or rather with someone working for them at that time). *FreeBSD based - we run FreeBSD almost exclusively and I prefer a solution which doesn't add yet another technology to the stack. One of the things to add is that even though the loadbalancer only has four physical ports, you can enable more ports by hooking up a switch to one of your physical ports - and hereby extending by There's not so much to say about this loadbalancer. It's been good to us and has been running without a reboot and any issues for 10 months or so now. Whenever a server failed, it was taken out of rotation instantly. Not so much I can complain. Initially there's a few things to get used and if I had to think about weak spots, only two come to mind: * *When you're handling more than 4 mbit/s incoming it can get a bit slow - and really, really slow when you enable features such as stickyness. We peak at 5-6 mbit/s usually but because we disabled stickyness, server agents, probes and use the very basic round_robin policy, it's all good. *The web interface use JavaScript/ajax for parts of the display - and those are pretty buggy, though a sales@ person told me they are resolved if we do the software update. All in all, the E250si saved us the all configuration and maintaining another server, etc.. But since I heard so many good things about HAproxy and pound, we will probably sooner or later migrate in this direction. If I go the software route though, I'd be very very picky after the components I put into the server - e.g. mainboard, network cards, etc.. A: We use keepalived on top of LVS. It's simple to add servers and has support for fail over load balancing servers. A: I have used F5 bigips at a couple of jobs, in addition to the usual hardware load balancing goodies i am particularly fond of irules which really offer some great rewriting flexibility its basically an event driven script language http://devcentral.f5.com/Default.aspx?tabid=75 there's a wiki but you need to create an account to access is A: HAProxy(loadbalancing) + Pound (SSL termnation) + keepalived (VRRP to have a live backup loadbalancer) A: Round-robin DNS will give you load-balancing, but not redundancy. If one of your servers fail, it'll still be hit by its share of requests. We use Apache mod_jk to handle load balancing and redundancy between pairs of Java application servers. This works extremely well, and it's simple. We also have a cold-failover Apache server in case the primary fails. Ideally we'd use something Linux-HA to achieve hot-failover for apache, but we're not sure if we can justify the complexity. A: A department at UCLA uses Juniper Acceleration Platform and they are very happy with it. It goes as far as taking over the task of SSL encryption, and boy, hardware-based SSL is so much faster! They are currently migrating more of their services to work with it. What's cool about it: * *Stores commonly accessed data patterns on dedicated hard drives *Hardware-based algorithms (talking speed!) *Supports most common protocols It's not cheap, but very efficient for companies with huge amounts of traffic. See specifications for UCLA's choice here. A: We currently use the Zeuz ZXTM load balancer and have been pleased with it so far. However, our hosting provider initially configured it on a virtual machine on top of the machine running firewall services. This was a pretty stupid mistake, it turned out, as the connections became saturated long before traffic should have been an issue. Once moved to its own dedicated box, we were able to handle 100Mb/s outgoing traffic without fail or issue (on a 4Gb/s burstable internet pipe). A: We are using HAProxy with great success. I had never seen it go above 2% CPU usage even during high load average. A: Round Robin with sticky sessions is what I believe we use. We have to have the setting so that the ASP/ASP.Net session information is preserved so that a user sticks to the one server that has the session. We did have a little problem once involving switching from http to SSL where our site would send authenticated users to a non-secure page and unauthenticated users would be sent to the secure login page that was kind of strange to see but did make some sense in the end that was solved through SSL termination for the best solution aside from going back to a single server which was the immediate solution. There may come a time when something more sophisticated will have to be used to determine which server is the "least busy" and send the next request to that machine but I'm not sure how the infrastructure guys will get to that functionality of the load balancers.
{ "language": "en", "url": "https://stackoverflow.com/questions/172394", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: How do I use BGGA closures prototype on standard Mac JDK6? I am trying to use the BGGA closures prototype with an existing JDK 6 (standard on Mac OS X Leopard). The sample code I'm compiling is from a BGGA tutorial: public static void main(String[] args) { // function with no arguments; return value is always 42 int answer = { => 42 }.invoke(); System.out.println(answer); } I have tried the following, and none work: * *Copied closures.jar to /System/Library/Frameworks/JavaVM.framework/Versions/1.6/Home/lib *Ran javac with -Xbootclasspath/a:/path/to/closures.jar *Ran javac with -J-Xbootclasspath/a:/path/to/closures.jar *Tried from eclipse ganymede by defining my own system library and attaching it to my project with code utilizing BGGA. In all four cases, I get compilation errors, indicating that the compiler did not pick up closures.jar on the bootstrap classpath. I'd really like to get this working from eclipse, or at the very least maven. Thanks! A: The TAR file distribution includes a modified javac.bat with a complete command line, including "-source 7", which is probably what you are missing here. A: Have you tried javac with -J-Xbootclasspath instead? That's used for passing -X arguments to the VM itself, which may be necessary for a change as low-level as this. I very much doubt this will work with Eclipse, though. System libraries are for APIs, not language changes. You'd need to patch the Eclipse compiler.
{ "language": "en", "url": "https://stackoverflow.com/questions/172397", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: What DB design to use for collecting configurable demographic data? I'm working on an application for a charitable student organization. The application will track participation and fund-raising for (primarily) student participants in an event. One of the things we'd like to do is collect some demographic information about students who register for the event from our enterprise directory to use in evaluating marketing and to construct reports for the administration on student participation by year, major, college, etc. One of the goals of the project is to market the application to similar organizations at other universities. I'm designing the app with a plugin architecture for authentication and directory access to make it more general. So far I've come up with a couple of different ways to store demographic information in the database. I can assume that most universities will like to collect (and have sources of information for) similar demographic information. In this case I can keep appropriate parts of the demographic information (those things that change yearly) in columns in the registrations table and the rest in the participants table (those things that are constant for an individual). Alternatively, I've considered keeping a demographics table that holds a registration id, attribute, value triple for each registration and desired attribute. I think that the first option is much easier to query against for reports, whereas the second option is much more flexible. I'm wondering if there are other alternatives that I haven't considered. Or, if you've faced a similar problem how did you handle it (and how satisfied were you with the result)? A: Here are my thoughts: * *You shouldn't tie in demographics with registration. It doesn't make sense logically and this can always lead to practical issues. You can instead create a demographics history table, e.g. StudentID, StartDate, EndDate, xxxDemographics, yyyDemographics...) *Different academic insituttions have may have quite different demographics needs. To reduce customization, you may want to softcode all the definitions in a configuration table e.g. Demographics (DemographicsID, DemographicsDesc) and keep a relationship table between Student and Demographics e.g. StudentDemographics (StudentID, DemographicsID...). The only trick with the above solution is that you may want to use PIVOTing on some of the reports. A: If you write your code in such a way that adding columns won't break it (or will be easy to update), for example being careful with SELECT * and specifying columns in INSERT, then from your description it doesn't sound like you need the ultra-flexibility of attribute-value, so I'd stick with option 1.
{ "language": "en", "url": "https://stackoverflow.com/questions/172408", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: .NET Table Adapters: Get vs. Fill? I always seem to use Get when working with data (strongly typed or otherwise) from the database and I have never really needed to use Fill although I just as easily could use Fill instead of get when pulling out and updating data. Can anyone provide guidance as to the implications and gotchas of each method? In what situations is it preferable to use one or the other? Any performance implications? Thanks in advance for the answers! I love this community! A: Using Fill can be great for debugging exceptions because the DataTable passed into the method can be interrogated for more details. Get does not return in the same situation. Tips: * *DataTable.GetErrors() returns an array of DataRow instances that are in error *DataRow.RowError contains a description of the row error *DataRow.GetColumnsInError() returns an array of DataColumn instances in error A: * *Get when you only want a single DataTable. *Fill when you want to add additional DataTables into a single DataSet. A: A particular gotcha of Fill, if the table already contains data is that you could get unique index exceptions when, for example, the query returns a row whose primary key is already in the table. I've worked with a lot of data-bound Windows Forms code where edit controls or a grid on the form is bound to a table and then Fill is used to load more rows from the database to the table. This can cause some interesting event firing sequences and intermittent errors from experience. Using Get to retrieve a new table with the new results then rebinding the form to the new table can avoid situations like this. I doubt there is much performance difference between the two unless using Fill on a table with existing rows. In this case the table's BeginLoadData method is ignored which would normally have delayed event firing and index rebuilding until the end. A: The only difference is that GetData instantiates a table for you, Fill will fill an existing table. It depends if you want or need to instantiate the DataTable. I often use Fill when filling a certain table member of a DataSet I already instantiated.
{ "language": "en", "url": "https://stackoverflow.com/questions/172436", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: How do I split a multi-line string into multiple lines? I have a multi-line string that I want to do an operation on each line, like so: inputString = """Line 1 Line 2 Line 3""" I want to iterate on each line: for line in inputString: doStuff() A: Use inputString.splitlines(). Why splitlines is better splitlines handles newlines properly, unlike split. It also can optionally return the newline character in the split result when called with a True argument, which is useful in some specific scenarios. Why you should NOT use split("\n") Using split creates very confusing bugs when sharing files across operating systems. \n in Python represents a Unix line-break (ASCII decimal code 10), independently of the OS where you run it. However, the ASCII linebreak representation is OS-dependent. On Windows, \n is two characters, CR and LF (ASCII decimal codes 13 and 10, \r and \n), while on modern Unix (Mac OS X, Linux, Android), it's the single character LF. print works correctly even if you have a string with line endings that don't match your platform: >>> print " a \n b \r\n c " a b c However, explicitly splitting on "\n", has OS-dependent behaviour: >>> " a \n b \r\n c ".split("\n") [' a ', ' b \r', ' c '] Even if you use os.linesep, it will only split according to the newline separator on your platform, and will fail if you're processing text created in other platforms, or with a bare \n: >>> " a \n b \r\n c ".split(os.linesep) [' a \n b ', ' c '] splitlines solves all these problems: >>> " a \n b \r\n c ".splitlines() [' a ', ' b ', ' c '] Reading files in text mode partially mitigates the newline representation problem, as it converts Python's \n into the platform's newline representation. However, text mode only exists on Windows. On Unix systems, all files are opened in binary mode, so using split('\n') in a UNIX system with a Windows file will lead to undesired behavior. This can also happen when transferring files in the network. A: inputString.splitlines() Will give you a list with each item, the splitlines() method is designed to split each line into a list element. A: Might be overkill in this particular case but another option involves using StringIO to create a file-like object for line in StringIO.StringIO(inputString): doStuff() A: inputString.split('\n') # --> ['Line 1', 'Line 2', 'Line 3'] This is identical to the above, but the string module's functions are deprecated and should be avoided: import string string.split(inputString, '\n') # --> ['Line 1', 'Line 2', 'Line 3'] Alternatively, if you want each line to include the break sequence (CR,LF,CRLF), use the splitlines method with a True argument: inputString.splitlines(True) # --> ['Line 1\n', 'Line 2\n', 'Line 3'] A: The original post requested for code which prints some rows (if they are true for some condition) plus the following row. My implementation would be this: text = """1 sfasdf asdfasdf 2 sfasdf asdfgadfg 1 asfasdf sdfasdgf """ text = text.splitlines() rows_to_print = {} for line in range(len(text)): if text[line][0] == '1': rows_to_print = rows_to_print | {line, line + 1} rows_to_print = sorted(list(rows_to_print)) for i in rows_to_print: print(text[i]) A: I would like to augment @1_CR 's answer: He led me to the following technique; it will use cStringIO if available (BUT NOTE: cStringIO and StringIO are not the same, because you cannot subclass cStringIO... it is a built-in... but for basic operations the syntax will be identical, so you can do this): try: import cStringIO StringIO = cStringIO except ImportError: import StringIO for line in StringIO.StringIO(variable_with_multiline_string): pass print line.strip()
{ "language": "en", "url": "https://stackoverflow.com/questions/172439", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "344" }
Q: GetOpt library for C# I'm looking for a getopt library for c#. So far I found a few (phpguru, XGetOptCS, getoptfordotnet) but these look more like unfinished attempts that only support a part of C's getopt. Is there a full getopt c# implementation? A: Here is a .NET Implementation of getopt: http://www.codeplex.com/getopt A: Miguel de Icaza raves about Mono.Options. You can use the nuget package, or just copy the single C# source file into your project. A: Here is something I wrote, it works rather nice, and has quite a lot of features for the tiny amount of code. It is not getopts however, but it may suit your needs. Feel free to ask some questions. A: For posterity: CommandParser is another one with a BSD license A: It's not getopt, but you might try NConsoler. It uses attributes to define arguments and actions. A: The Mono Project has (or rather had) one based on attributes, but last I checked it was marked as obsolete. But since it's open source, you might be able to pull the code out and use it yourself. A: A friend of mine suggested docopt.net, a command-line argument parsing library based on the docopt library for Node.JS. It is very simple to use, yet advanced and parses arguments based on the help string you write. Here's some sample code: using System; using DocoptNet; namespace MyProgram { static class Program { static void Main(string[] args) { // Usage string string usage = @"This program does this thing. Usage: program set <something> program do <something> [-o <optionalthing>] program do <something> [somethingelse]"; try { var arguments = new Docopt().Apply(usage, args, version: "My program v0.1.0", exit: false); foreach(var argument in arguments) Console.WriteLine("{0} = {1}", argument.Key, argument.Value); } catch(Exception ex) { //Parser errors are thrown as exceptions. Console.WriteLine(ex.Message); } } } } You can find documentation for it (including its help message format) at both the first link and here. Hope it helps someone! A: For the record, NUnit includes a simple one-file command-line parser in src\ClientUtilities\util\CommandLineOptions.cs (see example usage in ConsoleRunner.cs and Runner.cs located under src\ConsoleRunner\nunit-console). The file itself does not include any licencing information, and a link to its "upstream" seems to be dead, so its legal status is uncertain. The parser supports named flag parameters (like /verbose), named parameters with values (like /filename:bar.txt) and unnamed parameters, that is, much in style of how Windows Scripting Host interprets them. Options might be prefixed with /, - and --.
{ "language": "en", "url": "https://stackoverflow.com/questions/172443", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "28" }
Q: Palm/Garnet OS Icon format? I have googled around and not seen any info. What format and icon color depths are used for applications? A: The Palm OS icon format is a variation of it's bitmap format. Palm OS supports a concept called bitmap families where multiple bitmaps of different color depths and pixel densities are bundled together, with the appropriate one chosen at runtime. An icon is just a bitmap stored in a 'tAIN' resource as part of the application. Bitmaps also can be compressed using either RLE or PackBits, an algorithm used in the original Mac OS. If you're using a tool like PilRC to compile your bitmaps, you should be sure to include a low density and a high density bitmap. Here's a sample icon definition that I've used in one of my own programs: ICON BEGIN BITMAP "LargeSXSW06Icon_1bpp_72ppi__22x22.bmp" BPP 1 DENSITY 72 BITMAP "LargeSXSW06Icon_1bpp_144ppi_44x44.bmp" BPP 1 DENSITY 144 BITMAP "LargeSXSWIcon_8bpp_108ppi_33x33.bmp" BPP 8 COMPRESS TRANSPARENTINDEX 0 DENSITY 108 BITMAP "LargeSXSWIcon_8bpp_144ppi_44x44.bmp" BPP 8 COMPRESS TRANSPARENTINDEX 0 DENSITY 144 END SMALLICON BEGIN BITMAP "SmallIcon_1bpp_72ppi_15x9.bmp" BPP 1 DENSITY 72 BITMAP "SmallIcon_8bpp_72ppi_15x9.bmp" BPP 8 DENSITY 72 BITMAP "SmallSXSWIcon_8bpp_108ppi23x14.bmp" BPP 8 DENSITY 108 BITMAP "SmallSXSWIcon_8bpp_144ppi_30x18.bmp" BPP 8 DENSITY 144 END I define two icons -- the standard large icon and a small icon that's used in the launcher in list view mode. The sizes are 22x22/44x44 for low and high density for the main icon, and 15x9/30x18 for the small icon. PilRC takes BMP files as input, but it outputs either .bin files for each resource or a combined PRC-format file with all the resources specified. The PilRC source code is the best reference to the actual binary format of the bitmap.
{ "language": "en", "url": "https://stackoverflow.com/questions/172448", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: I can't seem to change drive drive using attached piece of code y: &pause cd ptls5.0 &pause sdp describe Integration.dpk &pause z: &pause cd ptls5.0 &pause dir &pause I have those commands in the 1.cmd file. First three are executed fine. The result of it is that after "sdp describe Integration.dpk &pause" is executed I'm given "press any key to continue..." after I hit any key. The command prompt quits. Instead of changing drive to z:>. What is wrong with it? A: If sdp is a .cmd or .bat file, change it to "call sdp....." A: Is "sdp" another batch file itself? If so, you will need to use call: call sdp describe Integration.dpk &pause
{ "language": "en", "url": "https://stackoverflow.com/questions/172465", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How can I ignore GCC compiler 'pedantic' errors in external library headers? I recently added -pedantic and -pedantic-errors to my make GCC compile options to help clean up my cross-platform code. All was fine until it found errors in external-included header files. Is there a way to turn off this error checking in external header files, i.e.: Keep checking for files included like this: #include "myheader.h" Stop checking for include files like this: #include <externalheader.h> Here are the errors I am getting: g++ -Wall -Wextra -Wno-long-long -Wno-unused-parameter -pedantic --pedantic-errors -O3 -D_FILE_OFFSET_BITS=64 -DMINGW -I"freetype/include" -I"jpeg" -I"lpng128" -I"zlib" -I"mysql/include" -I"ffmpeg/libswscale" -I"ffmpeg/libavformat" -I"ffmpeg/libavcodec" -I"ffmpeg/libavutil" -o omingwd/kguimovie.o -c kguimovie.cpp In file included from ffmpeg/libavutil/avutil.h:41, from ffmpeg/libavcodec/avcodec.h:30, from kguimovie.cpp:44: ffmpeg/libavutil/mathematics.h:32: error: comma at end of enumerator list In file included from ffmpeg/libavcodec/avcodec.h:30, from kguimovie.cpp:44: ffmpeg/libavutil/avutil.h:110: error: comma at end of enumerator list In file included from kguimovie.cpp:44: ffmpeg/libavcodec/avcodec.h:277: error: comma at end of enumerator list ffmpeg/libavcodec/avcodec.h:303: error: comma at end of enumerator list ffmpeg/libavcodec/avcodec.h:334: error: comma at end of enumerator list ffmpeg/libavcodec/avcodec.h:345: error: comma at end of enumerator list ffmpeg/libavcodec/avcodec.h:2249: warning: `ImgReSampleContext' is deprecated (declared at ffmpeg/libavcodec/avcodec.h:2243) ffmpeg/libavcodec/avcodec.h:2259: warning: `ImgReSampleContext' is deprecated (declared at ffmpeg/libavcodec/avcodec.h:2243) In file included from kguimovie.cpp:45: ffmpeg/libavformat/avformat.h:262: error: comma at end of enumerator list In file included from ffmpeg/libavformat/rtsp.h:26, from ffmpeg/libavformat/avformat.h:465, from kguimovie.cpp:45: ffmpeg/libavformat/rtspcodes.h:38: error: comma at end of enumerator list In file included from ffmpeg/libavformat/avformat.h:465, from kguimovie.cpp:45: ffmpeg/libavformat/rtsp.h:32: error: comma at end of enumerator list ffmpeg/libavformat/rtsp.h:69: error: comma at end of enumerator list A: Using the -Wsystem-headers option, GCC will print warning messages associated with system headers, which are normally suppressed. However, you're looking to have GCC basically treat these files as system headers, so you might try passing "-isystem /usr/local/ffmpeg" (or wherever you installed that package) to get GCC to ignore errors from files included in these directories as well. A: I don't know of a way to tell GCC to stop emitting those warnings. However, you could hackishly remove third-party warnings with something like llvm-gcc (or just gcc) -pedantic 2>&1|grep -v "/usr/". A: One idea that comes to my mind (I don't know if there's an 'out of the box' parameter for this): Prepare a script that will take your compiler's output, and remove all the lines that contain headers that aren't in a specific list (your headers). It shouldn't be that hard doing it this way. A: You could fix the headers and submit a patch to FFmpeg; compatibility with -pedantic is a worthy goal, so I'm sure they'd consider it, especially if it just involved removing trailing commas and suchlike. A: You can't tell GCC to be pedantic about some headers and not others at this time. You might suggest it as a feature, although I suspect it'll be resisted as ideally everyone would be pedantic. What you can do is fix the headers yourself, generate a patch, and then apply that patch to later versions of the headers if you upgrade the library. Submit the patch to FFmpeg as well in the hopes that they'll adopt it, but either way you're covered even if they don't accept it.
{ "language": "en", "url": "https://stackoverflow.com/questions/172484", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: What (pure) Python library to use for AES 256 encryption? I am looking for a (preferably pure) python library to do AES 256 encryption and decryption. This library should support the CBC cipher mode and use PKCS7 padding according to the answer to an earlier question of mine. The library should at least work on Mac OS X (10.4) and Windows XP. Ideally just by dropping it into the source directory of my project. I have seen this by Josh Davis, but am not sure about how good it is and if it does the required CBC cipher mode... Scanning the source suggests it doesn't A: Since I found this question when searching for the same thing I would like to add another one to the list: SlowAES – http://code.google.com/p/slowaes/ It's a development of Josh Davis' code, with the help of some other people. It seems to work fine. A: How about ncrypt? It's not pure python but it is a lot faster as a result. It is basically a nice python wrapper on OpenSSL, so you know there's quality code behind it. A: PyCrypto should be the one for you. Edit 02/10/2020: unfortunately I cannot delete this post, since it's the accepted answer. As people pointed out in the comments, this library is not mantained anymore and probably also vulnerable from a security point of view. So please, take a look to the below answers instead. A: https://github.com/caller9/pythonaes That is pure python with PKCS7 padding. Supports CBC, CFB, and OFB modes. The problem is that python is not super fast for this type of thing. The code from serprex's fork is a little bit inscrutable, but much faster than mine due to using all kinds of tricks to squeeze every last bit of speed out of Python. Really though, the best libraries for this are compiled and hook into SSE/MMX stuff. Also Intel is baking in AES instructions since the Core(tm) line of chips. I wrote my version to get a true pure Python version out there to be able to run on any architecture, cross-platform, and with 3.x as well as 2.7. A: PyCrypto is not clearly pythonic so you can get troubles compiling it on some platforms (AIX, HP-UX etc)
{ "language": "en", "url": "https://stackoverflow.com/questions/172486", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "32" }
Q: So - which exciting algorithms have you "discovered" recently? I like to read about new and clever algorithms. And I like to think out of the box, so all kinds of algorithms from all fields of computation are welcome. From time to time I read research papers to keep up with the current research and expand my horizon. I also like to learn new tricks. Unfortunately I tend to concentrate only on my field of interest, so I miss a lot of usefull stuff. Let's just not post mainstream things. Instead write about something special that made you think: "Wow - now that's a clever solution!". A: It's not something completely new or exciting, but I like the Levenshtein Distance. The Levenshtein Distance is often referred to as the edit distance between two strings and is basically a metric that measures the difference between two strings by counting the minimum number of operations to convert one string to the other. I'm using this algorithm to suggest a sorting of a number of strings to match the order of an external source of (possibly different) strings. A: I recently rediscovered a binary variant of the old Marchant calculator algorithm for integer square roots. No multiplies or divides, only addition, subtraction, and shifts. I'm sorry, I lost the reference: def assert raise "Assertion failed !" if $DEBUG and not yield end def sqrt(v) value = v.abs residue = value root = 0 onebit = 1 onebit <<= 8 while (onebit < residue) onebit >>= 2 while (onebit > residue) while (onebit > 0) x = root + onebit if (residue >= x) then residue -= x root = x + onebit end root >>= 1 onebit >>= 2 end assert {value == (root**2+residue)} assert {value < ((root+1)**2)} return [root,residue] end $DEBUG = true a = sqrt(4141290379431273280) puts a.inspect Doubly sorry, forgot to say that this is Ruby, for those unfamiliar. A: I always thought the magic square-root functions in Quake were very clever. It is very fast, because it avoids any of the slower operations such as divide etc. float SquareRootFloat(float num) { long i; float x, y; const float f = 1.5F; x = num * 0.5F; y = num; i = * ( long * ) &y; i = 0x5f3759df - ( i >> 1 ); y = * ( float * ) &i; y = y * ( f - ( x * y * y ) ); y = y * ( f - ( x * y * y ) ); return num * y; } He also has a related magic inverse square-root. A: Here's an implementation of the Viterbi algorithm that I "discovered" recently. The purpose here is to decide the optimal distribution of frame types in video encoding. Viterbi itself is a bit hard to understand sometimes, so I think the best method is via actual example. In this example, Max Consecutive B-frames is 2. All paths must end with a P-frame. Path length of 1 gives us P as our best path, since all paths must end on a P-frame, there's no other choice. Path length of 2 gives us BP and _P. "_" is the best path of length 1. This gives us BP and PP. Now, we calculate the actual costs. Let's say, for the sake of this example, that BP is best. Path length of 3 gives us BBP and _BP and __P. "__" is the best path of length 2. This gives us BBP and PBP and BPP. Now, we calculate the actual costs. Let's say, for the sake of this example, that BBP is best. Path length of 4 gives us _BBP and __BP and ___P. "___" is the best path of length 3. This gives us PBBP and BPBP and BBPP. Now, we calculate the actual costs. Let's say, for the sake of this example, that BPBP is best. Path length of 4 gives us __BBP and ___BP and ____P. "____" is the best path of length 4. This gives us BPBBP and BBPBP and BPBPP. Now--wait a minute--all of the paths agree that the first frame is a B! So the first frame is a B. Process is repeated until they agree on which frame is the first P-frame, and then encoding starts. This algorithm can be adapted to a huge variety of problems in many fields; its also the same algorithm I referred to in this post. A: I was impressed when I learned of the Burrows-Wheeler block sorting algorithm for data compression (as used in bzip2). The surprising thing is that the sorting step is reversible! A: bioinformatics is full of cases of experiments generating loads of data in weird forms requiring imaginative algorithms to process. an introduction to bioinformatics algorithms is a great read for this kind of stuff A: Dynamic programming takes all its power with optimal control problems. Very refreshing. A: I'll start with something everyone can use: introspective sort. http://en.wikipedia.org/wiki/Introsort A new sort algorithms that combines the best of quick, insertion and heap sort. To be exact it's not a new algorithm by itself but a very clever combination. You get the speed of quick-sort up to the point where the quick-sort runs into the degenerated O(n²) case. That gets detected for almost no cost. The remaining partition get sorted using heap- or merge-sort. This not only avoids the degenerated case but creates an clear defined upper bound for stack-usage as well. Insertion sort takes - as usual - care about all small partitions that are left over from the quick-sort pass. For me that was a new discovery because I stopped to use quick-sort for my applications. I do a lot of work on embedded devices and I do have to care about stack usage. Using quick-sort was always a bit risky because the faint chance that it runs amok on the stack. Even if you know that with the current data everything will be fine you never know if someone later cut'n'pastes your code into a different project and uses it for data it was never ment for. Thanks to introspective sort I now have full control over the stack usage and get a performance boost as well. A: It's not as flashy as the others, but it came in handy: ((m+n) + (m-n)) / 2 === m (for any two real numbers m and n) I was using some aggregate query logic in SQL to count ratings of an item. Ratings are either +1 and -1. I needed to know the number of positive ratings (m) given only the total number of ratings, and their sum. Using this logic really sped up the query and allowed me to return results for items with 0 ratings. (I didn't choose +1 and -1; I inherited that.) A: I found this very useful proof that a^n = b^n + c^n but only for n=2. Unfortunately this comment box is too small to contain it!
{ "language": "en", "url": "https://stackoverflow.com/questions/172504", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: How to track third-party sources with ClearCase without a headache? First of all: I am not an experienced ClearCase user, but I have lots of experience with other VCS and *nix command-line tools. WIth ClearCase, I use command-line tool ("cleartool") working in a Unix shell. Problem: I have a small set of sources stored in the ClearCase. Once in a while a fresh .tgz with the same sources comes in and I have to update sources in the repository (process could not be changed so that other party will use ClearCase). Now I do the following: * *Extract tgz into, say, "~/new_src" *"ct setview ..." and cd to the place where the sources are (say, "/vobs/src") *I compare the sources with "diff -Naurb . ~/new_src", examine diff's output and: * *Copy new files to the /vobs/src and do "cleartool mkelem" on them *Checkout changed files, copy new sources over and commit them *Do "cleartool mkdir" for new dirs and populate them This process is slowly driving me crazy since in almost any other version control system I would just checkout the sources, copy new sources over, examine diffs, add new files and then commit the whole lot. Or, better yet, use tags/branches, though they are really not needed in this case - I need to have an up-to-date version of the sources in the repo, that's all. I tried to checkout everything (using "cleartool co -nc find ."), copy new sources over, and commit changed files/add new files afterward. But this requires parsing of the "cleartool ls" output and is even messier. I could miss something obvious, but several forays into Google tell me that I'm not. However, I'd like to hear it from ClearCase powerusers - is there any hope for clueless like me or not? :) A: I just want to be sure: You do know about clearfsimport, right ? Because after reading (may be too quickly) your question, that command may be what you are after... That is what I thought... If you need more details, leave a comment to this answer. I will monitor those. A: I store a bunch of Perl modules in clearcase. But I just check in the tar.gz files, and have a script go and extract & install them (into the build tree) as part of the build process. I'd probably lean towards the same idea with other languages as well - just have a step in the make files to extract the tarballs before the rest of the build continues. Makes it really easy to substitute new versions. A: If you use ClearCase UCM, so there is another approach to handle with 3rd party repository - use components (read-write or, usually, read-only). BR, Tamir Gefen CM and ALM Consultant My blog: http://almmmm.wordpress.com
{ "language": "en", "url": "https://stackoverflow.com/questions/172510", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Populate a form with data from an associative array with jQuery Last time I asked about the reverse process, and got some very efficient answers. I'm aiming for least lines of code here. I have a form of fields and an associative array in the {fieldname:data} format, I want to populate a corresponding form with it. A: When I did this for a project, I found that setting the value of select fields, radio buttons and checkboxes necessitated more complex code, something along the lines of: jQuery.each(data, function (name,value) { jQuery("input[name='"+name+"'],select[name='"+name+"']").each(function() { switch (this.nodeName.toLowerCase()) { case "input": switch (this.type) { case "radio": case "checkbox": if (this.value==value) { jQuery(this).click(); } break; default: jQuery(this).val(value); break; } break; case "select": jQuery("option",this).each(function(){ if (this.value==value) { this.selected=true; } }); break; } }); }); I haven't tested this code so I hope there are no silly syntax errors that I should have caught. Hope this helps. I am not allowed to comment on the comments here (yet), so .... As noted in the comment, the jQuery .val(val) method handles setting radio buttons,checkboxes and selects. You will still need to put select[name=...] into your jQuery selector pattern or the select elements won't be updated. A: Or similar to the previous suggestion using the field names instead of ids: $.each(data, function(name,value) { $("input[name='" + name + "']").val(value); }); A: If your form elements have their ID set to the fieldname: $.each(myAssocArry, function(i,val) { $('#'+i).val(val); }); A: I have not seen jQuery handle passing a single (non-array) value into val() for a radio or checkbox input. You have to be sure to wrap the single value into an array. I have also typically not wanted to alter the values of button-ish inputs, so I filter those out. Here's a function that handles the array wrapping, button filtering, and also restricts the input selection to a given form element. The form parameter is optional. If left off/null/undefined, then all inputs on the page will be selected. function populateForm(data, form) { $.each( data, function(name, value) { var input = $(":input[name='" + name + "']:not(:button,:reset,:submit,:image)", form ); input.val( ( !$.isArray( value ) && ( input.is(':checkbox') || input.is(':radio') ) ) ? [ value ] : value ); } ); };
{ "language": "en", "url": "https://stackoverflow.com/questions/172524", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: SQL Cursors...Any use cases you would defend? I'll go first. I'm 100% in the set-operations camp. But what happens when the set logic on the entire desired input domain leads to a such a large retrieval that the query slows down significantly, comes to a crawl, or basically takes infinite time? That's one case where I'll use a itty-bitty cursor (or a while loop) of perhaps most dozens of rows (as opposed to the millions I'm targeting). Thus, I'm still working in (partitioned sub) sets, but my retrieval runs faster. Of course, an even faster solution would be to call the partioned input domains in parallel from outside, but that introduces an interaction will an external system, and when "good enough" speed can be achieved by looping in serial, just may not be worth it (epecially during development). A: I've got plenty of cases where rows from a configuration table have to be read and code generated and executed, or in many meta-programming scenarios. There are also cases when cursors simply outperform because the optimizer is not smart enough. In those cases, either there is meta-information in your head which is simply not revealed to the optimizer through the indexes or statistics on the tables, or the code is just so complicated that the joins (and usually, re-joins) simply can't be optimized in the way you can visualize them in a cursor-based fashion. In SQL Server 2005, I believe CTEs tend to make this look a lot simpler in the code, but whether the optimizer also sees them as simpler is hard to know - it comes down to comparing the execution plan to how you think it could be done most efficiently and making the call. General rule - don't use a cursor unless necessary. But when necessary, don't give yourself a hard time about it. A: There are lots of different cursor behaviors. * *STATIC vs KEYSET vs DYNAMIC *SCROLL vs FORWARD ONLY vs FAST FORWARD *INSENSITIVE or not *OPTIMISTIC or READ ONLY or not *LOCAL vs GLOBAL (at least this is easy) You should never use a cursor unless you can explain all of these options and which ones are on by default. And so, I never do. Instead, when I feel the urge to loop over something in T-SQL... I load it into a variable table, which is something like a LOCAL STATIC SCROLL cursor... except that it can be indexed and joined (edit: and the downside of preventing the use of parallelism). A: In a pure SQL environment, I'd rather avoid cursors as you suggest. But once you cross over into procedural language (like PL/SQL), there are a number of uses. For example, if you want to retrieve certain rows and want "to do" something more complex than update it with them. A: Very occasionally you will get an operation that needs a cursor but in T-SQL it is fairly rare. Identity(int) columns or sequences order things in ways within set operations. Aggregations where calculations might change at certain points (such as accumulating claims from ground up to a limit or excess point) are inherently procedural, so those are a candidate for a cursor. Other candidates would be inherently procedural such as looping through a configuration table and generating and executing a series of queries. A: Sure, there are a number of places where cursors might be better than set-based operations. One is if you're updating a lot of data in a table (for example a SQL Agent job to pre-compute data on a schedule) then you might use cursors to do it in multiple small sets rather than one large one to reduce the amount of concurrent locking and thus reduce the chance of lock contention and/or deadlocks with other processes accessing the data. Another is if you want to take application-level locks using the sp_getapplock stored procedure, which is useful when you want to ensure rows that are being polled for by multiple processes are retrieved exactly once (example here). In general though, I'd agree that it's best to start using set based operations if possible, and only move to cursors if required either for functionality or performance reasons (with evidence to back the latter up). A: Along with what David B said, I, too, prefer the loop/table approach. With that out of the way, one use case for cursors and the loop/table approach involves extremely large updates. Let's say you have to update 1 billion rows. In many instances, this may not need to be transactional. For example, it might be a data warehouse aggregation where you have the potential to reconstruct from source files if things go south. In this case, it may be best to do the update in "chunks", perhaps 1 million or 10 million rows at a time. This helps keep resource usage to a minimum, and allows concurrent use of the machine to be maximized while you update that billion rows. A looped/chunked approach might be best here. Billion row updates on less-than-stellar hardware tend to cause problems. A: Cursors are also handy when you want to run a system proc multiple times with different input values. I have no intention of trying to rewrite system procs to be set-based, so I will use a cursor then. Plus you are usually going through a very limited number of objects. You can do the same thing with an existing proc that inserts only one record at a time, but from a performance view, this is usually a bad thing if you have alot of records to run through. Those I will rewrite to be set-based. Running totals as discussed by others can be faster. If you are emailing from the database (not the best idea but sometimes it is what you are stuck with), then a cursor can ensure that customer a doesn't see customer b's email address when you send both the same email. A: Well one operation where cursors are better than sets is when calculating a running total and similar stuff. A: Having to use a cursor is generally a sign that you are doing in the database what ought to be done in the application. As others have said, cursors are generally needed when a stored procedure is calculating running totals, or when you're generating code and/or meta-programming. But why are you doing that kind of work in a stored procedure in the first place? Is that really the best use of your database server? Is T-SQL really the right language to use when generating code? Sure, sometimes the answer is "yes," or, more likely, "no, but it's simpler this way." In my view, keeping things simple trumps premature optimization any day of the week. So I use cursors. But when I think I need to use a cursor, the universe is asking me a question that I should really have a good answer to. A: If a table is un-indexed for some reason, a cursor will be faster than other methods of iterating over a table. I found this information in this blog post on cursors in SQL Server last year. While the author is in favor of "use only as a last resort" approach (as is everyone here), she does find a case or two where cursors perform as well as other available alternatives (including the running totals pointed out by Robert Rossney). Among other interesting points she makes, she indicates that cursors operate more efficiently inside stored procedures than as ad-hoc queries. The author also does an excellent job of pointing out when the performance problems we all associate with cursors begin to occur. The blog post contains actual code, so readers can try the queries themselves and see the results.
{ "language": "en", "url": "https://stackoverflow.com/questions/172526", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Ignore folders/files when Directory.GetFiles() is denied access I am trying to display a list of all files found in the selected directory (and optionally any subdirectories). The problem I am having is that when the GetFiles() method comes across a folder that it cannot access, it throws an exception and the process stops. How do I ignore this exception (and ignore the protected folder/file) and continue adding accessible files to the list? try { if (cbSubFolders.Checked == false) { string[] files = Directory.GetFiles(folderBrowserDialog1.SelectedPath); foreach (string fileName in files) ProcessFile(fileName); } else { string[] files = Directory.GetFiles(folderBrowserDialog1.SelectedPath, "*.*", SearchOption.AllDirectories); foreach (string fileName in files) ProcessFile(fileName); } lblNumberOfFilesDisplay.Enabled = true; } catch (UnauthorizedAccessException) { } finally {} A: A simple way to do this is by using a List for files and a Queue for directories. It conserves memory. If you use a recursive program to do the same task, that could throw OutOfMemory exception. The output: files added in the List, are organised according to the top to bottom (breadth first) directory tree. public static List<string> GetAllFilesFromFolder(string root, bool searchSubfolders) { Queue<string> folders = new Queue<string>(); List<string> files = new List<string>(); folders.Enqueue(root); while (folders.Count != 0) { string currentFolder = folders.Dequeue(); try { string[] filesInCurrent = System.IO.Directory.GetFiles(currentFolder, "*.*", System.IO.SearchOption.TopDirectoryOnly); files.AddRange(filesInCurrent); } catch { // Do Nothing } try { if (searchSubfolders) { string[] foldersInCurrent = System.IO.Directory.GetDirectories(currentFolder, "*.*", System.IO.SearchOption.TopDirectoryOnly); foreach (string _current in foldersInCurrent) { folders.Enqueue(_current); } } } catch { // Do Nothing } } return files; } Steps: * *Enqueue the root in the queue *In a loop, Dequeue it, Add the files in that directory to the list, and Add the subfolders to the queue. *Repeat untill the queue is empty. A: You will have to do the recursion manually; don't use AllDirectories - look one folder at a time, then try getting the files from sub-dirs. Untested, but something like below (note uses a delegate rather than building an array): using System; using System.IO; static class Program { static void Main() { string path = ""; // TODO ApplyAllFiles(path, ProcessFile); } static void ProcessFile(string path) {/* ... */} static void ApplyAllFiles(string folder, Action<string> fileAction) { foreach (string file in Directory.GetFiles(folder)) { fileAction(file); } foreach (string subDir in Directory.GetDirectories(folder)) { try { ApplyAllFiles(subDir, fileAction); } catch { // swallow, log, whatever } } } } A: Since .NET Standard 2.1 (.NET Core 3+, .NET 5+), you can now just do: var filePaths = Directory.EnumerateFiles(@"C:\my\files", "*.xml", new EnumerationOptions { IgnoreInaccessible = true, RecurseSubdirectories = true }); According to the MSDN docs about IgnoreInaccessible: Gets or sets a value that indicates whether to skip files or directories when access is denied (for example, UnauthorizedAccessException or SecurityException). The default is true. Default value is actually true, but I've kept it here just to show the property. The same overload is available for DirectoryInfo as well. A: see https://stackoverflow.com/a/10728792/89584 for a solution that handles the UnauthorisedAccessException problem. All the solutions above will miss files and/or directories if any calls to GetFiles() or GetDirectories() are on folders with a mix of permissions. A: Here's a full-featured, .NET 2.0-compatible implementation. You can even alter the yielded List of files to skip over directories in the FileSystemInfo version! (Beware null values!) public static IEnumerable<KeyValuePair<string, string[]>> GetFileSystemInfosRecursive(string dir, bool depth_first) { foreach (var item in GetFileSystemObjectsRecursive(new DirectoryInfo(dir), depth_first)) { string[] result; var children = item.Value; if (children != null) { result = new string[children.Count]; for (int i = 0; i < result.Length; i++) { result[i] = children[i].Name; } } else { result = null; } string fullname; try { fullname = item.Key.FullName; } catch (IOException) { fullname = null; } catch (UnauthorizedAccessException) { fullname = null; } yield return new KeyValuePair<string, string[]>(fullname, result); } } public static IEnumerable<KeyValuePair<DirectoryInfo, List<FileSystemInfo>>> GetFileSystemInfosRecursive(DirectoryInfo dir, bool depth_first) { var stack = depth_first ? new Stack<DirectoryInfo>() : null; var queue = depth_first ? null : new Queue<DirectoryInfo>(); if (depth_first) { stack.Push(dir); } else { queue.Enqueue(dir); } for (var list = new List<FileSystemInfo>(); (depth_first ? stack.Count : queue.Count) > 0; list.Clear()) { dir = depth_first ? stack.Pop() : queue.Dequeue(); FileSystemInfo[] children; try { children = dir.GetFileSystemInfos(); } catch (UnauthorizedAccessException) { children = null; } catch (IOException) { children = null; } if (children != null) { list.AddRange(children); } yield return new KeyValuePair<DirectoryInfo, List<FileSystemInfo>>(dir, children != null ? list : null); if (depth_first) { list.Reverse(); } foreach (var child in list) { var asdir = child as DirectoryInfo; if (asdir != null) { if (depth_first) { stack.Push(asdir); } else { queue.Enqueue(asdir); } } } } } A: This simple function works well and meets the questions requirements. private List<string> GetFiles(string path, string pattern) { var files = new List<string>(); var directories = new string[] { }; try { files.AddRange(Directory.GetFiles(path, pattern, SearchOption.TopDirectoryOnly)); directories = Directory.GetDirectories(path); } catch (UnauthorizedAccessException) { } foreach (var directory in directories) try { files.AddRange(GetFiles(directory, pattern)); } catch (UnauthorizedAccessException) { } return files; } A: This should answer the question. I've ignored the issue of going through subdirectories, I'm assuming you have that figured out. Of course, you don't need to have a seperate method for this, but you might find it a useful place to also verify the path is valid, and deal with the other exceptions that you could encounter when calling GetFiles(). Hope this helps. private string[] GetFiles(string path) { string[] files = null; try { files = Directory.GetFiles(path); } catch (UnauthorizedAccessException) { // might be nice to log this, or something ... } return files; } private void Processor(string path, bool recursive) { // leaving the recursive directory navigation out. string[] files = this.GetFiles(path); if (null != files) { foreach (string file in files) { this.Process(file); } } else { // again, might want to do something when you can't access the path? } } A: I prefer using c# framework functions, but the function i need will be included in .net framework 5.0, so i have to write it. // search file in every subdirectory ignoring access errors static List<string> list_files(string path) { List<string> files = new List<string>(); // add the files in the current directory try { string[] entries = Directory.GetFiles(path); foreach (string entry in entries) files.Add(System.IO.Path.Combine(path,entry)); } catch { // an exception in directory.getfiles is not recoverable: the directory is not accessible } // follow the subdirectories try { string[] entries = Directory.GetDirectories(path); foreach (string entry in entries) { string current_path = System.IO.Path.Combine(path, entry); List<string> files_in_subdir = list_files(current_path); foreach (string current_file in files_in_subdir) files.Add(current_file); } } catch { // an exception in directory.getdirectories is not recoverable: the directory is not accessible } return files; }
{ "language": "en", "url": "https://stackoverflow.com/questions/172544", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "80" }
Q: How to use CMFCListCtrl with CListView? I'd like to use the new CMFCListCtrl features with my CListView class (and, of course, the new CMFCHeaderCtrl inside it). Unfortunately, you can't use Attach() or SubclassWindow() because the SysListView32 window is already associated with a CListView object. Do I have to override CListView's OnCmdMsg() and route all messages to my own instance of CMFCListCtrl? (Will that even work?) Or is there an easier/cleaner solution? A: I'd inherit from CFormView and let the CMFCListCtrl occupy the complete dialog of the form view. A: If you want your own CMFCHeaderCtrl (f.e. m_myHeaderCtrl derived from CMFCHeaderCtrl) you have to override these three functions in your own CMFCListCtrl CMFCHeaderCtrl& CMyMFCListCtrl::GetHeaderCtrl() { return m_myHeaderCtrl; } void CMyMFCListCtrl::InitHeader() { // Initialize header control: m_myHeaderCtrl.SubclassDlgItem(0, this); } void CMyMFCListCtrl::OnSize(UINT nType, int cx, int cy) { CListCtrl::OnSize(nType, cx, cy); if (myHeaderCtrl.GetSafeHwnd() != NULL) { myHeaderCtrl.RedrawWindow(); } } Now you have the full responce in your own myHeaderCtrl defining some more functions (f.e. multipe lines in header): OnDrawItem(CDC* pDC, int iItem, CRect rect, BOOL bIsPressed, BOOL bIsHighlighted); or defining your own layout by afx_msg LRESULT OnHeaderLayout(WPARAM wp, LPARAM lp); Examples are in the MFC-Code. A: CListView doesn't have a lot of functionality. Like you said in the comment above, just derive your own view class from CView, handle WM_SIZE to resize the CMFCListCtrl and you're good to go.
{ "language": "en", "url": "https://stackoverflow.com/questions/172546", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Where to create temp files when access to /tmp/ is denied? I wrote a short bash script to complete a task that involves creating a temporary directory and storing various files in it and performing various operations on it. In my first pass I just created the temp dir at /tmp/$$.$script", but then I tested the script on a computer where I didn't have write access to /tmp/, and I'd like to take that case into account. So my question is where's a good secondary location for this temp dir? Should I just use the current directory? The home directory? ~/tmp/? The output location of the script? All created files do get cleaned up on script exit. A: Many systems also have a /var/tmp. If the sysadmin doesn't want you writing in to /tmp, presumably they have provided some alternative… is the $TMPDIR environment variable set? For example, on my Mac: $ echo $TMPDIR /var/folders/jf/jfu4pjGtGGGkUuuq8HL7UE+++TI/-Tmp-/ A: I would suggest ~/.[your script name]/tmp, if TMPDIR is not set, instead of ~/tmp/ since the user may have created that on their own (and you may not want to accidentally override things in there). Just as an off the cuff thought in bash -- case $TMPDIR in '') tmp_dir=".${0}/tmp";; *) tmp_dir=$TMPDIR;; esac A: Use ${TMPDIR:-/tmp} ($TMPDIR or /tmp if $TMPDIR is not set). If that's not writable, then exit with an error saying so, or ask the user for input defining it. I think asking the user where temp files should go is preferable to assuming somewhere and leaving them there if your process gets killed. A: You could try using mktemp (assuming it's configured correctly for the system) e.g. MYTMPDIR=$(mktemp -d) A: You could try /var/tmp, although it's likely that /tmp is a symlink to that (or vice-versa).
{ "language": "en", "url": "https://stackoverflow.com/questions/172552", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Most efficient way to index a returned array? function returnsAnArray () { return array ('test'); } echo returnsAnArray ()[0]; generates a syntax error in PHP. What's the most efficient way to directly obtain an element from a returned array without assigning the result to a temp variable? A: Here's one way, using the list language construct function returnsAnArray () { return array ('test'); } list($foo)=returnsAnArray(); You could grab a sequence of elements from an offset by combining this with array_slice list($third,$fourth,$fifth)=array_slice(returnsAnArray(), 2, 3); A: Define a new function for returning a specific index from an array. function arr_index($arr, $i) { return $arr[$i]; } You might want to add some error and type checking there. And then use it like this: echo arr_index(returnsAnArray(), 0); Happy Coding :) A: This will work if there is only one member in the array: <?php echo current(returnsAnArray()); ?> A: Another option: <?php echo reset(functionThatReturnsAnArray()); ?> Similar thread: PHP: Can I reference a single member of an array that is returned by a function? A: For regular numerically indexed arrays, where func() returns such an array and $n is the index you want: array_pop(array_slice(func(),$n,1)); For associative arrays (e.g. strings or other things as keys), or numeric arrays that aren't numbered and complete from 0..n, it's a little more convoluted. Where $key is the key you want: array_pop(array_intersect_keys(func(),Array($key => "")); This would also work for the first case. A: You could do this for an indexed array of unknown length. foreach ( returnsAnArray() as $item ) echo $item; A: I ask myself why one would like to avoid creating a temporary variable for a returned array. Why don't you just return one value instead of an whole array? Maybe you'll have to overthink your program logic. Or is it a performance/memory issue? Consider using references instead of always creating a new array object and returning it.
{ "language": "en", "url": "https://stackoverflow.com/questions/172559", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Is there a better Java implementation of SSH2 than JSch? I've been using JSch for a couple of weeks now. It seems to work okay, but its API is a little bit cumbersome. I'm also a little off put by its total lack of documentation (not even javadoc style comments). Has anyone used a good Java SSH2 library that they'd recommend. I'm particularly interested in SCP file transfer and issuing commands to a remote Linux box programmatically via the SSH protocol. A: I am using J2SSH, works pretty well. I don't know how it compares to JSch though. A: Have you tried Orion SSH (Ganymed SSH-2), not tried much but seems good :)
{ "language": "en", "url": "https://stackoverflow.com/questions/172573", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: What is the difference between g++ and gcc? What is the difference between g++ and gcc? Which one of them should be used for general c++ development? A: gcc and g++ are compiler-drivers of the GNU Compiler Collection (which was once upon a time just the GNU C Compiler). Even though they automatically determine which backends (cc1 cc1plus ...) to call depending on the file-type, unless overridden with -x language, they have some differences. The probably most important difference in their defaults is which libraries they link against automatically. According to GCC's online documentation link options and how g++ is invoked, g++ is equivalent to gcc -xc++ -lstdc++ -shared-libgcc (the 1st is a compiler option, the 2nd two are linker options). This can be checked by running both with the -v option (it displays the backend toolchain commands being run). A: “GCC” is a common shorthand term for the GNU Compiler Collection. This is both the most general name for the compiler, and the name used when the emphasis is on compiling C programs (as the abbreviation formerly stood for “GNU C Compiler”). When referring to C++ compilation, it is usual to call the compiler “G++”. Since there is only one compiler, it is also accurate to call it “GCC” no matter what the language context; however, the term “G++” is more useful when the emphasis is on compiling C++ programs. You could read more here. A: What is the difference between g++ and gcc? gcc has evolved from a single language "GNU C Compiler" to be a multi-language "GNU Compiler Collection". The term gcc may still sometimes refer to the "GNU C Compiler" in the context of C programming. man gcc # GCC(1) GNU # # NAME # gcc - GNU project C and C++ compiler However, g++ is the C++ compiler for the GNU Compiler Collection. Like gnat is the Ada compiler for gcc. see Using the GNU Compiler Collection (GCC) For example, the Ubuntu 16.04 and 18.04 man g++ command returns the GCC(1) manual page. The Ubuntu 16.04 and 18.04 man gcc states that ... g++ accepts mostly the same options as gcc and that the default ... ... use of gcc does not add the C++ library. g++ is a program that calls GCC and automatically specifies linking against the C++ library. It treats .c, .h and .i files as C++ source files instead of C source files unless -x is used. This program is also useful when precompiling a C header file with a .h extension for use in C++ compilations. Search the gcc man pages for more details on the option variances between gcc and g++. Which one should be used for general c++ development? Technically, either gcc or g++ can be used for general C++ development with applicable option settings. However, the g++ default behavior is naturally aligned to a C++ development. The Ubuntu 18.04 'gcc' man page added, and Ubuntu 20.04 continues to have, the following paragraph: The usual way to run GCC is to run the executable called gcc, or machine-gcc when cross-compiling, or machine-gcc-version to run a specific version of GCC. When you compile C++ programs, you should invoke GCC as g++ instead. Side Note: In the case of the Xcode.app embedded toolchain, g++ simply links to gcc. Thus, g++ invocations may vary on a per-toolchain basis. ls -l /Applications/Xcode.app/Contents/Developer/usr/bin # … # lrwxr-xr-x 1 root wheel 3 Apr 27 2021 g++ -> gcc # -rwxr-xr-x 1 root wheel 167120 Nov 23 20:51 gcc ### -- versus -- which -a g++ # /usr/bin/g++ ls -l /usr/bin/g++ # -rwxr-xr-x 1 root wheel 137616 Jan 1 2020 /usr/bin/g++ A: GCC: GNU Compiler Collection * *Referrers to all the different languages that are supported by the GNU compiler. gcc: GNU C      Compiler g++: GNU C++ Compiler The main differences: * *gcc will compile: *.c\*.cpp files as C and C++ respectively. *g++ will compile: *.c\*.cpp files but they will all be treated as C++ files. *Also if you use g++ to link the object files it automatically links in the std C++ libraries (gcc does not do this). *gcc compiling C files has fewer predefined macros. *gcc compiling *.cpp and g++ compiling *.c\*.cpp files has a few extra macros. Extra Macros when compiling *.cpp files: #define __GXX_WEAK__ 1 #define __cplusplus 1 #define __DEPRECATED 1 #define __GNUG__ 4 #define __EXCEPTIONS 1 #define __private_extern__ extern A: One notable difference is that if you pass a .c file to gcc it will compile as C. The default behavior of g++ is to treat .c files as C++ (unless -x c is specified). A: Although the gcc and g++ commands do very similar things, g++ is designed to be the command you'd invoke to compile a C++ program; it's intended to automatically do the right thing. Behind the scenes, they're really the same program. As I understand, both decide whether to compile a program as C or as C++ based on the filename extension. Both are capable of linking against the C++ standard library, but only g++ does this by default. So if you have a program written in C++ that doesn't happen to need to link against the standard library, gcc will happen to do the right thing; but then, so would g++. So there's really no reason not to use g++ for general C++ development. A: I became interested in the issue and perform some experiments * *I found that description here, but it is very short. *Then I tried to experiment with gcc.exe and g++.exe on my windows machine: $ g++ --version | head -n1 g++.exe (gcc-4.6.3 release with patches [build 20121012 by perlmingw.sf.net]) 4.6.3 $ gcc --version | head -n1 gcc.exe (gcc-4.6.3 release with patches [build 20121012 by perlmingw.sf.net]) 4.6.3 *I tried to compile c89, c99, and c++1998 simple test files and It's work well for me with correct extensions matching for language gcc -std=c99 test_c99.c gcc -std=c89 test_c89.c g++ -std=c++98 test_cpp.cpp gcc -std=c++98 test_cpp.cpp *But when I try to run "gnu compiler collection" tool in that fashion: $ gcc -std=c++98 test_cpp.c cc1.exe: warning: command line option '-std=c++98' is valid for C++/ObjC++ but not for C [enabled by default] *But this one still work with no errors $ gcc -x c++ -std=c++98 test_cpp.c *And this also $ g++ -std=c++0x test_cpp_11.cpp p.s. Test files $ cat test_c89.c test_c99.c test_cpp.cpp // C89 compatible file int main() { int x[] = {0, 2}; return sizeof(x); } // C99 compatible file int main() { int x[] = {[1]=2}; return sizeof(x); } // C++1998,2003 compatible file class X{}; int main() { X x; return sizeof(x); } // C++11 #include <vector> enum class Color : int{red,green,blue}; // scoped enum int main() { std::vector<int> a {1,2,3}; // bracket initialization return 0; } Findings: * *If look at process tree then it seems that gcc, and g++ is backend to other tools, which in my environment are: cc1plus.exe, cc1.exe, collect2.exe, as.exe, ld.exe *gcc works fine as metatool for if you have correct extension or set correct -std -x flags. See this A: For c++ you should use g++. It's the same compiler (e.g. the GNU compiler collection). GCC or G++ just choose a different front-end with different default options. In a nutshell: if you use g++ the frontend will tell the linker that you may want to link with the C++ standard libraries. The gcc frontend won't do that (also it could link with them if you pass the right command line options). A: I was testing gcc and g++ in a linux system. By using MAKEFILE, I can define the compliler used by "GNU make". I tested with the so called "dynamic memory" locating feature of "C plus plus" by : int main(){ int * myptr = new int; * myptr = 1; printf("myptr[0] is %i\n",*myptr); return 0; } Only g++ can successfully compile on my computer while gcc will report error undefined reference to `operator new(unsigned long)' So my own conclusion is gcc does not fully support "C plus plus". It seems that choosing g++ for C++ source files is a better option. A: gcc and g ++ are both GNU compiler. They both compile c and c++. The difference is for *.c files gcc treats it as a c program, and g++ sees it as a c ++ program. *.cpp files are considered to be c ++ programs. c++ is a super set of c and the syntax is more strict, so be careful about the suffix.
{ "language": "en", "url": "https://stackoverflow.com/questions/172587", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1120" }
Q: How to discover the type of media inserted in a DVD/CD drive? (java) When I insert a DVD or CD, I want to programmatically know what type of media(DVD or CD) is it. A: IMHO impossible to get this solved with pure Java. The only thing you can do is via the FileSystemView and detect whether a certain file is a cd/dvd drive but not if it contains a CD or DVD as media. Although a one can perform an educated guess by getting the total used space. For a working solution you'll need at least JNI code for the three "big" OS. I'm not aware of any project that has done this. There are only platform specific libraries / utilities for Linux that use the usual cdrw/dvdrw tools in the background.
{ "language": "en", "url": "https://stackoverflow.com/questions/172588", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Best way to define private methods for a class in Objective-C I just started programming Objective-C and, having a background in Java, wonder how people writing Objective-C programs deal with private methods. I understand there may be several conventions and habits and think about this question as an aggregator of the best techniques people use dealing with private methods in Objective-C. Please include an argument for your approach when posting it. Why is it good? Which drawbacks does it have (that you know of) and how you deal with them? As for my findings so far. It is possible to use categories [e.g. MyClass (Private)] defined in MyClass.m file to group private methods. This approach has 2 issues: * *Xcode (and compiler?) does not check if you define all methods in private category in corresponding @implementation block *You have to put @interface declaring your private category in the begin of MyClass.m file, otherwise Xcode complains with a message like "self may not respond to message "privateFoo". The first issue can be worked around with empty category [e.g. MyClass ()]. The second one bothers me a lot. I'd like to see private methods implemented (and defined) near the end of the file; I do not know if that's possible. A: There isn't really a "private method" in Objective-C, if the runtime can work out which implementation to use it will do it. But that's not to say that there aren't methods which aren't part of the documented interface. For those methods I think that a category is fine. Rather than putting the @interface at the top of the .m file like your point 2, I'd put it into its own .h file. A convention I follow (and have seen elsewhere, I think it's an Apple convention as Xcode now gives automatic support for it) is to name such a file after its class and category with a + separating them, so @interface GLObject (PrivateMethods) can be found in GLObject+PrivateMethods.h. The reason for providing the header file is so that you can import it in your unit test classes :-). By the way, as far as implementing/defining methods near the end of the .m file is concerned, you can do that with a category by implementing the category at the bottom of the .m file: @implementation GLObject(PrivateMethods) - (void)secretFeature; @end or with a class extension (the thing you call an "empty category"), just define those methods last. Objective-C methods can be defined and used in any order in the implementation, so there's nothing to stop you putting the "private" methods at the end of the file. Even with class extensions I will often create a separate header (GLObject+Extension.h) so that I can use those methods if required, mimicking "friend" or "protected" visibility. Since this answer was originally written, the clang compiler has started doing two passes for Objective-C methods. This means you can avoid declaring your "private" methods completely, and whether they're above or below the calling site they'll be found by the compiler. A: There isn't, as others have already said, such a thing as a private method in Objective-C. However, starting in Objective-C 2.0 (meaning Mac OS X Leopard, iPhone OS 2.0, and later) you can create a category with an empty name (i.e. @interface MyClass ()) called Class Extension. What's unique about a class extension is that the method implementations must go in the same @implementation MyClass as the public methods. So I structure my classes like this: In the .h file: @interface MyClass { // My Instance Variables } - (void)myPublicMethod; @end And in the .m file: @interface MyClass() - (void)myPrivateMethod; @end @implementation MyClass - (void)myPublicMethod { // Implementation goes here } - (void)myPrivateMethod { // Implementation goes here } @end I think the greatest advantage of this approach is that it allows you to group your method implementations by functionality, not by the (sometimes arbitrary) public/private distinction. A: While I am no Objective-C expert, I personally just define the method in the implementation of my class. Granted, it must be defined before (above) any methods calling it, but it definitely takes the least amount of work to do. A: every objects in Objective C conform to NSObject protocol, which holds onto the performSelector: method. I was also previously looking for a way to create some "helper or private" methods that I did not need exposed on a public level. If you want to create a private method with no overhead and not having to define it in your header file then give this a shot... define the your method with a similar signature as the code below... -(void)myHelperMethod: (id) sender{ // code here... } then when you need to reference the method simply call it as a selector... [self performSelector:@selector(myHelperMethod:)]; this line of code will invoke the method you created and not have an annoying warning about not having it defined in the header file. A: You could use blocks? @implementation MyClass id (^createTheObject)() = ^(){ return [[NSObject alloc] init];}; NSInteger (^addEm)(NSInteger, NSInteger) = ^(NSInteger a, NSInteger b) { return a + b; }; //public methods, etc. - (NSObject) thePublicOne { return createTheObject(); } @end I'm aware this is an old question, but it's one of the first I found when I was looking for an answer to this very question. I haven't seen this solution discussed anywhere else, so let me know if there's something foolish about doing this. A: Defining your private methods in the @implementation block is ideal for most purposes. Clang will see these within the @implementation, regardless of declaration order. There is no need to declare them in a class continuation (aka class extension) or named category. In some cases, you will need to declare the method in the class continuation (e.g. if using the selector between the class continuation and the @implementation). static functions are very good for particularly sensitive or speed critical private methods. A convention for naming prefixes can help you avoid accidentally overriding private methods (I find the class name as a prefix safe). Named categories (e.g. @interface MONObject (PrivateStuff)) are not a particularly good idea because of potential naming collisions when loading. They're really only useful for friend or protected methods (which are very rarely a good choice). To ensure you are warned of incomplete category implementations, you should actually implement it: @implementation MONObject (PrivateStuff) ...HERE... @end Here's a little annotated cheat sheet: MONObject.h @interface MONObject : NSObject // public declaration required for clients' visibility/use. @property (nonatomic, assign, readwrite) bool publicBool; // public declaration required for clients' visibility/use. - (void)publicMethod; @end MONObject.m @interface MONObject () @property (nonatomic, assign, readwrite) bool privateBool; // you can use a convention where the class name prefix is reserved // for private methods this can reduce accidental overriding: - (void)MONObject_privateMethod; @end // The potentially good thing about functions is that they are truly // inaccessible; They may not be overridden, accidentally used, // looked up via the objc runtime, and will often be eliminated from // backtraces. Unlike methods, they can also be inlined. If unused // (e.g. diagnostic omitted in release) or every use is inlined, // they may be removed from the binary: static void PrivateMethod(MONObject * pObject) { pObject.privateBool = true; } @implementation MONObject { bool anIvar; } static void AnotherPrivateMethod(MONObject * pObject) { if (0 == pObject) { assert(0 && "invalid parameter"); return; } // if declared in the @implementation scope, you *could* access the // private ivars directly (although you should rarely do this): pObject->anIvar = true; } - (void)publicMethod { // declared below -- but clang can see its declaration in this // translation: [self privateMethod]; } // no declaration required. - (void)privateMethod { } - (void)MONObject_privateMethod { } @end Another approach which may not be obvious: a C++ type can be both very fast and provide a much higher degree of control, while minimizing the number of exported and loaded objc methods. A: If you wanted to avoid the @interface block at the top you could always put the private declarations in another file MyClassPrivate.h not ideal but its not cluttering up the implementation. MyClass.h interface MyClass : NSObject { @private BOOL publicIvar_; BOOL privateIvar_; } @property (nonatomic, assign) BOOL publicIvar; //any other public methods. etc @end MyClassPrivate.h @interface MyClass () @property (nonatomic, assign) BOOL privateIvar; //any other private methods etc. @end MyClass.m #import "MyClass.h" #import "MyClassPrivate.h" @implementation MyClass @synthesize privateIvar = privateIvar_; @synthesize publicIvar = publicIvar_; @end A: One more thing that I haven't seen mentioned here - Xcode supports .h files with "_private" in the name. Let's say you have a class MyClass - you have MyClass.m and MyClass.h and now you can also have MyClass_private.h. Xcode will recognize this and include it in the list of "Counterparts" in the Assistant Editor. //MyClass.m #import "MyClass.h" #import "MyClass_private.h" A: You could try defining a static function below or above your implementation that takes a pointer to your instance. It will be able to access any of your instances variables. //.h file @interface MyClass : Object { int test; } - (void) someMethod: anArg; @end //.m file @implementation MyClass static void somePrivateMethod (MyClass *myClass, id anArg) { fprintf (stderr, "MyClass (%d) was passed %p", myClass->test, anArg); } - (void) someMethod: (id) anArg { somePrivateMethod (self, anArg); } @end A: There's no way of getting around issue #2. That's just the way the C compiler (and hence the Objective-C compiler) work. If you use the XCode editor, the function popup should make it easy to navigate the @interface and @implementation blocks in the file. A: There is a benefit of private methods absence. You can move the logic that you intended to hide to the separate class and use it as delegate. In this case you can mark delegate object as private and it will not be visible from outside. Moving logic to the separate class (maybe several) makes better design of your project. Cause your classes become simpler and your methods are grouped in classes with proper names. A: As other people said defining private methods in the @implementation block is OK for most purposes. On the topic of code organization - I like to keep them together under pragma mark private for easier navigation in Xcode @implementation MyClass // .. public methods # pragma mark private // ... @end
{ "language": "en", "url": "https://stackoverflow.com/questions/172598", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "362" }