source_id
int64
1
74.7M
question
stringlengths
0
40.2k
response
stringlengths
0
111k
metadata
dict
131,406
There are several different methods for converting floating point numbers to Integers in JavaScript. My question is what method gives the best performance, is most compatible, or is considered the best practice? Here are a few methods that I know of: var a = 2.5;window.parseInt(a); // 2Math.floor(a); // 2a | 0; // 2 I'm sure there are others out there. Suggestions?
According to this website : parseInt is occasionally used as a means of turning a floating point number into an integer. It is very ill suited to that task because if its argument is of numeric type it will first be converted into a string and then parsed as a number... For rounding numbers to integers one of Math.round, Math.ceil and Math.floor are preferable...
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/131406", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10942/" ] }
131,439
I want a C program to produce a core dump under certain circumstances. This is a program that runs in a production environment and isn't easily stopped and restarted to adjust other kinds of debugging code. Also, since it's in a production environment, I don't want to call abort(). The issues under investigation aren't easily replicated in a non-production environment. What I'd like is for the program, when it detects certain issues, to produce a core dump on its own, preferably with enough information to rename the file, and then continue.
void create_dump(void){ if(!fork()) { // Crash the app in your favorite way here *((void*)0) = 42; }} Fork the process then crash the child - it'll give you a snapshot whenever you want
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/131439", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14732/" ] }
131,456
How do I apply the MarshalAsAttribute to the return type of the code below? public ISomething Foo(){ return new MyFoo();}
According to http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshalasattribute.aspx : [return: MarshalAs(<your marshal type>)]public ISomething Foo(){ return new MyFoo();}
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/131456", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21429/" ] }
131,473
G'day Stackoverflowers, I'm the author of Perl's autodie pragma, which changes Perl's built-ins to throw exceptions on failure. It's similar to Fatal , but with lexical scope, an extensible exception model, more intelligent return checking, and much, much nicer error messages. It will be replacing the Fatal module in future releases of Perl (provisionally 5.10.1+), but can currently be downloaded from the CPAN for Perl 5.8.0 and above. The next release of autodie will add special handling for calls to flock with the LOCK_NB (non-blocking) option. While a failed flock call would normally result in an exception under autodie , a failed call to flock using LOCK_NB will merely return false if the returned errno ( $! ) is EWOULDBLOCK . The reason for this is so people can continue to write code like: use Fcntl qw(:flock);use autodie; # All perl built-ins now succeed or die.open(my $fh, '<', 'some_file.txt');my $lock = flock($fh, LOCK_EX | LOCK_NB); # Lock the file if we can.if ($lock) { # Opportuntistically do something with the locked file.} In the above code, a lock that fails because someone else has the file locked already ( EWOULDBLOCK ) is not considered to be a hard error, so autodying flock merely returns a false value. In the situation that we're working with a filesystem that doesn't support file-locks, or a network filesystem and the network just died, then autodying flock generates an appropriate exception when it sees that our errno is not EWOULDBLOCK . This works just fine in my dev version on Unix-flavoured systems, but it fails horribly under Windows. It appears that while Perl under Windows supports the LOCK_NB option, it doesn't define EWOULDBLOCK . Instead, the errno returned is 33 ("Domain error") when blocking would occur. Obviously I can hard-code this as a constant into autodie , but that's not what I want to do here, because it means that I'm screwed if the errno ever changes (or has changed). I would love to compare it to the Windows equivalent of POSIX::EWOULDBLOCK , but I can't for the life of me find where such a thing would be defined. If you can help, let me know. Answers I specifically don't want: Suggestions to hard-code it as a constant (or worse still, leave a magic number floating about). Not supporting LOCK_NB functionality at all under Windows. Assuming that any failure from a LOCK_NB call to flock should return merely false. Suggestions that I ask on p5p or perlmonks . I already know about them. An explanation of how flock , or exceptions, or Fatal work. I already know. Intimately.
Under Win32 "native" Perl, note that $^E is more descriptive at 33, "The process cannot access the file because another process locked a portion of the file" which is ERROR_LOCK_VIOLATION (available from Win32::WinError ).
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/131473", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19422/" ] }
131,559
Is there a way to search for multiple strings simultaneously in Vim? I recall reading somewhere that it was possible but somehow forgot the technique. So for example, I have a text file and I want to search for "foo" and "bar" simultaneously (not necessarily as a single string, can be in different lines altogether). How do I achieve that?
/^joe.*fred.*bill/ : find joe AND fred AND Bill (Joe at start of line)/fred\|joe : Search for FRED OR JOE
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/131559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17716/" ] }
131,605
What version control systems have you used with MS Excel (2003/2007)? What would you recommend and Why? What limitations have you found with your top rated version control system? To put this in perspective, here are a couple of use cases: version control for VBA modules more than one person is working on a Excel spreadsheet and they may be making changes to the same worksheet, which they want to merge and integrate. This worksheet may have formulae, data, charts etc the users are not too technical and the fewer version control systems used the better Space constraint is a consideration. Ideally only incremental changes are saved rather than the entire Excel spreadsheet.
I've just setup a spreadsheet that uses Bazaar, with manual checkin/out via TortiseBZR. Given that the topic helped me with the save portion, I wanted to post my solution here. The solution for me was to create a spreadsheet that exports all modules on save, and removes and re-imports the modules on open. Yes, this could be potentially dangerous for converting existing spreadsheets. This allows me to edit the macros in the modules via Emacs (yes, emacs) or natively in Excel, and commit my BZR repository after major changes. Because all the modules are text files, the standard diff-style commands in BZR work for my sources except the Excel file itself. I've setup a directory for my BZR repository, X:\Data\MySheet. In the repo are MySheet.xls and one .vba file for each of my modules (ie: Module1Macros). In my spreadsheet I've added one module that is exempt from the export/import cycle called "VersionControl". Each module to be exported and re-imported must end in "Macros". Contents of the "VersionControl" module: Sub SaveCodeModules()'This code Exports all VBA modulesDim i%, sName$With ThisWorkbook.VBProject For i% = 1 To .VBComponents.Count If .VBComponents(i%).CodeModule.CountOfLines > 0 Then sName$ = .VBComponents(i%).CodeModule.Name .VBComponents(i%).Export "X:\Tools\MyExcelMacros\" & sName$ & ".vba" End If Next iEnd WithEnd SubSub ImportCodeModules()With ThisWorkbook.VBProject For i% = 1 To .VBComponents.Count ModuleName = .VBComponents(i%).CodeModule.Name If ModuleName <> "VersionControl" Then If Right(ModuleName, 6) = "Macros" Then .VBComponents.Remove .VBComponents(ModuleName) .VBComponents.Import "X:\Data\MySheet\" & ModuleName & ".vba" End If End If Next iEnd WithEnd Sub Next, we have to setup event hooks for open / save to run these macros. In the code viewer, right click on "ThisWorkbook" and select "View Code". You may have to pull down the select box at the top of the code window to change from "(General)" view to "Workbook" view. Contents of "Workbook" view: Private Sub Workbook_Open()ImportCodeModulesEnd SubPrivate Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)SaveCodeModulesEnd Sub I'll be settling into this workflow over the next few weeks, and I'll post if I have any problems. Thanks for sharing the VBComponent code!
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/131605", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20879/" ] }
131,628
I wrote some code with a lot of recursion, that takes quite a bit of time to complete. Whenever I "pause" the run to look at what's going on I get: Cannot evaluate expression because the code of the current method is optimized. I think I understand what that means. However, what puzzles me is that after I hit step, the code is not "optimized" anymore, and I can look at my variables. How does this happen? How can the code flip back and forth between optimized and non-optimzed code?
The Debugger uses FuncEval to allow you to "look at" variables. FuncEval requires threads to be stopped in managed code at a GarbageCollector safe point. Manually "pausing" the run in the IDE causes all threads to stop as soon as possible. Your highly recursive code will tend to stop at an unsafe point. Hence, the debugger is unable to evaluate expressions. Pressing F10 will move to the next Funceval Safe point and will enable function evaluation. For further information review the rules of FuncEval .
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/131628", "https://Stackoverflow.com", "https://Stackoverflow.com/users/781/" ] }
131,653
I know that embedding CSS styles directly into the HTML tags they affect defeats much of the purpose of CSS, but sometimes it's useful for debugging purposes, as in: <p style="font-size: 24px">asdf</p> What's the syntax for embedding a rule like: a:hover {text-decoration: underline;} into the style attribute of an A tag? It's obviously not this... <a href="foo" style="text-decoration: underline">bar</a> ...since that would apply all the time, as opposed to just during hover.
I'm afraid it can't be done, the pseudo-class selectors can't be set in-line, you'll have to do it on the page or on a stylesheet. I should mention that technically you should be able to do it according to the CSS spec , but most browsers don't support it Edit: I just did a quick test with this: <a href="test.html" style="{color: blue; background: white} :visited {color: green} :hover {background: yellow} :visited:hover {color: purple}">Test</a> And it doesn't work in IE7, IE8 beta 2, Firefox or Chrome. Can anyone else test in any other browsers?
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/131653", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7598/" ] }
131,681
What techniques and/or modules are available to implement robust rate limiting (requests|bytes/ip/unit time) in apache?
The best mod_evasive (Focused more on reducing DoS exposure) mod_cband (Best featured for 'normal' bandwidth control) and the rest mod_limitipconn mod_bw mod_bwshare
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/131681", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8171/" ] }
131,690
Several years back, I innocently tried to write a little app to save my tactically placed desktop icons because I was sick of dragging them back to their locations when some event reset them. I gave up after buring WAY too much time having failed to find a way to query, much less save and reset, my icons' desktop position. Anyone know where Windows persists this info and if there's an API to set them? Thanks,Richard
If I'm not mistaken the desktop is just a ListView, and you'll have to send the LVM_SETITEMPOSITION message to the handle of the desktop. I googled a bit for some c# code and couldn't find a example, but I did found the following article. Torry: ...get/set the positions of desktop icons? . It's delphi code, but I find it very readable and with some P/Invokes you'll be able to translate it to c#.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/131690", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11314/" ] }
131,704
Eclipse 3.4[.x] - also known as Ganymede - comes with this new mechanism of provisioning called p2 . "Provisioning" is the process allowing to discover and update on demand some parts of an application, as explained in general in this article on the Sun Web site . Eclipse has an extended wiki section in which p2 details are presented. Specifically, it says in this wiki page that p2 will look for new componentsHowever after reading it. I suppose (but you may confirm that point by your own experience), that p2 can function file "file://" protocol, which would allow it to provision with local file (either on your computer or on an UNC path '\server\path'), as illustrated here , but also by the files: [eclipse-SDK-3.4-win32]\eclipse\configuration\.settings\org.eclipse.equinox.p2.artifact.repository.prefs [eclipse-SDK-3.4-win32]\eclipse\configuration\.settings\org.eclipse.equinox.p2.metadata.repository.prefs p2 mechanism is used to update eclipse itself, through an eclipse 3.4 update site , and reference in those '.prefs' files with line like: repositories/file:_C:_jv_eclipse_eclipse-SDK-3.4-win32_eclipse/url=file:/C:/jv/eclipse/eclipse-SDK-3.4-win32/eclipse/ Now, how could I replicate the eclipse components present in that update site into a local directory and reference those components through the mentioned '.prefs' files, in order to have an upgrade process entirely run locally , without having to access the web? I suppose that some p2 metadata files present in the distant 'update site' need to be replicated and changed as well. Do you have any thoughts/advice/tips on that ? (i.e. on how to discover and retrieve and update the complete structure needed for a full eclipse installation, in order to run that installation locally)
Yes, you can specify the repository locations if you use the p2.director this for example is a snippet of a script that I use to install eclipse (Ganymede) from a local copy of the Ganymede repository ./eclipse\ -nosplash -consolelog -debug\ -vm "${VM}"\ -application org.eclipse.equinox.p2.director.app.application\ -metadataRepository file:${SHARED_REPOSITORY_DIR}\ -artifactRepository file:${SHARED_REPOSITORY_DIR}\ -installIU "${4-org.eclipse.sdk.ide}"\ -destination "${3}"\ -profile "${1}"\ -profileProperties org.eclipse.update.install.features=true\ -bundlepool ${SHARED_BUNDLEPOOL_DIR}\ -p2.os linux\ -p2.ws gtk\ -p2.arch "${2}"\ \ -vmargs\ -Xms64m -Xmx1024m -XX:MaxPermSize=256m\ -Declipse.p2.data.area=${SHARED_P2_DIR} Here are some links to use the p2 director http://eclipse.dzone.com/articles/understanding-eclipse-p2-provi http://wiki.eclipse.org/Equinox_p2_director_application
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/131704", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6309/" ] }
131,803
I notice that modern C and C++ code seems to use size_t instead of int / unsigned int pretty much everywhere - from parameters for C string functions to the STL. I am curious as to the reason for this and the benefits it brings.
The size_t type is the unsigned integer type that is the result of the sizeof operator (and the offsetof operator), so it is guaranteed to be big enough to contain the size of the biggest object your system can handle (e.g., a static array of 8Gb). The size_t type may be bigger than, equal to, or smaller than an unsigned int , and your compiler might make assumptions about it for optimization. You may find more precise information in the C99 standard, section 7.17, a draft of which is available on the Internet in pdf format, or in the C11 standard, section 7.19, also available as a pdf draft .
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/131803", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9236/" ] }
131,818
Application has an auxiliary thread. This thread is not meant to run all the time, but main process can call it very often. So, my question is, what is more optimal in terms of CPU performance: suspend thread when it is not being used or keep it alive and use WaitForSingleObject function in order to wait for a signal from main process?
In terms of CPU resources used, both solutions are the same - the thread which is suspended and thread which is waiting in WaitForSingleObject for an object which is not signalled both get no CPU cycles at all. That said, WaitForSingleObject is almost always a prefered solution because the code using it will be much more "natural" - easier to read, and easier to make right. Suspending/Resuming threads can be dangerous, because you need to take a lot of care to make sure you know you are suspending a thread in a state where suspending it will do no harm (imagine suspending a thread which is currently holding a mutex).
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/131818", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ] }
131,871
I'd love to figure it out myself but I was wondering roughly what's the algorithm for converting a function with yield statements into a state machine for an enumerator? For example how does C# turn this: IEnumerator<string> strings(IEnumerable<string> args) { IEnumerator<string> enumerator2 = getAnotherEnumerator(); foreach(var arg in arg) { enumerator2.MoveNext(); yield return arg+enumerator.Current; } } into this: bool MoveNext() { switch (this.state) { case 0: this.state = -1; this.enumerator2 = getAnotherEnumerator(); this.argsEnumerator = this.args.GetEnumerator(); this.state = 1; while (this.argsEnumerator.MoveNext()) { this.arg = this.argsEnumerator.Current; this.enumerator2.MoveNext(); this.current = this.arg + this.enumerator2.Current; this.state = 2; return true; state1: this.state = 1; } this.state = -1; if (this.argsEnumerator != null) this.argsEnumerator.Dispose(); break; case 2: goto state1; } return false;} Of course the result can be completely different depending on the original code.
The particular code sample you are looking at involves a series of transformations.Please note that this is an approximate description of the algorithm. The actual names used by the compiler and the exact code it generates may be different. The idea is the same, however. The first transformation is the "foreach" transformation, which transforms this code: foreach (var x in y){ //body} into this code: var enumerator = y.GetEnumerator();while (enumerator.MoveNext()){ var x = enumerator.Current; //body}if (y != null){ enumerator.Dispose();} The second transformation finds all the yield return statements in the function body, assigns a number to each (a state value), and creates a "goto label" right after the yield. The third transformation lifts all the local variables and function arguments in the method body into an object called a closure. Given the code in your example, that would look similar to this: class ClosureEnumerable : IEnumerable<string> { private IEnumerable<string> args; private ClassType originalThis; public ClosureEnumerator(ClassType origThis, IEnumerable<string> args) { this.args = args; this.origianlThis = origThis; } public IEnumerator<string> GetEnumerator() { return new Closure(origThis, args); } }class Closure : IEnumerator<string>{ public Closure(ClassType originalThis, IEnumerable<string> args) { state = 0; this.args = args; this.originalThis = originalThis; } private IEnumerable<string> args; private IEnumerator<string> enumerator2; private IEnumerator<string> argEnumerator; //- Here ClassType is the type of the object that contained the method // This may be optimized away if the method does not access any // class members private ClassType originalThis; //This holds the state value. private int state; //The current value to return private string currentValue; public string Current { get { return currentValue; } }} The method body is then moved from the original method to a method inside "Closure" called MoveNext, which returns a bool, and implements IEnumerable.MoveNext.Any access to any locals is routed through "this", and any access to any class members are routed through this.originalThis. Any "yield return expr" is translated into: currentValue = expr;state = //the state number of the yield statement;return true; Any yield break statement is translated into: state = -1;return false; There is an "implicit" yield break statement at the end of the function.A switch statement is then introduced at the beginning of the procedure that looks at the state number and jumps to the associated label. The original method is then translated into something like this: IEnumerator<string> strings(IEnumerable<string> args){ return new ClosureEnumerable(this,args);} The fact that the state of the method is all pushed into an object and that the MoveNext method uses a switch statement / state variable is what allows the iterator to behave as if control is being passed back to the point immediately after the last "yield return" statement the next time "MoveNext" is called. It is important to point out, however, that the transformation used by the C# compiler is not the best way to do this. It suffers from poor performance when trying to use "yield" with recursive algorithms. There is a good paper that outlines a better way to do this here: http://research.microsoft.com/en-us/projects/specsharp/iterators.pdf It's worth a read if you haven't read it yet.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/131871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1659/" ] }
131,901
I am trying to copy a file using the following code: File targetFile = new File(targetPath + File.separator + filename);...targetFile.createNewFile();fileInputStream = new FileInputStream(fileToCopy);fileOutputStream = new FileOutputStream(targetFile);byte[] buffer = new byte[64*1024];int i = 0;while((i = fileInputStream.read(buffer)) != -1) { fileOutputStream.write(buffer, 0, i);} For some users the targetFile.createNewFile results in this exception: java.io.IOException: The filename, directory name, or volume label syntax is incorrect at java.io.WinNTFileSystem.createFileExclusively(Native Method) at java.io.File.createNewFile(File.java:850) Filename and directory name seem to be correct. The directory targetPath is even checked for existence before the copy code is executed and the filename looks like this: AB_timestamp.xml The user has write permissions to the targetPath and can copy the file without problems using the OS. As I don't have access to a machine this happens on yet and can't reproduce the problem on my own machine I turn to you for hints on the reason for this exception.
This can occur when filename has timestamp with colons, eg. myfile_HH:mm:ss.csv Removing colons fixed the issue.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/131901", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5271/" ] }
131,955
Is there a keyboard shortcut for pasting the content of the clipboard into a command prompt window on Windows XP (instead of using the right mouse button)? The typical Shift + Insert does not seem to work here.
Yes.. but awkward. Link alt + Space , e , k <-- for copy and alt + Space , e , p <-- for paste.
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/131955", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4497/" ] }
131,975
I understand benefits of dependency injection itself. Let's take Spring for instance. I also understand benefits of other Spring featureslike AOP, helpers of different kinds, etc. I'm just wondering, what are the benefits of XML configuration such as: <bean id="Mary" class="foo.bar.Female"> <property name="age" value="23"/></bean><bean id="John" class="foo.bar.Male"> <property name="girlfriend" ref="Mary"/></bean> compared to plain old java code such as: Female mary = new Female();mary.setAge(23);Male john = new Male();john.setGirlfriend(mary); which is easier debugged, compile time checked and can be understood by anyone who knows only java.So what is the main purpose of a dependency injection framework? (or a piece of code that shows its benefits.) UPDATE: In case of IService myService;// ...public void doSomething() { myService.fetchData();} How can IoC framework guess which implementation of myService I want to be injected if there is more than one? If there is only one implementation of given interface, and I let IoC container automatically decide to use it, it will be broken after a second implementation appears. And if there is intentionally only one possible implementation of an interface then you do not need to inject it. It would be really interesting to see small piece of configuration for IoC which shows it's benefits. I've been using Spring for a while and I can not provide such example. And I can show single lines which demonstrate benefits of hibernate, dwr, and other frameworks which I use. UPDATE 2: I realize that IoC configuration can be changed without recompiling. Is it really such a good idea? I can understand when someone wants to change DB credentials without recompiling - he may be not developer. In your practice, how often someone else other than developer changes IoC configuration? I think that for developers there is no effort to recompile that particular class instead of changing configuration. And for non-developer you would probably want to make his life easier and provide some simpler configuration file. UPDATE 3: External configuration of mapping between interfaces and their concrete implementations What is so good in making it extenal? You don't make all your code external, while you definitely can - just place it in ClassName.java.txt file, read and compile manually on the fly - wow, you avoided recompiling. Why should compiling be avoided?! You save coding time because you provide mappings declaratively, not in a procedural code I understand that sometimes declarative approach saves time. For example, I declare only once a mapping between a bean property and a DB column and hibernate uses this mapping while loading, saving, building SQL based on HSQL, etc. This is where the declarative approach works. In case of Spring (in my example), declaration had more lines and had the same expressiveness as corresponding code. If there is an example when such declaration is shorter than code - I would like to see it. Inversion of Control principle allows for easy unit testing because you can replace real implementations with fake ones (like replacing SQL database with an in-memory one) I do understand inversion of control benefits (I prefer to call the design pattern discussed here as Dependency Injection, because IoC is more general - there are many kinds of control, and we are inverting only one of them - control of initialization). I was asking why someone ever needs something other than a programming language for it. I definitely can replace real implementations with fake ones using code. And this code will express same thing as configuration - it will just initialize fields with fake values. mary = new FakeFemale(); I do understand benefits of DI. I do not understand what benefits are added by external XML configuration compared to configuring code that does the same. I do not think that compiling should be avoided - I compile every day and I'm still alive. I think configuration of DI is bad example of declarative approach. Declaration can be useful if is declared once AND is used many times in different ways - like hibernate cfg, where mapping between bean property and DB column is used for saving, loading, building search queries, etc. Spring DI configuration can be easily translated to configuring code, like in the beginning of this question, can it not? And it is used only for bean initialization, isn't it? Which means a declarative approach does not add anything here, does it? When I declare hibernate mapping, I just give hibernate some information, and it works based on it - I do not tell it what to do. In case of spring, my declaration tells spring exactly wht to do - so why declare it, why not just do it? LAST UPDATE: Guys, a lot of answers are telling me about dependency injection, which I KNOW IS GOOD.The question is about purpose of DI configuration instead of initializing code - I tend to think that initializing code is shorter and clearer.The only answer I got so far to my question, is that it avoids recompiling, when the configuration changes. I guess I should post another question, because it is a big secret for me, why compiling should be avoided in this case.
For myself one of the main reasons to use an IoC (and make use of external configuration) is around the two areas of: Testing Production maintenance Testing If you split your testing into 3 scenarios (which is fairly normal in large scale development): Unit testing Integration testing Black box testing What you will want to do is for the last two test scenarios (Integration & Black box), is not recompile any part of the application. If any of your test scenarios require you to change the configuration (ie: use another component to mimic a banking integration, or do a performance load), this can be easily handled (this does come under the benefits of configuring the DI side of an IoC though. Additionally if your app is used either at multiple sites (with different server and component configuration) or has a changing configuration on the live environment you can use the later stages of testing to verify that the app will handle those changes. Production As a developer you don't (and should not) have control of the production environment (in particular when your app is being distributed to multiple customers or seperate sites), this to me is the real benefit of using both an IoC and external configuration, as it is up to the infrastructure/production support to tweak and adjust the live environment without having to go back to developers and through test (higher cost when all they want to do is move a component). Summary The main benefits that external configuration of an IoC come from giving others (non-developers) the power to configure your application, in my experience this is only useful under a limited set of circumstances: Application is distributed to multiple sites/clients where environments will differ. Limited development control/input over the production environment and setup. Testing scenarios. In practice I've found that even when developing something that you do have control over the environment it will be run on, over time it is better to give someone else the capabilities to change the configuration: When developing you don't know when it will change (the app is so useful your company sells it to someone else). I don't want to be stuck with changing the code every time a slight change is requested that could have been handled by setting up and using a good configuration model. Note: Application refers to the complete solution (not just the executable), so all files required for the application to run .
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/131975", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5507/" ] }
131,985
See the question. I want to see the methods and classes offered by a DLLs library.
This is exactly what the Object Browser is for. Add a reference to the DLL. Right click it in the list. Click View in Object Browser .
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/131985", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6583/" ] }
131,989
I want to find out all the subdomains of a given domain. I found a hint which tells me to dig the authoritative Nameserver with the following option: dig @ns1.foo.example example.com axfr But this never works. Has anyone a better idea/approach
The hint (using axfr) only works if the NS you're querying ( ns1.foo.example in your example) is configured to allow AXFR requests from the IP you're using; this is unlikely, unless your IP is configured as a secondary for the domain in question. Basically, there's no easy way to do it if you're not allowed to use axfr. This is intentional, so the only way around it would be via brute force (i.e. dig a.example.com , dig b.example.com , ...), which I can't recommend, as it could be viewed as a denial of service attack.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/131989", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22029/" ] }
132,052
I deploy a webapp on two different containers (Tomcat and Jetty), but their default servlets for serving the static content have a different way of handling the URL structure I want to use ( details ). I am therefore looking to include a small servlet in the webapp to serve its own static content (images, CSS, etc.). The servlet should have the following properties: No external dependencies Simple and reliable Support for If-Modified-Since header (i.e. custom getLastModified method) (Optional) support for gzip encoding, etags,... Is such a servlet available somewhere? The closest I can find is example 4-10 from the servlet book. Update: The URL structure I want to use - in case you are wondering - is simply: <servlet-mapping> <servlet-name>main</servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>/static/*</url-pattern> </servlet-mapping> So all requests should be passed to the main servlet, unless they are for the static path. The problem is that Tomcat's default servlet does not take the ServletPath into account (so it looks for the static files in the main folder), while Jetty does (so it looks in the static folder).
There is no need for completely custom implementation of the default servlet in this case, you can use this simple servlet to wrap request to the container's implementation: package com.example;import java.io.*;import javax.servlet.*;import javax.servlet.http.*;public class DefaultWrapperServlet extends HttpServlet{ public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { RequestDispatcher rd = getServletContext().getNamedDispatcher("default"); HttpServletRequest wrapped = new HttpServletRequestWrapper(req) { public String getServletPath() { return ""; } }; rd.forward(wrapped, resp); }}
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/132052", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6918/" ] }
132,058
I have this Python application that gets stuck from time to time and I can't find out where. Is there any way to signal Python interpreter to show you the exact code that's running? Some kind of on-the-fly stacktrace? Related questions: Print current call stack from a method in Python code Check what a running process is doing: print stack trace of an uninstrumented Python program
I have module I use for situations like this - where a process will be running for a long time but gets stuck sometimes for unknown and irreproducible reasons. Its a bit hacky, and only works on unix (requires signals): import code, traceback, signaldef debug(sig, frame): """Interrupt running process, and provide a python prompt for interactive debugging.""" d={'_frame':frame} # Allow access to frame object. d.update(frame.f_globals) # Unless shadowed by global d.update(frame.f_locals) i = code.InteractiveConsole(d) message = "Signal received : entering python shell.\nTraceback:\n" message += ''.join(traceback.format_stack(frame)) i.interact(message)def listen(): signal.signal(signal.SIGUSR1, debug) # Register handler To use, just call the listen() function at some point when your program starts up (You could even stick it in site.py to have all python programs use it), and let it run. At any point, send the process a SIGUSR1 signal, using kill, or in python: os.kill(pid, signal.SIGUSR1) This will cause the program to break to a python console at the point it is currently at, showing you the stack trace, and letting you manipulate the variables. Use control-d (EOF) to continue running (though note that you will probably interrupt any I/O etc at the point you signal, so it isn't fully non-intrusive. I've another script that does the same thing, except it communicates with the running process through a pipe (to allow for debugging backgrounded processes etc). Its a bit large to post here, but I've added it as a python cookbook recipe .
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/132058", "https://Stackoverflow.com", "https://Stackoverflow.com/users/189/" ] }
132,092
I think everyone would agree that the MATLAB language is not pretty, or particularly consistent. But nevermind! We still have to use it to get things done. What are your favourite tricks for making things easier? Let's have one per answer so people can vote them up if they agree. Also, try to illustrate your answer with an example.
Turn a matrix into a vector using a single colon. x = rand(4,4);x(:)
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/132092", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15368/" ] }
132,134
What is the best way to secure an intranet website developed using PHP from outside attacks?
That's a stunningly thought-provoking question, and I'm surprised that you haven't received better answers. Summary Everything you would do for an external-facing application, and then some. Thought Process If I'm understanding you correctly, then you are asking a question which very few developers are asking themselves. Most companies have poor defence in depth, and once an attacker is in, he's in. Clearly you want to take it up a level. So, what kind of attack are we thinking about? If I'm the attacker and I'm attacking your intranet application, then I must have got access to your network somehow. This may not be as difficult as it sounds - I might try spearphishing (targetting email to individuals in your organisation, containing either malware attachements or links to sites which install malware) to get a trojan installed on an internal machine. Once I've done this (and got control of an internal PC), I'll try all the same attacks I would try against any internet application. However, that's not the end of the story. I've got more options: if I've got one of your user's PCs, then I might well be able to use a keylogger to gather usernames and passwords, as well as watching all your email for names and phone numbers. Armed with these, I may be able to log into your application directly. I may even learn an admin username/password. Even if I don't, a list of names and phone numbers along with a feel for company lingo gives me a decent shot at socially engineering my way into wider access within your company. Recommendations First and foremost, before all technical solutions: TRAIN YOUR USERS IN SECURITY The common answers to securing a web app: Use multi-factor authentication e.g. username/password and some kind of pseudo-random number gadget. Sanitise all your input. to protect against cross-site scripting and SQL injection. Use SSL (otherwise known as HTTPS). this is a pain to set up (EDIT: actually that's improving), but it makes for much better security. Adhere to the principals of "Segregation of Duties" and "Least Priviledge" In other words, by ensuring that all users have only the permissions they need to do their jobs (and nobody else's jobs) you make sure they have the absolute minimum ability to do damage.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/132134", "https://Stackoverflow.com", "https://Stackoverflow.com/users/950778/" ] }
132,194
I just figured out that I can actually store objects in the $_SESSION and I find it quite cool because when I jump to another page I still have my object. Now before I start using this approach I would like to find out if it is really such a good idea or if there are potential pitfalls involved. I know that if I had a single point of entry I wouldn't need to do that but I'm not there yet so I don't have a single point of entry and I would really like to keep my object because I don't lose my state like that. (Now I've also read that I should program stateless sites but I don't understand that concept yet.) So in short : Is it ok to store objects in the session, are there any problems with it? Edit: Temporary summary : By now I understand that it is probably better to recreate the object even if it involves querying the database again. Further answers could maybe elaborate on that aspect a bit more!
I know this topic is old, but this issue keeps coming up and has not been addressed to my satisfaction: Whether you save objects in $_SESSION, or reconstruct them whole cloth based on data stashed in hidden form fields, or re-query them from the DB each time, you are using state. HTTP is stateless (more or less; but see GET vs. PUT) but almost everything anybody cares to do with a web app requires state to be maintained somewhere. Acting as if pushing the state into nooks and crannies amounts to some kind of theoretical win is just wrong. State is state. If you use state, you lose the various technical advantages gained by being stateless. This is not something to lose sleep over unless you know in advance that you ought to be losing sleep over it. I am especially flummoxed by the blessing received by the "double whammy" arguments put forth by Hank Gay. Is the OP building a distributed and load-balanced e-commerce system? My guess is no; and I will further posit that serializing his $User class, or whatever, will not cripple his server beyond repair. My advice: use techniques that are sensible to your application. Objects in $_SESSION are fine, subject to common sense precautions. If your app suddenly turns into something rivaling Amazon in traffic served, you will need to re-adapt. That's life.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/132194", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11995/" ] }
132,231
When I'm writing a Spring command line application which parses command line arguments, how do I pass them to Spring? Would I want to have my main() structured so that it first parses the command line args and then inits Spring? Even so, how would it pass the object holding the parsed args to Spring?
Two possibilities I can think of. 1) Set a static reference. (A static variable, although typically frowned upon, is OK in this case, because there can only be 1 command line invocation). public class MyApp { public static String[] ARGS; public static void main(String[] args) { ARGS = args; // create context }} You can then reference the command line arguments in Spring via: <util:constant static-field="MyApp.ARGS"/> Alternatively (if you are completely opposed to static variables), you can: 2) Programmatically add the args to the application context: public class MyApp2 { public static void main(String[] args) { DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); // Define a bean and register it BeanDefinition beanDefinition = BeanDefinitionBuilder. rootBeanDefinition(Arrays.class, "asList") .addConstructorArgValue(args).getBeanDefinition(); beanFactory.registerBeanDefinition("args", beanDefinition); GenericApplicationContext cmdArgCxt = new GenericApplicationContext(beanFactory); // Must call refresh to initialize context cmdArgCxt.refresh(); // Create application context, passing command line context as parent ApplicationContext mainContext = new ClassPathXmlApplicationContext(CONFIG_LOCATIONS, cmdArgCxt); // See if it's in the context System.out.println("Args: " + mainContext.getBean("args")); } private static String[] CONFIG_LOCATIONS = new String[] { "applicationContext.xml" }; } Parsing the command line arguments is left as an exercise to the reader.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/132231", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22063/" ] }
132,241
I know there is a standard behind all C compiler implementations, so there should be no hidden features. Despite that, I am sure all C developers have hidden/secret tricks they use all the time.
Function pointers. You can use a table of function pointers to implement, e.g., fast indirect-threaded code interpreters (FORTH) or byte-code dispatchers, or to simulate OO-like virtual methods. Then there are hidden gems in the standard library, such as qsort(),bsearch(), strpbrk(), strcspn() [the latter two being useful for implementing a strtok() replacement]. A misfeature of C is that signed arithmetic overflow is undefined behavior (UB). So whenever you see an expression such as x+y, both being signed ints, it might potentially overflow and cause UB.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/132241", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21548/" ] }
132,277
I've got a web application that is running against Windows Authentication using our Active Directory. I've got a new requirement to pull some personal information through from the Active Directory entry. What would be the easiest way to get access to this information?
Accessing the user directly through a DirectoryEntry seems like the most straightforward approach. Here are some AD-related tidbits I learned from my first AD-related project: In a URI, write LDAP in lowercase. Otherwise you'll get a mystery error. I spent more than a day on this depressing issue... To clear a single-valued property, set it to an empty string, not null. Null causes an exception. To clear a multi-valued property, use the DirectoryEntry.Property.Clear() method. The Active Directory schema reference will say which data type a value will be and whether it is multi-value or single-value. You do not need to manually RefreshCache() on a Directoryentry but if you ever use it and specify which properties to cache, know that it will not auto-retrieve any other properties in the future. A COMException can be thrown at absolutely any time you use the classes in System.DirectoryServices. Keep an eye on those try blocks. Do not assume anything is safe. You'll probably need to use DirectorySearcher to get your user's directory entry if you don't know its path (which you wouldn't, just by having him logged in). Using it was fairly easy but beware of the quirks in LDAP syntax; namely, having to encode non-ASCII (and other?) characters. The search string you'd use would probably be something like: (&(sAMAccountName=whatever)(class=user)) . This is off the top of my head and may be slightly incorrect. The Active Directory schema reference will be useful. Do understand that the schema can be modified and extended (e.g. installing Exchange will add mailbox information to users). AD Explorer is a useful tool which you can use for debugging and low-level AD data management. I've found it useful when I know which property I want to set but cannot find the right dialog box in the AD management tool.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/132277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5802/" ] }
132,318
I have an ANSI encoded text file that should not have been encoded as ANSI as there were accentedcharacters that ANSI does not support. I would rather work with UTF-8. Can the data be decoded correctly or is it lost in transcoding? What tools could I use? Here is a sample of what I have: ç é I can tell from context (café should be café) that these should be these two characters: ç é
EDIT: A simple possibility to eliminate before getting into more complicated solutions: have you tried setting the character set to utf8 in the text editor in which you're reading the file? This could just be a case of somebody sending you a utf8 file that you're reading in an editor set to say cp1252. Just taking the two examples, this is a case of utf8 being read through the lens of a single-byte encoding, likely one of iso-8859-1, iso-8859-15, or cp1252. If you can post examples of other problem characters, it should be possible to narrow that down more. As visual inspection of the characters can be misleading, you'll also need to look at the underlying bytes: the § you see on screen might be either 0xa7 or 0xc2a7, and that will determine the kind of character set conversion you have to do. Can you assume that all of your data has been distorted in exactly the same way - that it's come from the same source and gone through the same sequence of transformations, so that for example there isn't a single é in your text, it's always ç? If so, the problem can be solved with a sequence of character set conversions. If you can be more specific about the environment you're in and the database you're using, somebody here can probably tell you how to perform the appropriate conversion. Otherwise, if the problem characters are only occurring in some places in your data, you'll have to take it instance by instance, based on assumptions along the lines of "no author intended to put ç in their text, so whenever you see it, replace by ç". The latter option is more risky, firstly because those assumptions about the intentions of the authors might be wrong, secondly because you'll have to spot every problem character yourself, which might be impossible if there's too much text to visually inspect or if it's written in a language or writing system that's foreign to you.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/132318", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18333/" ] }
132,323
When iterating over elements of a vector it is preferred to use iterators instead of an index (see Why use iterators instead of array indices? ). std::vector<T> vec;std::vector<T>::iterator it;for ( it = vec.begin(); it != vec.end(); ++it ){ // do work} However, it can be necessary to use the index in the body of the loop. Which of the following would be preferable in that case, considering performance and flexibility/extensibility? Revert to the indexed loop std::vector vec;size_t i;for ( i = 0; i < vec.size(); ++i ){ // use i} Calculate offset std::vector vec;std::vector::iterator it;for ( it = vec.begin(); it != vec.end(); ++it ){ size_t i = it - vec.begin(); // use i} Use std::distance std::vector vec;std::vector::iterator it;for ( it = vec.begin(); it != vec.end(); ++it ){ size_t i = std::distance( vec.begin(), it ); // use i}
If you're planning on using exclusively a vector, you may want to switch back to the indexed loop, since it conveys your intent more clearly than iterator-loop. However, if evolution of your program in the future may lead to a change of container, you should stick to the iterators and use std::distance, which is guaranteed to work with all standard iterators.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/132323", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19863/" ] }
132,358
In order to improve performance reading from a file, I'm trying to read the entire content of a big (several MB) file into memory and then use a istringstream to access the information. My question is, which is the best way to read this information and "import it" into the string stream? A problem with this approach (see bellow) is that when creating the string stream the buffers gets copied, and memory usage doubles. #include <fstream>#include <sstream>using namespace std;int main() { ifstream is; is.open (sFilename.c_str(), ios::binary ); // get length of file: is.seekg (0, std::ios::end); long length = is.tellg(); is.seekg (0, std::ios::beg); // allocate memory: char *buffer = new char [length]; // read data as a block: is.read (buffer,length); // create string stream of memory contents // NOTE: this ends up copying the buffer!!! istringstream iss( string( buffer ) ); // delete temporary buffer delete [] buffer; // close filestream is.close(); /* ================================== * Use iss to access data */}
std::ifstream has a method rdbuf() , that returns a pointer to a filebuf . You can then "push" this filebuf into your stringstream : #include <fstream>#include <sstream>int main(){ std::ifstream file( "myFile" ); if ( file ) { std::stringstream buffer; buffer << file.rdbuf(); file.close(); // operations on the buffer... }} EDIT: As Martin York remarks in the comments, this might not be the fastest solution since the stringstream 's operator<< will read the filebuf character by character. You might want to check his answer, where he uses the ifstream 's read method as you used to do, and then set the stringstream buffer to point to the previously allocated memory.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/132358", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20317/" ] }
132,359
What are the technologies and programming decisions that make Google able to serve a query so fast? Every time I search something (one of the several times per day) it always amazes me how they serve the results in near or less than 1 second time. What sort of configuration and algorithms could they have in place that accomplishes this? Side note: It is kind of overwhelming thinking that even if I was to put a desktop application and use it on my machine probably would not be half as fast as Google. Keep on learning I say. Here are some of the great answers and pointers provided: Google Platform Map Reduce Algorithms carefully crafted Hardware - cluster farms and massive number of cheap computers Caching and Load Balancing Google File System
Latency is killed by disk accesses. Hence it's reasonable to believe that all data used to answer queries is kept in memory. This implies thousands of servers, each replicating one of many shards. Therefore the critical path for search is unlikely to hit any of their flagship distributed systems technologies GFS, MapReduce or BigTable. These will be used to process crawler results, crudely. The handy thing about search is that there's no need to have either strongly consistent results or completely up-to-date data, so Google are not prevented from responding to a query because a more up-to-date search result has become available. So a possible architecture is quite simple: front end servers process the query, normalising it (possibly by stripping out stop words etc.) then distributing it to whatever subset of replicas owns that part of the query space (an alternative architecture is to split the data up by web pages, so that one of every replica set needs to be contacted for every query). Many, many replicas are probably queried, and the quickest responses win. Each replica has an index mapping queries (or individual query terms) to documents which they can use to look up results in memory very quickly. If different results come back from different sources, the front-end server can rank them as it spits out the html. Note that this is probably a long way different from what Google actually do - they will have engineered the life out of this system so there may be more caches in strange areas, weird indexes and some kind of funky load-balancing scheme amongst other possible differences.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/132359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6508/" ] }
132,397
When I do an "os.execute" in Lua, a console quickly pops up, executes the command, then closes down. But is there some way of getting back the console output only using the standard Lua libraries?
I think you want this http://pgl.yoyo.org/luai/i/io.popen io.popen. But it's not always compiled in.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/132397", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12291/" ] }
132,405
Are there any good alternatives that support writing regexps in different flavors and allow you to test them?
Here's a list of the Regex tools mentioned across the threads: Regulator Expresso .NET Regular Expression Designer Regex-Coach larsolavtorvik online tool Regex Pal Regular Expression Workbench Rubular Reggy RegExr
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/132405", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11439/" ] }
132,445
Consider the following code: void Handler(object o, EventArgs e){ // I swear o is a string string s = (string)o; // 1 //-OR- string s = o as string; // 2 // -OR- string s = o.ToString(); // 3} What is the difference between the three types of casting (okay, the 3rd one is not a casting, but you get the intent). Which one should be preferred?
string s = (string)o; // 1 Throws InvalidCastException if o is not a string . Otherwise, assigns o to s , even if o is null . string s = o as string; // 2 Assigns null to s if o is not a string or if o is null . For this reason, you cannot use it with value types (the operator could never return null in that case). Otherwise, assigns o to s . string s = o.ToString(); // 3 Causes a NullReferenceException if o is null . Assigns whatever o.ToString() returns to s , no matter what type o is. Use 1 for most conversions - it's simple and straightforward. I tend to almost never use 2 since if something is not the right type, I usually expect an exception to occur. I have only seen a need for this return-null type of functionality with badly designed libraries which use error codes (e.g. return null = error, instead of using exceptions). 3 is not a cast and is just a method invocation. Use it for when you need the string representation of a non-string object.
{ "score": 11, "source": [ "https://Stackoverflow.com/questions/132445", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6621/" ] }
132,478
I need to perform Diffs between Java strings. I would like to be able to rebuild a string using the original string and diff versions. Has anyone done this in Java? What library do you use? String a1; // This can be a long textString a2; // ej. above text with spelling correctionsString a3; // ej. above text with spelling corrections and an additional sentenceDiff diff = new Diff();String differences_a1_a2 = Diff.getDifferences(a,changed_a);String differences_a2_a3 = Diff.getDifferences(a,changed_a); String[] diffs = new String[]{a,differences_a1_a2,differences_a2_a3};String new_a3 = Diff.build(diffs);a3.equals(new_a3); // this is true
This library seems to do the trick: google-diff-match-patch . It can create a patch string from differences and allow to reapply the patch. edit : Another solution might be to https://code.google.com/p/java-diff-utils/
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/132478", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2138/" ] }
132,489
I'm pretty sure most of us are familiar with the concept of a project's requirements changing after it starts, this becomes more and more of an issue the less the client knows about how things work and the closer you work with them. How then can I design a system (specifically a website but general advice will probably be best here) so that smallish changes can be made, are there any programming strategies that deal with this issue?
All the normal oo principles apply here, reduce coupling, increase cohesion, don't repeat yourself etc. This will make sure you have a flexible and extendible code base. Apart from that don't try to preempt change. Apply YAGNI (You aint gonna need it) everywhere. Only build stuff you know your users need. Dont build stuff you think you're going to need. You're more likely to guess wrong and then you've got a bunch of code that's probably only in the way.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/132489", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1384652/" ] }
132,544
I have a .NET application which has different configuration files for Debug and Release builds. E.g. the debug app.config file points to a development SQL Server which has debugging enabled and the release target points to the live SQL Server. There are also other settings, some of which are different in debug/release. I currently use two separate configuration files (debug.app.config and release.app.config). I have a build event on the project which says if this is a release build then copy release.app.config to app.config, else copy debug.app.config to app.config. The problem is that the application seems to get its settings from the settings.settings file, so I have to open settings.settings in Visual Studio which then prompts me that the settings have changed so I accept the changes, save settings.settings and have to rebuild to make it use the correct settings. Is there a better/recommended/preferred method for achieving a similar effect? Or equally, have I approached this completely wrong and is there a better approach?
Any configuration that might differ across environments should be stored at the machine level , not the application level . (More info on configuration levels.) These are the kinds of configuration elements that I typically store at the machine level: Application settings Connection strings retail=true Smtp settings Health monitoring Hosting environment Machine key When each environment (developer, integration, test, stage, live) has its own unique settings in the c:\Windows\Microsoft.NET\Framework64\v2.0.50727\CONFIG directory, then you can promote your application code between environments without any post-build modifications. And obviously, the contents of the machine-level CONFIG directory get version-controlled in a different repository or a different folder structure from your app. You can make your .config files more source-control friendly through intelligent use of configSource . I've been doing this for 7 years, on over 200 ASP.NET applications at 25+ different companies. (Not trying to brag, just want to let you know that I've never seen a situation where this approach doesn't work.)
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/132544", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8354/" ] }
132,564
I'm working in Java with XML and I'm wondering; what's the difference between an element and a node?
The Node object is the primary data type for the entire DOM. A node can be an element node, an attribute node, a text node, or any other of the node types explained in the "Node types" chapter. An XML element is everything from (including) the element's start tag to (including) the element's end tag.
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/132564", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21709/" ] }
132,620
Here's the scenario: You have a Windows server that users remotely connect to via RDP. You want your program (which runs as a service) to know who is currently connected. This may or may not include an interactive console session. Please note that this is the not the same as just retrieving the current interactive user. I'm guessing that there is some sort of API access to Terminal Services to get this info?
Here's my take on the issue: using System;using System.Collections.Generic;using System.Runtime.InteropServices;namespace EnumerateRDUsers{ class Program { [DllImport("wtsapi32.dll")] static extern IntPtr WTSOpenServer([MarshalAs(UnmanagedType.LPStr)] string pServerName); [DllImport("wtsapi32.dll")] static extern void WTSCloseServer(IntPtr hServer); [DllImport("wtsapi32.dll")] static extern Int32 WTSEnumerateSessions( IntPtr hServer, [MarshalAs(UnmanagedType.U4)] Int32 Reserved, [MarshalAs(UnmanagedType.U4)] Int32 Version, ref IntPtr ppSessionInfo, [MarshalAs(UnmanagedType.U4)] ref Int32 pCount); [DllImport("wtsapi32.dll")] static extern void WTSFreeMemory(IntPtr pMemory); [DllImport("wtsapi32.dll")] static extern bool WTSQuerySessionInformation( IntPtr hServer, int sessionId, WTS_INFO_CLASS wtsInfoClass, out IntPtr ppBuffer, out uint pBytesReturned); [StructLayout(LayoutKind.Sequential)] private struct WTS_SESSION_INFO { public Int32 SessionID; [MarshalAs(UnmanagedType.LPStr)] public string pWinStationName; public WTS_CONNECTSTATE_CLASS State; } public enum WTS_INFO_CLASS { WTSInitialProgram, WTSApplicationName, WTSWorkingDirectory, WTSOEMId, WTSSessionId, WTSUserName, WTSWinStationName, WTSDomainName, WTSConnectState, WTSClientBuildNumber, WTSClientName, WTSClientDirectory, WTSClientProductId, WTSClientHardwareId, WTSClientAddress, WTSClientDisplay, WTSClientProtocolType } public enum WTS_CONNECTSTATE_CLASS { WTSActive, WTSConnected, WTSConnectQuery, WTSShadow, WTSDisconnected, WTSIdle, WTSListen, WTSReset, WTSDown, WTSInit } static void Main(string[] args) { ListUsers(Environment.MachineName); } public static void ListUsers(string serverName) { IntPtr serverHandle = IntPtr.Zero; List<string> resultList = new List<string>(); serverHandle = WTSOpenServer(serverName); try { IntPtr sessionInfoPtr = IntPtr.Zero; IntPtr userPtr = IntPtr.Zero; IntPtr domainPtr = IntPtr.Zero; Int32 sessionCount = 0; Int32 retVal = WTSEnumerateSessions(serverHandle, 0, 1, ref sessionInfoPtr, ref sessionCount); Int32 dataSize = Marshal.SizeOf(typeof(WTS_SESSION_INFO)); IntPtr currentSession = sessionInfoPtr; uint bytes = 0; if (retVal != 0) { for (int i = 0; i < sessionCount; i++) { WTS_SESSION_INFO si = (WTS_SESSION_INFO)Marshal.PtrToStructure((System.IntPtr)currentSession, typeof(WTS_SESSION_INFO)); currentSession += dataSize; WTSQuerySessionInformation(serverHandle, si.SessionID, WTS_INFO_CLASS.WTSUserName, out userPtr, out bytes); WTSQuerySessionInformation(serverHandle, si.SessionID, WTS_INFO_CLASS.WTSDomainName, out domainPtr, out bytes); Console.WriteLine("Domain and User: " + Marshal.PtrToStringAnsi(domainPtr) + "\\" + Marshal.PtrToStringAnsi(userPtr)); WTSFreeMemory(userPtr); WTSFreeMemory(domainPtr); } WTSFreeMemory(sessionInfoPtr); } } finally { WTSCloseServer(serverHandle); } } }}
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/132620", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7837/" ] }
132,649
What is the difference between overflow:hidden and display:none?
Example: .oh{ height: 50px; width: 200px; overflow: hidden;} If text in the block with this class is bigger (longer) than what this little box can display, the excess will be just hidden. You will see the start of the text only. display: none; will just hide the block. Note you have also visibility: hidden; which hides the content of the block, but the block will be still in the layout, moving things around.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/132649", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21067/" ] }
132,667
While developing a C++ application, I had to use a third-party library which produced a huge amount of warnings related with a harmless #pragma directive being used. ../File.hpp:1: warning: ignoring #pragma identIn file included from ../File2.hpp:47, from ../File3.hpp:57, from File4.h:49, Is it possible to disable this kind of warnings, when using the GNU C++ compiler?
I believe you can compile with -Wno-unknown-pragmas to suppress these.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/132667", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20317/" ] }
132,685
When setting the size of fonts in CSS, should I be using a percent value ( % ) or em ? Can you explain the advantage?
There's a really good article on web typography on A List Apart . Their conclusion: Sizing text and line-height in ems, with a percentage specified on the body (and an optional caveat for Safari 2), was shown to provide accurate, resizable text across all browsers in common use today. This is a technique you can put in your kit bag and use as a best practice for sizing text in CSS that satisfies both designers and readers.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/132685", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16440/" ] }
132,719
I have a Visual Studio (2008) solution consisting of several projects, not all in the same namespace. When I build the solution, all the DLL files used by the top level project, TopProject , are copied into the TopProject\bin\debug folder. However, the corresponding .pdb files are only copied for some of the other projects. This is a pain, for example when using NDepend . How does Visual Studio decide which .pdb files to copy into higher level bin\debug folders? How can I get Visual Studio to copy the others too? References are as follows: all the DLL files are copied to a central location, without their PDB files. TopProject only has references to these copied DLL files; the DLL files themselves, however, evidently know where their PDB files are, and (most of them) get copied to the debug folder correctly.
From MSDN : A program database (PDB) file holds debugging and project state information that allows incremental linking of a Debug configuration of your program. A PDB file is created when you compile a C/C++ program with /ZI or /Zi or a Visual Basic/C#/JScript .NET program with /debug. So it looks like the "issue" here (for lack of a better word) is that some of your DLLs are being built in debug mode (and hence emitting PDB files), and some are being built in release mode (hence not emitting PDB files). If that's the case, it should be easy to fix -- go into each project and update its build settings. This would be the default scenario, if you haven't done any tweaking of command line options. However, it will get trickier if that isn't the case. Maybe you're all in release or debug mode. Now you need to look at the command line compile options (specified in the project properties) for each project. Update them to /debug accordingly if you want the debugger, or remove it if you don't. Edit in Response to Edit Yes, the DLL files "know" that they have PDB files, and have paths to them, but that doesn't mean too much. Copying just DLL files to a given directory, as others have mentioned, won't clear this issue up. You need the PDB files as well. Copying individual files in Windows, with the exception of certain "bundle"-type files (I don't know Microsoft's term for this, but "complete HTML packages" are the concept) doesn't copy associated files. DLL files aren't assembled in the "bundle" way, so copying them leaves their PDB file behind. I'd say the only answer you're going to have is to update your process for getting the DLL files to those central locations, and include the PDB files ... I'd love to be proven wrong on that, though!
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/132719", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6091/" ] }
132,725
I'm new to Delphi, and I've been running some tests to see what object variables and stack variables are initialized to by default: TInstanceVariables = class fBoolean: boolean; // always starts off as false fInteger: integer; // always starts off as zero fObject: TObject; // always starts off as nilend; This is the behaviour I'm used to from other languages, but I'm wondering if it's safe to rely on it in Delphi? For example, I'm wondering if it might depend on a compiler setting, or perhaps work differently on different machines. Is it normal to rely on default initialized values for objects, or do you explicitly set all instance variables in the constructor? As for stack (procedure-level) variables, my tests are showing that unitialized booleans are true, unitialized integers are 2129993264, and uninialized objects are just invalid pointers (i.e. not nil). I'm guessing the norm is to always set procedure-level variables before accessing them?
Yes, this is the documented behaviour: Object fields are always initialized to 0, 0.0, '', False, nil or whatever applies. Global variables are always initialized to 0 etc as well; Local reference-counted* variables are always initialized to nil or ''; Local non reference-counted* variables are uninitialized so you have to assign a value before you can use them. I remember that Barry Kelly somewhere wrote a definition for "reference-counted", but cannot find it any more, so this should do in the meantime: reference-counted == that are reference-counted themselves, or directly or indirectly contain fields (for records) or elements (for arrays) that are reference-counted like: string, variant, interface or dynamic array or static array containing such types. Notes: record itself is not enough to become reference-counted I have not tried this with generics yet
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/132725", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11961/" ] }
132,738
I'm a C/C++ developer, and here are a couple of questions that always baffled me. Is there a big difference between "regular" code and inline code? Which is the main difference? Is inline code simply a "form" of macros? What kind of tradeoff must be done when choosing to inline your code? Thanks
Is there a big difference between "regular" code and inline code? Yes and no. No, because an inline function or method has exactly the same characteristics as a regular one, most important one being that they are both type safe. And yes, because the assembly code generated by the compiler will be different; with a regular function, each call will be translated into several steps: pushing parameters on the stack, making the jump to the function, popping the parameters, etc, whereas a call to an inline function will be replaced by its actual code, like a macro. Is inline code simply a "form" of macros? No ! A macro is simple text replacement, which can lead to severe errors. Consider the following code: #define unsafe(i) ( (i) >= 0 ? (i) : -(i) )[...]unsafe(x++); // x is incremented twice!unsafe(f()); // f() is called twice![...] Using an inline function, you're sure that parameters will be evaluated before the function is actually performed. They will also be type checked, and eventually converted to match the formal parameters types. What kind of tradeoff must be done when choosing to inline your code? Normally, program execution should be faster when using inline functions, but with a bigger binary code. For more information, you should read GoTW#33 .
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/132738", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20317/" ] }
132,799
How can you you insert a newline from your batch file output? I want to do something like: echo hello\nworld Which would output: helloworld
echo hello & echo.world This means you could define & echo. as a constant for a newline \n .
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/132799", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3153/" ] }
132,812
I created a report model using SSRS (2005) and published to the local server. But when I tried to run the report for the model I published using report builder I get the following error. Report execution error:The permissions granted to user are insufficient for performing this operation. (rsAccessDenied)
It's because of lack of privilege for the user you are running the report builder, just give that user or a group a privilege to run report builder.Please visit this article Or for shortcut: Start Internet Explorer using "Run as Administrator" Open http://localhost/reports Go to properties tab (SSRS 2008) Security->New Role Assignment Add DOMAIN/USERNAME or DOMAIN/USERGROUP Check Report builder
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/132812", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14752/" ] }
132,867
The question I'm really asking is why require does not take the name of the gem. Also, In the case that it doesn't, what's the easiest way to find the secret incantation to require the damn thing!? As an example if I have memcache-client installed then I have to require it using require 'rubygems'require 'memcache'
There is no standard for what the file you need to include is. However there are some commonly followed conventions that you can can follow try and make use of: Often the file is called the samename as the gem. So require mygem will work. Often the file isthe only .rb file in the libsubdirectory of the gem, So if youcan get the name of the gem (maybeyou are itterating throughvendor/gems in a pre 2.1 railsproject), then you can inspect #{gemname}/lib for .rb files, andif there is only one, its a prettygood bet that is the one to require If all of that works, then all you can do is look into the gem's directory (which you can find by running gem environment | grep INSTALLATION | awk '{print $4}' and looking in the lib directory, You will probably need to read the files and hope there is a comment explaining what to do
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/132867", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18751/" ] }
132,885
I need to switch among 3 different environments when developing my web app - Development, UAT, and Prod. I have different database connections in my configuration files for all 3. I have seen switching these settings done manually by changing all references and then rebuilding the solution, and also done with preprocessor directives. Is there an easy way to do this based on some variable so that the configuration doesn't have to be revised when deploying to a new environment every time?
To me it seems that you can benefit from the Visual Studio 2005 Web Deployment Project s. With that, you can tell it to update/modify sections of your web.config file depending on the build configuration. Take a look at this blog entry from Scott Gu for a quick overview/sample.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/132885", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1284/" ] }
132,902
I need to move entire tables from one MySQL database to another. I don't have full access to the second one, only phpMyAdmin access. I can only upload (compressed) sql files smaller than 2MB. But the compressed output from a mysqldump of the first database's tables is larger than 10MB. Is there a way to split the output from mysqldump into smaller files? I cannot use split(1) since I cannot cat(1) the files back on the remote server. Or is there another solution I have missed? Edit The --extended-insert=FALSE option to mysqldump suggested by the first poster yields a .sql file that can then be split into importable files, provided that split(1) is called with a suitable --lines option. By trial and error I found that bzip2 compresses the .sql files by a factor of 20, so I needed to figure out how many lines of sql code correspond roughly to 40MB.
First dump the schema (it surely fits in 2Mb, no?) mysqldump -d --all-databases and restore it. Afterwards dump only the data in separate insert statements, so you can split the files and restore them without having to concatenate them on the remote server mysqldump --all-databases --extended-insert=FALSE --no-create-info=TRUE
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/132902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1428/" ] }
132,940
Recently I noticed my application appears to be eating memory that never gets released. After profiling with CLRProfiler I've found that the Castle Windsor container I'm using is holding onto objects. These objects are declared with the lifestyle="transient" attribute in the config xml. I've found if I put an explicit call to IWindsorContainer.Release(hangingObject) , that it will drop its references. This is causing a problem though, I wasn't expecting that with a transient lifestyle object CastleWindsor would keep a reference and effectively create a leak. It's going to be a rather mundane and error prone task going around inserting explicit Release calls in all the appropriate places. Have you seen this problem, and do you have any suggestions for how to get around it?
I think the answers here are missing a vital point - that this behavior is configurable out of the box via release policies - check out the documentation on the castle project site here . In many scenarios especially where your container exists for the lifetime of the hosting application, and where transient components really don't need to be tracked (because you're handling disposal in your calling code or component that's been injected with the service) then you can just set the release policy to the NoTrackingReleasePolicy implementation and be done with it. Prior to Castle v 1.0 I believe Component Burden will be implemented/introduced - which will help alleviate some of these issues as well around disposal of injected dependencies etc. Edit: Check out the following posts for more discussion of component burden. The Component Burden - Davy Brions Also component burden is implemented in the official 2.0 release of the Windsor Container.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/132940", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11898/" ] }
132,955
How do I have a script run every, say 30 minutes? I assume there are different ways for different OSs. I'm using OS X.
Just use launchd . It is a very powerful launcher system and meanwhile it is the standard launcher system for Mac OS X (current OS X version wouldn't even boot without it). For those who are not familiar with launchd (or with OS X in general), it is like a crossbreed between init , cron , at , SysVinit ( init.d ), inetd , upstart and systemd . Borrowing concepts of all these projects, yet also offering things you may not find elsewhere. Every service/task is a file. The location of the file depends on the questions: "When is this service supposed to run?" and "Which privileges will the service require?" System tasks go to /Library/LaunchDaemons/ if they shall run no matter if any user is logged in to the system or not. They will be started with "root" privileges. If they shall only run if any user is logged in, they go to /Library/LaunchAgents/ and will be executed with the privileges of the user that just logged in. If they shall run only if you are logged in, they go to ~/Library/LaunchAgents/ where ~ is your HOME directory. These task will run with your privileges, just as if you had started them yourself by command line or by double clicking a file in Finder. Note that there also exists /System/Library/LaunchDaemons and /System/Library/LaunchAgents , but as usual, everything under /System is managed by OS X. You shall not place any files there, you shall not change any files there, unless you really know what you are doing. Messing around in the Systems folder can make your system unusable (get it into a state where it will even refuse to boot up again). These are the directories where Apple places the launchd tasks that get your system up and running during boot, automatically start services as required, perform system maintenance tasks, and so on. Every launchd task is a file in PLIST format. It should have reverse domain name notation. E.g. you can name your task com.example.my-fancy-task.plist This plist can have various options and settings. Writing one per hand is not for beginners, so you may want to get a tool like LaunchControl (commercial, $18) or Lingon (commercial, $14.99) to create your tasks. Just as an example, it could look like this <?xml version="1.0" encoding="UTF-8"?><!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"><plist version="1.0"><dict> <key>Label</key> <string>com.example.my-fancy-task</string> <key>OnDemand</key> <true/> <key>ProgramArguments</key> <array> <string>/bin/sh</string> <string>/usr/local/bin/my-script.sh</string> </array> <key>StartInterval</key> <integer>1800</integer></dict></plist> This agent will run the shell script /usr/local/bin/my-script.sh every 1800 seconds (every 30 minutes). You can also have task run on certain dates/times (basically launchd can do everything cron can do) or you can even disable "OnDemand" causing launchd to keep the process permanently running (if it quits or crashes, launchd will immediately restart it). You can even limit how much resources a process may use. Update: Even though OnDemand is still supported, it is deprecated. The new setting is named KeepAlive , which makes much more sense. It can have a boolean value, in which case it is the exact opposite of OnDemand (setting it to false behaves as if OnDemand is true and the other way round). The great new feature is, that it can also have a dictionary value instead of a boolean one. If it has a dictionary value, you have a couple of extra options that give you more fine grain control under which circumstances the task shall be kept alive. E.g. it is only kept alive as long as the program terminated with an exit code of zero, only as long as a certain file/directory on disk exists, only if another task is also alive, or only if the network is currently up. Also you can manually enable/disable tasks via command line: launchctl <command> <parameter> command can be load or unload , to load a plist or unload it again, in which case parameter is the path to the file. Or command can be start or stop , to just start or stop such a task, in which case parameter is the label ( com.example.my-fancy-task ). Other commands and options exist as well. Update: Even though load , unload , start , and stop do still work, they are legacy now. The new commands are bootstrap , bootout , enable , and disable with slightly different syntax and options. One big difference is that disable is persistent, so once a service has been disabled, it will stay disabled, even across reboots until you enable it again. Also you can use kickstart to run a task immediately, regardless how it has been configured to run. The main difference between the new and the old commands is that they separate tasks by "domain". The system has domain and so has every user. So equally labeled tasks may exist in different domains and launctl can still distinguish them. Even different login and different UI sessions of the same user have their own domain (e.g. the same user may once be logged locally and once remote via SSH and different tasks may run for either session) and so does every single running processes. Thus instead of com.example.my-fancy-task , you now would use system/com.example.my-fancy-task or user/501/com.example.my-fancy-task to identify a task, with 501 being the user ID of a specific user. See documentation of the plist format and of the launchctl command line tool .
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/132955", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1615/" ] }
132,971
A Google search turned up software that performs the same functions as cron, but nothing built into Windows. I'm running Windows XP Professional, but advice for any version of Windows would be potentially helpful to someone. Is there also a way to invoke this feature (which based on answers is called the Task Scheduler) programatically or via the command line?
For the original question, asking about Windows XP (and Windows 7): Windows Task Scheduler For command-line usage, you can schedule with the AT command . For newer Microsoft OS versions, Windows Server 2012 / Windows 8, look at the schtasks command line utility. If using PowerShell, the Scheduled Tasks Cmdlets in Windows PowerShell are made for scripting.
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/132971", "https://Stackoverflow.com", "https://Stackoverflow.com/users/572/" ] }
132,988
My Google-fu has failed me. In Python, are the following two tests for equality equivalent? n = 5# Test one.if n == 5: print 'Yay!'# Test two.if n is 5: print 'Yay!' Does this hold true for objects where you would be comparing instances (a list say)? Okay, so this kind of answers my question: L = []L.append(1)if L == [1]: print 'Yay!'# Holds true, but...if L is [1]: print 'Yay!'# Doesn't. So == tests value where is tests to see if they are the same object?
is will return True if two variables point to the same object (in memory), == if the objects referred to by the variables are equal. >>> a = [1, 2, 3]>>> b = a>>> b is a True>>> b == aTrue# Make a new copy of list `a` via the slice operator, # and assign it to variable `b`>>> b = a[:] >>> b is aFalse>>> b == aTrue In your case, the second test only works because Python caches small integer objects, which is an implementation detail. For larger integers, this does not work: >>> 1000 is 10**3False>>> 1000 == 10**3True The same holds true for string literals: >>> "a" is "a"True>>> "aa" is "a" * 2True>>> x = "a">>> "aa" is x * 2False>>> "aa" is intern(x*2)True Please see this question as well.
{ "score": 11, "source": [ "https://Stackoverflow.com/questions/132988", "https://Stackoverflow.com", "https://Stackoverflow.com/users/61/" ] }
133,008
What is Big O notation? Do you use it? I missed this university class I guess :D Does anyone use it and give some real life examples of where they used it? See also: Big-O for Eight Year Olds? Big O, how do you calculate/approximate it? Did you apply computational complexity theory in real life?
One important thing most people forget when talking about Big-O, thus I feel the need to mention that: You cannot use Big-O to compare the speed of two algorithms. Big-O only says how much slower an algorithm will get (approximately) if you double the number of items processed, or how much faster it will get if you cut the number in half. However, if you have two entirely different algorithms and one ( A ) is O(n^2) and the other one ( B ) is O(log n) , it is not said that A is slower than B . Actually, with 100 items, A might be ten times faster than B . It only says that with 200 items, A will grow slower by the factor n^2 and B will grow slower by the factor log n . So, if you benchmark both and you know how much time A takes to process 100 items, and how much time B needs for the same 100 items, and A is faster than B , you can calculate at what amount of items B will overtake A in speed (as the speed of B decreases much slower than the one of A , it will overtake A sooner or later—this is for sure).
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/133008", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3208/" ] }
133,031
I need to add a specific column if it does not exist. I have something like the following, but it always returns false: IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'myTableName' AND COLUMN_NAME = 'myColumnName') How can I check if a column exists in a table of the SQL Server database?
SQL Server 2005 onwards: IF EXISTS(SELECT 1 FROM sys.columns WHERE Name = N'columnName' AND Object_ID = Object_ID(N'schemaName.tableName'))BEGIN -- Column ExistsEND Martin Smith's version is shorter: IF COL_LENGTH('schemaName.tableName', 'columnName') IS NOT NULLBEGIN -- Column ExistsEND
{ "score": 12, "source": [ "https://Stackoverflow.com/questions/133031", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2631856/" ] }
133,051
The CSS rules visibility:hidden and display:none both result in the element not being visible. Are these synonyms?
display:none means that the tag in question will not appear on the page at all (although you can still interact with it through the dom). There will be no space allocated for it between the other tags. visibility:hidden means that unlike display:none , the tag is not visible, but space is allocated for it on the page. The tag is rendered, it just isn't seen on the page. For example: test | <span style="[style-tag-value]">Appropriate style in this tag</span> | test Replacing [style-tag-value] with display:none results in: test | | test Replacing [style-tag-value] with visibility:hidden results in: test |                        | test
{ "score": 12, "source": [ "https://Stackoverflow.com/questions/133051", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14749/" ] }
133,081
In MS SQL 2000 and 2005, given a datetime such as '2008-09-25 12:34:56' what is the most efficient way to get a datetime containing only '2008-09-25'? Duplicated here .
I must admit I hadn't seen the floor-float conversion shown by Matt before. I had to test this out. I tested a pure select (which will return Date and Time, and is not what we want), the reigning solution here (floor-float), a common 'naive' one mentioned here (stringconvert) and the one mentioned here that I was using (as I thought it was the fastest). I tested the queries on a test-server MS SQL Server 2005 running on a Win 2003 SP2 Server with a Xeon 3GHz CPU running on max memory (32 bit, so that's about 3.5 Gb). It's night where I am so the machine is idling along at almost no load. I've got it all to myself. Here's the log from my test-run selecting from a large table containing timestamps varying down to the millisecond level. This particular dataset includes dates ranging over 2.5 years. The table itself has over 130 million rows, so that's why I restrict to the top million. SELECT TOP 1000000 CRETS FROM tblMeasureLogv2 SELECT TOP 1000000 CAST(FLOOR(CAST(CRETS AS FLOAT)) AS DATETIME) FROM tblMeasureLogv2SELECT TOP 1000000 CONVERT(DATETIME, CONVERT(VARCHAR(10), CRETS, 120) , 120) FROM tblMeasureLogv2 SELECT TOP 1000000 DATEADD(DAY, DATEDIFF(DAY, 0, CRETS), 0) FROM tblMeasureLogv2 SQL Server parse and compile time: CPU time = 0 ms, elapsed time = 1 ms. (1000000 row(s) affected) Table 'tblMeasureLogv2'. Scan count 1, logical reads 4752, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0. SQL Server Execution Times: CPU time = 422 ms, elapsed time = 33803 ms. (1000000 row(s) affected) Table 'tblMeasureLogv2'. Scan count 1, logical reads 4752, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0. SQL Server Execution Times: CPU time = 625 ms, elapsed time = 33545 ms. (1000000 row(s) affected) Table 'tblMeasureLogv2'. Scan count 1, logical reads 4752, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0. SQL Server Execution Times: CPU time = 1953 ms, elapsed time = 33843 ms. (1000000 row(s) affected) Table 'tblMeasureLogv2'. Scan count 1, logical reads 4752, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0. SQL Server Execution Times: CPU time = 531 ms, elapsed time = 33440 ms. SQL Server parse and compile time: CPU time = 0 ms, elapsed time = 1 ms. SQL Server Execution Times: CPU time = 0 ms, elapsed time = 1 ms. What are we seeing here? Let's focus on the CPU time (we're looking at conversion), and we can see that we have the following numbers: Pure-Select: 422Floor-cast: 625String-conv: 1953DateAdd: 531 From this it looks to me like the DateAdd (at least in this particular case) is slightly faster than the floor-cast method. Before you go there, I ran this test several times, with the order of the queries changed, same-ish results. Is this something strange on my server, or what?
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/133081", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16881/" ] }
133,092
I have an XPath expression which provides me a sequence of values like the one below: 1 2 2 3 4 5 5 6 7 This is easy to convert to a sequence of unique values 1 2 3 4 5 6 7 using distinct-values() . However, what I want to extract is the list of duplicate values = 2 5 . I can't think of an easy way to do this. Can anyone help?
Use this simple XPath 2.0 expression : $vSeq[index-of($vSeq,.)[2]] where $vSeq is the sequence of values in which we want to find the duplicates. For explanation of how this "works", see : http://dnovatchev.wordpress.com/2008/11/16/xpath-2-0-gems-find-all-duplicate-values-in-a-sequence-part-2/ TLDR;This picture can be a visual explanation. If the sequence is: $vSeq = 1, 2, 3, 2, 4, 5, 6, 7, 5, 7, 5 Then evaluating the above XPath expression produces: 2, 5, 7
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/133092", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ] }
133,106
Imagine that you have a simple site with only 2 pages: login.aspx and secret.aspx. Your site is secured using nothing but ASP.net forms authentication and an ASP.net Login server control on login.aspx. The details are as follows: The site is configured to use the SqlMembershipProvider The site denies all anonymous users Cookies are disabled The are obviously many things to consider regarding security but I am more interested in the zero code out of box experience that comes with the .net framework. If, for the sake of this question, the only attack points are the username/password textboxes in login.aspx, can a hacker inject code that will allow them to gain access to our secret.aspx page? How secure is the zero code out-of-box experience that Microsoft provides?
You still have some variables that aren't accounted for: Security into the data store used by your membership provider (in this case, the Sql Server database). security of other sites hosted in the same IIS general network security of the machines involved in hosting the site, or on the same network where the site is hosted physical security of the machines hosting the site Are you using appropriate measures to encrypt authentication traffic? (HTTPS/SSL) Not all of those issues are MS specific, but they're worth mentioning because any of them could easily outweigh the issue you're asking about, if not taken care of. But, for the purpose of your question I'll assume there aren't any problems with them. In that case, I'm pretty sure the forms authentication does what it's supposed to do. I don't think there's any currently active exploit out there.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/133106", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3742/" ] }
133,122
I want to make a .NET Form as a TopMost Form for another external App (not .NET related, pure Win32) so it stays above that Win32App, but not the rest of the apps running. I Have the handle of the Win32App (provided by the Win32App itself), and I've tried Win32 SetParent() function , via P/Invoke in C# , but then my .NET Form gets confined into the Win32App and that's not what I want.
I think you're looking for is to P/Invoke SetWindowLongPtr(win32window, GWLP_HWNDPARENT, formhandle) Google Search
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/133122", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10136/" ] }
133,129
I use Eclipse 3.3 in my daily work, and have also used Eclipse 3.2 extensively as well. In both versions, sometimes the Search options (Java Search, File Search, etc) in the menu get disabled, seemingly at random times. However, with Ctrl + H , I am able to access the search functionality. Does anyone know why this happens? Has it been fixed in Eclipse 3.4 ?
window > close all perspective works for me.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/133129", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8026/" ] }
133,154
While normally it's good to always choose the right language for the job, it can sometimes be instructive to try and do something in a language which is wildly inappropriate. It can help you understand the problem better. Maybe you don't have to solve it the way you thought you did. It can help you understand the language better. Maybe it supports more features than you realized. And pushing this idea to it's illogical conclusion...how would you implement quicksort in a batch file? Is it even possible?
Turns out, it's not as hard as you might think. The syntax is ugly as hell, but the batch syntax is actually capable of some surprising things, including recursion, local variables, and some surprisingly sophisticated parsing of strings. Don't get me wrong, it's a terrible language, but to my surprise, it isn't completely crippled. I don't think I learnt anything about quicksort, but I learned a lot about batch files! In any case, here's quicksort in a batch file - and I hope you have as much fun trying to understand the bizarre syntax while reading it as I did while writing it. :-) @echo offSETLOCAL ENABLEDELAYEDEXPANSIONcall :qSort %*for %%i in (%return%) do set results=!results! %%iecho Sorted result: %results%ENDLOCALgoto :eof:qSortSETLOCAL set list=%* set size=0 set less= set greater= for %%i in (%*) do set /a size=size+1 if %size% LEQ 1 ENDLOCAL & set return=%list% & goto :eof for /f "tokens=2* delims== " %%i in ('set list') do set p=%%i & set body=%%j for %%x in (%body%) do (if %%x LEQ %p% (set less=%%x !less!) else (set greater=%%x !greater!)) call :qSort %less% set sorted=%return% call :qSort %greater% set sorted=%sorted% %p% %return%ENDLOCAL & set return=%sorted%goto :eof Call it by giving it a set of numbers to sort on the command line, seperated by spaces. Example: C:\dev\sorting>qsort.bat 1 3 5 1 12 3 47 3Sorted result: 1 1 3 3 3 5 12 47 The code is a bit of a pain to understand. It's basically standard quicksort. Key bits are that we're storing numbers in a string - poor man's array. The second for loop is pretty obscure, it's basically splitting the array into a head (the first element) and a tail (all other elements). Haskell does it with the notation x:xs, but batch files do it with a for loop called with the /f switch. Why? Why not? The SETLOCAL and ENDLOCAL calls let us do local variables - sort of. SETLOCAL gives us a complete copy of the original variables, but all changes are completely wiped when we call ENDLOCAL, which means you can't even communicate with the calling function using globals. This explains the ugly "ENDLOCAL & set return=%sorted%" syntax, which actually works despite what logic would indicate. When the line is executed the sorted variable hasn't been wiped because the line hasn't been executed yet - then afterwards the return variable isn't wiped because the line has already been executed. Logical! Also, amusingly, you basically can't use variables inside a for loop because they can't change - which removes most of the point of having a for loop. The workaround is to set ENABLEDELAYEDEXPANSION which works, but makes the syntax even uglier than normal. Notice we now have a mix of variables referenced just by their name, by prefixing them with a single %, by prefixing them with two %, by wrapping them in %, or by wrapping them in !. And these different ways of referencing variables are almost completely NOT interchangeable! Other than that, it should be relatively easy to understand!
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/133154", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17086/" ] }
133,204
How do I get a list of the files checked out by users (including the usernames) using P4V or P4? I want to provide a depot location and see a list of any files under that location (including sub folders) that are checked out.
From the command line: p4 opened -a //depot/Your/Location/... The ... indicates that sub folders should be included.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/133204", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20457/" ] }
133,214
We need to implement a simple state machine in C . Is a standard switch statement the best way to go? We have a current state (state) and a trigger for the transition. switch(state){ case STATE_1: state = DoState1(transition); break; case STATE_2: state = DoState2(transition); break;}...DoState2(int transition){ // Do State Work ... if(transition == FROM_STATE_2) { // New state when doing STATE 2 -> STATE 2 } if(transition == FROM_STATE_1) { // New State when moving STATE 1 -> STATE 2 } return new_state;} Is there a better way for simple state machines EDIT: For C++, I think the Boost Statechart library might be the way to go. However, it does not help with C. Lets concentrate on the C use case.
I prefer to use a table driven approach for most state machines: typedef enum { STATE_INITIAL, STATE_FOO, STATE_BAR, NUM_STATES } state_t;typedef struct instance_data instance_data_t;typedef state_t state_func_t( instance_data_t *data );state_t do_state_initial( instance_data_t *data );state_t do_state_foo( instance_data_t *data );state_t do_state_bar( instance_data_t *data );state_func_t* const state_table[ NUM_STATES ] = { do_state_initial, do_state_foo, do_state_bar};state_t run_state( state_t cur_state, instance_data_t *data ) { return state_table[ cur_state ]( data );};int main( void ) { state_t cur_state = STATE_INITIAL; instance_data_t data; while ( 1 ) { cur_state = run_state( cur_state, &data ); // do other program logic, run other state machines, etc }} This can of course be extended to support multiple state machines, etc. Transition actions can be accommodated as well: typedef void transition_func_t( instance_data_t *data );void do_initial_to_foo( instance_data_t *data );void do_foo_to_bar( instance_data_t *data );void do_bar_to_initial( instance_data_t *data );void do_bar_to_foo( instance_data_t *data );void do_bar_to_bar( instance_data_t *data );transition_func_t * const transition_table[ NUM_STATES ][ NUM_STATES ] = { { NULL, do_initial_to_foo, NULL }, { NULL, NULL, do_foo_to_bar }, { do_bar_to_initial, do_bar_to_foo, do_bar_to_bar }};state_t run_state( state_t cur_state, instance_data_t *data ) { state_t new_state = state_table[ cur_state ]( data ); transition_func_t *transition = transition_table[ cur_state ][ new_state ]; if ( transition ) { transition( data ); } return new_state;}; The table driven approach is easier to maintain and extend and simpler to map to state diagrams.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/133214", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10703/" ] }
133,225
I set up 404 handler page in web.config, but it works ONLY when extension of URL is .aspx (or other which is handled by ASP.NET).I know I can setup static HTML page in website options, but I want to have a page.Is there any options to assign ASPX handler page for all request extensions in IIS?
The direct question was whether or not there are options to assign the ASPX handler to all request extensions: Yes, there is. I'll discuss how to do that shortly. First, I think the "hidden" question -- the answer you really want -- is whether or not there's a way to redirect all 404 errors for pages other than ASPX, ASMX, etc. Yes, there is, and this is the better choice if it'll solve the issue you're having. To redirect all 404s in IIS 6, right click your web application root (whether it be its own site or a virtual directory in the main site), and choose "Properties." From there, choose the "Custom Errors" tab. Find 404 in the list and change it to the redirect you want. Now, if that won't suffice -- and I really hope it does -- yes, you can run every page through the ASPX handler. However, doing so comes at a fairly high cost in terms of efficiency -- raw HTML/image serving is considerably faster than anything dynamic. To do this, right click your web application root and choose "Properties." Choose the "Home Directory" tab. Click "Configuration;" a new window will pop up. Copy the path from one of the ASP.NET page serves, and then use it for a wildcard application map. Bear in mind, again, this is the wrong answer most of the time. It will negatively impact your performance, and is the equivalent of using a chainsaw to carve a turkey. I highly recommend the first option over this one, if it will work out for you.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/133225", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11768/" ] }
133,236
I am wanting to store the "state" of some actions the user is performing in a series of different ASP.Net webforms. What are my choices for persisting state, and what are the pros/cons of each solution? I have been using Session objects, and using some helper methods to strongly type the objects: public static Account GetCurrentAccount(HttpSessionState session) { return (Account)session[ACCOUNT]; } public static void SetCurrentAccount(Account obj, HttpSessionState session) { session[ACCOUNT] = obj; } I have been told by numerous sources that "Session is evil", so that is really the root cause of this question. I want to know what you think "best practice", and why.
There is nothing inherently evil with session state. There are a couple of things to keep in mind that might bite you though: If the user presses the browser back button you go back to the previous page but your session state is not reverted. So your CurrentAccount might not be what it originally was on the page. ASP.NET processes can get recycled by IIS. When that happens you next request will start a new process. If you are using in process session state, the default, it will be gone :-( Session can also timeout with the same result if the user isn't active for some time. This defaults to 20 minutes so a nice lunch will do it. Using out of process session state requires all objects stored in session state to be serializable. If the user opens a second browser window he will expect to have a second and distinct application but the session state is most likely going to be shared between to two. So changing the CurrentAccount in one browser window will do the same in the other.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/133236", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10589/" ] }
133,270
I would like to code a little program which visually illustrates the behavior of the volatile keyword. Ideally, it should be a program which performs concurrent access to a non volatile static field and which gets incorrect behavior because of that. Adding the volatile keyword in the same program should fix the problem. That something I didn't manage to achieve. Even trying several times, enabling optimization, etc., I always get a correct behavior without the 'volatile' keyword. Do you have any idea about this topic? Do you know how to simulate such a problem in a simple demo app? Does it depend on hardware?
I've achieved a working example! The main idea received from wiki, but with some changes for C#. The wiki article demonstrates this for static field of C++, it is looks like C# always carefully compile requests to static fields... and i make example with non static one: If you run this example in Release mode and without debugger (i.e. using Ctrl+F5) then the line while (test.foo != 255) will be optimized to 'while(true)' and this program never returns.But after adding volatile keyword, you always get 'OK'. class Test{ /*volatile*/ int foo; static void Main() { var test = new Test(); new Thread(delegate() { Thread.Sleep(500); test.foo = 255; }).Start(); while (test.foo != 255) ; Console.WriteLine("OK"); }}
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/133270", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4687/" ] }
133,310
I have a JavaScript widget which provides standard extension points. One of them is the beforecreate function. It should return false to prevent an item from being created. I've added an Ajax call into this function using jQuery: beforecreate: function (node, targetNode, type, to) { jQuery.get('http://example.com/catalog/create/' + targetNode.id + '?name=' + encode(to.inp[0].value), function (result) { if (result.isOk == false) alert(result.message); });} But I want to prevent my widget from creating the item, so I should return false in the mother-function, not in the callback. Is there a way to perform a synchronous AJAX request using jQuery or any other in-browser API?
From the jQuery documentation : you specify the asynchronous option to be false to get a synchronous Ajax request. Then your callback can set some data before your mother function proceeds. Here's what your code would look like if changed as suggested: beforecreate: function (node, targetNode, type, to) { jQuery.ajax({ url: 'http://example.com/catalog/create/' + targetNode.id + '?name=' + encode(to.inp[0].value), success: function (result) { if (result.isOk == false) alert(result.message); }, async: false });}
{ "score": 11, "source": [ "https://Stackoverflow.com/questions/133310", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2313/" ] }
133,313
I'm trying to design some tables to store some data, which has to be converted to different languages later. Can anybody provide some "best practices" or guidelines for this? Thanks
Let's say you have a products table that looks like this: Products----------idpriceProducts_Translations----------------------product_idlocalenamedescription Then you just join on product_id = product.id and where locale='en-US' of course this has an impact on performance, since you now need a join to get the name and description, but it allows any number of locales later on.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/133313", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22016/" ] }
133,357
How do I find the name of the namespace or module 'Foo' in the filter below? class ApplicationController < ActionController::Base def get_module_name @module_name = ??? endendclass Foo::BarController < ApplicationController before_filter :get_module_nameend
None of these solutions consider a constant with multiple parent modules. For instance: A::B::C As of Rails 3.2.x you can simply: "A::B::C".deconstantize #=> "A::B" As of Rails 3.1.x you can: constant_name = "A::B::C"constant_name.gsub( "::#{constant_name.demodulize}", '' ) This is because #demodulize is the opposite of #deconstantize: "A::B::C".demodulize #=> "C" If you really need to do this manually, try this: constant_name = "A::B::C"constant_name.split( '::' )[0,constant_name.split( '::' ).length-1]
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/133357", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21872/" ] }
133,364
Which is your favorite way to go with strings in C++? A C-style array of char s? Or wchar_t ? CString , std::basic_string , std::string , BSTR or CComBSTR ? Certainly each of these has its own area of application, but anyway, which is your favorite and why?
std::string or std::wstring, depending on your needs. Why? They're standard They're portable They can handle I18N They have performance guarantees (as per the standard) Protected against buffer overflows and similar attacks Are easily converted to other types as needed Are nicely templated, giving you a wide variety of options while reducing code bloat and improving performance. Really. Compilers that can't handle templates are long gone now. A C-style array of chars is just asking for trouble. You'll still need to deal with them on occasion (and that's what std::string.c_str() is for), but, honestly -- one of the biggest dangers in C is programmers doing Bad Things with char* and winding up with buffer overflows. Just don't do it. An array of wchar__t is the same thing, just bigger. CString, BSTR, and CComBSTR are not standard and not portable. Avoid them unless absolutely forced. Optimally, just convert a std::string/std::wstring to them when needed, which shouldn't be very expensive. Note that std::string is just a child of std::basic_string, but you're still better off using std::string unless you have a really good reason not to. Really Good. Let the compiler take care of the optimization in this situation.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/133364", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19024/" ] }
133,374
When trying to call Close or Dispose on an SqlDataReader i get a timeout expired exception. If you have a DbConnection to SQL Server, you can reproduce it yourself with: String CRLF = "\r\n";String sql = "SELECT * " + CRLF + "FROM (" + CRLF + " SELECT (a.Number * 256) + b.Number AS Number" + CRLF + " FROM master..spt_values a," + CRLF + " master..spt_values b" + CRLF + " WHERE a.Type = 'p'" + CRLF + " AND b.Type = 'p') Numbers1" + CRLF + " FULL OUTER JOIN (" + CRLF + " SELECT (print("code sample");a.Number * 256) + b.Number AS Number" + CRLF + " FROM master..spt_values a," + CRLF + " master..spt_values b" + CRLF + " WHERE a.Type = 'p'" + CRLF + " AND b.Type = 'p') Numbers2" + CRLF + " ON 1=1";DbCommand cmd = connection.CreateCommand();cmd.CommandText = sql;DbDataReader rdr = cmd.ExecuteReader();rdr.Close(); If you call reader.Close() or reader.Dispose() it will throw a System.Data.SqlClient.SqlException: ErrorCode: -2146232060 (0x80131904) Message: "Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding."
it's because you have just opened the data reader and have not completely iterated through it yet. you will need to .Cancel() your DbCommand object before you attempt to close a data reader that hasn't completed yet (and the DbConnection as well). of course, by .Cancel()-ing your DbCommand, I'm not sure of this but you might encounter some other exception. but you should just catch it if it happens.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/133374", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12597/" ] }
133,379
I'm trying to install a service using InstallUtil.exe but invoked through Process.Start . Here's the code: ProcessStartInfo startInfo = new ProcessStartInfo (m_strInstallUtil, strExePath);System.Diagnostics.Process.Start (startInfo); where m_strInstallUtil is the fully qualified path and exe to "InstallUtil.exe" and strExePath is the fully qualified path/name to my service. Running the command line syntax from an elevated command prompt works; running from my app (using the above code) does not. I assume I'm dealing with some process elevation issue, so how would I run my process in an elevated state? Do I need to look at ShellExecute for this? This is all on Windows Vista. I am running the process in the VS2008 debugger elevated to admin privilege. I also tried setting startInfo.Verb = "runas"; but it didn't seem to solve the problem.
You can indicate the new process should be started with elevated permissions by setting the Verb property of your startInfo object to 'runas', as follows: startInfo.Verb = "runas"; This will cause Windows to behave as if the process has been started from Explorer with the "Run as Administrator" menu command. This does mean the UAC prompt will come up and will need to be acknowledged by the user: if this is undesirable (for example because it would happen in the middle of a lengthy process), you'll need to run your entire host process with elevated permissions by Create and Embed an Application Manifest (UAC) to require the 'highestAvailable' execution level: this will cause the UAC prompt to appear as soon as your app is started, and cause all child processes to run with elevated permissions without additional prompting. Edit: I see you just edited your question to state that "runas" didn't work for you. That's really strange, as it should (and does for me in several production apps). Requiring the parent process to run with elevated rights by embedding the manifest should definitely work, though.
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/133379", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1683/" ] }
133,393
I need to store database passwords in a config file. For obvious reasons, I want to encrypt them (preferably with AES). Does anyone know a Delphi implementation that is easy to introduce into an existing project with > 10,000 lines of historically grown (URGH!) source code? Clarification: Easy means adding the unit to the project, adding max. 5 lines of code where the config file is read and be done with it. Should not take more than 15 minutes. Another clarification: The password is needed in order to create a connection to the db, not to support a user management scheme for the application. So using hashes does not help. The db engine checks if the password is valid, not the app.
I second the recommendation for David Barton's DCPCrypt library . I've used it successfuly in several projects, and it won't take more than 15 minutes after you've read the usage examples. It uses MIT license, so you can use it freely in commercial projects and otherwise. DCPCrypt implements a number of algorithms, including Rijndael, which is AES. There are many googlable stand-alone (single-unit) implementations too - the question is which one you trust, unless you are prepared to verify the correctedness of a particular library yourself.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/133393", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22114/" ] }
133,394
I am developing a Joomla component and one of the views needs to render itself as PDF. In the view, I have tried setting the content-type with the following line, but when I see the response, it is text/html anyways. header('Content-type: application/pdf'); If I do this in a regular php page, everything works as expected. It seems that I need to tell Joomla to use application/pdf instead of text/html. How can I do it? Note: Setting other headers, such as Content-Disposition , works as expected.
Since version 1.5 Joomla has the JDocument object. Use JDocument::setMimeEncoding() to set the content type. $doc =& JFactory::getDocument();$doc->setMimeEncoding('application/pdf'); In your special case, a look at JDocumentPDF may be worthwile.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/133394", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2680/" ] }
133,436
I'm using Java 6, Tomcat 6, and Metro. I use WebService and WebMethod annotations to expose my web service. I would like to obtain information about the request. I tried the following code, but wsCtxt is always null. What step must I take to not get null for the WebServiceContext. In other words: how can I execute the following line to get a non-null value for wsCtxt? MessageContext msgCtxt = wsCtxt.getMessageContext(); @WebServicepublic class MyService{ @Resource WebServiceContext wsCtxt; @WebMethod public void myWebMethod(){ MessageContext msgCtxt = wsCtxt.getMessageContext(); HttpServletRequest req = (HttpServletRequest)msgCtxt.get(MessageContext.SERVLET_REQUEST); String clientIP = req.getRemoteAddr(); }
I recommend you either rename your variable from wsCtxt to wsContext or assign the name attribute to the @Resource annotation. The J2ee tutorial on @Resource indicates that the name of the variable is used as part of the lookup. I've encountered this same problem using resource injection in Glassfish injecting a different type of resource. Though your correct name may not be wsContext. I'm following this java tip . If you like the variable name wsCtxt, then use the name attribute in the variable declaration: @Resource(name="wsContext") WebServiceContext wsCtxt;
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/133436", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2959/" ] }
133,569
I usually use C++ stdlib map whenever I need to store some data associated with a specific type of value (a key value - e.g. a string or other object). The stdlib map implementation is based on trees which provides better performance (O(log n)) than the standard array or stdlib vector. My questions is, do you know of any C++ "standard" hashtable implementation that provides even better performance (O(1))? Something similar to what is available in the Hashtable class from the Java API.
If you're using C++11, you have access to the <unordered_map> and <unordered_set> headers. These provide classes std::unordered_map and std::unordered_set . If you're using C++03 with TR1, you have access to the classes std::tr1::unordered_map and std::tr1::unordered_set , using the same headers (unless you're using GCC, in which case the headers are <tr1/unordered_map> and <tr1/unordered_set> instead). In all cases, there are corresponding unordered_multimap and unordered_multiset types too.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/133569", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20317/" ] }
133,571
Wanted to convert <br/><br/><br/><br/><br/> into <br/>
You can do this with a regular expression: preg_replace("/(<br\s*\/?>\s*)+/", "<br/>", $input); This if you pass in your source HTML, this will return a string with a single <br/> replacing every run of them.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/133571", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20907/" ] }
133,601
Is it possible to write a regular expression that matches a nested pattern that occurs an unknown number of times? For example, can a regular expression match an opening and closing brace when there are an unknown number of open/close braces nested within the outer braces? For example: public MyMethod(){ if (test) { // More { } } // More { }} // End Should match: { if (test) { // More { } } // More { }}
No. It's that easy. A finite automaton (which is the data structure underlying a regular expression) does not have memory apart from the state it's in, and if you have arbitrarily deep nesting, you need an arbitrarily large automaton, which collides with the notion of a finite automaton. You can match nested/paired elements up to a fixed depth, where the depth is only limited by your memory, because the automaton gets very large. In practice, however, you should use a push-down automaton, i.e a parser for a context-free grammar, for instance LL (top-down) or LR (bottom-up). You have to take the worse runtime behavior into account: O(n^3) vs. O(n), with n = length(input). There are many parser generators avialable, for instance ANTLR for Java. Finding an existing grammar for Java (or C) is also not difficult. For more background: Automata Theory at Wikipedia
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/133601", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1199234/" ] }
133,610
Ok, this is another one in the theory realm for the CS guys around. In the 90's I did fairly well in implementing BST's. The only thing I could never get my head around was the intricacy of the algorithm to balance a Binary Tree (AVL). Can you guys help me on this?
A scapegoat tree possibly has the simplest balance-determination algorithm to understand. If any insertion causes the new node to be too deep, it finds a node around which to rebalance, by looking at weight balance rather than height balance. The rule for whether to rebalance on delete is also simple. It doesn't store any arcane information in the nodes. It's trickier to prove that it's correct, but you don't need that to understand the algorithm... However, unlike an AVL it isn't height-balanced at all times. Like red-black its unbalance is bounded, but unlike red-black it's tunable with a parameter, so for most practical purposes it looks as balanced as you need it to be. I suspect that if you tune it too tightly, though, it ends up as bad or worse than AVL for worst-case insertions. Response to question edit I'll provide my personal path to understanding AVL trees. First you have to understand what a tree rotation is, so ignore everything else you've ever heard the AVL algorithms and understand that. Get straight in your head which is a right rotation and which is a left rotation, and what each does to the tree, or else the descriptions of the precise methods will just confuse you. Next, understand that the trick for balancing AVL trees is that each node records in it the difference between the height of its left and right subtrees. The definition of 'height balanced' is that this is between -1 and 1 inclusive for every node in the tree. Next, understand that if you have added or removed a node, you may have unbalanced the tree. But you can only have changed the balance of nodes which are ancestors of the node you added or removed. So, what you're going to do is work your way back up the tree, using rotations to balance any unbalanced nodes you find, and updating their balance score, until the tree is balanced again. The final part of understanding it is to look up in a decent reference the specific rotations used to rebalance each node you find: this is the "technique" of it as opposed to the high concept. You only have to remember the details while modifying AVL tree code or maybe during data structures exams. It's years since I last had AVL tree code so much as open in the debugger - implementations tend to get to a point where they work and then stay working. So I really do not remember. You can sort of work it out on a table using a few poker chips, but it's hard to be sure you've really got all the cases (there aren't many). Best just to look it up. Then there's the business of translating it all into code. I don't think that looking at code listings helps very much with any stage except the last, so ignore them. Even in the best case, where the code is clearly written, it will look like a textbook description of the process, but without the diagrams. In a more typical case it's a mess of C struct manipulation. So just stick to the books.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/133610", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8167/" ] }
133,626
I am using Vim for windows installed in Unix mode. Thanks to this site I now use the gf command to go to a file under the cursor. I'm looking for a command to either: return to the previous file (similarto Ctrl + T for ctags), or remap gf to automatically launch the new filein a new window.
I use Ctrl - O
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/133626", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5823/" ] }
133,660
I need to create a directory on a mapped network drive. I am using a code: DirectoryInfo targetDirectory = new DirectoryInfo(path);if (targetDirectory != null){ targetDirectory.Create();} If I specify the path like "\\\\ServerName\\Directory", it all goes OK. If I map the "\\ServerName\Directory" as, say drive Z:, and specify the path like "Z:\\", it fails. After the creating the targetDirectory object, VS shows (in the debug mode) that targetDirectory.Exists = false, and trying to do targetDirectory.Create() throws an exception: System.IO.DirectoryNotFoundException: "Could not find a part of the path 'Z:\'." However, the same code works well with local directories, e.g. C:. The application is a Windows service (WinXP Pro, SP2, .NET 2) running under the same account as the user that mapped the drive. Qwinsta replies that the user's session is the session 0, so it is the same session as the service's.
Mapped network drives are user specific, so if the app is running under a different identity than the user that created the mapped drive letter (z:) it won't work.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/133660", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ] }
133,671
In my ASP.net MVC app I have a view that looks like this: ...<label>Due Date</label><%=Html.TextBox("due")%>... I am using a ModelBinder to bind the post to my model (the due property is of DateTime type). The problem is when I put "01/01/2009" into the textbox, and the post does not validate (due to other data being input incorrectly). The binder repopulates it with the date and time "01/01/2009 00:00:00 ". Is there any way to tell the binder to format the date correctly (i.e. ToShortDateString() )?
I just came across this very simple and elegant solution, available in MVC 2: http://geekswithblogs.net/michelotti/archive/2010/02/05/mvc-2-editor-template-with-datetime.aspx Basically if you are using MVC 2.0, use the following in your view. <%=Html.LabelFor(m => m.due) %> <%=Html.EditorFor(m => m.due)%> then create a partial view in /Views/Shared/EditorTemplates, called DateTime.ascx <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<System.DateTime?>" %><%=Html.TextBox("", (Model.HasValue ? Model.Value.ToShortDateString() : string.Empty), new { @class = "datePicker" }) %> When the EditorFor<> is called it will find a matching Editor Template.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/133671", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1736/" ] }
133,675
I need to implement red eye reduction for an application I am working on. Googling mostly provides links to commercial end-user products. Do you know a good red eye reduction algorithm, which could be used in a GPL application?
I'm way late to the party here, but for future searchers I've used the following algorithm for a personal app I wrote. First of all, the region to reduce is selected by the user and passed to the red eye reducing method as a center Point and radius. The method loops through each pixel within the radius and does the following calculation: //Value of red divided by average of blue and green:Pixel pixel = image.getPixel(x,y);float redIntensity = ((float)pixel.R / ((pixel.G + pixel.B) / 2));if (redIntensity > 1.5f) // 1.5 because it gives the best results{ // reduce red to the average of blue and green bm.SetPixel(i, j, Color.FromArgb((pixel.G + pixel.B) / 2, pixel.G, pixel.B));} I really like the results of this because they keep the color intensity, which means the light reflection of the eye is not reduced. (This means eyes keep their "alive" look.)
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/133675", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20107/" ] }
133,686
I'd like to find a way to determine how long each function in PHP, and each file in PHP is taking to run. I've got an old legacy PHP application that I'm trying to find the "rough spots" in and so I'd like to locate which routines and pages are taking a very long time to load, objectively. Are there any pre-made tools that allow for this, or am I stuck using microtime, and building my own profiling framework?
I have actually done some optimisation work last week. XDebug is indeed the way to go. Just enable it as an extension (for some reason it wouldn't work with ze_extension on my windows machine) , setup your php.ini with xdebug.profiler_enable_trigger=On and call your normal urls with XDEBUG_PROFILE=1 as either a get or a post variable to profile that very request. There's nothing easier! Also, i can really reccommend webgrind , a webbased (php) google Summer Of Code project that can read and parse your debug output files!
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/133686", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21973/" ] }
133,698
I've created a new C++ project in Visual Studio 2008. No code has been written yet; Only project settings have been changed. When I compile the project, I receive the following fatal error: fatal error LNK1104: cannot open file 'C:\Program.obj'
This particular issue is caused by specifying a dependency to a lib file that had spaces in its path. The path needs to be surrounded by quotes for the project to compile correctly. On the Configuration Properties -> Linker -> Input tab of the project’s properties, there is an Additional Dependencies property. This issue was fixed by adding the quotes. For example, changing this property from: C:\Program Files\sofwaresdk\lib\library.lib To: "C:\Program Files\sofwaresdk\lib\library.lib" where I added the quotes.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/133698", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21277/" ] }
133,710
When I use the task, the property is only set to TRUE if the resource (say file) is available. If not, the property is undefined. When I print the value of the property, it gives true if the resource was available, but otherwise just prints the property name. Is there a way to set the property to some value if the resource is not available? I have tried setting the property explicitly before the available check, but then ant complains: [available] DEPRECATED - used to override an existing property.[available] Build file should not reuse the same property name for different values.
You can use a condition in combination with not: http://ant.apache.org/manual/Tasks/condition.html <condition property="fooDoesNotExist"> <not> <available filepath="path/to/foo"/> </not> </condition>
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/133710", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ] }
133,719
I am running Ruby and MySQL on a Windows box. I have some Ruby code that needs to connect to a MySQL database a perform a select. To connect to the database I need to provide the password among other things. The Ruby code can display a prompt requesting the password, the user types in the password and hits the Enter key. What I need is for the password, as it is typed, to be displayed as a line of asterisks. How can I get Ruby to display the typed password as a line of asterisks in the 'dos box'?
To answer my own question, and for the benefit of anyone else who would like to know, there is a Ruby gem called HighLine that you need. require 'rubygems'require 'highline/import'def get_password(prompt="Enter Password") ask(prompt) {|q| q.echo = false}endthePassword = get_password()
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/133719", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15868/" ] }
133,721
Lately I've be moving source files around in our source tree. For example placing a bunch of files into a common assembly. I've been doing this my deleting the file from CVS and then adding it again in the new spot. The problem is the revision number of the file resets back to 1.1. Is there some simple way to move things without having the number reset. I probably should have mentioned that I don't have access to the repository so anything that requires that doesn't help me but it might help others.
The generally accepted way to achieve this effect is to perform the following steps. The technical term for this is a repocopy. Login on the server hosting the CVS repository and copy (don't move) the repository file from the location you want it to the new location. On the client side cvs delete the file from the old location. On the client side cvs update the directory contents in the new location (so that the file will appear there). On the client side perform a forced cvs commit (using the -f flag) of the copied file to log the fact that it was repocopied (add a log comment to that effect). This procedure maintains the file history in its new location, and also doesn't break the backward continuity of the repository. If you move back in time, the file will correctly appear in its old location. You can also use the same procedure to rename a file.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/133721", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7176/" ] }
133,837
What might be the best way to start programming using boost lambda libraries.
Remaining within the boundaries of the C++ language and libraries, I would suggest first getting used to programming using STL algorithm function templates, as one the most common use you will have for boost::lambda is to replace functor classes with inlined expressions inlined. The library documentation itself gives you an up-front example of what it is there for: for_each(a.begin(), a.end(), std::cout << _1 << ' '); where std::cout << _1 << ' ' produces a function object that, when called, writes its first argument to the cout stream. This is something you could do with a custom functor class, std::ostream_iterator or an explicit loop, but boost::lambda wins in conciseness and probably clarity -- at least if you are used to the functional programming concepts. When you (over-)use the STL, you find yourself gravitating towards boost::bind and boost::lambda. It comes in really handy for things like: std::sort( c.begin(), c.end(), bind(&Foo::x, _1) < bind(&Foo::x, _2) ); Before you get to that point, not so much. So use STL algorithms, write your own functors and then translate them into inline expressions using boost::lambda. From a professional standpoint, I believe the best way to get started with boost::lambda is to get usage of boost::bind understood and accepted. Use of placeholders in a boost::bind expression looks much less magical than "naked" boost::lambda placeholders and finds easier acceptance during code reviews. Going beyond basic boost::lambda use is quite likely to get you grief from your coworkers unless you are in a bleeding-edge C++ shop. Try not to go overboard - there are times when and places where a for -loop really is the right solution.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/133837", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22076/" ] }
133,840
I have heard that it's best not to actually have any html in your helpers; my question is, Why not? And furthermore, if you were trying to generate an html list or something like that, how can I avoid actual tags? Thanks! -fREW
My advice - if it's small pieces of HTML (a couple of tags) don't worry about it. More than that - think about partials (as pulling strings of html together in a helper is a pain that's what the views are good at). I regularly include HTML in my helpers (either directly or through calls to Rails methods like link_to). My world has not come crashing down around me. In fact I'd to so far as to say my code is very clean, maintainable and understandable because of it. Only last night I wrote a link_to_user helper to spits out html with normal link to the user along with the user's icon next to it. I could have done it in a partial, but I think link_to_user is a much cleaner way to handle it.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/133840", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12448/" ] }
133,879
When developing an app that will listen on a TCP/IP port, how should one go about selecting a default port? Assume that this app will be installed on many computers, and that avoiding port conflicts is desired.
Go here and pick a port with the description Unassigned
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/133879", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4792/" ] }
133,883
How can I script a bat or cmd to stop and start a service reliably with error checking (or let me know that it wasn't successful for whatever reason)?
Use the SC (service control) command, it gives you a lot more options than just start & stop . DESCRIPTION: SC is a command line program used for communicating with the NT Service Controller and services. USAGE: sc <server> [command] [service name] ... The option <server> has the form "\\ServerName" Further help on commands can be obtained by typing: "sc [command]" Commands: query-----------Queries the status for a service, or enumerates the status for types of services. queryex---------Queries the extended status for a service, or enumerates the status for types of services. start-----------Starts a service. pause-----------Sends a PAUSE control request to a service. interrogate-----Sends an INTERROGATE control request to a service. continue--------Sends a CONTINUE control request to a service. stop------------Sends a STOP request to a service. config----------Changes the configuration of a service (persistant). description-----Changes the description of a service. failure---------Changes the actions taken by a service upon failure. qc--------------Queries the configuration information for a service. qdescription----Queries the description for a service. qfailure--------Queries the actions taken by a service upon failure. delete----------Deletes a service (from the registry). create----------Creates a service. (adds it to the registry). control---------Sends a control to a service. sdshow----------Displays a service's security descriptor. sdset-----------Sets a service's security descriptor. GetDisplayName--Gets the DisplayName for a service. GetKeyName------Gets the ServiceKeyName for a service. EnumDepend------Enumerates Service Dependencies. The following commands don't require a service name: sc <server> <command> <option> boot------------(ok | bad) Indicates whether the last boot should be saved as the last-known-good boot configuration Lock------------Locks the Service Database QueryLock-------Queries the LockStatus for the SCManager Database EXAMPLE: sc start MyService
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/133883", "https://Stackoverflow.com", "https://Stackoverflow.com/users/730/" ] }
133,897
I have a line that I draw in a window and I let the user drag it around. So, my line is defined by two points: (x1,y1) and (x2,y2). But now I would like to draw "caps" at the end of my line, that is, short perpendicular lines at each of my end points. The caps should be N pixels in length. Thus, to draw my "cap" line at end point (x1,y1), I need to find two points that form a perpendicular line and where each of its points are N/2 pixels away from the point (x1,y1). So how do you calculate a point (x3,y3) given it needs to be at a perpendicular distance N/2 away from the end point (x1,y1) of a known line, i.e. the line defined by (x1,y1) and (x2,y2)?
You need to compute a unit vector that's perpendicular to the line segment. Avoid computing the slope because that can lead to divide by zero errors. dx = x1-x2dy = y1-y2dist = sqrt(dx*dx + dy*dy)dx /= distdy /= distx3 = x1 + (N/2)*dyy3 = y1 - (N/2)*dxx4 = x1 - (N/2)*dyy4 = y1 + (N/2)*dx
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/133897", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12058/" ] }
133,925
I'm trying to direct a browser to a different page. If I wanted a GET request, I might say document.location.href = 'http://example.com/q=a'; But the resource I'm trying to access won't respond properly unless I use a POST request. If this were not dynamically generated, I might use the HTML <form action="http://example.com/" method="POST"> <input type="hidden" name="q" value="a"></form> Then I would just submit the form from the DOM. But really I would like JavaScript code that allows me to say post_to_url('http://example.com/', {'q':'a'}); What's the best cross browser implementation? Edit I'm sorry I was not clear. I need a solution that changes the location of the browser, just like submitting a form. If this is possible with XMLHttpRequest , it is not obvious. And this should not be asynchronous, nor use XML, so Ajax is not the answer.
Dynamically create <input> s in a form and submit it /** * sends a request to the specified url from a form. this will change the window location. * @param {string} path the path to send the post request to * @param {object} params the parameters to add to the url * @param {string} [method=post] the method to use on the form */function post(path, params, method='post') { // The rest of this code assumes you are not using a library. // It can be made less verbose if you use one. const form = document.createElement('form'); form.method = method; form.action = path; for (const key in params) { if (params.hasOwnProperty(key)) { const hiddenField = document.createElement('input'); hiddenField.type = 'hidden'; hiddenField.name = key; hiddenField.value = params[key]; form.appendChild(hiddenField); } } document.body.appendChild(form); form.submit();} Example: post('/contact/', {name: 'Johnny Bravo'}); EDIT : Since this has gotten upvoted so much, I'm guessing people will be copy-pasting this a lot. So I added the hasOwnProperty check to fix any inadvertent bugs.
{ "score": 12, "source": [ "https://Stackoverflow.com/questions/133925", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16981/" ] }
133,953
I am developing, a simple SharePoint Sequential Workflow which should be bound to a document library. When associating the little workflow to a document library, I checked these options Allow this workflow to be manuallystarted by an authenticated userwith Edit Items Permissions. Startthis workflow when a new item iscreated. Start this workflow whenan item is changed. Now I upload a document to this library and the workflow starts and for instance sends a mail. It completes and everything is fine. When I select Edit Properties on the new Item and save a change, the workflow is fired again. Absolutely what we expected. Even when copying a new Item into the library with help of the Copy.asmx Webservice, the workflow starts normally. But now I want to update the item via the SharePoint WebService Lists.asmx . My CAML goes here: <Method ID='1' Cmd='Update'> <Field Name='ID'>1</Field> <Field Name='myDummyPropertyField'>NewValue</Field></Method> The Item is being updated (timestamp changed and a dummy property, too) but the workflow does NOT start again. This behaviour is reproducable on our development and test system. Checking the error logs (C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\LOGS) I discovered a strange error message: 09/25/2008 16:51:40.17 w3wp.exe (0x1D94) 0x1D60 Windows SharePoint Services General 6875 Critical Error loading and running event receiver Microsoft.SharePoint.Workflow.SPWorkflowAutostartEventReceiver in Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c. Additional information is below. : The object specified does not belong to a list. Anybody who can confirm this behavior? Or any solution hints? I am keeping you informed of any developments on this topic.
Finally, we got through the support services processes at Microsoft and got a solution! First, Microsoft stated this to be a bug. It is a minor bug, because there is a good workaround, so it may take some longer time, until this bug will be fixed (the support technician said something with next service pack oder next version (!)). But now for the problem. The reaseon Let's take a look at the CAML code from my question: <Method ID='1' Cmd='Update'> <Field Name='ID'>1</Field> <Field Name='myDummyPropertyField'>NewValue</Field></Method> For any reason the Workflow Manager does not work with the ID, we entered in the second line. Strange, all other SharePoint commands are working with the ID, but not the Workflow Manager. The Workflow Manager works with the "fully qualified" document name. So, because we had no clue and didn't entered any fully qualified document name, the Workflow Manager defaults to the name of the current document library. And now the error message begins to make sense: The object specified does not belong to a list. Of course, the object (document library) does not belong to a list, it IS the list. The solution We have to add one more line to our CAML Query: <Field Name='FileRef'>/sites/mySite/myDocLib/myFolder/myDocument.txt</Field> The FileRef passes the fully qualified document name to the Workflow Manager, which - now totally happy - starts the workflow of the item. Be careful, you have to include the full absolute server path, omitting your server name (found for example in ServerRelativePath property of your SPItem). Full working CAML Query: <Method ID='1' Cmd='Update'> <Field Name='ID'>1</Field> <Field Name='FileRef'>/sites/mySite/myDocLib/myFolder/myDocument.txt</Field> <Field Name='myDummyPropertyField'>NewValue</Field> </Method> The future Perhaps this undocumented behaviour will be fixed in one of the upcoming service packs, perhaps not. Microsoft Support apologized and is going to release an MSDN Article on this topic. For the next month I hope this article on stackoverflow will help developers in the same situation. Thanks for reading!
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/133953", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18246/" ] }
133,956
I am currently running into a problem where an element is coming back from my xml file with a single quote in it. This is causing xml_parse to break it up into multiple chunks, example: Get Wired, You're Hired!Is then enterpreted as 'Get Wired, You' being one object, the single quote being a second, and 're Hired!' as a third. What I want to do is: while($data = fread($fp, 4096)){ if(!xml_parse($xml_parser, htmlentities($data,ENT_QUOTES), feof($fp))) { break; } } But that keeps breaking. I can run a str_replace in place of htmlentities and it runs without issue, but does not want to with htmlentities. Any ideas? Update: As per JimmyJ's response below, I have attempted the following solution with no luck (FYI there is a response or two above the linked post that update the code that is linked directly): function XMLEntities($string) { $string = preg_replace('/[^\x09\x0A\x0D\x20-\x7F]/e', '_privateXMLEntities("$0")', $string); return $string; } function _privateXMLEntities($num) { $chars = array( 39 => '&#39;', 128 => '&#8364;', 130 => '&#8218;', 131 => '&#402;', 132 => '&#8222;', 133 => '&#8230;', 134 => '&#8224;', 135 => '&#8225;', 136 => '&#710;', 137 => '&#8240;', 138 => '&#352;', 139 => '&#8249;', 140 => '&#338;', 142 => '&#381;', 145 => '&#8216;', 146 => '&#8217;', 147 => '&#8220;', 148 => '&#8221;', 149 => '&#8226;', 150 => '&#8211;', 151 => '&#8212;', 152 => '&#732;', 153 => '&#8482;', 154 => '&#353;', 155 => '&#8250;', 156 => '&#339;', 158 => '&#382;', 159 => '&#376;'); $num = ord($num); return (($num > 127 && $num < 160) ? $chars[$num] : "&#".$num.";" ); }if(!xml_parse($xml_parser, XMLEntities($data), feof($fp))) { break; } Update: As per tom's question below, magic quotes is/was indeed turned off. Solution: What I have ended up doing to solve the problem is the following: After collecting the data for each individual item/post/etc, I store that data to an array that I use later for output, then clear the local variables used during collection. I added in a step that checks if data is already present, and if it is, I concatenate it to the end, rather than overwriting it. So, if I end up with three chunks (as above, let's stick with 'Get Wired, You're Hired!', I will then go from doing $x = 'Get Wired, You'$x = "'"$x = 're Hired!' To doing: $x = 'Get Wired, You' . "'" . 're Hired!' This isn't the optimal solution, but appears to be working.
Finally, we got through the support services processes at Microsoft and got a solution! First, Microsoft stated this to be a bug. It is a minor bug, because there is a good workaround, so it may take some longer time, until this bug will be fixed (the support technician said something with next service pack oder next version (!)). But now for the problem. The reaseon Let's take a look at the CAML code from my question: <Method ID='1' Cmd='Update'> <Field Name='ID'>1</Field> <Field Name='myDummyPropertyField'>NewValue</Field></Method> For any reason the Workflow Manager does not work with the ID, we entered in the second line. Strange, all other SharePoint commands are working with the ID, but not the Workflow Manager. The Workflow Manager works with the "fully qualified" document name. So, because we had no clue and didn't entered any fully qualified document name, the Workflow Manager defaults to the name of the current document library. And now the error message begins to make sense: The object specified does not belong to a list. Of course, the object (document library) does not belong to a list, it IS the list. The solution We have to add one more line to our CAML Query: <Field Name='FileRef'>/sites/mySite/myDocLib/myFolder/myDocument.txt</Field> The FileRef passes the fully qualified document name to the Workflow Manager, which - now totally happy - starts the workflow of the item. Be careful, you have to include the full absolute server path, omitting your server name (found for example in ServerRelativePath property of your SPItem). Full working CAML Query: <Method ID='1' Cmd='Update'> <Field Name='ID'>1</Field> <Field Name='FileRef'>/sites/mySite/myDocLib/myFolder/myDocument.txt</Field> <Field Name='myDummyPropertyField'>NewValue</Field> </Method> The future Perhaps this undocumented behaviour will be fixed in one of the upcoming service packs, perhaps not. Microsoft Support apologized and is going to release an MSDN Article on this topic. For the next month I hope this article on stackoverflow will help developers in the same situation. Thanks for reading!
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/133956", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22216/" ] }
133,965
How can I find/replace all CR/LF characters in Notepad++? I am looking for something equivalent to the ^p special character in Microsoft Word.
[\r\n]+ should work too Update March, 26th 2012, release date of Notepad++ 6.0 : OMG, it actually does work now!!! Original answer 2008 (Notepad++ 4.x) - 2009-2010-2011 (Notepad++ 5.x) Actually no, it does not seem to work with regexp... But if you have Notepad++ 5.x, you can use the ' extended ' search mode and look for \r\n . That does find all your CRLF . (I realize this is the same answer than the others, but again, 'extended mode' is only available with Notepad++ 4.9, 5.x and more) Since April 2009, you have a wiki article on the Notepad++ site on this topic: " How To Replace Line Ends, thus changing the line layout ". (mentioned by georgiecasey in his/her answer below ) Some relevant extracts includes the following search processes: Simple search ( Ctrl + F ), Search Mode = Normal You can select an EOL in the editing window. Just move the cursor to the end of the line, and type Shift + Right Arrow. or, to select EOL with the mouse, start just at the line end and drag to the start of the next line; dragging to the right of the EOL won't work. You can manually copy the EOL and paste it into the field for Unix files ( LF -only). Simple search (Ctrl+F), Search Mode = Extended The "Extended" option shows \n and \r as characters that could be matched. As with the Normal search mode, Notepad++ is looking for the exact character. Searching for \r in a UNIX-format file will not find anything, but searching for \n will. Similarly, a Macintosh-format file will contain \r but not \n . Simple search (Ctrl+F), Search Mode = Regular expression Regular expressions use the characters ^ and $ to anchor the match string to the beginning or end of the line. For instance, searching for return;$ will find occurrences of "return;" that occur with no subsequent text on that same line. The anchor characters work identically in all file formats. The '.' dot metacharacter does not match line endings. [Tested in Notepad++ 5.8.5]: a regular expression search with an explicit \r or \n does not work (contrary to the Scintilla documentation ) . Neither does a search on an explicit (pasted) LF, or on the (invisible) EOL characters placed in the field when an EOL is selected. Advanced search ( Ctrl + R ) without regexp Ctrl + M will insert something that matches newlines. They will be replaced by the replace string. I recommend this method as the most reliable, unless you really need to use regex. As an example, to remove every second newline in a double spaced file, enter Ctrl + M twice in the search string box, and once in the replace string box. Advanced search ( Ctrl + R ) with Regexp. Neither Ctrl + M , $ nor \r\n are matched. The same wiki also mentions the Hex editor alternative : Type the new string at the beginning of the document. Then select to view the document in Hex mode . Select one of the new lines and hit Ctrl + H . While you have the Replace dialog box up, select on the background the new replacement string and Ctrl + C copy it to paste it in the Replace with text input. Then Replace or Replace All as you wish. Note: the character selected for new line usually appears as 0a . It may have a different value if the file is in Windows Format. In that case you can always go to Edit -> EOL Conversion -> Convert to Unix Format , and after the replacement switch it back and Edit -> EOL Conversion -> Convert to Windows Format .
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/133965", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8754/" ] }
133,973
I just came across an interesting situation in JavaScript. I have a class with a method that defines several objects using object-literal notation. Inside those objects, the this pointer is being used. From the behavior of the program, I have deduced that the this pointer is referring to the class on which the method was invoked, and not the object being created by the literal. This seems arbitrary, though it is the way I would expect it to work. Is this defined behavior? Is it cross-browser safe? Is there any reasoning underlying why it is the way it is beyond "the spec says so" (for instance, is it a consequence of some broader design decision/philosophy)? Pared-down code example: // inside class definition, itself an object literal, we have this function:onRender: function() { this.menuItems = this.menuItems.concat([ { text: 'Group by Module', rptletdiv: this }, { text: 'Group by Status', rptletdiv: this }]); // etc}
Cannibalized from another post of mine, here's more than you ever wanted to know about this . Before I start, here's the most important thing to keep in mind about Javascript, and to repeat to yourself when it doesn't make sense. Javascript does not have classes (ES6 class is syntactic sugar ). If something looks like a class, it's a clever trick. Javascript has objects and functions . (that's not 100% accurate, functions are just objects, but it can sometimes be helpful to think of them as separate things) The this variable is attached to functions. Whenever you invoke a function, this is given a certain value, depending on how you invoke the function. This is often called the invocation pattern. There are four ways to invoke functions in javascript. You can invoke the function as a method , as a function , as a constructor , and with apply . As a Method A method is a function that's attached to an object var foo = {};foo.someMethod = function(){ alert(this);} When invoked as a method, this will be bound to the object the function/method is a part of. In this example, this will be bound to foo. As A Function If you have a stand alone function, the this variable will be bound to the "global" object, almost always the window object in the context of a browser. var foo = function(){ alert(this); } foo(); This may be what's tripping you up , but don't feel bad. Many people consider this a bad design decision. Since a callback is invoked as a function and not as a method, that's why you're seeing what appears to be inconsistent behavior. Many people get around the problem by doing something like, um, this var foo = {};foo.someMethod = function (){ var that=this; function bar(){ alert(that); }} You define a variable that which points to this . Closure (a topic all it's own) keeps that around, so if you call bar as a callback, it still has a reference. NOTE: In use strict mode if used as function, this is not bound to global. (It is undefined ). As a Constructor You can also invoke a function as a constructor. Based on the naming convention you're using (TestObject) this also may be what you're doing and is what's tripping you up . You invoke a function as a Constructor with the new keyword. function Foo(){ this.confusing = 'hell yeah';}var myObject = new Foo(); When invoked as a constructor, a new Object will be created, and this will be bound to that object. Again, if you have inner functions and they're used as callbacks, you'll be invoking them as functions, and this will be bound to the global object. Use that var that = this trick/pattern. Some people think the constructor/new keyword was a bone thrown to Java/traditional OOP programmers as a way to create something similar to classes. With the Apply Method Finally, every function has a method (yes, functions are objects in Javascript) named "apply". Apply lets you determine what the value of this will be, and also lets you pass in an array of arguments. Here's a useless example. function foo(a,b){ alert(a); alert(b); alert(this);}var args = ['ah','be'];foo.apply('omg',args);
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/133973", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10861/" ] }