source_id
int64 1
74.7M
| question
stringlengths 0
40.2k
| response
stringlengths 0
111k
| metadata
dict |
---|---|---|---|
142,548 | Is there a way to deploy a given war file on Tomcat server? I want to do this without using the web interface. | There are several ways to deploy a Tomcat webapp: Dropping into $CATALINA_HOME/webapps, as was already mentioned. Using your build scripts to deploy automatically via the manager interface (that comes with Tomcat). Here are the two ways for Maven : use the tomcat plugin. You don't need to include it in pom.xml , just issue the goal mvn tomcat:deploy , the plugin is included in Maven 2. This assumes several defaults explained in the documentation , you can configure the behaviour in the pom.xml . There are other goals that let you deploy as an exploded archive etc . for Ant : something like this: <property name="manager.url" value="http://localhost:8080/manager"/> <property name="manager.username" value="manager"/> <property name="manager.password" value="foobar"/> <!-- Task definitions --> <taskdef name="deploy" classname="org.apache.catalina.ant.DeployTask"/> <taskdef name="list" classname="org.apache.catalina.ant.ListTask"/> <taskdef name="reload" classname="org.apache.catalina.ant.ReloadTask"/> <taskdef name="undeploy" classname="org.apache.catalina.ant.UndeployTask"/> <!-- goals --> <target name="install" depends="compile" description="Install application to servlet container"> <deploy url="${manager.url}" username="${manager.username}" password="${manager.password}" path="${app.path}" localWar="file://${build.home}"/> </target> <target name="list" description="List installed applications on servlet container"> <list url="${manager.url}" username="${manager.username}" password="${manager.password}"/> </target> <target name="reload" depends="compile" description="Reload application on servlet container"> <reload url="${manager.url}" username="${manager.username}" password="${manager.password}" path="${app.path}"/> </target> <target name="remove" description="Remove application on servlet container"> <undeploy url="${manager.url}" username="${manager.username}" password="${manager.password}" path="${app.path}"/> </target> All of those will require you to have a Tomcat user configuration. It lives $CATALINA_BASE/conf/tomcat-users.xml , but since you know already how to use the web interface, I assume you know how to configure the users and passwords. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/142548",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17712/"
]
} |
142,559 | I have pushed my .htaccess files to the production severs, but they don't work. Would a restart be the next step, or should I check something else. | A restart is not required for changes to .htaccess. Something else is wrong. Make sure your .htaccess includes the statement RewriteEngine on which is required even if it's also present in httpd.conf. Also check that .htaccess is readable by the httpd process. Check the error_log - it will tell you of any errors in .htaccess if it's being used.Putting an intentional syntax error in .htaccess is a good check to make sure the file is being used -- you should get a 500 error on any page in the same directory. Lastly, you can enable a rewrite log using commands like the following in your httpd.conf: RewriteLog "logs/rewritelog" RewriteLogLevel 7 The log file thus generated will give you the gory detail of which rewrite rules matched and how they were handled. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/142559",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22325/"
]
} |
142,614 | Does anyone have C# code handy for doing a ping and traceroute to a target computer? I am looking for a pure code solution, not what I'm doing now, which is invoking the ping.exe and tracert.exe program and parsing the output. I would like something more robust. | Given that I had to write a TraceRoute class today I figured I might as well share the source code. using System.Collections.Generic;using System.Net.NetworkInformation;using System.Text;using System.Net;namespace Answer{ public class TraceRoute { private const string Data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; public static IEnumerable<IPAddress> GetTraceRoute(string hostNameOrAddress) { return GetTraceRoute(hostNameOrAddress, 1); } private static IEnumerable<IPAddress> GetTraceRoute(string hostNameOrAddress, int ttl) { Ping pinger = new Ping(); PingOptions pingerOptions = new PingOptions(ttl, true); int timeout = 10000; byte[] buffer = Encoding.ASCII.GetBytes(Data); PingReply reply = default(PingReply); reply = pinger.Send(hostNameOrAddress, timeout, buffer, pingerOptions); List<IPAddress> result = new List<IPAddress>(); if (reply.Status == IPStatus.Success) { result.Add(reply.Address); } else if (reply.Status == IPStatus.TtlExpired || reply.Status == IPStatus.TimedOut) { //add the currently returned address if an address was found with this TTL if (reply.Status == IPStatus.TtlExpired) result.Add(reply.Address); //recurse to get the next address... IEnumerable<IPAddress> tempResult = default(IEnumerable<IPAddress>); tempResult = GetTraceRoute(hostNameOrAddress, ttl + 1); result.AddRange(tempResult); } else { //failure } return result; } }} And a VB version for anyone that wants/needs it Public Class TraceRoute Private Const Data As String = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" Public Shared Function GetTraceRoute(ByVal hostNameOrAddress As String) As IEnumerable(Of IPAddress) Return GetTraceRoute(hostNameOrAddress, 1) End Function Private Shared Function GetTraceRoute(ByVal hostNameOrAddress As String, ByVal ttl As Integer) As IEnumerable(Of IPAddress) Dim pinger As Ping = New Ping Dim pingerOptions As PingOptions = New PingOptions(ttl, True) Dim timeout As Integer = 10000 Dim buffer() As Byte = Encoding.ASCII.GetBytes(Data) Dim reply As PingReply reply = pinger.Send(hostNameOrAddress, timeout, buffer, pingerOptions) Dim result As List(Of IPAddress) = New List(Of IPAddress) If reply.Status = IPStatus.Success Then result.Add(reply.Address) ElseIf reply.Status = IPStatus.TtlExpired Then 'add the currently returned address result.Add(reply.Address) 'recurse to get the next address... Dim tempResult As IEnumerable(Of IPAddress) tempResult = GetTraceRoute(hostNameOrAddress, ttl + 1) result.AddRange(tempResult) Else 'failure End If Return result End FunctionEnd Class | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/142614",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
142,633 | I have a Button inside an UpdatePanel. The button is being used as the OK button for a ModalPopupExtender. For some reason, the button click event is not firing. Any ideas? Am I missing something? <asp:updatepanel id="UpdatePanel1" runat="server"> <ContentTemplate> <cc1:ModalPopupExtender ID="ModalDialog" runat="server" TargetControlID="OpenDialogLinkButton" PopupControlID="ModalDialogPanel" OkControlID="ModalOKButton" BackgroundCssClass="ModalBackground"> </cc1:ModalPopupExtender> <asp:Panel ID="ModalDialogPanel" CssClass="ModalPopup" runat="server"> ... <asp:Button ID="ModalOKButton" runat="server" Text="OK" onclick="ModalOKButton_Click" /> </asp:Panel> </ContentTemplate></asp:updatepanel> | Aspx <ajax:ModalPopupExtender runat="server" ID="modalPop" PopupControlID="pnlpopup" TargetControlID="btnGo" BackgroundCssClass="modalBackground" DropShadow="true" CancelControlID="btnCancel" X="470" Y="300" />//Codebehind protected void OkButton_Clicked(object sender, EventArgs e) { modalPop.Hide(); //Do something in codebehind } And don't set the OK button as OkControlID. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/142633",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21461/"
]
} |
142,644 | We recently attempted to break apart some of our Visual Studio projects into libraries, and everything seemed to compile and build fine in a test project with one of the library projects as a dependency. However, attempting to run the application gave us the following nasty run-time error message: Run-Time Check Failure #0 - The value of ESP was not properly saved across a function call. This is usually a result of calling a function pointer declared with a different calling convention. We have never even specified calling conventions (__cdecl etc.) for our functions, leaving all the compiler switches on the default. I checked and the project settings are consistent for calling convention across the library and test projects. Update: One of our devs changed the "Basic Runtime Checks" project setting from "Both (/RTC1, equiv. to /RTCsu)" to "Default" and the run-time vanished, leaving the program running apparently correctly. I do not trust this at all. Was this a proper solution, or a dangerous hack? | This debug error means that the stack pointer register is not returned to its original value after the function call, i.e. that the number of pushes before the function call were not followed by the equal number of pops after the call. There are 2 reasons for this that I know (both with dynamically loaded libraries). #1 is what VC++ is describing in the error message, but I don't think this is the most often cause of the error (see #2). 1) Mismatched calling conventions: The caller and the callee do not have a proper agreement on who is going to do what. For example, if you're calling a DLL function that is _stdcall , but you for some reason have it declared as a _cdecl (default in VC++) in your call. This would happen a lot if you're using different languages in different modules etc. You would have to inspect the declaration of the offending function, and make sure it is not declared twice, and differently. 2) Mismatched types: The caller and the callee are not compiled with the same types. For example, a common header defines the types in the API and has recently changed, and one module was recompiled, but the other was not--i.e. some types may have a different size in the caller and in the callee. In that case, the caller pushes the arguments of one size, but the callee (if you're using _stdcall where the callee cleans the stack) pops the different size. The ESP is not, thus, returned to the correct value. (Of course, these arguments, and others below them, would seem garbled in the called function, but sometimes you can survive that without a visible crash.) If you have access to all the code, simply recompile it. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/142644",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11180/"
]
} |
142,653 | I have DocumentRoot /var/www/test in my .htaccess file. This is causing the apache server to give me a 500 internal server error. The error log file shows:alert] [client 127.0.0.1] /var/www/.htaccess: DocumentRoot not allowed here AllowOveride All is set in my conf file. Any idea why this is happening? | The DocumentRoot directive cannot appear in a .htaccess file. Put it in httpd.conf instead. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/142653",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
142,693 | You know those websites that let you type in your checking account number and the routing number, and then they can transfer money to and from your account? How does that work? Any good services or APIs for doing that? Any gotchas? | The banks do have APIs for doing this, but only approved people/companies are allowed to interface with these systems. Because it actually involves transferring money around, the security requirements are pretty high in terms of how you handle the account numbers on your system. Many sites that offer this feature for buying goods actually use a third party system to handle the actual money transfer into their account. This lowers the amount of trouble to implement the API, as well as putting the burden of security on the third party handling the money transfers. If you are serious about setting up a system where you can accept bank account numbers, and exchange funds, you should contact your bank, and see what the actual requirements for implementing such a system. Each bank has their own system, along with their own rate regarding the cost of these transactions. Some third parties I'm aware of are Moneris Cactus Beanstream I'm in Canada, although I think Moneris and Cactus operate in the US. I think Beanstream doesn't. Again, you can talk to your bank, and they can probably get you in touch with a third party who will help you with the transactions. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/142693",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17076/"
]
} |
142,764 | I'd like to how to upgrade the default python installation(2.5.2) supplied with ubuntu 8.04 to python 2.6rc2. I'd like to make 2.6 the default python version on the system and migrate all the other useful installed python libraries installed on 2.5.2 to python 2.6rc2. Please let me know how I can achieve this. ThanksDirk | With the warning that I think it's a tremendously bad idea to replace the default Python with an unreleased beta version: First, install 2.6rc2. You can download the source from the Python website . Standard ./configure && make && sudo make install installation style. Next, remove the /usr/bin/python symlink. Do not remove /usr/bin/python2.5 . Add a symlink to 2.6 with ln -s /usr/local/bin/python2.6 /usr/bin/python . Once again, I think this is a terrible idea. There is almost certainly a better way to do whatever you're trying to accomplish. Migrating installed libraries is a much longer process. Look in the /usr/lib/python2.5/site-packages/ and /usr/local/lib/python2.5/site-packages/ directories. Any libraries installed to them will need to be re-installed with 2.6. Since you're not using a packaged Python version, you cannot use Ubuntu's packages -- you'll have to manually upgrade all the libraries yourself. Most of them can probably be installed with sudo easy_install <name> , but some like PyGTK+ are not so easy. You'll have to follow custom installation procedures for each such library. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/142764",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
142,789 | From the reading that I have done, Core Audio relies heavily on callbacks (and C++, but that's another story). I understand the concept (sort of) of setting up a function that is called by another function repeatedly to accomplish a task. I just don't understand how they get set up and how they actually work. Any examples would be appreciated. | There is no "callback" in C - not more than any other generic programming concept. They're implemented using function pointers. Here's an example: void populate_array(int *array, size_t arraySize, int (*getNextValue)(void)){ for (size_t i=0; i<arraySize; i++) array[i] = getNextValue();}int getNextRandomValue(void){ return rand();}int main(void){ int myarray[10]; populate_array(myarray, 10, getNextRandomValue); ...} Here, the populate_array function takes a function pointer as its third parameter, and calls it to get the values to populate the array with. We've written the callback getNextRandomValue , which returns a random-ish value, and passed a pointer to it to populate_array . populate_array will call our callback function 10 times and assign the returned values to the elements in the given array. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/142789",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22913/"
]
} |
142,812 | I need a compact representation of an array of booleans, does Python have a builtin bitfield type or will I need to find an alternate solution? | Bitarray was the best answer I found, when I recently had a similar need. It's a C extension (so much faster than BitVector, which is pure python) and stores its data in an actual bitfield (so it's eight times more memory efficient than a numpy boolean array, which appears to use a byte per element.) | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/142812",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10471/"
]
} |
142,820 | I've create a WinForms control that inherits from System.Windows.Forms.UserControl...I've got some custom events on the control that I would like the consumer of my control to be able to see. I'm unable to actually get my events to show up in the Events tab of the Properties window during design time. This means the only way to assign the events is to programmatically write myUserControl.MyCustomEvent += new MyUserControl.MyCustomEventHandler(EventHandlerFunction); this is fine for me I guess but when someone else comes to use my UserControl they are not going to know that these events exist (unless they read the library doco...yeah right). I know the event will show up using Intellisense but it would be great if it could show in the properties window too. | Make sure your events are exposed as public. For example... [Browsable(true)]public event EventHandler MyCustomEvent; | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/142820",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4403/"
]
} |
142,826 | I've been working on a web crawling .NET app in my free time, and one of the features of this app that I wanted to included was a pause button to pause a specific thread. I'm relatively new to multi-threading and I haven't been able to figure out a way to pause a thread indefinitely that is currently supported. I can't remember the exact class/method, but I know there is a way to do this but it has been flagged as obsolete by the .NET framework. Is there any good general purpose way to indefinitely pause a worker thread in C# .NET. I haven't had a lot of time lately to work on this app and the last time I touched it was in the .NET 2.0 framework. I'm open to any new features (if any) that exist in the .NET 3.5 framework, but I'd like to know of solution that also works in the 2.0 framework since that's what I use at work and it would be good to know just in case. | Never, ever use Thread.Suspend . The major problem with it is that 99% of the time you can't know what that thread is doing when you suspend it. If that thread holds a lock, you make it easier to get into a deadlock situation, etc. Keep in mind that code you are calling may be acquiring/releasing locks behind the scenes. Win32 has a similar API: SuspendThread and ResumeThread . The following docs for SuspendThread give a nice summary of the dangers of the API: http://msdn.microsoft.com/en-us/library/ms686345(VS.85).aspx This function is primarily designed for use by debuggers. It is not intended to be used for thread synchronization. Calling SuspendThread on a thread that owns a synchronization object, such as a mutex or critical section, can lead to a deadlock if the calling thread tries to obtain a synchronization object owned by a suspended thread. To avoid this situation, a thread within an application that is not a debugger should signal the other thread to suspend itself. The target thread must be designed to watch for this signal and respond appropriately. The proper way to suspend a thread indefinitely is to use a ManualResetEvent . The thread is most likely looping, performing some work. The easiest way to suspend the thread is to have the thread "check" the event each iteration, like so: while (true){ _suspendEvent.WaitOne(Timeout.Infinite); // Do some work...} You specify an infinite timeout so when the event is not signaled, the thread will block indefinitely, until the event is signaled at which point the thread will resume where it left off. You would create the event like so: ManualResetEvent _suspendEvent = new ManualResetEvent(true); The true parameter tells the event to start out in the signaled state. When you want to pause the thread, you do the following: _suspendEvent.Reset(); And to resume the thread: _suspendEvent.Set(); You can use a similar mechanism to signal the thread to exit and wait on both events, detecting which event was signaled. Just for fun I'll provide a complete example: public class Worker{ ManualResetEvent _shutdownEvent = new ManualResetEvent(false); ManualResetEvent _pauseEvent = new ManualResetEvent(true); Thread _thread; public Worker() { } public void Start() { _thread = new Thread(DoWork); _thread.Start(); } public void Pause() { _pauseEvent.Reset(); } public void Resume() { _pauseEvent.Set(); } public void Stop() { // Signal the shutdown event _shutdownEvent.Set(); // Make sure to resume any paused threads _pauseEvent.Set(); // Wait for the thread to exit _thread.Join(); } public void DoWork() { while (true) { _pauseEvent.WaitOne(Timeout.Infinite); if (_shutdownEvent.WaitOne(0)) break; // Do the work here.. } }} | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/142826",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/392/"
]
} |
142,830 | I have seen the other questions but I am still not satisfied with the way this subject is covered . I would like to extract a distiled list of things to check on comments at a code inspection. I am sure people will say things that will just cancel each other. But hey, maybe we can build a list for each camp. For those who don't comment at all the list will just be very short :) | I have one simple rule about commenting: Your code should tell the story of what you are doing; your comments should tell the story of why you are doing it. This way, I make sure that whoever inherits my code will be able to understand the intent behind the code. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/142830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14921/"
]
} |
142,844 | I would like to drag and drop my data file onto a Python script and have it process the file and generate output. The Python script accepts the name of the data file as a command-line parameter, but Windows Explorer doesn't allow the script to be a drop target. Is there some kind of configuration that needs to be done somewhere for this work? | Sure. From a mindless technology article called "Make Python Scripts Droppable in Windows" , you can add a drop handler by adding a registry key: Here’s a registry import file that you can use to do this. Copy the following into a .reg file and run it (Make sure that your .py extensions are mapped to Python.File). Windows Registry Editor Version 5.00[HKEY_CLASSES_ROOT\Python.File\shellex\DropHandler]@="{60254CA5-953B-11CF-8C96-00AA00B8708C}" This makes Python scripts use the WSH drop handler, which is compatible with long filenames. To use the short filename handler, replace the GUID with 86C86720-42A0-1069-A2E8-08002B30309D . A comment in that post indicates that one can enable dropping on "no console Python files ( .pyw )" or "compiled Python files ( .pyc )" by using the Python.NoConFile and Python.CompiledFile classes. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/142844",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4859/"
]
} |
142,863 | Comment on Duplicate Reference: Why would this be marked duplicate when it was asked years prior to the question referenced as a duplicate? I also believe the question, detail, and response is much better than the referenced question. I've been a C++ programmer for quite a while but I'm new to Java and new to Eclipse. I want to use the touch graph "Graph Layout" code to visualize some data I'm working with. This code is organized like this: ./com./com/touchgraph./com/touchgraph/graphlayout./com/touchgraph/graphlayout/Edge.java./com/touchgraph/graphlayout/GLPanel.java./com/touchgraph/graphlayout/graphelements./com/touchgraph/graphlayout/graphelements/GESUtils.java./com/touchgraph/graphlayout/graphelements/GraphEltSet.java./com/touchgraph/graphlayout/graphelements/ImmutableGraphEltSet.java./com/touchgraph/graphlayout/graphelements/Locality.java./com/touchgraph/graphlayout/graphelements/TGForEachEdge.java./com/touchgraph/graphlayout/graphelements/TGForEachNode.java./com/touchgraph/graphlayout/graphelements/TGForEachNodePair.java./com/touchgraph/graphlayout/graphelements/TGNodeQueue.java./com/touchgraph/graphlayout/graphelements/VisibleLocality.java./com/touchgraph/graphlayout/GraphLayoutApplet.java./com/touchgraph/graphlayout/GraphListener.java./com/touchgraph/graphlayout/interaction./com/touchgraph/graphlayout/interaction/DragAddUI.java./com/touchgraph/graphlayout/interaction/DragMultiselectUI.java./com/touchgraph/graphlayout/interaction/DragNodeUI.java./com/touchgraph/graphlayout/interaction/GLEditUI.java./com/touchgraph/graphlayout/interaction/GLNavigateUI.java./com/touchgraph/graphlayout/interaction/HVRotateDragUI.java./com/touchgraph/graphlayout/interaction/HVScroll.java./com/touchgraph/graphlayout/interaction/HyperScroll.java./com/touchgraph/graphlayout/interaction/LocalityScroll.java./com/touchgraph/graphlayout/interaction/RotateScroll.java./com/touchgraph/graphlayout/interaction/TGAbstractClickUI.java./com/touchgraph/graphlayout/interaction/TGAbstractDragUI.java./com/touchgraph/graphlayout/interaction/TGAbstractMouseMotionUI.java./com/touchgraph/graphlayout/interaction/TGAbstractMousePausedUI.java./com/touchgraph/graphlayout/interaction/TGSelfDeactivatingUI.java./com/touchgraph/graphlayout/interaction/TGUIManager.java./com/touchgraph/graphlayout/interaction/TGUserInterface.java./com/touchgraph/graphlayout/interaction/ZoomScroll.java./com/touchgraph/graphlayout/LocalityUtils.java./com/touchgraph/graphlayout/Node.java./com/touchgraph/graphlayout/TGAbstractLens.java./com/touchgraph/graphlayout/TGException.java./com/touchgraph/graphlayout/TGLayout.java./com/touchgraph/graphlayout/TGLensSet.java./com/touchgraph/graphlayout/TGPaintListener.java./com/touchgraph/graphlayout/TGPanel.java./com/touchgraph/graphlayout/TGPoint2D.java./com/touchgraph/graphlayout/TGScrollPane.java./TG-APACHE-LICENSE.txt./TGGL ReleaseNotes.txt./TGGraphLayout.html./TGGraphLayout.jar How do I add this project in Eclipse and get it compiling and running quickly? | Create a new Java project in Eclipse. This will create a src folder (to contain your source files). Also create a lib folder (the name isn't that important, but it follows standard conventions). Copy the ./com/* folders into the /src folder (you can just do this using the OS, no need to do any fancy importing or anything from the Eclipse GUI). Copy any dependencies ( jar files that your project itself depends on) into /lib (note that this should NOT include the TGGL jar - thanks to commenter Mike Deck for pointing out my misinterpretation of the OPs post! ) Copy the other TGGL stuff into the root project folder (or some other folder dedicated to licenses that you need to distribute in your final app) Back in Eclipse, select the project you created in step 1, then hit the F5 key (this refreshes Eclipse's view of the folder tree with the actual contents. The content of the /src folder will get compiled automatically (with class files placed in the /bin file that Eclipse generated for you when you created the project). If you have dependencies (which you don't in your current project, but I'll include this here for completeness), the compile will fail initially because you are missing the dependency jar files from the project classpath. Finally, open the /lib folder in Eclipse, right click on each required jar file and choose Build Path->Add to build path. That will add that particular jar to the classpath for the project. Eclipse will detect the change and automatically compile the classes that failed earlier, and you should now have an Eclipse project with your app in it. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/142863",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22917/"
]
} |
142,868 | How do I change Oracle from port 8080? My Eclipse is using 8080, so I can't use that. | From Start | Run open a command window.Assuming your environmental variables are set correctly start with the following: C:\>sqlplus /nologSQL*Plus: Release 10.2.0.1.0 - Production on Tue Aug 26 10:40:44 2008Copyright (c) 1982, 2005, Oracle. All rights reserved.SQL> connectEnter user-name: systemEnter password: <enter password if will not be visible>Connected.SQL> Exec DBMS_XDB.SETHTTPPORT(3010); [Assuming you want to have HTTP going to this port] PL/SQL procedure successfully completed.SQL>quit then open browser and use 3010 port. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/142868",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22916/"
]
} |
142,877 | I have a very large codebase (read: thousands of modules) that has code shared across numerous projects that all run on different operating systems with different C++ compilers. Needless to say, maintaining the build process can be quite a chore. There are several places in the codebase where it would clean up the code substantially if only there were a way to make the pre-processor ignore certain #includes if the file didn't exist in the current folder. Does anyone know a way to achieve that? Presently, we use an #ifdef around the #include in the shared file, with a second project-specific file that #defines whether or not the #include exists in the project. This works, but it's ugly. People often forget to properly update the definitions when they add or remove files from the project. I've contemplated writing a pre-build tool to keep this file up to date, but if there's a platform-independent way to do this with the preprocessor I'd much rather do it that way instead. Any ideas? | Little Update Some compilers might support __has_include ( header-name ) . The extension was added to the C++17 standard ( P0061R1 ). Compiler Support Clang GCC from 5.X Visual Studio from VS2015 Update 2 (?) Example (from clang website): // Note the two possible file name string formats.#if __has_include("myinclude.h") && __has_include(<stdint.h>)# include "myinclude.h"#endif Sources SD-6: SG10 Feature Test Recommendations Clang Language Extensions | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/142877",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
142,878 | I'm currently learning Haskell, Which language (F# or Haskell) do you prefer for programming general purpose applications? Which do you think is the stronger language? | I'd go for Haskell. HackageDB is a great collection of libraries that are written specifically for the language. In the case of F# you'd have to use mostly libraries that are not written with a functional language in mind so they will not be as 'elegant' to use. But, of course it depends largely on how much functional programming you want to do and constraints of the project you want to use it for. Even 'general purpose' does not mean it should be used in all cases ;) | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/142878",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21734/"
]
} |
142,944 | I remember seeing the code for a Highpass filter a few days back somewhere in the samples, however I can't find it anywhere now! Could someone remember me where the Highpass filter implementation code was? Or better yet post the algorithm? Thanks! | From the idevkit.com forums: #define kFilteringFactor 0.1static UIAccelerationValue rollingX=0, rollingY=0, rollingZ=0;- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration { // Calculate low pass values rollingX = (acceleration.x * kFilteringFactor) + (rollingX * (1.0 - kFilteringFactor)); rollingY = (acceleration.y * kFilteringFactor) + (rollingY * (1.0 - kFilteringFactor)); rollingZ = (acceleration.z * kFilteringFactor) + (rollingZ * (1.0 - kFilteringFactor)); // Subtract the low-pass value from the current value to get a simplified high-pass filter float accelX = acceleration.x - rollingX; float accelY = acceleration.y - rollingY; float accelZ = acceleration.z - rollingZ; // Use the acceleration data.} | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/142944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15124/"
]
} |
142,948 | Functional languages are good because they avoid bugs by eliminating state, but also because they can be easily parallelized automatically for you, without you having to worry about the thread count. As a Win32 developer though, can I use Haskell for some dlls of my application? And if I do, is there a real advantage that would be taken automatically for me? If so what gives me this advantage, the compiler? Does F# parallelize functions you write across multiple cores and cpu's automatically for you? Would you ever see the thread count in task manager increase? Basically my question is, how can I start using Haskell in a practical way, and will I really see some benefits if I do? | It seems like the book Real World Haskell is just what you're looking for. You can read it free online: http://book.realworldhaskell.org/ | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/142948",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3153/"
]
} |
143,020 | Does anyone know of such a library that performs mathematical optimization (linear programming, convex optimization, or more general types of problems)? I'm looking for something like MATLAB, but with the ability to handle larger problems. Do I have to write my own implementations, or buy one of those commercial products (CPLEX and the like)? | A good answer is dependent on what you mean by "convex" and "more general" If you are trying to solve large or challenging linear or convex-quadratic optimization problems (especially with a discrete component to them), then it's hard to beat the main commercial solvers, gurobi , cplex and Dash unless money is a big issue for you. They all have clean JNI interfaces and are available on most major platforms. The coin-or project has several optimizers and have a project for JNI interface. It is totally free ( EPL license), but will take more work to set-up and probably not give you the same performance. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/143020",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20029/"
]
} |
143,025 | struct a{ char *c; char b;}; What is sizeof(a)? | #include <stdio.h>typedef struct { char* c; char b; } a;int main(){ printf("sizeof(a) == %d", sizeof(a));} I get "sizeof(a) == 8", on a 32-bit machine. The total size of the structure will depend on the packing: In my case, the default packing is 4, so 'c' takes 4 bytes, 'b' takes one byte, leaving 3 padding bytes to bring it to the next multiple of 4: 8. If you want to alter this packing, most compilers have a way to alter it, for example, on MSVC: #pragma pack(1)typedef struct { char* c; char b; } a; gives sizeof(a) == 5. If you do this, be careful to reset the packing before any library headers! | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/143025",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
143,072 | Possible Duplicate: Emacs, switch to previous window other-window advances me to the next window in the current frame, but I also want a way to move back to the previous window. Emacs has next-buffer and previous-buffer , but no analogous interactive functions for window navigation. Just other-window . | Provide a negative argument with C-u - ("Control+U" then "minus"), or even more simply C-- ("Control minus"). Move to previous window: C-- C-x o Move to previous frame: C-- C-x 5 o From code, (other-window -1) or (other-frame -1) will do the same thing. Check out the help for the key you want to reverse (e.g. C-h k C-x o to show help for C-x o ) and if it says "A negative argument..." you know you can use C-- . | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/143072",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8913/"
]
} |
143,075 | I'm trying to print out the date in a certain format: NSDate *today = [[NSDate alloc] init];NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];[dateFormatter setDateFormat:@"yyyyMMddHHmmss"];NSString *dateStr = [dateFormatter stringFromDate:today]; If the iPhone is set to 24 hour time, this works fine, if on the other hand the user has set it to 24 hour time, then back to AM/PM (it works fine until you toggle this setting) then it appends the AM/PM on the end even though I didn't ask for it: 20080927030337 PM Am I doing something wrong or is this a bug with firmware 2.1? Edit 1: Made description clearer Edit 2 workaround: It turns out this is a bug, to fix it I set the AM and PM characters to "": [dateFormatter setAMSymbol:@""];[dateFormatter setPMSymbol:@""]; | Using the code you posted on both the simulator and a phone with the 2.1 firmware and 24-hour time set to off, I never had an AM/PM appended to dateStr when I do: NSLog(@"%@", dateStr); Are you doing anything else with dateStr that you didn't post here? How are you checking the value? Follow up Try turning the am/pm setting on then off. I didn't have the problem either, until I did that. I am printing it out the same way you are. Okay, I see it when I do this also. It's gotta be a bug. I recommend you file a bug report and just check for and filter out the unwanted characters in the meantime. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/143075",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6044/"
]
} |
143,084 | Let's say I have one class Foo that has a bunch of logic in it and another class Bar which is essentially the same. However, as Foo and Bar are different (but related) entities I need the difference to be apparent from my code (i.e. I can tell whether an instance is a Foo or a Bar ) As I was whacking this together without much thought I ended up with the following: public class Foo { /* constructors, fields, method, logic and what-not */}public class Bar extends Foo { /* nothing here but constructors */ } Is this OK? Is it better to make Bar a composite class? e.g: public class Bar { private Foo foo; /* constructors and a bunch of wrapper methods that call into foo */} Or even, while we're at it, something much more low-tech: public class Foo { /* constructors, fields, method, logic and what-not */ private boolean isABar; // Could be an enum} What do you think? How do you deal with these 'marker classes'? As an example of how my code may wish to treat Foo and Bar differently, my code would need to be able to do stuff like List<Foo> and List<Bar> . A Foo couldn't go in a List<Bar> and vice versa. | In my opinion, it's best if Foo and Bar subclass off a common ancestor class (maybe AbstractFoo ), which has all the functionality. What difference in behaviour should exist between Foo and Bar ? Code that difference as an abstract method in AbstractFoo , not by using a if statement in your code. Example: Rather than this: if (foo instanceof Bar) { // Do Bar-specific things} Do this instead: class Bar extends AbstractFoo { public void specialOp() { // Do Bar-specific things }}// ...foo.specialOp(); The benefit of this approach is that if you need a third class, that's much like Foo but has just a little bit of difference, you don't have to go through all your code and add edit all the if statements. :-) | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/143084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1666/"
]
} |
143,108 | Just as in title. Is suspect it is, but I couldn't find it anywhere explicitly stated. And for this property I wouldn't like to rely on speculations. | If you use the multithreaded version of the CRT, all functions are thread safe, because any thread-specific information is stored in TLS . rand_s actually doesn't use state information in the first place, since it just calls an OS API, so question of thread-safety doesn't arise for rand_s. rand(), however depends on a seed value to generate a random number. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/143108",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9403/"
]
} |
143,122 | Is it possible to use PHP's SimpleXML functions to create an XML object from scratch? Looking through the function list, there's ways to import an existing XML string into an object that you can then manipulate, but if I just want to generate an XML object programmatically from scratch, what's the best way to do that? I figured out that you can use simplexml_load_string() and pass in the root string that you want, and then you've got an object you can manipulate by adding children... although this seems like kind of a hack, since I have to actually hardcode some XML into the string before it can be loaded. I've done it using the DOMDocument functions , although it's a little confusing because I'm not sure what the DOM has to do with creating a pure XML document... so maybe it's just badly named :-) | Sure you can. Eg. <?php$newsXML = new SimpleXMLElement("<news></news>");$newsXML->addAttribute('newsPagePrefix', 'value goes here');$newsIntro = $newsXML->addChild('content');$newsIntro->addAttribute('type', 'latest');Header('Content-type: text/xml');echo $newsXML->asXML();?> Output <?xml version="1.0"?><news newsPagePrefix="value goes here"> <content type="latest"/></news> Have fun. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/143122",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20903/"
]
} |
143,123 | Using C / C++ socket programming, and the "read(socket, buffer, BUFSIZE)" method. What exactly is the "buffer" I know that char and byte are the same thing, but does it matter how many elements the byte array has in it? Does the buffer need to be able to hold the entire message until the null character? | BUFSIZE should be equal to the size of your buffer in bytes. read() will stop reading when the buffer is full. Here is an example: #define MY_BUFFER_SIZE 1024char mybuffer[MY_BUFFER_SIZE];int nBytes = read(sck, mybuffer, MY_BUFFER_SIZE); | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/143123",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3484/"
]
} |
143,130 | My company has a subsidiary with a slow Internet connection. Our developers there suffer to interact with our central Subversion server. Is it possible to configure a slave/mirror for them? They would interact locally with the server and all the commits would be automatically synchronized to the master server. This should work as transparently as possible for the developers. Usability is a must. Please, no suggestions to change our version control system. | It is possible but not necessarily simple: the problem you are trying to solve is dangerously close to setting up a distributed development environment which is not exactly what SVN is designed for. The SVN-mirror way You can use svn mirror as explained in the SVN book documentation to create a read-only mirror of your master repository. Your developers each interact with the mirror closest to them. However users of the slave repository will have to use svn switch --relocate master_url before they can commit and they will have to remember to relocate back on the slave once they are done. This could be automated using a wrapper script around the repository modifying commands on SVN if you use the command line client. Keep in mind that the relocate operation while fast adds a bit of overhead. (And be careful to duplicate the repository uuid - see the SVN documentation .) [Edit - Checking the TortoiseSVN documentation it seems that you can have TortoiseSVN execute hook scripts client side . You may be able to create a pre/post commit script at this point. Either that or try to see if you can use the TortoiseSVN automation interface to do it]. The SVK way svk is a set of Perl scripts which emulate a distributed mirroring service over SVN. You can set it up so that the local branch (the mirror) is shared by multiple developers. Then basic usage for the developers will be completely transparent. You will have to use the svk client for cherry picking, merging and starmerging. It is doable if you can get your head around the distributed concepts. The git-svn way While I never used that myself, you could also have distant developers use git locally and use the git-svn gateway for synchronization. Final words It all depends on your development environment and the level of integration you require. Depending on your IDE (and if you can change SCM ) you might want to have a look at other fully distributed SCMs (think Mercurial / Bazaar / Git /...) which support distributed development out of the box. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/143130",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10335/"
]
} |
143,171 | I'm trying to copy a bunch of files below a directory and a number of the files have spaces and single-quotes in their names. When I try to string together find and grep with xargs , I get the following error: find .|grep "FooBar"|xargs -I{} cp "{}" ~/foo/barxargs: unterminated quote Any suggestions for a more robust usage of xargs? This is on Mac OS X 10.5.3 (Leopard) with BSD xargs . | You can combine all of that into a single find command: find . -iname "*foobar*" -exec cp -- "{}" ~/foo/bar \; This will handle filenames and directories with spaces in them. You can use -name to get case-sensitive results. Note: The -- flag passed to cp prevents it from processing files starting with - as options. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/143171",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17339/"
]
} |
143,174 | Is there a platform-agnostic and filesystem-agnostic method to obtain the full path of the directory from where a program is running using C/C++? Not to be confused with the current working directory. (Please don't suggest libraries unless they're standard ones like clib or STL.) (If there's no platform/filesystem-agnostic method, suggestions that work in Windows and Linux for specific filesystems are welcome too.) | Here's code to get the full path to the executing app: Variable declarations: char pBuf[256];size_t len = sizeof(pBuf); Windows: int bytes = GetModuleFileName(NULL, pBuf, len);return bytes ? bytes : -1; Linux: int bytes = MIN(readlink("/proc/self/exe", pBuf, len), len - 1);if(bytes >= 0) pBuf[bytes] = '\0';return bytes; | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/143174",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1630/"
]
} |
143,234 | In Lua, using the = operator without an l-value seems to be equivalent to a print(r-value), here are a few examples run in the Lua standalone interpreter: > = anil> a = 8> = a8> = 'hello'hello> = printfunction: 003657C8 And so on... My question is : where can I find a detailed description of this use for the = operator? How does it work? Is it by implying a special default l-value? I guess the root of my problem is that I have no clue what to type in Google to find info about it :-) edit : Thanks for the answers, you are right it's a feature of the interpreter. Silly question, for I don't know which reason I completely overlooked the obvious. I should avoid posting before the morning coffee :-) For completeness, here is the code dealing with this in the interpreter: while ((status = loadline(L)) != -1) { if (status == 0) status = docall(L, 0, 0); report(L, status); if (status == 0 && lua_gettop(L) > 0) { /* any result to print? */ lua_getglobal(L, "print"); lua_insert(L, 1); if (lua_pcall(L, lua_gettop(L)-1, 0, 0) != 0) l_message(progname, lua_pushfstring(L, "error calling " LUA_QL("print") " (%s)", lua_tostring(L, -1))); }} edit2 : To be really complete, the whole trick about pushing values on the stack is in the "pushline" function: if (firstline && b[0] == '=') /* first line starts with `=' ? */ lua_pushfstring(L, "return %s", b+1); /* change it to `return' */ | Quoting the man page : In interactive mode ... If a line starts with '=', then lua displays the values of all the expressions in the remainder of the line. The expressions must be separated by commas. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/143234",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12291/"
]
} |
143,285 | For example if I have an Enum with two cases, does it make take more memory than a boolean? Languages: Java, C++ | In Java, an enum is a full-blown class : Java programming language enum types are much more powerful than their counterparts in other languages. The enum declaration defines a class (called an enum type). The enum class body can include methods and other fields. In order to see the actual size of each enum , let's make an actual enum and examine the contents of the class file it creates. Let's say we have the following Constants enum class: public enum Constants { ONE, TWO, THREE;} Compiling the above enum and disassembling resulting class file with javap gives the following: Compiled from "Constants.java"public final class Constants extends java.lang.Enum{ public static final Constants ONE; public static final Constants TWO; public static final Constants THREE; public static Constants[] values(); public static Constants valueOf(java.lang.String); static {};} The disassembly shows that that each field of an enum is an instance of the Constants enum class. (Further analysis with javap will reveal that each field is initialized by creating a new object by calling the new Constants(String) constructor in the static initialization block.) Therefore, we can tell that each enum field that we create will be at least as much as the overhead of creating an object in the JVM. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/143285",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
143,296 | I've got such a simple code: <div class="div1"> <div class="div2">Foo</div> <div class="div3"> <div class="div4"> <div class="div5"> Bar </div> </div> </div></div> and this CSS: .div1{ position: relative;}.div1 .div3 { position: absolute; top: 30px; left: 0px; width: 250px; display: none;}.div1:hover .div3 { display: block;}.div2{ width: 200px; height: 30px; background: red;}.div4 { background-color: green; color: #000; }.div5 {} The problem is: When I move the cursor from .div2 to .div3 ( .div3 should stay visible because it's the child of .div1 ) then the hover is disabled. I'm testing it in IE7, in FF it works fine. What am I doing wrong? I've also realized that when i remove .div5 tag than it's working. Any ideas? | IE7 won't allow you to apply :hover pseudo-classes to non-anchor elements unless you explicitly specify a doctype. Just add a doctype declaration to your page and it should work perfectly. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> More on IE7/quirks mode can be found on this blog post . | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/143296",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20403/"
]
} |
143,367 | Simple question - I've got a bucketload of cruddy html pages to clean up and I'm looking for a open source or freeware script/utility to remove any junk and reformat them into nicely laid out consistent code. Any recommendations? If it's relevant I generally manipulate HTML inside Dreamweaver - but by editing the code and using the wysiwyg window as preview rather than vica-versa - so a Dreamweaver compatible script would be a plus. | I don't think it plugs into Dreamweaver but whenever i need html cleaned up HTML Tidy is my go to guy | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/143367",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7315/"
]
} |
143,374 | A long time ago I had an apple ][ . I remember the command call – 151 But I can not remember what it did ? | CALL -151 Enter the machine code monitor - http://www.skepticfiles.org/cowtext/apple/memorytx.htm Update: That link appears to be dead, here's a Wayback Machine alternative: http://web.archive.org/web/20090315100335/http://www.skepticfiles.org/cowtext/apple/memorytx.htm Here's the full article just in case Wayback goes away: APPLE CALL, PEEK, POKE LIST CALL 144 SCAN THE INPUT BUFFER CALL 151 ENTER THE MONITOR NORM APPLE CALL, PEEK, POKE LIST------------------------------------------------------------------------------CALL -144 SCAN THE INPUT BUFFERCALL -151 ENTER THE MONITOR NORMALLYCALL -155 ENTER THE MONITOR & SOUND BELLCALL -167 ENTER MONITOR AND RESETCALL -198 RING BELL (SIMULATE CONTROL G)CALL -211 PRINT "ERR" AND RING BELLCALL -259 READ FROM TAPECALL -310 WRITE TO TAPECALL -321 DISPLAYS A, S, Y, P, & S REGISTERSCALL -380 SET NORMAL VIDEO MODECALL -384 SET INVERSE VIDEO MODECALL -415 DISASSEMBLE 20 INSTRUCTIONSCALL -458 VERIFY (COMPARE & LIST DIFFERENCES)CALL -468 MEMORY MOVE AFTER POKING 60,61 OLD START - 62,63 OLD END 64,65 NEW END - 66,67 NEW STARCALL -484 MOVECALL -517 DISPLAY CHARACTER & UPDATE SCREEN LOCATIONCALL -531 DISPLAY CHARACTER, MASK CONTROL CHAR., & SAVE 7 REG. & ACCUCALL -550 DISPLAY HEX VALUE OF A-REGISTER (ACCUMULATOR)CALL -656 RING BELL AND WAIT FOR A CARRIAGE RETURNCALL -657 GET LINE OF INPUT, NO PROMPT, NO L/F, & WAIT(COMMA,COLON OKCALL -662 GET LINE OF INPUT, WITH PROMPT, NO L/F, & WAITCALL -665 GET LINE OF INPUT, WITH PROMPT, LINE FEED, & WAITTHE ABOVE 3 CALLS (-657, -662, -665) REFER TO THE INPUT BUFFER FROM 512-767CALL -715 GET CHARACTERCALL -756 WAIT FOR KEY PRESSCALL -856 TIME DELAY (POKE 69,XX TO SET TIME OF DELAY)CALL -868 CLEARS CURSOR LINE FROM CURSOR TO END OF LINECALL -912 SCROLLS TEXT UP 1 LINECALL -922 LINE FEEDCALL -936 CLEAR SCREEN (HOME)CALL -958 CLEAR SCREEN FROM CURSOR TO BOTTOM OF SCREENCALL -998 MOVES CURSOR UP 1 LINECALL -1008 MOVES CURSOR BACKWARD 1 SPACECALL -1024 DISPLAY CHARACTER ONLYCALL -1036 MOVES CURSOR FORWARD 1 SPACECALL -1063 SEND BELL TO CURRENT OUTPUT DEVICECALL -1216 TEXT & GRAPHICS MODECALL -1233 MOVE CURSOR TO BOTTOM OF SCREENCALL -1321 CONTROL ECALL -1717 MOVES CURSOR DOWN 5 LINESCALL -1840 DISASSEMBLE 1 INSTRUCTIONCALL -1953 CHANGE COLOR BY +3CALL -1994 CLEAR LO-RES SCREEN (TOP 40 LINES)CALL -1998 CLEAR GRAPHIC SCREEN (LO-RES)CALL -2007 VERTICAL LINECALL -2023 HORIZONTAL LINECALL -2458 ENTER MINI ASSEMBLERCALL -3100 TURNS ON HIRES PAGE 1, WITHOUT CLEARING ITCALL -3776 SAVE INTEGERCALL -3973 LOAD INTEGERCALL -6090 RUN INTEGERCALL -8117 LIST INTEGERCALL -8189 ENTER BASIC & CONTINUECALL -8192 ENTER BASIC AND RESET (INTEGER BASIC KILL)CALL -16303 TEXT MODECALL -16304 GRAPHICS MODECALL -16336 TOGGLE SPEAKERCALL 42350 CATALOGS DISKCALL 54915 CLEANS STACK, CLEARS THE "OUT OF MEMORY" ERRORCALL 64166 INITIATES A COLD START (BOOT OF THE DISK)CALL 64246 BRAND NEW-YOU FIGURE IT OUTCALL 64367 SCANS MEMORY LOC 1010 & 1011 & POKES VALUE INTO LOCATIONS 1012 THAT IS EQUAL TO (PEEK(1011)-165)------------------------------------------------------------------------------PEEK 33 WIDTH OF TEXT WINDOW (1-40)PEEK 34 TOP EDGE OF TEXT WINDOW (0-22)PEEK 35 BOTTOM OF TEXT WINDOW (1-24)PEEK 36 HORIZONTAL CURSOR POSITION (0-39)PEEK 37 VERTICAL CURSOR POSITION (0-23)PEEK 43 BOOT SLOT X 16 (AFTER BOOT)PEEK 44 END POINT OF LAST HLIN, VLIN, OR PLOTPEEK 48 LO-RES COLOR VALUE X 17PEEK 50 TEXT OUTPUT FORMAT: 63=INVERSE 255=NORMAL 127=FLASH ( WITH PEEK 243 SET TO 64)PEEK 51 PROMPT CHARACTERPEEK 74,75 LOMEM ADDRESS (INT)PEEK 76,77 HIMEM ADDRESS (INT)PEEK 103,104 FP PROGRAM STARTING ADDRESSPEEK 104 IF 8 IS RETURNED, THEN FP IS IN ROMPEEK 105,106 FP VARIABLE SPACE STARTING ADDRESSPEEK 107,108 FP ARRAY STARTING ADDRESSPEEK 109,110 FP END OF NUMERIC STORAGE ADDRESSPEEK 111,112 FP STRING STORAGE STARTING ADDRESSPEEK 115,116 FP HIMEM ADDRESSPEEK 117,118 FP LINE NUMBER BEING EXECUTEDPEEK 119,120 FP LINE WHERE PROGRAM STOPPEDPEEK 121,122 FP LINE BEING EXECUTED ADDRESSPEEK 123,124 LINE WHERE DATA BEING READPEEK 125,126 DATA LOCATION ADDRESSPEEK 127,128 INPUT OR DATA ADDRESSPEEK 129,130 FP LAST USED VARIABLE NAMEPEEK 131,132 FP LAST USED VARIABLE ADDRESSPEEK 175,176 FP END OF PROGRAM ADDRESSPEEK 202,203 INT PROGRAM STARTING ADDRESSPEEK 204,205 INT END OF VARIABLE STORAGEPEEK 214 FP RUN FLAG (AUTO-RUN IF >127)PEEK 216 ONERR FLAG (>127 IF ONERR IS ACTIVE)PEEK 218,219 LINE WHERE ONERR OCCUREDPEEK 222 ONERR ERROR CODEPEEK 224,225 X-COORDINATE OF LAST HPLOTPEEK 226 Y-COORDINATE OF LAST HPLOTPEEK 228 HCOLOR VALUE 0=0 85=2 128=4 213=6 42=1 127=3 170=5 255=7PEEK 230 HI-RES PLOTING PAGE (32=PAGE 1 64=PAGE 2 96=PAGE 3)PEEK 231 SCALE VALUEPEEK 232,233 SHAPE TABLE STARTING ADDRESSPEEK 234 HI-RES COLLISION COUNTERPEEK 241 256 MINUS SPEED VALUEPEEK 243 FLASH MASK (64=FLASH WHEN PEEK 50 SET TO 127)PEEK 249 ROT VLAUEPEEK 976-978 DOS RE-ENTRY VECTORPEEK 1010-1012 RESET VECTORPEEK 1013-1015 AMPERSAND (&) VECTORPEEK 1016-1018 CONTROL-Y VECTORPEEK 43140-43271 DOS COMMAND TABLEPEEK 43378-43582 DOS ERROR MESSAGE TABLEPEEK 43607 MAXFILES VALUEPEEK 43616,46617 LENGTH OF LAST BLOADPEEK 43624 DRIVE NUMBERPEEK 43626 SLOT NUMBERPEEK 43634,43635 STARTING ADDRESS OF LAST BLOADPEEK 43697 MAXFILES DEFAULT VALUEPEEK 43698 DOS COMMAND CHARACTERPEEK 43702 BASIC FLAG (0=INT 64=FP ROM 128=FP RAM)PEEK 44033 CATALOG TRACK NUMBER (17 IS STANDARD)PEEK 44567 NUMBER OF CHARACTERS MINUS 1 IN CATALOG FILE NAMESPEEK 44611 NUMBER OF DIGITS MINUS 1 IN SECTOR AND VOLUME NUMBERSPEEK 45991-45998 FILE-TYPE CODE TABLEPEEK 45999-46010 DISK VOLUME HEADINGPEEK 46017 DISK VOLUME NUMBERPEEK 46064 NUMBER OF SECTORS (13=DOS 3.2 16=DOS 3.3)PEEK 49152 READ KEYBOARD (IF >127 THEN KEY HAS BEEN PRESSEDPEEK 49200 TOGGLE SPEAKER (CLICK)PEEK 49248 CASSETTE INPUT (>127=BINARY 1, 127 IF BUTTON PRESSED)PEEK 49250 PADDLE 1 BUTTON (>127 IF BUTTON PRESSGD)PEEK 49251 PADDLE 2 BUTTON (>127 IF BUTTON PRESSED)PEEK 49252 READ GAME PADDLE 0 (0-255)PEEK 49253 READ GAME PADDLE 1 (0-255)PEEK 49254 READ GAME PADDLE 2 (0-255)PEEK 49255 READ GAME PADDLE 3 (0-255)PEEK 49408 READ SLOT 1PEEK 49664 READ SLOT 2PEEK 49920 READ SLOT 3PEEK 50176 READ SLOT 4PEEK 50432 READ SLOT 5PEEK 50688 READ SLOT 6 (162=DISK CONROLLOR CARD)PEEK 50944 READ SLOT 7PEEK 64899 INDICATES WHICH COMPUTER YOU'RE USING 223=APPLE II OR II+, 234=FRANKLIN ACE OR ?, 255=APPLE IIEPOKE 33,33 SCRUNCH LISTING AND REMOVE SPACES IN QUOTE STATEMENTSPOKE 36,X USE AS PRINTER TAB (X=TAB - 1)POKE 50,128 MAKES ALL OUTPUT TO THE SCREEN INVISIBLEPOKE 50,RANDOM SCRAMBLES OUTPUT TO SCREENPOKE 51,0 DEFEATS "NOT DIRECT COMMAND", SOMETIMES DOESN'T WORKPOKE 82,128 MAKE CASETTE PROGRAM AUTO-RUN WHEN LOADEDPOKE 214,255 SETS RUN FLAG IN FP & ANY KEY STROKES WILL RUN DISK PROGRAPOKE 216,0 CANCEL ONERR FLAGPOKE 1010,3 SETS THE RESET VECTOR TO INITIATEPOKE 1011,150 A COLD START (BOOT)POKE 1010,102 MAKEPOKE 1011,213 RESETPOKE 1012,112 RUNPOKE 1014,165 SETS THE AMPERSAND (&) VECTORPOKE 1015,214 TO LIST YOUR PROGRAMPOKE 1014,110 SETS THE AMPERSAND (&) VECTORPOKE 1015,165 TO CATALOG A DISKPOKE 1912+SLOT,1 ON APPLE PARALLEL CARD (WITH P1-02 PROM) WILL ENABLE L/F'SPOKE 1912+SLOT,0 ON APPLE PARALLEL CARD (WITH P1-02 PROM) WILL ENABLE L/F'SPOKE 2049,1 THIS WILL CAUSE THE FIRST LINE OF PROGRAM TO LIST REPEATEDLYPOKE 40514,20 ALLOWS TEXT FILE GREETING PROGRAMPOKE 40514,52 ALLOWS BINARY FILE GREETING PROGRAMPOKE 40993,24 THIS ALLOWSPOKE 40994,234 DISK COMMANDS INPOKE 40995,234 THE DIRECT MODEPOKE 42319,96 DISABLES THE INIT COMMANDPOKE 42768,234 CANCEL ALLPOKE 42769,234 DOS ERRORPOKE 42770,234 MESSAGESPOKE 43624,X SELECTS DISK DRIVE WITHOUT EXECUTING A COMMAND (48K SYSTEM)POKE 43699,0 TURNS AN EXEC FILE OFF BUT LEAVES IT OPEN UNTIL A FP, CLOSEPOKE 43699,1 TURNS AN EXEC FILE BACK ON. INIT, OR MAXFILES IS ISSUEPOKE 44452,24 ALLOWS 20 FILE NAMES (2 EXTRA)POKE 44605,23 BEFORE CATALOG PAUSEPOKE 44505,234 REVEALS DELETED FILEPOKE 44506,234 NAMES IN CATALGPOKE 44513,67 CATALOG WILL RETURN ONLY LOCKED FILESPOKE 44513,2 RETURN CATALOG TO NORMALPOKE 44578,234 CANCEL CARRIAGEPOKE 44579,234 RETURNS AFTER CATALOGPOKE 44580,234 FILE NAMESPOKE 44596,234 CANCELPOKE 44597,234 CATALOG-STOPPOKE 44598,234 WHEN SCREEN IS FULLPOKE 44599,234 STOP CATALOG AT EACH FILEPOKE 44600,234 NAME AND WAIT FOR A KEYPRESSPOKE 46922,96 THIS ALLOWS DISKPOKE 46923,234 INITIALATIONPOKE 46924,234 WITHOUT PUTTINGPOKE 44723,4 DOS ON THE DISKPOKE 49107,234 PREVENT LANGUAGEPOKE 49108,234 CARD FROM LOADINGPOKE 49109,234 DURING RE-BOOTPOKE 49168,0 CLEAR KEYBOARDPOKE 49232,0 DISPLAY GRAPHICSPOKE 49233,0 DISPLAY TEXTPOKE 49234,0 DISPLAY FULL GRAPHICSPOKE 49235,0 DISPLAY TEXT/GRAPHICSPOKE 49236,0 DISPLAY GRAPHICS PAGE 1POKE 49237,0 DISPLAY GRAPHICS PAGE 2POKE 49238,0 DISPLAY LORESPOKE 49239,0 DISPLAY HIRES------------------------------------------------------------------------------ 48K MEMORY MAP DECIMAL HEX USAGE------------------------------------------------------------------------------ 0-255 $0-$FF ZERO-PAGE SYSTEM STORAGE 256-511 $100-$1FF SYSTEM STACK 512-767 $200-$2FF KEYBOARD CHARACTER BUFFER 768-975 $300-$3CF OFTEN AVAILABLE AS FREE SPACE FOR USER PROGRAMS 976-1023 $3D0-3FF SYSTEM VECTORS 1024-2047 $400-$7FF TEXT AND LO-RES GRAPHICS PAGE 1 2048-LOMEM $800-LOMEM PROGRAM STORAGE 2048-3071 $800-$BFF TEXT AND LO-RES GRAPHICS PAGE 2 OR FREE SPACE 3072-8191 $C00-$1FFF FREE SPACE UNLESS RAM APPLESOFT IS IN USE 8192-16383 $2000-$3FFF HI-RES PAGE 1 OR FREE SPACE16384-24575 $4000-$5FFF HI-RES PAGE 2 OR FREE SPACE24576-38999 $6000-$95FF FREE SPACE AND STRING STORAGE38400-49151 $9600-$BFFF DOS49152-53247 $C000-$CFFF I/O HARDWARE (RESERVED)53248-57343 $D000-$DFFF APPLESOFT IN LANGUAGE CARD OR ROM57344-63487 $E000-$F7FF APPLESOFT OR INTEGER BASIC IN LANGUAGE CARD OR ROM63488-65535 $F800-$FFFF SYSTEM MONITORPEEK: TO EXAMINE ANY MEMORY LOCATION L, PRINT PEEK (L), WHERE L IS A DECIMALNUMBER 0-65535. TO PEEK AT A TWO-BYTE NUMBER AT CONSEQUTIVE LOCATIONS L ANDL+1, PRINT PEEK (L) + PEEK (L+1) * 256POKE: TO ASSIGN A VALUE X (0-255) TO LOCATION L; POKE L,X. TO POKE A TWO-BYTNUMBER (NECESSARY IF X>255), POKE L,X-INT(X/256)*256, AND POKE L+1,INT(X/256).CALL: TO EXECUTE A MACHINE LANGUAGE SUB ROUTINE AT LOCATION L, CALL L.JUST FOR FUN TRY THIS: POKE 33,90. THEN TRY LISTING YOUR PROGRAM. OR TRY:0,99 OR POKE 50,250 OR POKE 50,127. USE RESET TO RETURN TO NORMAL.FOR TRUE RANDOM NUMBER GENERATION TRY THIS:X= RND(PEEK(78)+PEEK(79)*256)TO LOCATE THE STARTING ADDRESS OF THE LAST BLOADED FILE USE: PEEK(-21902)+PEEK(-21901)*256 (RESULT IS IN HEX)TO DETERMINE THE LENGTH OF THE LAST BLOADED FILE USE: PEEK(-21920)+PEEK(-21919*256 (RESULT IS IN HEX)TO DETERMINE THE LINE NUMBER THAT CAUSED AN ERROR TO OCCUR, SET X TO: PEEK(218+PEEK(219)*256------------------------------------------------------------------------------E-Mail Fredric L. Rice / The Skeptic Tank | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/143374",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17560/"
]
} |
143,390 | I'm now in search for a Java Text to Speech (TTS) framework. During my investigations I've found several JSAPI1.0-(partially)-compatible frameworks listed on JSAPI Implementations page , as well as a pair of Java TTS frameworks which do not appear to follow JSAPI spec ( Mary , Say-It-Now ). I've also noted that currently no reference implementation exists for JSAPI. Brief tests I've done for FreeTTS (first one listed in JSAPI impls page) show that it is far from reading simple and obvious words (examples: ABC, blackboard). Other tests are currently in progress. And here goes the question (6, actually): Which of the Java-based TTS frameworks have you used? Which ones, by your opinion, are capable of reading the largest wordbase? What about their voice quality? What about their performance? Which non-Java frameworks with Java bindings are there on the scene? Which of them would you recommend? Thank you in advance for your comments and suggestions. | I've actually had pretty good luck with FreeTTS | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/143390",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17707/"
]
} |
143,405 | What are the differences in implementing interfaces implicitly and explicitly in C#? When should you use implicit and when should you use explicit? Are there any pros and/or cons to one or the other? Microsoft's official guidelines (from first edition Framework Design Guidelines ) states that using explicit implementations are not recommended , since it gives the code unexpected behaviour. I think this guideline is very valid in a pre-IoC-time , when you don't pass things around as interfaces. Could anyone touch on that aspect as well? | Implicit is when you define your interface via a member on your class. Explicit is when you define methods within your class on the interface. I know that sounds confusing but here is what I mean: IList.CopyTo would be implicitly implemented as: public void CopyTo(Array array, int index){ throw new NotImplementedException();} and explicitly as: void ICollection.CopyTo(Array array, int index){ throw new NotImplementedException();} The difference is that implicit implementation allows you to access the interface through the class you created by casting the interface as that class and as the interface itself. Explicit implementation allows you to access the interface only by casting it as the interface itself. MyClass myClass = new MyClass(); // Declared as concrete classmyclass.CopyTo //invalid with explicit((IList)myClass).CopyTo //valid with explicit. I use explicit primarily to keep the implementation clean, or when I need two implementations. Regardless, I rarely use it. I am sure there are more reasons to use/not use explicit that others will post. See the next post in this thread for excellent reasoning behind each. | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/143405",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2429/"
]
} |
143,420 | Does anyone know how to modify an existing import specification in Microsoft Access 2007 or 2010? In older versions there used to be an Advanced button presented during the import wizard that allowed you to select and edit an existing specification. I no longer see this feature but hope that it still exists and has just been moved somewhere else. | I am able to use this feature on my machine using MS Access 2007. On the Ribbon, select External Data Select the "Text File" option This displays the Get External Data Wizard Specify the location of the file you wish to import Click OK. This displays the "Import Text Wizard" On the bottom of this dialog screen is the Advanced button you referenced Clicking on this button should display the Import Specification screen and allow you to select and modify an existing import spec. For what its worth, I'm using Access 2007 SP1 | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/143420",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
143,429 | We all know that commenting our code is an important part of coding style for making our code understandable to the next person who comes along, or even ourselves in 6 months or so. However, sometimes a comment just doesn't cut the mustard. I'm not talking about obvious jokes or vented frustraton, I'm talking about comments that appear to be making an attempt at explanation, but do it so poorly they might as well not be there. Comments that are too short , are too cryptic , or are just plain wrong . As a cautonary tale, could you share something you've seen that was really just that bad , and if it's not obvious, show the code it was referring to and point out what's wrong with it? What should have gone in there instead? See also: When NOT to comment your code How do you like your comments? (Best Practices) What is the best comment in source code you have ever encountered? | Just the typical Comp Sci 101 type comments: $i = 0; //set i to 0$i++; //use sneaky trick to add 1 to i!if ($i==$j) { // I made sure to use == rather than = here to avoid a bug That sort of thing. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/143429",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21632/"
]
} |
143,484 | I want to change the title showing in a page based on information I pick up from within the page (eg to show the number of inbox messages) document.getElementsByTagName('title')[0].innerHTML="foo"; does change the title tag, but firefox does not update the displayed title (in window and tags) when this happens. Is this possible? | Try using this instead: document.title = "MyTitle"; | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/143484",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7473/"
]
} |
143,486 | I've recently read the Yahoo manifesto Best Practices for Speeding Up Your Web Site . They recommend to put the JavaScript inclusion at the bottom of the HTML code when we can. But where exactly and when? Should we put it before closing </html> or after ? And above all, when should we still put it in the <head> section? | There are two possibilities for truly unobtrusive scripts: including an external script file via a script tag in the head section including an external script file via a script tag at the bottom of the body (before </body></html> ) The second one can be faster as the original Yahoo research showed some browsers try to load script files when they hit the script tag and therefore don't load the rest of the page until they have finished. However, if your script has a 'ready' portion which must execute as soon as the DOM is ready you may need to have it in the head. Another issue is layout - if your script is going to change the page layout you want it loaded as early as possible so your page does not spend a long time redrawing itself in front of your users. If the external script site is on another domain (like external widgets) it may be worth putting it at the bottom to avoid it delaying loading of the page. And for any performance issues do your own benchmarks - what may be true at one time when a study is done might change with your own local setup or changes in browsers. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/143486",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9951/"
]
} |
143,487 | I'm using netbeans on ubuntu, I would like to add some fonts to it. Could anyone tell me how this is done ? | There are two possibilities for truly unobtrusive scripts: including an external script file via a script tag in the head section including an external script file via a script tag at the bottom of the body (before </body></html> ) The second one can be faster as the original Yahoo research showed some browsers try to load script files when they hit the script tag and therefore don't load the rest of the page until they have finished. However, if your script has a 'ready' portion which must execute as soon as the DOM is ready you may need to have it in the head. Another issue is layout - if your script is going to change the page layout you want it loaded as early as possible so your page does not spend a long time redrawing itself in front of your users. If the external script site is on another domain (like external widgets) it may be worth putting it at the bottom to avoid it delaying loading of the page. And for any performance issues do your own benchmarks - what may be true at one time when a study is done might change with your own local setup or changes in browsers. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/143487",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11234/"
]
} |
143,552 | In MySQL, If I have a list of date ranges (range-start and range-end). e.g. 10/06/1983 to 14/06/198315/07/1983 to 16/07/198318/07/1983 to 18/07/1983 And I want to check if another date range contains ANY of the ranges already in the list, how would I do that? e.g. 06/06/1983 to 18/06/1983 = IN LIST10/06/1983 to 11/06/1983 = IN LIST14/07/1983 to 14/07/1983 = NOT IN LIST | This is a classical problem, and it's actually easier if you reverse the logic. Let me give you an example. I'll post one period of time here, and all the different variations of other periods that overlap in some way. |-------------------| compare to this one |---------| contained within |----------| contained within, equal start |-----------| contained within, equal end |-------------------| contained within, equal start+end |------------| not fully contained, overlaps start |---------------| not fully contained, overlaps end |-------------------------| overlaps start, bigger |-----------------------| overlaps end, bigger |------------------------------| overlaps entire period on the other hand, let me post all those that doesn't overlap: |-------------------| compare to this one |---| ends before |---| starts after So if you simple reduce the comparison to: starts after endends before start then you'll find all those that doesn't overlap, and then you'll find all the non-matching periods. For your final NOT IN LIST example, you can see that it matches those two rules. You will need to decide wether the following periods are IN or OUTSIDE your ranges: |-------------| |-------| equal end with start of comparison period |-----| equal start with end of comparison period If your table has columns called range_end and range_start, here's some simple SQL to retrieve all the matching rows: SELECT *FROM periodsWHERE NOT (range_start > @check_period_end OR range_end < @check_period_start) Note the NOT in there. Since the two simple rules finds all the non-matching rows, a simple NOT will reverse it to say: if it's not one of the non-matching rows, it has to be one of the matching ones . Applying simple reversal logic here to get rid of the NOT and you'll end up with: SELECT *FROM periodsWHERE range_start <= @check_period_end AND range_end >= @check_period_start | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/143552",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5777/"
]
} |
143,571 | I'm building my first ASP.NET MVC application and I am having some troubles with Partial Views. If I, as an example, want to put a "Footer" as a Partial I create an "MVC View User Control" in "/Views/Shared/Footer.ascx". (I leave it empty for now) What is the correct way for adding it to my Layout? I have tried: <%=Html.RenderPartial("Footer")%> and: <%=Html.RenderPartial("~/Views/Shared/Footer.ascx")%> For each one I get an exception: "CS1502: The best overloaded method match for 'System.IO.TextWriter.Write(char)' has some invalid arguments" What is the correct way to deal with partials in ASP.NET MVC? | In this case don't use the <%= syntax. Just use the <% %> syntax. Then the first form in your examples should work. For more info, check here: http://bradwilson.typepad.com/blog/2008/08/partial-renderi.html | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/143571",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
143,622 | This may seem like a programming 101 question and I had thought I knew the answer but now find myself needing to double check. In this piece of code below, will the exception thrown in the first catch block then be caught by the general Exception catch block below? try { // Do something} catch(IOException e) { throw new ApplicationException("Problem connecting to server");} catch(Exception e) { // Will the ApplicationException be caught here?} I always thought the answer would be no, but now I have some odd behaviour that could be caused by this. The answer is probably the same for most languages but I'm working in Java. | No, since the new throw is not in the try block directly. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/143622",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/270/"
]
} |
143,708 | Is it possible that Microsoft will be able to make F# programs, either at VM execution time, or more likely at compile time, detect that a program was built with a functional language and automatically parallelize it better? Right now I believe there is no such effort to try and execute a program that was built as single threaded program as a multi threaded program automatically. That is to say, the developer would code a single threaded program. And the compiler would spit out a compiled program that is multi-threaded complete with mutexes and synchronization where needed. Would these optimizations be visible in task manager in the process thread count, or would it be lower level than that? | I think this is unlikely in the near future. And if it does happen, I think it would be more likely at the IL level (assembly rewriting) rather than language level (e.g. something specific to F#/compiler). It's an interesting question, and I expect that some fine minds have been looking at this and will continue to look at this for a while, but in the near-term, I think the focus will be on making it easier for humans to direct the threading/parallelization of programs, rather than just having it all happen as if by magic. (Language features like F# async workflows , and libraries like the task-parallel library and others , are good examples of near-term progress here; they can do most of the heavy lifting for you, especially when your program is more declarative than imperative, but they still require the programmer to opt-in, do analysis for correctness/meaningfulness, and probably make slight alterations to the structure of the code to make it all work.) Anyway, that's all speculation; who can say what the future will bring? I look forward to finding out (and hopefully making some of it happen). :) | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/143708",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3153/"
]
} |
143,712 | Is there a way of comparing two bitmasks in Transact-SQL to see if any of the bits match? I've got a User table with a bitmask for all the roles the user belongs to, and I'd like to select all the users that have any of the roles in the supplied bitmask. So using the data below, a roles bitmask of 6 (designer+programmer) should select Dave, Charlie and Susan, but not Nick. User Table----------ID Username Roles1 Dave 62 Charlie 23 Susan 44 Nick 1Roles Table-----------ID Role1 Admin2 Programmer4 Designer Any ideas? Thanks. | The answer to your question is to use the Bitwise & like this: SELECT * FROM UserTable WHERE Roles & 6 != 0 The 6 can be exchanged for any combination of your bitfield where you want to check that any user has one or more of those bits. When trying to validate this I usually find it helpful to write this out longhand in binary. Your user table looks like this: 1 2 4------------------Dave 0 1 1Charlie 0 1 0Susan 0 0 1 Nick 1 0 0 Your test (6) is this 1 2 4------------------Test 0 1 1 If we go through each person doing the bitwaise And against the test we get these: 1 2 4------------------Dave 0 1 1 Test 0 1 1Result 0 1 1 (6)Charlie 0 1 0Test 0 1 1Result 0 1 0 (2)Susan 0 0 1Test 0 1 1Result 0 0 1 (4)Nick 1 0 0Test 0 1 1Result 0 0 0 (0) The above should demonstrate that any records where the result is not zero has one or more of the requested flags. Edit: Here's the test case should you want to check this with test (id, username, roles)AS( SELECT 1,'Dave',6 UNION SELECT 2,'Charlie',2 UNION SELECT 3,'Susan',4 UNION SELECT 4,'Nick',1)select * from test where (roles & 6) != 0 // returns dave, charlie & susan or select * from test where (roles & 2) != 0 // returns Dave & Charlie or select * from test where (roles & 7) != 0 // returns dave, charlie, susan & nick | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/143712",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14072/"
]
} |
143,714 | In PHP, a string enclosed in "double quotes" will be parsed for variables to replace whereas a string enclosed in 'single quotes' will not. In Python, does this also apply? | No : 2.4.1. String and Bytes literals ...In plain English: Both types of literals can be enclosed in matching single quotes ( ' ) or double quotes ( " ). They can also be enclosed in matching groups of three single or double quotes (these are generally referred to as triple-quoted strings). The backslash ( \ ) character is used to escape characters that otherwise have a special meaning, such as newline, backslash itself, or the quote character... | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/143714",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2183/"
]
} |
143,745 | One thing that's really been making life difficult in getting up to speed on the codebase on an ASP classic project is that the include file situation is kind of a mess. I sometimes find the function I was looking for being included in an include file that is totally unrelated. Does anyone have any advice on how to refactor this such that one can more easily tell where a function is if they need to find it? EDIT: One thing I forgot to ask: does vbscript have any kind of mechanism for preventing a file from being included twice? Sorta like #ifndef's from C? | There are a few basic things you can do when taking over a classic ASP application, but you will probably end up regretting doing them. Eliminate duplicate include files . Every classic ASP app I've ever seen has had 5 "login.asp" pages and 7 "datepicker.js" files and so forth. Hunt down and remove all the duplicates, and then change references in the rest of the app as necessary. Be careful to do a diff check on each file as you remove it - often the duplicated files have slight differences because the original author copied it and then changed just the copy. This is a great thing for Evolution, but not so much for code. Create a rational folder structure and move all the files into it. This one is obvious, but it's the one you will most regret doing. Whether the links in the application are relative or absolute, you'll have to change most of them. Combine all of your include files into one big file . You can then re-order all the functions logically and break them up into separate, sensibly-named files. You'll then have to go through the app page by page and figure out what the include statements on each page need to be (or stick with the one file, and just include it on every page - I can't remember whether or not that's a good idea in ASP). I can't comprehend the pain level involved here, and that's assuming that the existing include files don't make heavy use of same-named globals. I wouldn't do any of this. To paraphrase Steve Yegge (I think), " there's nothing wrong with a classic ASP application that can't be fixed with a total rewrite ". I'm very serious about this - I don't think there's a bigger waste of a programmer's time in this world than maintaining an ASP app, and the problem just gets worse as ASP gets more and more out of date. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/143745",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2147/"
]
} |
143,747 | I'm writing some JavaScript code that needs to fire the click event for a link. In Internet Explorer I can do this var button = document.getElementById('myButton');button.click(); But this doesn't work in Firefox, and I assume any other browser. In Firefox, I've done this var button = document.getElementById('myButton');window.location = button.href; I feel like this is not the best way to do this. Is there a better way to trigger a click event? Preferably something that works regardless of the type of element or the browser. | http://jehiah.cz/archive/firing-javascript-events-properly function fireEvent(element,event) { if (document.createEvent) { // dispatch for firefox + others var evt = document.createEvent("HTMLEvents"); evt.initEvent(event, true, true ); // event type,bubbling,cancelable return !element.dispatchEvent(evt); } else { // dispatch for IE var evt = document.createEventObject(); return element.fireEvent('on'+event,evt) }} | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/143747",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/392/"
]
} |
143,756 | I need to rename the database but when I do in PGAdmin : ALTER DATABASE "databaseName" RENAME TO "databaseNameOld" it told me that it cannot. How can I do it? ( Version 8.3 on WindowsXP ) Update The first error message : Cannot because I was connect to it. So I selected an other database and did the queries. I get a second error message telling me that it has come user connect. I see in the PGAdmin screen that it has many PID but they are inactive... I do not see how to kill them. | Try not quoting the database name: ALTER DATABASE people RENAME TO customers; Also ensure that there are no other clients connected to the database at the time. Lastly, try posting the error message it returns so we can get a bit more information. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/143756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13913/"
]
} |
143,808 | We have fairly large C++ application which is composed of about 60 projects in Visual Studio 2005. It currently takes 7 minutes to link in Release mode and I would like to try to reduce the time. Are there any tips for improving the link time? Most of the projects compile to static libraries, this makes testing easier since each one also has a set of associated unit tests. It seems the use of static libraries prevents VS2005 from using incremental linking, so even with incremental linking turned on it does a full link every time. Would using DLLs for the sub projects make any difference? I don't really want to go through all the headers and add macros to export the symbols (even using a script) but if it would do something to reduce the 7 minute link time I will certainly consider it. For some reason using nmake from the command line is slightly faster and linking the same application on Linux (with GCC) is much faster. Visual Studio IDE 7 minutes Visual C++ using nmake from the command line - 5 minutes GCC on Linux 34 seconds | If you're using the /GL flag to enable Whole Program Optimization (WPO) or the /LTCG flag to enable Link Time Code Generation, turning them off will improve link times significantly, at the expense of some optimizations. Also, if you're using the /Z7 flag to put debug symbols in the .obj files, your static libraries are probably huge. Using /Zi to create separate .pdb files might help if it prevents the linker from reading all of the debug symbols from disk. I'm not sure if it actually does help because I have not benchmarked it. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/143808",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5022/"
]
} |
143,815 | Can I use JavaScript to check (irrespective of scrollbars) if an HTML element has overflowed its content? For example, a long div with small, fixed size, the overflow property set to visible, and no scrollbars on the element. | Normally, you can compare the client[Height|Width] with scroll[Height|Width] in order to detect this... but the values will be the same when overflow is visible. So, a detection routine must account for this: // Determines if the passed element is overflowing its bounds,// either vertically or horizontally.// Will temporarily modify the "overflow" style to detect this// if necessary.function checkOverflow(el){ var curOverflow = el.style.overflow; if ( !curOverflow || curOverflow === "visible" ) el.style.overflow = "hidden"; var isOverflowing = el.clientWidth < el.scrollWidth || el.clientHeight < el.scrollHeight; el.style.overflow = curOverflow; return isOverflowing;} Tested in FF3, FF40.0.2, IE6, Chrome 0.2.149.30. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/143815",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
143,822 | this wiki page gave a general idea of how to convert a single char to ascii http://en.wikibooks.org/wiki/Ruby_Programming/ASCII But say if I have a string and I wanted to get each character's ascii from it, what do i need to do? "string".each_byte do |c| $char = c.chr $ascii = ?char puts $asciiend It doesn't work because it's not happy with the line $ascii = ?char syntax error, unexpected '?' $ascii = ?char ^ | The c variable already contains the char code! "string".each_byte do |c| puts cend yields 115116114105110103 | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/143822",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2668/"
]
} |
143,847 | What is the best way to find if an object is in an array? This is the best way I know: function include(arr, obj) { for (var i = 0; i < arr.length; i++) { if (arr[i] == obj) return true; }}console.log(include([1, 2, 3, 4], 3)); // trueconsole.log(include([1, 2, 3, 4], 6)); // undefined | As of ECMAScript 2016 you can use includes() arr.includes(obj); If you want to support IE or other older browsers: function include(arr,obj) { return (arr.indexOf(obj) != -1);} EDIT:This will not work on IE6, 7 or 8 though. The best workaround is to define it yourself if it's not present: Mozilla's (ECMA-262) version: if (!Array.prototype.indexOf) { Array.prototype.indexOf = function(searchElement /*, fromIndex */) { "use strict"; if (this === void 0 || this === null) throw new TypeError(); var t = Object(this); var len = t.length >>> 0; if (len === 0) return -1; var n = 0; if (arguments.length > 0) { n = Number(arguments[1]); if (n !== n) n = 0; else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) n = (n > 0 || -1) * Math.floor(Math.abs(n)); } if (n >= len) return -1; var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0); for (; k < len; k++) { if (k in t && t[k] === searchElement) return k; } return -1; }; } Daniel James 's version: if (!Array.prototype.indexOf) { Array.prototype.indexOf = function (obj, fromIndex) { if (fromIndex == null) { fromIndex = 0; } else if (fromIndex < 0) { fromIndex = Math.max(0, this.length + fromIndex); } for (var i = fromIndex, j = this.length; i < j; i++) { if (this[i] === obj) return i; } return -1; }; } roosteronacid 's version: Array.prototype.hasObject = ( !Array.indexOf ? function (o) { var l = this.length + 1; while (l -= 1) { if (this[l - 1] === o) { return true; } } return false; } : function (o) { return (this.indexOf(o) !== -1); } ); | {
"score": 11,
"source": [
"https://Stackoverflow.com/questions/143847",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17533/"
]
} |
143,850 | let's say we have a c++ class like: class MyClass{ void processArray( <an array of 255 integers> ) { int i ; for (i=0;i<255;i++) { // do something with values in the array } }} and one instance of the class like: MyClass myInstance ; and 2 threads which call the processArray method of that instance (depending on how system executes threads, probably in a completely irregular order). There is no mutex lock used in that scope so both threads can enter. My question is what happens to the i ? Does each thread scope has it's own "i" or would each entering thread modify i in the for loop, causing i to be changing weirdly all the time. | i is allocated on the stack. Since each thread has its own separate stack, each thread gets its own copy of i . | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/143850",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23000/"
]
} |
143,872 | I am writing a data conversion in PL/SQL that processes data and loads it into a table. According to the PL/SQL Profiler, one of the slowest parts of the conversion is the actual insert into the target table. The table has a single index. To prepare the data for load, I populate a variable using the rowtype of the table, then insert it into the table like this: insert into mytable values r_myRow; It seems that I could gain performance by doing the following: Turn logging off during the insert Insert multiple records at once Are these methods advisable? If so, what is the syntax? | It's much better to insert a few hundred rows at a time, using PL/SQL tables and FORALL to bind into insert statement. For details on this see here . Also be careful with how you construct the PL/SQL tables. If at all possible, prefer to instead do all your transforms directly in SQL using "INSERT INTO t1 SELECT ..." as doing row-by-row operations in PL/SQL will still be slower than SQL. In either case, you can also use direct-path inserts by using INSERT /*+APPEND*/ , which basically bypasses the DB cache and directly allocates and writes new blocks to data files. This can also reduce the amount of logging, depending on how you use it. This also has some implications, so please read the fine manual first. Finally, if you are truncating and rebuilding the table it may be worthwhile to first drop (or mark unusable) and later rebuild indexes. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/143872",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20625/"
]
} |
143,925 | I want to be able to run a single spec file's tests — for the one file I'm editing, for example. rake spec executes all the specs. My project is not a Rails project, so rake spec:doc doesn't work. Don't know if this matters, but here is my directory structure. ./Rakefile./lib./lib/cushion.rb./lib/cushion./lib/cushion/doc.rb./lib/cushion/db.rb./spec./spec/spec.opts./spec/spec_helper.rb./spec/db_spec.rb | Or you can skip rake and use the 'rspec' command: bundle exec rspec path/to/spec/file.rb In your case I think as long as your ./spec/db_spec.rb file includes the appropriate helpers, it should work fine. If you're using an older version of rspec it is: bundle exec spec path/to/spec/file.rb | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/143925",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12887/"
]
} |
143,997 | In Jesse Liberty's Learning C# book, he says "Objects of one type can be converted into objects of another type. This is called casting." If you investigate the IL generated from the code below, you can clearly see that the casted assignment isn't doing the same thing as the converted assignment. In the former, you can see the boxing/unboxing occurring; in the latter you can see a call to a convert method. I know in the end it may be just a silly semantic difference--but is casting just another word for converting. I don't mean to be snarky, but I'm not interested in anyone's gut feeling on this--opinions don't count here! Can anyone point to a definitive reference that confirms or denies if casting and converting are the same thing? object x; int y; x = 4; y = ( int )x; y = Convert.ToInt32( x ); Thank you rp Note added after Matt's comment about explicit/implicit: I don't think implicit/explicit is the difference. In the code I posted, the change is explicit in both cases. An implicit conversion is what occurs when you assign a short to an int. Note to Sklivvz: I wanted confirmation that my suspicion of the looseness of Jesse Liberty's (otherwise usually lucid and clear) language was correct. I thought that Jesse Liberty was being a little loose with his language. I understand that casting is routed in object hierarchy--i.e., you can't cast from an integer to a string but you could cast from custom exception derived from System.Exception to a System.Exception. It's interesting, though, that when you do try to cast from an int to a string the compiler tells you that it couldn't "convert" the value. Maybe Jesse is more correct than I thought! | Absolutely not! Convert tries to get you an Int32 via "any means possible". Cast does nothing of the sort. With cast you are telling the compiler to treat the object as Int, without conversion. You should always use cast when you know (by design) that the object is an Int32 or another class that has an casting operator to Int32 (like float, for example). Convert should be used with String, or with other classes. Try this static void Main(string[] args){ long l = long.MaxValue; Console.WriteLine(l); byte b = (byte) l; Console.WriteLine(b); b = Convert.ToByte(l); Console.WriteLine(b);} Result: 9223372036854775807 255 Unhandled Exception: System.OverflowException: Value is greater than Byte.MaxValue or less than Byte.MinValue at System.Convert.ToByte (Int64 value) [0x00000] at Test.Main (System.String[] args) [0x00019] in /home/marco/develop/test/Exceptions.cs:15 | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/143997",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2536/"
]
} |
144,088 | I'm playing with ASP.NET MVC for the last few days and was able to build a small site. Everything works great. Now, I need to pass the page's META tags (title, description, keywords, etc.) via the ViewData. (i'm using a master page). How you're dealing with this? Thank you in advance. | Here is how I am currently doing it... In the masterpage, I have a content place holder with a default title, description and keywords: <head><asp:ContentPlaceHolder ID="cphHead" runat="server"> <title>Default Title</title> <meta name="description" content="Default Description" /> <meta name="keywords" content="Default Keywords" /></asp:ContentPlaceHolder></head> And then in the page, you can override all this content: <asp:Content ID="headContent" ContentPlaceHolderID="cphHead" runat="server"> <title>Page Specific Title</title> <meta name="description" content="Page Specific Description" /> <meta name="keywords" content="Page Specific Keywords" /></asp:Content> This should give you an idea on how to set it up. Now you can put this information in your ViewData (ViewData["PageTitle"]) or include it in your model (ViewData.Model.MetaDescription - would make sense for blog posts, etc) and make it data driven. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/144088",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19610/"
]
} |
144,113 | I'm getting ORA-01031: insufficient privileges when creating a package my own schema. Shouldn't I have complete control over my schema. If this is not the case, what privileges does my schema need? | You may need to have GRANT CREATE PROCEDURE TO USERNAME . | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/144113",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22769/"
]
} |
144,117 | Wondering if there is any Text to Speech software available as a plug in for IE or Firefox. | WebAnywhere is a university project aimed at creating a site that allows you to use text to speech from any browser at any location, without installing anything or using any plugins. You can try it out and see for yourself. I was pretty impressed with it when I first heard of it. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/144117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8091/"
]
} |
144,118 | While trying to generate classes from a xsd, i got this error: java.lang.IllegalArgumentException: Illegal class inheritance loop. Outer class OrderPropertyList may not subclass from inner class: OrderPropertyList My xsd define a element to group a unbounded element like this: <element minOccurs="0" name="orderPropertyList"> <complexType> <sequence> <element maxOccurs="unbounded" name="orderProperty" type="tns:orderProperty" /> </sequence> </complexType> </element> And my customization binding follows as specified on this page , but it doesn´t work.Here my binding: <jaxb:bindings schemaLocation="../xsd/Schema.xsd" node="/xs:schema"> <jaxb:bindings node="//xs:element[@name='orderPropertyList']"> <jaxb:class name="OrderPropertyList"/> </jaxb:bindings></jaxb:bindings> My intention is to generate a individual class for orderPropertyList, not the default behave that is generating a inner class inside the root element of the xsd. I´ve watched someone with the same intention here and here , but it doesn´t work properly for me. :( JAXB version: Specification-Version: 2.1Implementation-Version: 2.1.8 Any help? | I believe what you need to to is set: <jaxb:globalBindings localScoping="toplevel"/> This will generate standalone classes instead of nested classes. Doing <jaxb:bindings schemaLocation="../xsd/Schema.xsd" node="/xs:schema"> <jaxb:bindings node="//xs:element[@name='orderPropertyList']"> <jaxb:class name="OrderPropertyList"/> </jaxb:bindings></jaxb:bindings> is a redundant binding, since orderPropertyList will map by default to OrderPropertyList. The name of the package includes the outer class name it is nested in by default, so you're not changing that. Also, if you did want to change the name of the generated class, I think the XPath would actually be: <jaxb:bindings node="//xs:element[@name='orderPropertyList']/xs:complexType"> with complexType on the end. I think excluding this was what was causing the error message you got. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/144118",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21370/"
]
} |
144,151 | My macro updates a large spreadsheet with numbers, but it runs very slowly as excel is rendering the result as it computes it. How do I stop excel from rendering the output until the macro is complete? | I use both of the proposed solutions: Application.ScreenUpdating = FalseApplication.Calculation = xlCalculationManual.........Application.Calculation = xlCalculationAutomaticApplication.ScreenUpdating = True | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/144151",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5472/"
]
} |
144,176 | I need to convert a (possibly) null terminated array of ascii bytes to a string in C# and the fastest way I've found to do it is by using my UnsafeAsciiBytesToString method shown below. This method uses the String.String(sbyte*) constructor which contains a warning in it's remarks: "The value parameter is assumed to point to an array representing a string encoded using the default ANSI code page (that is, the encoding method specified by Encoding.Default). Note: * Because the default ANSI code page is system-dependent, the string created by this constructor from identical signed byte arrays may differ on different systems. * ... * If the specified array is not null-terminated, the behavior of this constructor is system dependent. For example, such a situation might cause an access violation. * " Now, I'm positive that the way the string is encoded will never change... but the default codepage on the system that my app is running on might change. So, is there any reason that I shouldn't run screaming from using String.String(sbyte*) for this purpose? using System;using System.Text;namespace FastAsciiBytesToString{ static class StringEx { public static string AsciiBytesToString(this byte[] buffer, int offset, int maxLength) { int maxIndex = offset + maxLength; for( int i = offset; i < maxIndex; i++ ) { /// Skip non-nulls. if( buffer[i] != 0 ) continue; /// First null we find, return the string. return Encoding.ASCII.GetString(buffer, offset, i - offset); } /// Terminating null not found. Convert the entire section from offset to maxLength. return Encoding.ASCII.GetString(buffer, offset, maxLength); } public static string UnsafeAsciiBytesToString(this byte[] buffer, int offset) { string result = null; unsafe { fixed( byte* pAscii = &buffer[offset] ) { result = new String((sbyte*)pAscii); } } return result; } } class Program { static void Main(string[] args) { byte[] asciiBytes = new byte[]{ 0, 0, 0, (byte)'a', (byte)'b', (byte)'c', 0, 0, 0 }; string result = asciiBytes.AsciiBytesToString(3, 6); Console.WriteLine("AsciiBytesToString Result: \"{0}\"", result); result = asciiBytes.UnsafeAsciiBytesToString(3); Console.WriteLine("UnsafeAsciiBytesToString Result: \"{0}\"", result); /// Non-null terminated test. asciiBytes = new byte[]{ 0, 0, 0, (byte)'a', (byte)'b', (byte)'c' }; result = asciiBytes.UnsafeAsciiBytesToString(3); Console.WriteLine("UnsafeAsciiBytesToString Result: \"{0}\"", result); Console.ReadLine(); } }} | Any reason not to use the String(sbyte*, int, int) constructor? If you've worked out which portion of the buffer you need, the rest should be simple: public static string UnsafeAsciiBytesToString(byte[] buffer, int offset, int length){ unsafe { fixed (byte* pAscii = buffer) { return new String((sbyte*)pAscii, offset, length); } }} If you need to look first: public static string UnsafeAsciiBytesToString(byte[] buffer, int offset){ int end = offset; while (end < buffer.Length && buffer[end] != 0) { end++; } unsafe { fixed (byte* pAscii = buffer) { return new String((sbyte*)pAscii, offset, end - offset); } }} If this truly is an ASCII string (i.e. all bytes are less than 128) then the codepage problem shouldn't be an issue unless you've got a particularly strange default codepage which isn't based on ASCII. Out of interest, have you actually profiled your application to make sure that this is really the bottleneck? Do you definitely need the absolute fastest conversion, instead of one which is more readable (e.g. using Encoding.GetString for the appropriate encoding)? | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/144176",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16387/"
]
} |
144,201 | I'm looking for a suite of plugins that can help me finally switch over to vim full-time. Right now I'm using Komodo with some good success, but their vim bindings have enough little errors that I'm tired of it. What I do love in Komodo, though, is the code completion. So, here's what I'm looking for (ordered by importance). Code completion, meaning: the ability to code complete modules/functions/etc. in any module that's on the pythonpath, not just system modules . Bonus points for showing docstrings when completing. Jump-to a class definition. I'm guessing CTAGS will do this, so how do you all manage automatically updating your tags files? Project type management for managing buffers: ideally the ability to grep for a filename in a directory structure to open it. Bonus for showing an index of class definitions while a buffer is open. Bzr integration. Not super important, since most of it I can just drop to the shell to do. | Here you can find some info about this. It covers code completion, having a list of classes and functions in open files. I haven't got around to do a full configuration for vim, since I don't use Python primarily, but I have the same interests in transforming vim in a better Python IDE. Edit: The original site is down, so found it saved on the web archive . | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/144201",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1367022/"
]
} |
144,226 | From what I know, the em keyword in CSS means the current size of a font. So if you put 1.2 em, it means 120% of the font height. It doesn't seem right though that em is used for setting the width of divs etc like YUI grids does: margin-right:24.0769em;*margin-right:23.62em; Everytime I read about em, I forget what it really represents. I'm hoping someone can explain it to me so it sticks in my head heeh. | Historically it is the width of an "M" in the font. Hence the name!In CSS2.1 it is defined to be the same as the font-size. In many cases it seems more natural to use em rather than points or pixels, because it is relative to the font size. For example you might define a text-column to have a width of 40em. If you later decide to change the font-size, the column will still keep the same number of letters per line. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/144226",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1368/"
]
} |
144,227 | Is there any C#/F# performance comparison available on web to show proper usage of new F# language? | Natural F# code (e.g. functional/immutable) is slower than natural (imperative/mutable object-oriented) C# code. However, this kind of F# is much shorter than usual C# code. Obviously, there is a trade-off. On the other hand, you can, in most cases, achieve performance of F# code equal to performance of C# code. This will usually require coding in imperative or mutable object-oriented style, profile and remove bottlenecks. You use that same tools that you would otherwise use in C#: e.g. .Net reflector and a profiler. That having said, it pays to be aware of some high-productivity constructs in F# that decrease performance. In my experience I have seen the following cases: references (vs. class instance variables), only in code executed billions of times F# comparison (<=) vs. System.Collections.Generic.Comparer, for example in binary search or sort tail calls -- only in certain cases that cannot be optimized by the compiler or .Net runtime. As noted in the comments, depends on the .Net runtime. F# sequences are twice slower than LINQ. This is due to references and the use of functions in F# library to implement translation of seq<_>. This is easily fixable, as you might replace the Seq module, by one with same signatures that uses Linq, PLinq or DryadLinq. Tuples, F# tuple is a class sorted on the heap. In some case, e.g. a int*int tuple it might pay to use a struct. Allocations, it's worth remembering that a closure is a class, created with the new operator, which remembers the accessed variables. It might be worth to "lift" the closure out, or replaced it with a function that explicitly takes the accessed variables as arguments. Try using inline to improve performance, especially for generic code. My experience is to code in F# first and optimize only the parts that matter. In certain cases, it might be easier to write the slow functions in C# rather that to try to tweak F#. However, from programmer efficiency point of view makes sense to start/prototype in F# then profile, disassemble and optimize. Bottom line is, your F# code might end-up slower than C# because of program design decisions, but ultimately efficiency can be obtained. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/144227",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22016/"
]
} |
144,250 | I am writing an iPhone application and need to essentially implement something equivalent to the 'eyedropper' tool in photoshop, where you can touch a point on the image and capture the RGB values for the pixel in question to determine and match its color. Getting the UIImage is the easy part, but is there a way to convert the UIImage data into a bitmap representation in which I could extract this information for a given pixel? A working code sample would be most appreciated, and note that I am not concerned with the alpha value. | A little more detail... I posted earlier this evening with a consolidation and small addition to what had been said on this page - that can be found at the bottom of this post. I am editing the post at this point, however, to post what I propose is (at least for my requirements, which include modifying pixel data) a better method, as it provides writable data (whereas, as I understand it, the method provided by previous posts and at the bottom of this post provides a read-only reference to data). Method 1: Writable Pixel Information I defined constants #define RGBA 4#define RGBA_8_BIT 8 In my UIImage subclass I declared instance variables: size_t bytesPerRow;size_t byteCount;size_t pixelCount;CGContextRef context;CGColorSpaceRef colorSpace;UInt8 *pixelByteData;// A pointer to an array of RGBA bytes in memoryRPVW_RGBAPixel *pixelData; The pixel struct (with alpha in this version) typedef struct RGBAPixel { byte red; byte green; byte blue; byte alpha;} RGBAPixel; Bitmap function (returns pre-calculated RGBA; divide RGB by A to get unmodified RGB): -(RGBAPixel*) bitmap { NSLog( @"Returning bitmap representation of UIImage." ); // 8 bits each of red, green, blue, and alpha. [self setBytesPerRow:self.size.width * RGBA]; [self setByteCount:bytesPerRow * self.size.height]; [self setPixelCount:self.size.width * self.size.height]; // Create RGB color space [self setColorSpace:CGColorSpaceCreateDeviceRGB()]; if (!colorSpace) { NSLog(@"Error allocating color space."); return nil; } [self setPixelData:malloc(byteCount)]; if (!pixelData) { NSLog(@"Error allocating bitmap memory. Releasing color space."); CGColorSpaceRelease(colorSpace); return nil; } // Create the bitmap context. // Pre-multiplied RGBA, 8-bits per component. // The source image format will be converted to the format specified here by CGBitmapContextCreate. [self setContext:CGBitmapContextCreate( (void*)pixelData, self.size.width, self.size.height, RGBA_8_BIT, bytesPerRow, colorSpace, kCGImageAlphaPremultipliedLast )]; // Make sure we have our context if (!context) { free(pixelData); NSLog(@"Context not created!"); } // Draw the image to the bitmap context. // The memory allocated for the context for rendering will then contain the raw image pixelData in the specified color space. CGRect rect = { { 0 , 0 }, { self.size.width, self.size.height } }; CGContextDrawImage( context, rect, self.CGImage ); // Now we can get a pointer to the image pixelData associated with the bitmap context. pixelData = (RGBAPixel*) CGBitmapContextGetData(context); return pixelData;} Read-Only Data (Previous information) - method 2: Step 1. I declared a type for byte: typedef unsigned char byte; Step 2. I declared a struct to correspond to a pixel: typedef struct RGBPixel{ byte red; byte green; byte blue; } RGBPixel; Step 3. I subclassed UIImageView and declared (with corresponding synthesized properties): // Reference to Quartz CGImage for receiver (self) CFDataRef bitmapData; // Buffer holding raw pixel data copied from Quartz CGImage held in receiver (self) UInt8* pixelByteData;// A pointer to the first pixel element in an array RGBPixel* pixelData; Step 4. Subclass code I put in a method named bitmap (to return the bitmap pixel data): //Get the bitmap data from the receiver's CGImage (see UIImage docs) [self setBitmapData: CGDataProviderCopyData(CGImageGetDataProvider([self CGImage]))];//Create a buffer to store bitmap data (unitialized memory as long as the data) [self setPixelBitData:malloc(CFDataGetLength(bitmapData))];//Copy image data into allocated buffer CFDataGetBytes(bitmapData,CFRangeMake(0,CFDataGetLength(bitmapData)),pixelByteData);//Cast a pointer to the first element of pixelByteData //Essentially what we're doing is making a second pointer that divides the byteData's units differently - instead of dividing each unit as 1 byte we will divide each unit as 3 bytes (1 pixel). pixelData = (RGBPixel*) pixelByteData;//Now you can access pixels by index: pixelData[ index ] NSLog(@"Pixel data one red (%i), green (%i), blue (%i).", pixelData[0].red, pixelData[0].green, pixelData[0].blue);//You can determine the desired index by multiplying row * column. return pixelData; Step 5. I made an accessor method: -(RGBPixel*)pixelDataForRow:(int)row column:(int)column{ //Return a pointer to the pixel data return &pixelData[row * column]; } | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/144250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17123/"
]
} |
144,254 | So, I'll be getting my T-Mobile G1 within a month or so, and I'm excited to start developing for it. Has anyone started using it yet? Is there a dev wiki or anything set up for it yet? | Google's android groups This is probably the best place to go. However, a good search on google will most likely take you to one of these discussion anyways. Here, you can discuss about your difficulties possibly with the core developers too. Anddev.org They're probably the most active groups so far (as of Sun, April 20, 2008) online regarding the development and the interactive community around android. Apart from the official google groups and the irc channel at #android on irc.freenode.net, they're probably the best place to go or ask questions. http://davanum.wordpress.com/ Development halted here but still some rather interesting things that have been done. phandroid.com Didn't see much development things Androforge.net A nice little repository, not a lot of files though. I pulled it from my development wiki which hasn't been updated for a while but best of luck working with Android ... and T-Mobile G1 | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/144254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1965/"
]
} |
144,261 | Does Apple's Xcode development environment provide any tools for memory leak detection? I am especially interested in tools that apply to the iPhone SDK. Currently my favourite platform for hobby programming projects Documentations/tutorials for said tools would be very helpful. | There is one specifically called Leaks and like a previous poster said, the easiest way to run it is straight from Xcode: run -> Start with Performance Tool -> Leaks It seems very good at detecting memory leaks, and was easy for a Non-C Head like me to figure out. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/144261",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22502/"
]
} |
144,277 | I'm wondering if mono.net is included in the default installation of Ubuntu, Kubuntu, and Fedora, and other popular distros? If so, does anyone have a good reason why NOT to use it to develop a new GUI application targeted mainly for linux? | It is included in Fedora, Ubuntu, Mandriva, Debian and OpenSUSE. The only major OS that does not include it is RHEL, but packages are available for it as a separate download. Additionally, you can bundle Mono with your application into a single binary if you need to (not recommended, but always possible). GUI-wise Mono supports the Windows.Forms API on Unix and MacOS, but if you want a more native experience you can use the Gtk# API (this provides a .NET API for the GNOME library stack) or you can use Qyoto if you want to integrate instead with the KDE APIs. There are many best-of-breed GUI applications for Linux that have been developed with Gtk# and Mono, some of the most popular ones include Gnome-Do (A quick application launcher), the F-Spot photo management software, the Banshee and Muine media players and the MonoDevelop IDE. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/144277",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3153/"
]
} |
144,283 | Is it just that nvarchar supports multibyte characters? If that is the case, is there really any point, other than storage concerns, to using varchars ? | An nvarchar column can store any Unicode data. A varchar column is restricted to an 8-bit codepage. Some people think that varchar should be used because it takes up less space. I believe this is not the correct answer. Codepage incompatabilities are a pain, and Unicode is the cure for codepage problems. With cheap disk and memory nowadays, there is really no reason to waste time mucking around with code pages anymore. All modern operating systems and development platforms use Unicode internally. By using nvarchar rather than varchar , you can avoid doing encoding conversions every time you read from or write to the database. Conversions take time, and are prone to errors. And recovery from conversion errors is a non-trivial problem. If you are interfacing with an application that uses only ASCII, I would still recommend using Unicode in the database. The OS and database collation algorithms will work better with Unicode. Unicode avoids conversion problems when interfacing with other systems. And you will be preparing for the future. And you can always validate that your data is restricted to 7-bit ASCII for whatever legacy system you're having to maintain, even while enjoying some of the benefits of full Unicode storage. | {
"score": 12,
"source": [
"https://Stackoverflow.com/questions/144283",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/361/"
]
} |
144,309 | I have to implement MPI system in a cluster. If anyone here has any experience with MPI (MPICH/OpenMPI), I'd like to know which is better and how the performance can be boosted on a cluster of x86_64 boxes. | MPICH has been around a lot longer. It's extremely portable and you'll find years worth of tips and tricks online. It's a safe bet and it's probably compatible with more MPI programs out there. OpenMPI is newer. While it's not quite as portable, it supports the most common platforms really well. Most people seem to think it's a lot better in several regards, especially for fault-tolerance - but to take advantage of this you may have to use some of its special features that aren't part of the MPI standard. As for performance, it depends a lot on the application; it's hard to give general advice. You should post a specific question about the type of calculation you want to run, the number of nodes, and the type of hardware - including what type of network hardware you're using. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/144309",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18501/"
]
} |
144,339 | A couple of days ago, I read a blog entry ( http://ayende.com/Blog/archive/2008/09/08/Implementing-generic-natural-language-DSL.aspx ) where the author discuss the idea of a generic natural language DSL parser using .NET. The brilliant part of his idea, in my opinion, is that the text is parsed and matched against classes using the same name as the sentences. Taking as an example, the following lines: Create user user1 with email [email protected] and password testLog user1 inTake user1 to category t-shirtsMake user1 add item Flower T-Shirt to cartTake user1 to checkout Would get converted using a collection of "known" objects, that takes the result of parsing. Some example objects would be (using Java for my example): public class CreateUser { private final String user; private String email; private String password; public CreateUser(String user) { this.user = user; } public void withEmail(String email) { this.email = email; } public String andPassword(String password) { this.password = password; }} So, when processing the first sentence, CreateUser class would be a match (obviously because it's a concatenation of "create user") and, since it takes a parameter on the constructor, the parser would take "user1" as being the user parameter. After that, the parser would identify that the next part, "with email" also matches a method name, and since that method takes a parameter, it would parse "[email protected]" as being the email parameter. I think you get the idea by now, right? One quite clear application of that, at least for me, would be to allow application testers create "testing scripts" in natural language and then parse the sentences into classes that uses JUnit to check for app behaviors. I'd like to hear ideas, tips and opinions on tools or resource that could code such parser using Java. Better yet if we could avoid using complex lexers, or frameworks like ANTLR, which I think maybe would be using a hammer to kill a fly. More than that, if anyone is up to start an open source project for that, I would definitely be interested. | Considering the complexity of lexing and parsing, I don't know if I'd want to code all that by hand. ANTLR isn't that hard to pickup and I think it is worthing looking into based on your problem. If you use a parse grammar to build and abstract syntax tree from the input, its pretty easy to then process that AST with a tree grammar. The tree grammar could easily handle executing the process you described. You'll find ANTLR in many places including Eclipse, Groovy, and Grails for a start. The Definitive ANTLR Reference even makes it fairly straightforward to get up to speed on the basic fairly quickly. I had a project that had to handle some user generated query text earlier this year. I started down a path to manually process it, but it quickly became overwhelming. I took a couple days to get up the speed on ANTLR and had an initial version of my grammar and processor running in a few days. Subsequent changes and adjustments to the requirements would have killed any custom version, but required relatively little effort to adjust once I had the ANTLR grammars up and running. Good luck! | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/144339",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14540/"
]
} |
144,344 | How do i store a directory / hierarchy / tree structure in the database? Namely MSSQL Server. @olavk: Doesn't look like you've seen my own answer. The way i use is way better than recursive queries :) p.p.s. This is the way to go! | There are many ways to store hierarchies in SQL databases. Which one to choose depends on which DBMS product you use, and how the data will be used. As you have used the MSSQL2005 tag, I think you should start considering the "Adjacency List" model; if you find that it doesn't perform well for your application, then have a look at Vadim Tropashko's comparison which highlights differences between models with a focus on multiple performance characteristics. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/144344",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3661/"
]
} |
144,360 | Could any one give an explanation on how a DHT works? Nothing too heavy, just the basics. | Ok, they're fundamentally a pretty simple idea. A DHT gives you a dictionary-like interface, but the nodes are distributed across the network. The trick with DHTs is that the node that gets to store a particular key is found by hashing that key, so in effect your hash-table buckets are now independent nodes in a network. This gives a lot of fault-tolerance and reliability, and possibly some performance benefit, but it also throws up a lot of headaches. For example, what happens when a node leaves the network, by failing or otherwise? And how do you redistribute keys when a node joins so that the load is roughly balanced. Come to think of it, how do you evenly distribute keys anyhow? And when a node joins, how do you avoid rehashing everything? (Remember you'd have to do this in a normal hash table if you increase the number of buckets). One example DHT that tackles some of these problems is a logical ring of n nodes, each taking responsibility for 1/n of the keyspace. Once you add a node to the network, it finds a place on the ring to sit between two other nodes, and takes responsibility for some of the keys in its sibling nodes. The beauty of this approach is that none of the other nodes in the ring are affected; only the two sibling nodes have to redistribute keys. For example, say in a three node ring the first node has keys 0-10, the second 11-20 and the third 21-30. If a fourth node comes along and inserts itself between nodes 3 and 0 (remember, they're in a ring), it can take responsibility for say half of 3's keyspace, so now it deals with 26-30 and node 3 deals with 21-25. There are many other overlay structures such as this that use content-based routing to find the right node on which to store a key. Locating a key in a ring requires searching round the ring one node at a time (unless you keep a local look-up table, problematic in a DHT of thousands of nodes), which is O(n)-hop routing. Other structures - including augmented rings - guarantee O(log n)-hop routing, and some claim to O(1)-hop routing at the cost of more maintenance. Read the wikipedia page, and if you really want to know in a bit of depth, check out this coursepage at Harvard which has a pretty comprehensive reading list. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/144360",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8167/"
]
} |
144,421 | I'm searching a small Java based RSS/Feed Generator, something like the FeedCreator.class.php library, any suggestions?, thanks! | There's the Rome framework as well http://rometools.github.io/rome/ Does RSS and Atom | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/144421",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4358/"
]
} |
144,435 | I'm looking into a mechanism for serialize data to be passed over a socket or shared-memory in a language-independent mechanism. I'm reluctant to use XML since this data is going to be very structured, and encoding/decoding speed is vital. Having a good C API that's liberally licensed is important, but ideally there should be support for a ton of other languages. I've looked at google's protocol buffers and ASN.1 . Am I on the right track? Is there something better? Should I just implement my own packed structure and not look for some standard? | Given your requirements, I would go with Google Protocol Buffers. It sounds like it's ideally suited to your application. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/144435",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14032/"
]
} |
144,439 | If i have lots of directory names either as literal strings or contained in variables, what is the easiest way of combining these to make a complete path? I know of Path.Combine but this only takes 2 string parameters, i need a solution that can take any number number of directory parameters. e.g: string folder1 = "foo";string folder2 = "bar";CreateAPath("C:", folder1, folder2, folder1, folder1, folder2, "MyFile.txt") Any ideas?Does C# support unlimited args in methods? | Does C# support unlimited args in methods? Yes, have a look at the params keyword. Will make it easy to write a function that just calls Path.Combine the appropriate number of times, like this (untested): string CombinePaths(params string[] parts) { string result = String.Empty; foreach (string s in parts) { result = Path.Combine(result, s); } return result;} | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/144439",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13227/"
]
} |
144,448 | I've seen a number of postgresql modules for python like pygresql, pypgsql, psyco. Most of them are Python DB API 2.0 compliant, some are not being actively developed anymore.Which module do you recommend? Why? | psycopg2 seems to be the most popular. I've never had any trouble with it. There's actually a pure Python interface for PostgreSQL too, called bpgsql . I wouldn't recommend it over psycopg2, but it's recently become capable enough to support Django and is useful if you can't compile C modules. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/144448",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20883/"
]
} |
144,453 | I want to get a files these attributes as integer values. | Delphians tend to like the FindFirst approach (the SearchRec structure has some of those), but I'd suggest the Win32 API function GetFileAttributesEx . | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/144453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
144,468 | Is there a way to track changes in Windows registry? I'd like to see what changes in the registry are made during installation of various programs. | Process Monitor allows you to monitor file and registry activity of various processes. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/144468",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11439/"
]
} |
144,474 | I'm used to working with PHP but lately I've been working with Java and I'm having a headache trying to figure this out. I want to save this representation in Java: Array ( ["col_name_1"] => Array ( 1 => ["col_value_1"], 2 => ["col_value_2"], ... , n => ["col_value_n"] ), ["col_name_n"] => Array ( 1 => ["col_value_1"], 2 => ["col_value_2"], ... , n => ["col_value_n"] )) Is there a clean way (i.e. no dirty code) to save this thing in Java? Note; I would like to use Strings as array indexes (in the first dimension) and I don't know the definite size of the arrays.. | You can use a Map and a List (these both are interfaces implemented in more than one way for you to choose the most adequate in your case). For more information check the tutorials for Map and List and maybe you should start with the Collections tutorial. An example: import java.util.*;public class Foo { public static void main(String[] args) { Map<String, List<String>> m = new HashMap<String, List<String>>(); List<String> l = new LinkedList<String>(); l.add("col_value_1"); l.add("col_value_2"); //and so on m.put("col_name_1",l); //repeat for the rest of the colnames //then, to get it you do List<String> rl = m.get("col_name_1"); }} | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/144474",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6618/"
]
} |
144,530 | Why use one over the other? | == is the identity test. It will return true if the two objects being tested are in fact the same object. Equals() performs an equality test, and will return true if the two objects consider themselves equal. Identity testing is faster, so you can use it when there's no need for more expensive equality tests. For example, comparing against null or the empty string. It's possible to overload either of these to provide different behavior -- like identity testing for Equals() --, but for the sake of anybody reading your code, please don't. Pointed out below: some types like String or DateTime provide overloads for the == operator that give it equality semantics. So the exact behavior will depend on the types of the objects you are comparing. See also: http://blogs.msdn.com/csharpfaq/archive/2004/03/29/102224.aspx | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/144530",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/230/"
]
} |
144,570 | I thought that there was some way in .net 3.0 to give an array list a type so that it didnt just return Object's but I'm having trouble doing so. Is it possible? If so, how? | List<T> was introduced with generics in .NET 2.0: using System.Collections.Generic;var list = new List<int>();list.Add(1);list.Add("string"); //compile-time error!int i = list[0]; | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/144570",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2128/"
]
} |
144,639 | By default (using the plain style) BibTeX orders citations alphabetically. How to order the citations by order of appearance in the document? | There are three good answers to this question. Use the unsrt bibliography style, if you're happy with its formatting otherwise Use the makebst (link) tool to design your own bibliography style And my personal recommendation: Use the biblatex package (link) . It's the most complete and flexible bibliography tool in the LaTeX world. Using biblatex , you'd write something like \documentclass[12pt]{article}\usepackage[sorting=none]{biblatex}\bibliography{journals,phd-references} % Where journals.bib and phd-references.bib are BibTeX databases\begin{document}\cite{robertson2007}\cite{earnshaw1842}\printbibliography\end{document} | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/144639",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/199/"
]
} |
144,642 | I require a tree / directed acyclic graph implementation something like this: public class TreeNode<K, V> { private K key; // 'key' for this node, always present private V value; // 'value' for this node, doesn't have to be set private TreeNode<K, V> parent; private Set<TreeNode<K, V>> children; } There is no sorting of any kind. The TreeNode is just a wrapper around the key and a possible value (nodes don't have to have values set). I require links to both the parent and the children. Is there anything out there in the standard APIs or Commons etc that will do this for me? I don't mind writing it myself (and I'm certainly not asking you folks to) I just don't want to re-invent the wheel. | There doesn't seem to be anything of the kind. I asked a similar question last week and ended up implementing my own tree. My implementation was very similar to what you're proposing: public class TreeNode<T>{ private LinkedList<TreeNode<T>> children = new LinkedList<TreeNode<T>>(); public T value { get; set; } public TreeNode(T value) { this.value = value; } public LinkedList<TreeNode<T>> GetChildren() { return children; }} You will have to add a link back to the parent(s). | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/144642",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1666/"
]
} |
144,661 | I'm currently primarily a D programmer and am looking to add another language to my toolbox, preferably one that supports the metaprogramming hacks that just can't be done in a statically compiled language like D. I've read up on Lisp a little and I would love to find a language that allows some of the cool stuff that Lisp does, but without the strange syntax, etc. of Lisp. I don't want to start a language flame war, and I'm sure both Ruby and Python have their tradeoffs, so I'll list what's important to me personally. Please tell me whether Ruby, Python, or some other language would be best for me. Important: Good metaprogramming. Ability to create classes, methods, functions, etc. at runtime. Preferably, minimal distinction between code and data, Lisp style. Nice, clean, sane syntax and consistent, intuitive semantics. Basically a well thought-out, fun to use, modern language. Multiple paradigms. No one paradigm is right for every project, or even every small subproblem within a project. An interesting language that actually affects the way one thinks about programming. Somewhat important: Performance. It would be nice if performance was decent, but when performance is a real priority, I'll use D instead. Well-documented. Not important: Community size, library availability, etc. None of these are characteristics of the language itself, and all can change very quickly. Job availability. I am not a full-time, professional programmer. I am a grad student and programming is tangentially relevant to my research. Any features that are primarily designed with very large projects worked on by a million code monkeys in mind. | I've read up on Lisp a little and I would love to find a language that allows some of the cool stuff that Lisp does, but without the strange syntax, etc. of Lisp. Wouldn't we all. minimal distinction between code and data, Lisp style Sadly, the minimal distinction between code and data and "strange" syntax are consequences of each other. If you want easy-to-read syntax, you have Python. However, the code is not represented in any of the commonly-used built-in data structures. It fails—as most languages do—in item #1 of your 'important' list. That makes it difficult to provide useful help. You can't have it all. Remember, you aren't the first to have this thought. If something like your ideal language existed, we'd all be using it. Since the real world falls short of your ideals, you'll have to re-prioritize your wish list. The "important" section has to be rearranged to identify what's really important to you. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/144661",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23903/"
]
} |
144,669 | I've removed a checked in file from the CVS branch, i.e.: cvs remove -f file.txtcvs commit How do I restore the file? | I believe that: cvs add file.txtcvs commit file.txt ... will resurrect it from the attic. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/144669",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4704/"
]
} |
144,682 | I think I might be missing the point of having a logging framework for your application. In all the small apps I've always written a small "Logging" class and just pass log messages to a method in it which is written to a file. What is the purpose of a 3rd party logging framework like log4net? Is it thread safety with logging write operations or am I missing something? | That's an excellent question. The first reason is "why not?" If you are using a logging framework, then you'll reap the maintainability benefits of using something already packaged. The second reason is that logging is subtle. Different threads, sessions, classes and object instances may all come into play in logging, and you don't want to have to figure this problem out on the fly. The third reason is that you may find a performance bottleneck in your code. Figuring out that your code is slow because you're writing to a file without buffering or your hard drive has run out of disk space because the logger doesn't rollover and compress old files can be a pain in the neck. The fourth reason is that you may want to append to syslog, or write to a database, or to a socket, or to different files. Frameworks have this functionality built in. But really, the first answer is the best one; there's very little benefit to writing your own, and a whole bunch of drawbacks. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/144682",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
144,696 | Django comes with CSRF protection middleware , which generates a unique per-session token for use in forms. It scans all incoming POST requests for the correct token, and rejects the request if the token is missing or invalid. I'd like to use AJAX for some POST requests, but said requests don't have the CSRF token availabnle. The pages have no <form> elements to hook into and I'd rather not muddy up the markup inserting the token as a hidden value. I figure a good way to do this is to expose a vew like /get-csrf-token/ to return the user's token, relying on browser's cross-site scripting rules to prevent hostile sites from requesting it. Is this a good idea? Are there better ways to protect against CSRF attacks while still allowing AJAX requests? | If you know you're going to need the CSRF token for AJAX requests, you can always embed it in the HTML somewhere; then you can find it through Javascript by traversing the DOM. This way, you'll still have access to the token, but you're not exposing it via an API. To put it another way: do it through Django's templates -- not through the URL dispatcher. It's much more secure this way. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/144696",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3560/"
]
} |
144,701 | I frequently start with a simple console application to try out an idea, then create a new GUI based project and copy the code in. Is there a better way? Can I convert my existing console application easily? | Just add a new Winform, add the following code to your Main : Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); Also, be sure the [STAThread] attribute is declared above your Main function to indicate the COM threading model your Windows application will use (more about STAThread here ). Then right click your project and select properties and change the "Output type" to Windows application and you're done. EDIT : In VS2008 the property to change is Application type | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/144701",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5/"
]
} |
144,713 | I have an XML document with un-namespaced elements, and I want to use XSLT to add namespaces to them. Most elements will be in namespace A; a few will be in namespace B. How do I do this? | With foo.xml <foo x="1"> <bar y="2"> <baz z="3"/> </bar> <a-special-element n="8"/></foo> and foo.xsl <xsl:template match="*"> <xsl:element name="{local-name()}" namespace="A" > <xsl:copy-of select="attribute::*"/> <xsl:apply-templates /> </xsl:element> </xsl:template> <xsl:template match="a-special-element"> <B:a-special-element xmlns:B="B"> <xsl:apply-templates match="children()"/> </B:a-special-element> </xsl:template></xsl:transform> I get <foo xmlns="A" x="1"> <bar y="2"> <baz z="3"/> </bar> <B:a-special-element xmlns:B="B"/></foo> Is that what you’re looking for? | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/144713",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3488/"
]
} |
144,730 | I'm starting a new project which involves developing an interface for a machine that measures wedge and roundness of lenses and stores the information in a database and reports on it. There's a decent chance we're going to be putting a touch screen on this machine so that it doesn't need to have a mouse or keyboard... I don't have any experience developing for full size touch screens, so I'm looking for advice/tips/info from you guys... I can imagine you want to make the elements a little larger than normal... space buttons out a bit more.... things like that... anyone have anything else to add? | A few things to consider: You need to account for parallax error when touching controls. Basically, the user may touch the screen above or below your actual control and therefore miss the control. This is a combination of the size of the control (eg you can have the active area larger than visual control to allow the user to miss and still activate the control), the viewing angle of the user (which you may or may not be able to predict/control) and the type of touch screen you're using. If you know where the user will be placed relative to the screen when using it, you can usually accommodate this with appropriate calibration. Depending on the type of touch screen, you may need to ensure that your users aren't wearing gloves or using an implement other than their fingers (eg the end of a pen) to touch the screen. Some screens (eg those depending on conductance) don't respond well to anything other than flesh and blood. Avoid using double clicks because it can be very hard for users to reliably double click a control. This can be partly mitigated if you've got experienced/trained users working in a fairly controlled environment where they're used to the screens. Linked to the above, if you are using double clicks, you may find the double click activated when the user only wants to single click. This is because it's very easy for the user's finger to bounce slightly on touching the screen and, depending on how sensitive the double click settings are, trigger a double rather than a single click. For this and the previous reason, we always disable double clicks and only use single clicks (or similar single activation controls). However big you think you need to make the controls to allow for touch activation, they almost certainly need to be bigger still. Make sure you test the interface with real users in the real deployment environment (or as close to it as you can get). For example, we deployed some screens with nice big buttons you couldn't miss only to find that the control room was unheated and that the users were wearing thick gloves in the middle of winter, making their fingers way bigger than we had allowed for. Don't put any controls near the edges of the screen - it's very hard to get your finger into the edges (particularly if the screen has a deep bezel) and a slight calibration problem can easily shift the control too close to the edge to use. Standard menus and scroll bars are a good example of controls that can be very tricky to use on a touch screen and you should either avoid them (which is preferable - they're not good for touch screens) or replicate them with jumbo equivalents. Remember that the user's hand will be over the screen, obscuring some of the screen and controls (typically those below where the user is touching, but it depends on the position of the user relative to the screen). Don't put instructions or indicators where the user's hand or arm will obscure them when trying to use the control they relate to (eg typically put them above rather than below the control). Depending on the environment, make sure your touch screen is suitably proofed against dust, damp, grease etc and make sure it's easy to clean without damaging it. You wouldn't believe the slime that can quickly accumulate on a touch screen in an industrial or public setting. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/144730",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3226/"
]
} |
144,734 | I was asked to do a code review and report on the feasibility of adding a new feature to one of our new products, one that I haven't personally worked on until now. I know it's easy to nitpick someone else's code, but I'd say it's in bad shape (while trying to be as objective as possible). Some highlights from my code review: Abuse of threads: QueueUserWorkItem and threads in general are used a lot , and Thread-pool delegates have uninformative names such as PoolStart and PoolStart2 . There is also a lack of proper synchronization between threads, in particular accessing UI objects on threads other than the UI thread. Magic numbers and magic strings : Some Const 's and Enum 's are defined in the code, but much of the code relies on literal values. Global variables : Many variables are declared global and may or may not be initialized depending on what code paths get followed and what order things occur in. This gets very confusing when the code is also jumping around between threads. Compiler warnings : The main solution file contains 500+ warnings, and the total number is unknown to me. I got a warning from Visual Studio that it couldn't display any more warnings. Half-finished classes : The code was worked on and added to here and there, and I think this led to people forgetting what they had done before, so there are a few seemingly half-finished classes and empty stubs. Not Invented Here : The product duplicates functionality that already exists in common libraries used by other products, such as data access helpers, error logging helpers, and user interface helpers. Separation of concerns : I think someone was holding the book upside down when they read about the typical "UI -> business layer -> data access layer" 3-tier architecture. In this codebase, the UI layer directly accesses the database, because the business layer is partially implemented but mostly ignored due to not being fleshed out fully enough, and the data access layer controls the UI layer. Most of the low-level database and network methods operate on a global reference to the main form, and directly show, hide, and modify the form. Where the rather thin business layer is actually used, it also tends to control the UI directly. Most of this lower-level code also uses MessageBox.Show to display error messages when an exception occurs, and most swallow the original exception. This of course makes it a bit more complicated to start writing units tests to verify the functionality of the program before attempting to refactor it. I'm just scratching the surface here, but my question is simple enough: Would it make more sense to take the time to refactor the existing codebase, focusing on one issue at a time, or would you consider rewriting the entire thing from scratch? EDIT : To clarify a bit, we do have the original requirements for the project, which is why starting over could be an option. Another way to phrase my question is: Can code ever reach a point where the cost of maintaining it would become greater than the cost of dumping it and starting over? | To actually scrap and start over? When the current code doesn't do what you would like it to do, and would be cost prohibitive to change. I'm sure someone will now link Joel's article about Netscape throwing their code away and how it's oh-so-terrible and a huge mistake. I don't want to talk about it in detail, but if you do link that article, before you do so, consider this: the IE engine, the engine that allowed MS to release IE 4, 5, 5.5, and 6 in quick succession, the IE engine that totally destroyed Netscape... it was new. Trident was a new engine after they threw away the IE 3 engine because it didn't provide a suitable basis for their future development work . MS did that which Joel says you must never do, and it is because MS did so that they had a browser that allowed them to completely eclipse Netscape. So please... just meditate on that thought for a moment before you link Joel and say "oh you should never do it, it's a terrible idea". | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/144734",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17862/"
]
} |
144,735 | What is the best way to get started with programming things outside of your computer? I don't mean mainstream things like cell phones with APIs. Please assume working knowledge of C/C++ | Brian, you might find the Arduino interesting. It is inexpensive and pretty popular. I started playing around with micro controller boards and such a few years back and that lead to an interest in robots. Kind of interesting, at least to me. If one is interested in a .NET-flavored development environment, there is an analog to the arduino call netduino that is worth a look. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/144735",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3153/"
]
} |
144,761 | I have a problem with a string in C++ which has several words in Spanish. This means that I have a lot of words with accents and tildes. I want to replace them for their not accented counterparts. Example: I want to replace this word: "había" for habia. I tried replace it directly but with replace method of string class but I could not get that to work. I'm using this code: for (it= dictionary.begin(); it != dictionary.end(); it++){ strMine=(it->first); found=toReplace.find_first_of(strMine); while (found!=std::string::npos) { strAux=(it->second); toReplace.erase(found,strMine.length()); toReplace.insert(found,strAux); found=toReplace.find_first_of(strMine,found+1); }} Where dictionary is a map like this (with more entries): dictionary.insert ( std::pair<std::string,std::string>("á","a") );dictionary.insert ( std::pair<std::string,std::string>("é","e") );dictionary.insert ( std::pair<std::string,std::string>("í","i") );dictionary.insert ( std::pair<std::string,std::string>("ó","o") );dictionary.insert ( std::pair<std::string,std::string>("ú","u") );dictionary.insert ( std::pair<std::string,std::string>("ñ","n") ); and toReplace strings is: std::string toReplace="á-é-í-ó-ú-ñ-á-é-í-ó-ú-ñ"; I obviously must be missing something. I can't figure it out.Is there any library I can use?. Thanks, | First, this is a really bad idea: you’re mangling somebody’s language by removing letters. Although the extra dots in words like “naïve” seem superfluous to people who only speak English, there are literally thousands of writing systems in the world in which such distinctions are very important. Writing software to mutilate someone’s speech puts you squarely on the wrong side of the tension between using computers as means to broaden the realm of human expression vs. tools of oppression. What is the reason you’re trying to do this? Is something further down the line choking on the accents? Many people would love to help you solve that. That said, libicu can do this for you. Open the transform demo ; copy and paste your Spanish text into the “Input” box; enter NFD; [:M:] remove; NFC as “Compound 1” and click transform. (With help from slide 9 of Unicode Transforms in ICU . Slides 29-30 show how to use the API.) | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/144761",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23084/"
]
} |
144,774 | I'm writing a program that uses SetWindowRgn to make transparent holes in a window that belongs to another process. (This is done only when the user explicitly requests it.) The program has to assume that the target window may already have holes which need to be preserved, so before it calls SetWindowRgn , it calls GetWindowRgn to get the current region, then combines the current region with the new one and calls SetWindowRgn : HRGN rgnOld = CreateRectRgn ( 0, 0, 0, 0 );int regionType = GetWindowRgn ( hwnd, rgnOld ); This works fine in XP, but the call to GetWindowRgn fails in Vista. I've tried turning off Aero and elevating my thread's privilege to SE_DEBUG_NAME with AdjustTokenPrivileges , but neither helps. GetLastError() doesn't seem to return a valid value for GetWindowRgn -- it returns 0 on one machine and 5 (Access denied) on another. Can anyone tell me what I'm doing wrong or suggest a different approach? | Are you sure your window has a region? Most top-level windows in XP do, simply because the default theme uses them for round corners... but this is still a bad assumption to be making, and may very well not hold once you get to Vista. If you haven't set a region yet, and the call fails, use a sensible default (the window rect) and don't let it ruin your life. Now, if SetWindowRgn() fails... | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/144774",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23091/"
]
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.