text
stringlengths
8
267k
meta
dict
Q: Debugging DLL Called With CeRapiInvoke I'm trying to debug into a C dll that is invoked on a Windows Mobile device using CeRapiInvoke() (Technically RAPI.Invoke() from OpenNETCF) from a Windows box. I'm very familiar with attaching to a process that is already running to debug a loaded dll (I've done it many time with Windows Mobile services) but I can't seem to figure out what process is actually running the dll. Even when running the Remote Process Viewer I don't see any new processes pop up, so it must be something that is already running... Any ideas as to which process to attach to in order to debug into the dll when invoked? Edit: After trying to attach to several different processes I found that it was "rapiclnt.exd" that did the trick. A: rapiclnt.exe is the process which loads the RAPI dlls. Read this for more on debugging RAPI dlls. http://knowledgepointer.wordpress.com/2008/11/08/debugging-rapi-dlls/
{ "language": "en", "url": "https://stackoverflow.com/questions/42973", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to use p4merge as the merge/diff tool for Mercurial? Does anyone know how to setup Mercurial to use p4merge as the merge/diff tool on OS X 10.5? A: This will work for merging: Place this into your ~/.hgrc (or, optionally, your Mercurial.ini on Windows): [merge-tools] p4.priority = 100 p4.premerge = True # change this to False if you're don't trust hg's internal merge p4.executable = /Applications/p4merge.app/Contents/MacOS/p4merge p4.gui = True p4.args = $base $local $other $output Requires Mercurial 1.0 or newer. Clearly you'll need to update the path to that executable to reflect where you'd got p4merge installed. You can't change what hg diff uses; but you can use the extdiff extension to create new diff commands that use the display you want. So hg pdiff could run p4 merge, etc. A: Maybe because I'm working on Windows, but the proposed solution didn't work for me. Instead, the following does work. In your ~/.hgrc/ / Mercurial.ini, I applied the following changes: Enabled "ExtDiff" extension: [extensions] hgext.extdiff = Added P4 extdiff command: [extdiff] cmd.p4diff = p4merge Configured it as the default visual diff tool: [tortoisehg] vdiff = p4diff A: I found Ry4an's answer to be a good solution, except for a minor problem, which left p4merge (under mac os) mixing up the command inputs. Do everything described in his answer and add the following line in the [merge-tools] section: p4.args=$base $local $other $output This line tells mercurial in which order p4merge takes its arguments. A: I am using version 1.0.1 of TortoiseHg and p4merge works out of the box. Just go to Global Settings -> TortoiseHg and select the following options: * *Three-way Merge Tool: p4merge *Visual Diff Tool: p4merge A: I'm guessing there's a CLI tool for p4merge (which I know nothing about). I wrote a blog post about using Changes.app, and some other GUI tools with Mercurial: Using Mercurial with GUI Tools. Basically, you need to know the calling expectations of the CLI tool that loads up the diff tool. IE, how to make it load data from a particular file, and how to make it wait for exit. There should be enough info on the post to give you some ideas. A: I use the following bit of Python to launch p4merge and use it with git : #!/usr/bin/python import sys import os os.system('/Applications/p4merge.app/Contents/MacOS/p4merge "%s" "%s"' % (sys.argv[2], sys.argv[5])) I'm not sure how mercurial looks to launch an external diff tool though ? Hopefully it's as simple as adjusting 2 & 5 in the above line to being the index of the arguments for 'checked in' and 'current working copy'.
{ "language": "en", "url": "https://stackoverflow.com/questions/42980", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "37" }
Q: How do you add a web reference through a proxy/firewall? I'm behind a firewall at work at the moment and I was testing something that I had deployed to my website, and the work proxy seems to be blocking it somewhat. Basically I am getting a message of: Operation is not valid due to the current state of the object I've got it down to my proxy interferring, but I can't see any advanced settings or anything I can set up to go through my proxy to get to my service. I did a quick google for it, but no joy. Anyone found a quick way to get around it? A: Edit, I forgot to write this part in the answer: You may need to add the web reference url to the safe list for your proxy. I am not sure what proxy you are using or if you have control of it, but this should solve your problem. If you don't have access to change the proxy, then I put a quick work around right below. Here's a quick work around, just use the browser to navigate to the WSDL. Grab the xml and save it as a .wsdl file on your computer you would like to generate the client on. Then use the wsdl.exe to generate the client pointing it to the path you saved the wsdl file. A: Another option is to go to your application's web config or app config and add the following under the element: <system.net> <defaultProxy useDefaultCredentials="false"> <proxy usesystemdefault="true" proxyaddress="10.0.0.1" port="80" bypassonlocal="true" /> </defaultProxy> </system.net> You can then add the web reference in the normal way.
{ "language": "en", "url": "https://stackoverflow.com/questions/42984", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: .NET IPC without having a service mediator I have two unrelated processes that use .NET assemblies as plugins. However, either process can be started/stopped at any time. I can't rely on a particular process being the server. In fact, there may be multiple copies running of one of the processes, but only one of the other. I initially implemented a solution based off of this article. However, this requires the one implementing the server to be running before the client. Whats the best way to implement some kind of notification to the server when the client(s) were running first? A: Using shared memory is tougher because you'll have to manage the size of the shared memory buffer (or just pre-allocate enough). You'll also have to manually manage the data structures that you put in there. Once you have it tested and working though, it will be easier to use and test because of its simplicity. If you go the remoting route, you can use the IpcChannel instead of the TCP or HTTP channels for a single system communication using Named Pipes. http://msdn.microsoft.com/en-us/library/4b3scst2.aspx. The problem with this solution is that you'll need to come up with a registry type solution (either in shared memory or some other persistent store) that processes can register their endpoints with. That way, when you're looking for them, you can find a way to query for all the endpoints that are running on the system and you can find what you're looking for. The benefits of going with Remoting are that the serialization and method calling are all pretty straightforward. Also, if you decide to move to multiple machines on a network, you could just flip the switch to use the networking channels instead. The cons are that Remoting can get frustrating unless you clearly separate what are "Remote" calls from what are "Local" calls. I don't know much about WCF, but that also might be worth looking into. Spider sense says that it probably has a more elegant solution to this problem... maybe. Alternatively, you can create a "server" process that is separate from all the other processes and that gets launched (use a system Mutex to make sure more than one isn't launched) to act as a go-between and registration hub for all the other processes. One more thing to look into the Publish-Subscribe model for events (Pub/Sub). This technique helps when you have a listener that is launched before the event source is available, but you don't want to wait to register for the event. The "server" process will handle the event registry to link up the publishers and subscribers. A: Why not host the server and the client on both sides, and whoever comes up first gets to be the server? And if the server drops out, the client that is still active switches roles. A: There are many ways to handle IPC (.net or not) and via a TCP/HTTP tunnel is one way...but can be a very bad choice (depending on circumstances and enviornment). Shared memory and named pipes are two ways (and yes they can be done in .Net) that might be better solutions for you. There is also the IPC class in the .Net Framework...but I personally don't like them due to some AppDomain issues... A: I agree with Garo. Using a pub/sub service would be a great solution. This obviously means that this service would need to be up and running before either of the other two. If you want to skip the pub/sub you can just implement the service in both applications with different end points. When either of the applications is launched it tries to access the other known object via the IPC proxy. If the proxy fails, the other object isn't up. -Scott A: I've spent 2 days meandering through all the options available for IPC while looking for a reliable, simple, and fast way to do full-duplex IPC. IPCLibrary, which I found on Codeplex.com, is so far working perfectly out of all the options that I tried. All with only 7 lines of code. :D If anyone stumbles across this trying to find a full-duplex IPC, save yourself a ton of time and give this library a try. Grab the source code, compile the data.dll and follow the examples given. HTH, Circ
{ "language": "en", "url": "https://stackoverflow.com/questions/42987", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Regex to match against something that is not a specific substring I am looking for a regex that will match a string that starts with one substring and does not end with a certain substring. Example: // Updated to be correct, thanks @Apocalisp ^foo.*(?<!bar)$ Should match anything that starts with "foo" and doesn't end with "bar". I know about the [^...] syntax, but I can't find anything that will do that for a string instead of single characters. I am specifically trying to do this for Java's regex, but I've run into this before so answers for other regex engines would be great too. Thanks to @Kibbee for verifying that this works in C# as well. A: I think in this case you want negative lookbehind, like so: foo.*(?<!bar) A: I'm not familiar with Java regex but documentation for the Pattern Class would suggest you could use (?!X) for a non-capturing zero-width negative lookahead (it looks for something that is not X at that postision, without capturing it as a backreference). So you could do: foo.*(?!bar) // not correct Update: Apocalisp's right, you want negative lookbehind. (you're checking that what the .* matches doesn't end with bar) A: Verified @Apocalisp's answer using: import java.util.regex.Pattern; public class Test { public static void main(String[] args) { Pattern p = Pattern.compile("^foo.*(?<!bar)$"); System.out.println(p.matcher("foobar").matches()); System.out.println(p.matcher("fooBLAHbar").matches()); System.out.println(p.matcher("1foo").matches()); System.out.println(p.matcher("fooBLAH-ar").matches()); System.out.println(p.matcher("foo").matches()); System.out.println(p.matcher("foobaz").matches()); } } This output the the right answers: false false false true true true A: As other commenters said, you need a negative lookahead. In Java you can use this pattern: "^first_string(?!.?second_string)\\z" * *^ - ensures that string starts with first_string *\z - ensures that string ends with second_string *(?!.?second_string) - means that first_string can't be followed by second_string
{ "language": "en", "url": "https://stackoverflow.com/questions/42990", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: ASP.NET MVC and Spring.NET Starting a new project and would like to use one of the MVC framworks. ASP.NET MVC is still in preview but Spring.net is in production and has a history with Java. I'd like to know the general lowdown between the two. Current questions.. What are the major feature differences? What about deployment/hosting issues? Future support? Do you think Spring.net will fade once ASP.NET MVC is in production. Current Support? I saw the Jeff twitting about a breaking change in the next preview. Thanks! A: I am a little confused by the question. Spring.Net is a dependency injection framework that you can use in ASP.NET MVC. I kind of based my answer off what you are actually asking though. The difference between ASP.NET MVC and another MVC framework that runs in ASP.NET. If you are worried about using ASP.NET MVC in production since it is not even in beta yet, then you may want to check out MonoRail as an alternate. There are some differences in features, but the two are pretty close in terminology and how MVC is implemented. To learn differences, here is a question that was posted, that you might want to monitor. I think once ASP.NET hits release, that most Microsoft shops will switch to it. With ASP.NET MVC still being developed, you will run into breaking changes that you will have to change when you upgrade to the next release. That goes with the territory of living on the edge. You just need to read the release notes before jumping to the latest release. A: I have an impression that Spring.NET never really took off, or at least not as much as Castle Project Monorail. From what I understand, Spring.NET has also departed from Java Spring's implementation, so there will a steeper than expected learning curve if you are coming from Java. From Spring.NET's overview: The design of Spring.NET is based on the Java version of the Spring Framework, which has shown real-world benefits and is used in thousands of enterprise applications world wide. Spring .NET is not a quick port from the Java version, but rather a 'spiritual port' based on following proven architectural and design patterns in that are not tied to a particular platform. As for your other questions, the breadth of the topics make them a bit difficult to answer in one go, but I am hoping Phil Haack will see this question and respond. :) A: Yes Spring.net adds enterprise solutions to Microsoft's codebase, Spring will fill the crucial missing gaps. I can attempt to answer your question on future support of Spring.net & ASP.net MVC. Apparently Spring will be releasing a new Milestone build when Microsoft go RTM/Final build: http://forum.springframework.net/showthread.php?p=14031#post14031 (Mark is the Spring.net lead and a Microsoft MVP) I've heard they don't want to give anything away until then, as they've had enough of Microsoft taking Springs ideas with no recognition. Current Support for Spring.net & Controller Dependency Injection can be found in MVCContrib
{ "language": "en", "url": "https://stackoverflow.com/questions/42996", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Transmiting data throught the Serial Port I'm working with the SerialPort class in the Compact Framework, but I can't recive more than 2047 bytes. Exists any limit for the amount of bytes that I can recive? or How can I setup the object? I was trying with the WriteBufferSize and ReadBufferSize properties but they didn't work. A: My guess is that it is either a processor or platform limitation. This post from the MSDN forums seems to confirm my suspicions. A: Can you set up a thread to pull the data into another (larger) buffer that you allocate yourself? I'd say that's the best workaround.
{ "language": "en", "url": "https://stackoverflow.com/questions/43006", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What does VS 2008's "Convert to Website" mean? I have upgraded a MS Visual Studio Application from VS 2003 to VS 2008 (Targeting .NET 2.0). As part of the conversion process the wizard said I needed to take the additional step of Converting my Project to a Website by Right-Clicking and blah blah blah... I didn't follow directions and the web application seems to be working fine. My question is, should I be concerned about pushing this to a production system? What exactly is going on here? A: There are two types of web applications in ASP.NET: The Web Site and Web Application Project. The difference between the two are discussed here: Difference between web site and web applications in Visual Studio 2005 Convert to Website allows you to convert a Web Application Project to a Web Site. Visual Studio 2003 used the Web Application Project style, but initially VS2005 only supported web sites. VS2005 SP1 brought back Web Applications. If you don't want to convert your project to a web site, apply SP1 if you're using VS2005. VS2008 can support either. A: Convert to Website moves all of your control declarations from the main page class to a secondary file (yourpage.aspx.designer.cs). It does this by using a partial class. That is, the same class for your page, but split into two seperate files. This allows the VS2k5 (and VS2k8) designer to generate code for your pages without dumping generated code spaghetti into the main class file. You don't need to do this step to build the project, but if you continue to maintain the project you will want too. EDIT: Hey look, MSDN backs me up: To convert the code to use the partial-class model * *Make sure the code compiles without errors. *In Solution Explorer, right-click the project name and click Convert to Web Application. This command iterates through each page and user control in the project. It moves all control declarations to a .designer.cs or designer.vb file. It also adds event handler declarations to the server-control markup in the .aspx and .ascx files. *When the process has finished, check the Task List window to see whether any conversion errors are reported. *If the Task List displays errors, right-click the relevant page in Solution Explorer and select View Code and View Code Gen File to examine the code and fix problems. *Recompile the project to make sure that it compiles without errors. A: There are two types of web applications in ASP.NET: The Web Site and Web Application Project. Convert to Website allows you to convert a Web Application Project to a Web Site. As far as I can recall, Convert to a Website does not do this, the Web Application project is a regular application structure with your typical \bin etc. The WebSite project instead is based upon the concept of an App_Code directory for classes, and an App_Date directory for data, with your regular ASPX files going anywhere. The idea is to avoid having to precompile into DLL's before deployment, which can be easier in some shared hosting situations. I am not aware of any wizard that will restructure the project between these types, but I may be wrong. A: The only thing you might have missed was whether or not you wanted to make a backup of the 2003 project (just in case). It's no big deal. Check out: Converting a Visual Studio .NET 2003 Web Project to a Visual Studio Web Application Project Visual Studio Conversion Wizard A: Convert to Website moves all of your control declarations from the main page class to a secondary file (yourpage.aspx.designer.cs). Why would I want to do this? It's bad enough that there is a .js .css .vb .aspx file for each page. Do I really need to split up the .vb into two more files just so I can hide the declarations ? page.designer.aspx.vb.h anyone?
{ "language": "en", "url": "https://stackoverflow.com/questions/43019", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: How do you get the index of the current iteration of a foreach loop? Is there some rare language construct I haven't encountered (like the few I've learned recently, some on Stack Overflow) in C# to get a value representing the current iteration of a foreach loop? For instance, I currently do something like this depending on the circumstances: int i = 0; foreach (Object o in collection) { // ... i++; } A: Ian Mercer posted a similar solution as this on Phil Haack's blog: foreach (var item in Model.Select((value, i) => new { i, value })) { var value = item.value; var index = item.i; } This gets you the item (item.value) and its index (item.i) by using this overload of LINQ's Select: the second parameter of the function [inside Select] represents the index of the source element. The new { i, value } is creating a new anonymous object. Heap allocations can be avoided by using ValueTuple if you're using C# 7.0 or later: foreach (var item in Model.Select((value, i) => ( value, i ))) { var value = item.value; var index = item.i; } You can also eliminate the item. by using automatic destructuring: foreach (var (value, i) in Model.Select((value, i) => ( value, i ))) { // Access `value` and `i` directly here. } A: int index; foreach (Object o in collection) { index = collection.indexOf(o); } This would work for collections supporting IList. A: // using foreach loop how to get index number: foreach (var result in results.Select((value, index) => new { index, value })) { // do something } A: Literal Answer -- warning, performance may not be as good as just using an int to track the index. At least it is better than using IndexOf. You just need to use the indexing overload of Select to wrap each item in the collection with an anonymous object that knows the index. This can be done against anything that implements IEnumerable. System.Collections.IEnumerable collection = Enumerable.Range(100, 10); foreach (var o in collection.OfType<object>().Select((x, i) => new {x, i})) { Console.WriteLine("{0} {1}", o.i, o.x); } A: The foreach is for iterating over collections that implement IEnumerable. It does this by calling GetEnumerator on the collection, which will return an Enumerator. This Enumerator has a method and a property: * *MoveNext() *Current Current returns the object that Enumerator is currently on, MoveNext updates Current to the next object. The concept of an index is foreign to the concept of enumeration, and cannot be done. Because of that, most collections are able to be traversed using an indexer and the for loop construct. I greatly prefer using a for loop in this situation compared to tracking the index with a local variable. A: Better to use keyword continue safe construction like this int i=-1; foreach (Object o in collection) { ++i; //... continue; //<--- safe to call, index will be increased //... } A: Using LINQ, C# 7, and the System.ValueTuple NuGet package, you can do this: foreach (var (value, index) in collection.Select((v, i)=>(v, i))) { Console.WriteLine(value + " is at index " + index); } You can use the regular foreach construct and be able to access the value and index directly, not as a member of an object, and keeps both fields only in the scope of the loop. For these reasons, I believe this is the best solution if you are able to use C# 7 and System.ValueTuple. A: You can write your loop like this: var s = "ABCDEFG"; foreach (var item in s.GetEnumeratorWithIndex()) { System.Console.WriteLine("Character: {0}, Position: {1}", item.Value, item.Index); } After adding the following struct and extension method. The struct and extension method encapsulate Enumerable.Select functionality. public struct ValueWithIndex<T> { public readonly T Value; public readonly int Index; public ValueWithIndex(T value, int index) { this.Value = value; this.Index = index; } public static ValueWithIndex<T> Create(T value, int index) { return new ValueWithIndex<T>(value, index); } } public static class ExtensionMethods { public static IEnumerable<ValueWithIndex<T>> GetEnumeratorWithIndex<T>(this IEnumerable<T> enumerable) { return enumerable.Select(ValueWithIndex<T>.Create); } } A: There's nothing wrong with using a counter variable. In fact, whether you use for, foreach while or do, a counter variable must somewhere be declared and incremented. So use this idiom if you're not sure if you have a suitably-indexed collection: var i = 0; foreach (var e in collection) { // Do stuff with 'e' and 'i' i++; } Else use this one if you know that your indexable collection is O(1) for index access (which it will be for Array and probably for List<T> (the documentation doesn't say), but not necessarily for other types (such as LinkedList)): // Hope the JIT compiler optimises read of the 'Count' property! for (var i = 0; i < collection.Count; i++) { var e = collection[i]; // Do stuff with 'e' and 'i' } It should never be necessary to 'manually' operate the IEnumerator by invoking MoveNext() and interrogating Current - foreach is saving you that particular bother ... if you need to skip items, just use a continue in the body of the loop. And just for completeness, depending on what you were doing with your index (the above constructs offer plenty of flexibility), you might use Parallel LINQ: // First, filter 'e' based on 'i', // then apply an action to remaining 'e' collection .AsParallel() .Where((e,i) => /* filter with e,i */) .ForAll(e => { /* use e, but don't modify it */ }); // Using 'e' and 'i', produce a new collection, // where each element incorporates 'i' collection .AsParallel() .Select((e, i) => new MyWrapper(e, i)); We use AsParallel() above, because it's 2014 already, and we want to make good use of those multiple cores to speed things up. Further, for 'sequential' LINQ, you only get a ForEach() extension method on List<T> and Array ... and it's not clear that using it is any better than doing a simple foreach, since you are still running single-threaded for uglier syntax. A: Finally C#7 has a decent syntax for getting an index inside of a foreach loop (i. e. tuples): foreach (var (item, index) in collection.WithIndex()) { Debug.WriteLine($"{index}: {item}"); } A little extension method would be needed: using System.Collections.Generic; public static class EnumExtension { public static IEnumerable<(T item, int index)> WithIndex<T>(this IEnumerable<T> self) => self.Select((item, index) => (item, index)); } A: If the collection is a list, you can use List.IndexOf, as in: foreach (Object o in collection) { // ... @collection.IndexOf(o) } A: This way you can use the index and value using LINQ: ListValues.Select((x, i) => new { Value = x, Index = i }).ToList().ForEach(element => { // element.Index // element.Value }); A: Using @FlySwat's answer, I came up with this solution: //var list = new List<int> { 1, 2, 3, 4, 5, 6 }; // Your sample collection var listEnumerator = list.GetEnumerator(); // Get enumerator for (var i = 0; listEnumerator.MoveNext() == true; i++) { int currentItem = listEnumerator.Current; // Get current item. //Console.WriteLine("At index {0}, item is {1}", i, currentItem); // Do as you wish with i and currentItem } You get the enumerator using GetEnumerator and then you loop using a for loop. However, the trick is to make the loop's condition listEnumerator.MoveNext() == true. Since the MoveNext method of an enumerator returns true if there is a next element and it can be accessed, making that the loop condition makes the loop stop when we run out of elements to iterate over. A: Just add your own index. Keep it simple. int i = -1; foreach (var item in Collection) { ++i; item.index = i; } A: My solution for this problem is an extension method WithIndex(), http://code.google.com/p/ub-dotnet-utilities/source/browse/trunk/Src/Utilities/Extensions/EnumerableExtensions.cs Use it like var list = new List<int> { 1, 2, 3, 4, 5, 6 }; var odd = list.WithIndex().Where(i => (i.Item & 1) == 1); CollectionAssert.AreEqual(new[] { 0, 2, 4 }, odd.Select(i => i.Index)); CollectionAssert.AreEqual(new[] { 1, 3, 5 }, odd.Select(i => i.Item)); A: For interest, Phil Haack just wrote an example of this in the context of a Razor Templated Delegate (http://haacked.com/archive/2011/04/14/a-better-razor-foreach-loop.aspx) Effectively he writes an extension method which wraps the iteration in an "IteratedItem" class (see below) allowing access to the index as well as the element during iteration. public class IndexedItem<TModel> { public IndexedItem(int index, TModel item) { Index = index; Item = item; } public int Index { get; private set; } public TModel Item { get; private set; } } However, while this would be fine in a non-Razor environment if you are doing a single operation (i.e. one that could be provided as a lambda) it's not going to be a solid replacement of the for/foreach syntax in non-Razor contexts. A: I don't think this should be quite efficient, but it works: @foreach (var banner in Model.MainBanners) { @Model.MainBanners.IndexOf(banner) } A: I built this in LINQPad: var listOfNames = new List<string>(){"John","Steve","Anna","Chris"}; var listCount = listOfNames.Count; var NamesWithCommas = string.Empty; foreach (var element in listOfNames) { NamesWithCommas += element; if(listOfNames.IndexOf(element) != listCount -1) { NamesWithCommas += ", "; } } NamesWithCommas.Dump(); //LINQPad method to write to console. You could also just use string.join: var joinResult = string.Join(",", listOfNames); A: You could wrap the original enumerator with another that does contain the index information. foreach (var item in ForEachHelper.WithIndex(collection)) { Console.Write("Index=" + item.Index); Console.Write(";Value= " + item.Value); Console.Write(";IsLast=" + item.IsLast); Console.WriteLine(); } Here is the code for the ForEachHelper class. public static class ForEachHelper { public sealed class Item<T> { public int Index { get; set; } public T Value { get; set; } public bool IsLast { get; set; } } public static IEnumerable<Item<T>> WithIndex<T>(IEnumerable<T> enumerable) { Item<T> item = null; foreach (T value in enumerable) { Item<T> next = new Item<T>(); next.Index = 0; next.Value = value; next.IsLast = false; if (item != null) { next.Index = item.Index + 1; yield return item; } item = next; } if (item != null) { item.IsLast = true; yield return item; } } } A: Why foreach ?! The simplest way is using for instead of foreach if you are using List: for (int i = 0 ; i < myList.Count ; i++) { // Do something... } Or if you want use foreach: foreach (string m in myList) { // Do something... } You can use this to know the index of each loop: myList.indexOf(m) A: Here's a solution I just came up with for this problem Original code: int index=0; foreach (var item in enumerable) { blah(item, index); // some code that depends on the index index++; } Updated code enumerable.ForEach((item, index) => blah(item, index)); Extension Method: public static IEnumerable<T> ForEach<T>(this IEnumerable<T> enumerable, Action<T, int> action) { var unit = new Unit(); // unit is a new type from the reactive framework (http://msdn.microsoft.com/en-us/devlabs/ee794896.aspx) to represent a void, since in C# you can't return a void enumerable.Select((item, i) => { action(item, i); return unit; }).ToList(); return pSource; } A: C# 7 finally gives us an elegant way to do this: static class Extensions { public static IEnumerable<(int, T)> Enumerate<T>( this IEnumerable<T> input, int start = 0 ) { int i = start; foreach (var t in input) { yield return (i++, t); } } } class Program { static void Main(string[] args) { var s = new string[] { "Alpha", "Bravo", "Charlie", "Delta" }; foreach (var (i, t) in s.Enumerate()) { Console.WriteLine($"{i}: {t}"); } } } A: Unless your collection can return the index of the object via some method, the only way is to use a counter like in your example. However, when working with indexes, the only reasonable answer to the problem is to use a for loop. Anything else introduces code complexity, not to mention time and space complexity. A: I don't believe there is a way to get the value of the current iteration of a foreach loop. Counting yourself, seems to be the best way. May I ask, why you would want to know? It seems that you would most likley be doing one of three things: 1) Getting the object from the collection, but in this case you already have it. 2) Counting the objects for later post processing...the collections have a Count property that you could make use of. 3) Setting a property on the object based on its order in the loop...although you could easily be setting that when you added the object to the collection. A: I just had this problem, but thinking around the problem in my case gave the best solution, unrelated to the expected solution. It could be quite a common case, basically, I'm reading from one source list and creating objects based on them in a destination list, however, I have to check whether the source items are valid first and want to return the row of any error. At first-glance, I want to get the index into the enumerator of the object at the Current property, however, as I am copying these elements, I implicitly know the current index anyway from the current destination. Obviously it depends on your destination object, but for me it was a List, and most likely it will implement ICollection. i.e. var destinationList = new List<someObject>(); foreach (var item in itemList) { var stringArray = item.Split(new char[] { ';', ',' }, StringSplitOptions.RemoveEmptyEntries); if (stringArray.Length != 2) { //use the destinationList Count property to give us the index into the stringArray list throw new Exception("Item at row " + (destinationList.Count + 1) + " has a problem."); } else { destinationList.Add(new someObject() { Prop1 = stringArray[0], Prop2 = stringArray[1]}); } } Not always applicable, but often enough to be worth mentioning, I think. Anyway, the point being that sometimes there is a non-obvious solution already in the logic you have... A: I wasn't sure what you were trying to do with the index information based on the question. However, in C#, you can usually adapt the IEnumerable.Select method to get the index out of whatever you want. For instance, I might use something like this for whether a value is odd or even. string[] names = { "one", "two", "three" }; var oddOrEvenByName = names .Select((name, index) => new KeyValuePair<string, int>(name, index % 2)) .ToDictionary(kvp => kvp.Key, kvp => kvp.Value); This would give you a dictionary by name of whether the item was odd (1) or even (0) in the list. A: This answer: lobby the C# language team for direct language support. The leading answer states: Obviously, the concept of an index is foreign to the concept of enumeration, and cannot be done. While this is true of the current C# language version (2020), this is not a conceptual CLR/Language limit, it can be done. The Microsoft C# language development team could create a new C# language feature, by adding support for a new Interface IIndexedEnumerable foreach (var item in collection with var index) { Console.WriteLine("Iteration {0} has value {1}", index, item); } //or, building on @user1414213562's answer foreach (var (item, index) in collection) { Console.WriteLine("Iteration {0} has value {1}", index, item); } If foreach () is used and with var index is present, then the compiler expects the item collection to declare IIndexedEnumerable interface. If the interface is absent, the compiler can polyfill wrap the source with an IndexedEnumerable object, which adds in the code for tracking the index. interface IIndexedEnumerable<T> : IEnumerable<T> { //Not index, because sometimes source IEnumerables are transient public long IterationNumber { get; } } Later, the CLR can be updated to have internal index tracking, that is only used if with keyword is specified and the source doesn't directly implement IIndexedEnumerable Why: * *Foreach looks nicer, and in business applications, foreach loops are rarely a performance bottleneck *Foreach can be more efficient on memory. Having a pipeline of functions instead of converting to new collections at each step. Who cares if it uses a few more CPU cycles when there are fewer CPU cache faults and fewer garbage collections? *Requiring the coder to add index-tracking code, spoils the beauty *It's quite easy to implement (please Microsoft) and is backward compatible While most people here are not Microsoft employees, this is a correct answer, you can lobby Microsoft to add such a feature. You could already build your own iterator with an extension function and use tuples, but Microsoft could sprinkle the syntactic sugar to avoid the extension function A: It's only going to work for a List and not any IEnumerable, but in LINQ there's this: IList<Object> collection = new List<Object> { new Object(), new Object(), new Object(), }; foreach (Object o in collection) { Console.WriteLine(collection.IndexOf(o)); } Console.ReadLine(); @Jonathan I didn't say it was a great answer, I just said it was just showing it was possible to do what he asked :) @Graphain I wouldn't expect it to be fast - I'm not entirely sure how it works, it could reiterate through the entire list each time to find a matching object, which would be a helluvalot of compares. That said, List might keep an index of each object along with the count. Jonathan seems to have a better idea, if he would elaborate? It would be better to just keep a count of where you're up to in the foreach though, simpler, and more adaptable. A: Could do something like this: public static class ForEachExtensions { public static void ForEachWithIndex<T>(this IEnumerable<T> enumerable, Action<T, int> handler) { int idx = 0; foreach (T item in enumerable) handler(item, idx++); } } public class Example { public static void Main() { string[] values = new[] { "foo", "bar", "baz" }; values.ForEachWithIndex((item, idx) => Console.WriteLine("{0}: {1}", idx, item)); } } A: I disagree with comments that a for loop is a better choice in most cases. foreach is a useful construct, and not replaceble by a for loop in all circumstances. For example, if you have a DataReader and loop through all records using a foreach it automatically calls the Dispose method and closes the reader (which can then close the connection automatically). This is therefore safer as it prevents connection leaks even if you forget to close the reader. (Sure it is good practise to always close readers but the compiler is not going to catch it if you don't - you can't guarantee you have closed all readers but you can make it more likely you won't leak connections by getting in the habit of using foreach.) There may be other examples of the implicit call of the Dispose method being useful. A: This is how I do it, which is nice for its simplicity/brevity, but if you're doing a lot in the loop body obj.Value, it is going to get old pretty fast. foreach(var obj in collection.Select((item, index) => new { Index = index, Value = item }) { string foo = string.Format("Something[{0}] = {1}", obj.Index, obj.Value); ... } A: How about something like this? Note that myDelimitedString may be null if myEnumerable is empty. IEnumerator enumerator = myEnumerable.GetEnumerator(); string myDelimitedString; string current = null; if( enumerator.MoveNext() ) current = (string)enumerator.Current; while( null != current) { current = (string)enumerator.Current; } myDelimitedString += current; if( enumerator.MoveNext() ) myDelimitedString += DELIMITER; else break; } A: Here is another solution to this problem, with a focus on keeping the syntax as close to a standard foreach as possible. This sort of construct is useful if you are wanting to make your views look nice and clean in MVC. For example instead of writing this the usual way (which is hard to format nicely): <%int i=0; foreach (var review in Model.ReviewsList) { %> <div id="review_<%=i%>"> <h3><%:review.Title%></h3> </div> <%i++; } %> You could instead write this: <%foreach (var review in Model.ReviewsList.WithIndex()) { %> <div id="review_<%=LoopHelper.Index()%>"> <h3><%:review.Title%></h3> </div> <%} %> I've written some helper methods to enable this: public static class LoopHelper { public static int Index() { return (int)HttpContext.Current.Items["LoopHelper_Index"]; } } public static class LoopHelperExtensions { public static IEnumerable<T> WithIndex<T>(this IEnumerable<T> that) { return new EnumerableWithIndex<T>(that); } public class EnumerableWithIndex<T> : IEnumerable<T> { public IEnumerable<T> Enumerable; public EnumerableWithIndex(IEnumerable<T> enumerable) { Enumerable = enumerable; } public IEnumerator<T> GetEnumerator() { for (int i = 0; i < Enumerable.Count(); i++) { HttpContext.Current.Items["LoopHelper_Index"] = i; yield return Enumerable.ElementAt(i); } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } In a non-web environment you could use a static instead of HttpContext.Current.Items. This is essentially a global variable, and so you cannot have more than one WithIndex loop nested, but that is not a major problem in this use case. A: This doesn't answer your specific question, but it DOES provide you with a solution to your problem: use a for loop to run through the object collection. then you will have the current index you are working on. // Untested for (int i = 0; i < collection.Count; i++) { Console.WriteLine("My index is " + i); } A: i want to discuss this question more theoretically (since it has already enough practical answers) .net has a very nice abstraction model for groups of data (a.k.a. collections) * *At the very top, and the most abstract, you have an IEnumerable it's just a group of data that you can enumerate. It doesn't matter HOW you enumerate, it's just that you can enumerate some data. And that enumeration is done by a completely different object, an IEnumerator these interfaces are defined is as follows: // // Summary: // Exposes an enumerator, which supports a simple iteration over a non-generic collection. public interface IEnumerable { // // Summary: // Returns an enumerator that iterates through a collection. // // Returns: // An System.Collections.IEnumerator object that can be used to iterate through // the collection. IEnumerator GetEnumerator(); } // // Summary: // Supports a simple iteration over a non-generic collection. public interface IEnumerator { // // Summary: // Gets the element in the collection at the current position of the enumerator. // // Returns: // The element in the collection at the current position of the enumerator. object Current { get; } // // Summary: // Advances the enumerator to the next element of the collection. // // Returns: // true if the enumerator was successfully advanced to the next element; false if // the enumerator has passed the end of the collection. // // Exceptions: // T:System.InvalidOperationException: // The collection was modified after the enumerator was created. bool MoveNext(); // // Summary: // Sets the enumerator to its initial position, which is before the first element // in the collection. // // Exceptions: // T:System.InvalidOperationException: // The collection was modified after the enumerator was created. void Reset(); } * *as you might have noticed, the IEnumerator interface doesn't "know" what an index is, it just knows what element it's currently pointing to, and how to move to the next one. *now here is the trick: foreach considers every input collection an IEnumerable, even if it is a more concrete implementation like an IList<T> (which inherits from IEnumerable), it will only see the abstract interface IEnumerable. *what foreach is actually doing, is calling GetEnumerator on the collection, and calling MoveNext until it returns false. *so here is the problem, you want to define a concrete concept "Indices" on an abstract concept "Enumerables", the built in foreach construct doesn't give you that option, so your only way is to define it yourself, either by what you are doing originally (creating a counter manually) or just use an implementation of IEnumerator that recognizes indices AND implement a foreach construct that recognizes that custom implementation. personally i would create an extension method like this public static class Ext { public static void FE<T>(this IEnumerable<T> l, Action<int, T> act) { int counter = 0; foreach (var item in l) { act(counter, item); counter++; } } } and use it like this var x = new List<string>() { "hello", "world" }; x.FE((ind, ele) => { Console.WriteLine($"{ind}: {ele}"); }); this also avoids any unnecessary allocations seen in other answers.
{ "language": "en", "url": "https://stackoverflow.com/questions/43021", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1233" }
Q: Algorithm to randomly generate an aesthetically-pleasing color palette I'm looking for a simple algorithm to generate a large number of random, aesthetically pleasing colors. So no crazy neon colors, colors reminiscent of feces, etc. I've found solutions to this problem but they rely on alternative color palettes than RGB. I would rather just use straight RGB than mapping back and forth. These other solutions also can at most generate only 32 or so pleasing random colors. Any ideas would be great. A: I would use a color wheel and given a random position you could add the golden angle (137,5 degrees) http://en.wikipedia.org/wiki/Golden_angle in order to get different colours each time that do not overlap. Adjusting the brightness for the color wheel you could get also different bright/dark color combinations. I've found this blog post that explains really well the problem and the solution using the golden ratio. http://martin.ankerl.com/2009/12/09/how-to-create-random-colors-programmatically/ UPDATE: I've just found this other approach: It's called RYB(red, yellow, blue) method and it's described in this paper: http://threekings.tk/mirror/ryb_TR.pdf as "Paint Inspired Color Compositing". The algorithm generates the colors and each new color is chosen to maximize its euclidian distance to the previously selected ones. Here you can find a a good implementation in javascript: http://afriggeri.github.com/RYB/ UPDATE 2: The Sciences Po Medialb have just released a tool called "I want Hue" that generate color palettes for data scientists. Using different color spaces and generating the palettes by using k-means clustering or force vectors ( repulsion graphs) The results from those methods are very good, they show the theory and an implementation in their web page. http://tools.medialab.sciences-po.fr/iwanthue/index.php A: I've had success using TriadMixing and CIE94 to avoid similar colors. The following image uses input colors red, yellow, and white. See here. // http://devmag.org.za/2012/07/29/how-to-choose-colours-procedurally-algorithms/#:~:text=120%20and%20240.-,7.%20Triad%20Mixing,-This%20algorithm%20takes public static Color RandomMix(Color color1, Color color2, Color color3, float greyControl) { int randomIndex = random.NextByte() % 3; float mixRatio1 = (randomIndex == 0) ? random.NextFloat() * greyControl : random.NextFloat(); float mixRatio2 = (randomIndex == 1) ? random.NextFloat() * greyControl : random.NextFloat(); float mixRatio3 = (randomIndex == 2) ? random.NextFloat() * greyControl : random.NextFloat(); float sum = mixRatio1 + mixRatio2 + mixRatio3; mixRatio1 /= sum; mixRatio2 /= sum; mixRatio3 /= sum; return Color.FromArgb( 255, (byte)(mixRatio1 * color1.R + mixRatio2 * color2.R + mixRatio3 * color3.R), (byte)(mixRatio1 * color1.G + mixRatio2 * color2.G + mixRatio3 * color3.G), (byte)(mixRatio1 * color1.B + mixRatio2 * color2.B + mixRatio3 * color3.B)); } A: An answer that shouldn't be overlooked, because it's simple and presents advantages, is sampling of real life photos and paintings. sample as many random pixels as you want random colors on thumbnails of modern art pics, cezanne, van gogh, monnet, photos... the advantage is that you can get colors by theme and that they are organic colors. just put 20 - 30 pics in a folder and random sample a random pic every time. Conversion to HSV values is a widespread code algorithm for psychologically based palette. hsv is easier to randomize. A: You could average the RGB values of random colors with those of a constant color: (example in Java) public Color generateRandomColor(Color mix) { Random random = new Random(); int red = random.nextInt(256); int green = random.nextInt(256); int blue = random.nextInt(256); // mix the color if (mix != null) { red = (red + mix.getRed()) / 2; green = (green + mix.getGreen()) / 2; blue = (blue + mix.getBlue()) / 2; } Color color = new Color(red, green, blue); return color; } Mixing random colors with white (255, 255, 255) creates neutral pastels by increasing the lightness while keeping the hue of the original color. These randomly generated pastels usually go well together, especially in large numbers. Here are some pastel colors generated using the above method: You could also mix the random color with a constant pastel, which results in a tinted set of neutral colors. For example, using a light blue creates colors like these: Going further, you could add heuristics to your generator that take into account complementary colors or levels of shading, but it all depends on the impression you want to achieve with your random colors. Some additional resources: * *http://en.wikipedia.org/wiki/Color_theory *http://en.wikipedia.org/wiki/Complementary_color A: In php: function pastelColors() { $r = dechex(round(((float) rand() / (float) getrandmax()) * 127) + 127); $g = dechex(round(((float) rand() / (float) getrandmax()) * 127) + 127); $b = dechex(round(((float) rand() / (float) getrandmax()) * 127) + 127); return "#" . $r . $g . $b; } source: https://stackoverflow.com/a/12266311/2875783 A: Use distinct-colors. Written in javascript. It generates a palette of visually distinct colors. distinct-colors is highly configurable: * *Choose how many colors are in the palette *Restrict the hue to a specific range *Restrict the chroma (saturation) to a specific range *Restrict the lightness to a specific range *Configure general quality of the palette A: Here is quick and dirty color generator in C# (using 'RYB approach' described in this article). It's a rewrite from JavaScript. Use: List<Color> ColorPalette = ColorGenerator.Generate(30).ToList(); First two colors tend to be white and a shade of black. I often skip them like this (using Linq): List<Color> ColorsPalette = ColorGenerator .Generate(30) .Skip(2) // skip white and black .ToList(); Implementation: public static class ColorGenerator { // RYB color space private static class RYB { private static readonly double[] White = { 1, 1, 1 }; private static readonly double[] Red = { 1, 0, 0 }; private static readonly double[] Yellow = { 1, 1, 0 }; private static readonly double[] Blue = { 0.163, 0.373, 0.6 }; private static readonly double[] Violet = { 0.5, 0, 0.5 }; private static readonly double[] Green = { 0, 0.66, 0.2 }; private static readonly double[] Orange = { 1, 0.5, 0 }; private static readonly double[] Black = { 0.2, 0.094, 0.0 }; public static double[] ToRgb(double r, double y, double b) { var rgb = new double[3]; for (int i = 0; i < 3; i++) { rgb[i] = White[i] * (1.0 - r) * (1.0 - b) * (1.0 - y) + Red[i] * r * (1.0 - b) * (1.0 - y) + Blue[i] * (1.0 - r) * b * (1.0 - y) + Violet[i] * r * b * (1.0 - y) + Yellow[i] * (1.0 - r) * (1.0 - b) * y + Orange[i] * r * (1.0 - b) * y + Green[i] * (1.0 - r) * b * y + Black[i] * r * b * y; } return rgb; } } private class Points : IEnumerable<double[]> { private readonly int pointsCount; private double[] picked; private int pickedCount; private readonly List<double[]> points = new List<double[]>(); public Points(int count) { pointsCount = count; } private void Generate() { points.Clear(); var numBase = (int)Math.Ceiling(Math.Pow(pointsCount, 1.0 / 3.0)); var ceil = (int)Math.Pow(numBase, 3.0); for (int i = 0; i < ceil; i++) { points.Add(new[] { Math.Floor(i/(double)(numBase*numBase))/ (numBase - 1.0), Math.Floor((i/(double)numBase) % numBase)/ (numBase - 1.0), Math.Floor((double)(i % numBase))/ (numBase - 1.0), }); } } private double Distance(double[] p1) { double distance = 0; for (int i = 0; i < 3; i++) { distance += Math.Pow(p1[i] - picked[i], 2.0); } return distance; } private double[] Pick() { if (picked == null) { picked = points[0]; points.RemoveAt(0); pickedCount = 1; return picked; } var d1 = Distance(points[0]); int i1 = 0, i2 = 0; foreach (var point in points) { var d2 = Distance(point); if (d1 < d2) { i1 = i2; d1 = d2; } i2 += 1; } var pick = points[i1]; points.RemoveAt(i1); for (int i = 0; i < 3; i++) { picked[i] = (pickedCount * picked[i] + pick[i]) / (pickedCount + 1.0); } pickedCount += 1; return pick; } public IEnumerator<double[]> GetEnumerator() { Generate(); for (int i = 0; i < pointsCount; i++) { yield return Pick(); } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } public static IEnumerable<Color> Generate(int numOfColors) { var points = new Points(numOfColors); foreach (var point in points) { var rgb = RYB.ToRgb(point[0], point[1], point[2]); yield return Color.FromArgb( (int)Math.Floor(255 * rgb[0]), (int)Math.Floor(255 * rgb[1]), (int)Math.Floor(255 * rgb[2])); } } } A: David Crow's method in an R two-liner: GetRandomColours <- function(num.of.colours, color.to.mix=c(1,1,1)) { return(rgb((matrix(runif(num.of.colours*3), nrow=num.of.colours)*color.to.mix)/2)) } A: In javascript: function pastelColors(){ var r = (Math.round(Math.random()* 127) + 127).toString(16); var g = (Math.round(Math.random()* 127) + 127).toString(16); var b = (Math.round(Math.random()* 127) + 127).toString(16); return '#' + r + g + b; } Saw the idea here: http://blog.functionalfun.net/2008/07/random-pastel-colour-generator.html A: function fnGetRandomColour(iDarkLuma, iLightLuma) { for (var i=0;i<20;i++) { var sColour = ('ffffff' + Math.floor(Math.random() * 0xFFFFFF).toString(16)).substr(-6); var rgb = parseInt(sColour, 16); // convert rrggbb to decimal var r = (rgb >> 16) & 0xff; // extract red var g = (rgb >> 8) & 0xff; // extract green var b = (rgb >> 0) & 0xff; // extract blue var iLuma = 0.2126 * r + 0.7152 * g + 0.0722 * b; // per ITU-R BT.709 if (iLuma > iDarkLuma && iLuma < iLightLuma) return sColour; } return sColour; } For pastel, pass in higher luma dark/light integers - ie fnGetRandomColour(120, 250) Credits: all credits to http://paulirish.com/2009/random-hex-color-code-snippets/ stackoverflow.com/questions/12043187/how-to-check-if-hex-color-is-too-black A: Converting to another palette is a far superior way to do this. There's a reason they do that: other palettes are 'perceptual' - that is, they put similar seeming colors close together, and adjusting one variable changes the color in a predictable manner. None of that is true for RGB, where there's no obvious relationship between colors that "go well together". A: JavaScript adaptation of David Crow's original answer, IE and Nodejs specific code included. generateRandomComplementaryColor = function(r, g, b){ //--- JavaScript code var red = Math.floor((Math.random() * 256)); var green = Math.floor((Math.random() * 256)); var blue = Math.floor((Math.random() * 256)); //--- //--- Extra check for Internet Explorers, its Math.random is not random enough. if(!/MSIE 9/i.test(navigator.userAgent) && !/MSIE 10/i.test(navigator.userAgent) && !/rv:11.0/i.test(navigator.userAgent)){ red = Math.floor((('0.' + window.crypto.getRandomValues(new Uint32Array(1))[0]) * 256)); green = Math.floor((('0.' + window.crypto.getRandomValues(new Uint32Array(1))[0]) * 256)); blue = Math.floor((('0.' + window.crypto.getRandomValues(new Uint32Array(1))[0]) * 256)); }; //--- //--- nodejs code /* crypto = Npm.require('crypto'); red = Math.floor((parseInt(crypto.randomBytes(8).toString('hex'), 16)) * 1.0e-19 * 256); green = Math.floor((parseInt(crypto.randomBytes(8).toString('hex'), 16)) * 1.0e-19 * 256); blue = Math.floor((parseInt(crypto.randomBytes(8).toString('hex'), 16)) * 1.0e-19 * 256); */ //--- red = (red + r)/2; green = (green + g)/2; blue = (blue + b)/2; return 'rgb(' + Math.floor(red) + ', ' + Math.floor(green) + ', ' + Math.floor(blue) + ')'; } Run the function using: generateRandomComplementaryColor(240, 240, 240); A: you could have them be within a certain brightness. that would control the ammount of "neon" colors a bit. for instance, if the "brightness" brightness = sqrt(R^2+G^2+B^2) was within a certain high bound, it would have a washed out, light color to it. Conversely, if it was within a certain low bound, it would be darker. This would eliminate any crazy, standout colors and if you chose a bound really high or really low, they would all be fairly close to either white or black. A: It's going to be hard to get what you want algorithmically - people have been studying color theory for a long time, and they don't even know all the rules. However, there are some rules which you can use to cull bad color combinations (ie, there are rules for clashing colors, and choosing complementary colors). I'd recommend you visit your library's art section and check out books on color theory to gain a better understanding of what is a good color before you try to make one - it appears you might not even know why certain combinations work and others don't. -Adam A: I'd strongly recommend using a CG HSVtoRGB shader function, they are awesome... it gives you natural color control like a painter instead of control like a crt monitor, which you arent presumably! This is a way to make 1 float value. i.e. Grey, into 1000 ds of combinations of color and brightness and saturation etc: int rand = a global color randomizer that you can control by script/ by a crossfader etc. float h = perlin(grey,23.3*rand) float s = perlin(grey,54,4*rand) float v = perlin(grey,12.6*rand) Return float4 HSVtoRGB(h,s,v); result is AWESOME COLOR RANDOMIZATION! it's not natural but it uses natural color gradients and it looks organic and controlleably irridescent / pastel parameters. For perlin, you can use this function, it is a fast zig zag version of perlin. function zig ( xx : float ): float{ //lfo nz -1,1 xx= xx+32; var x0 = Mathf.Floor(xx); var x1 = x0+1; var v0 = (Mathf.Sin (x0*.014686)*31718.927)%1; var v1 = (Mathf.Sin (x1*.014686)*31718.927)%1; return Mathf.Lerp( v0 , v1 , (xx)%1 )*2-1; } A: Here is something I wrote for a site I made. It will auto-generate a random flat background-color for any div with the class .flat-color-gen. Jquery is only required for the purposes of adding css to the page; it's not required for the main part of this, which is the generateFlatColorWithOrder() method. JsFiddle Link (function($) { function generateFlatColorWithOrder(num, rr, rg, rb) { var colorBase = 256; var red = 0; var green = 0; var blue = 0; num = Math.round(num); num = num + 1; if (num != null) { red = (num*rr) % 256; green = (num*rg) % 256; blue = (num*rb) % 256; } var redString = Math.round((red + colorBase) / 2).toString(); var greenString = Math.round((green + colorBase) / 2).toString(); var blueString = Math.round((blue + colorBase) / 2).toString(); return "rgb("+redString+", "+greenString+", "+blueString+")"; //return '#' + redString + greenString + blueString; } function generateRandomFlatColor() { return generateFlatColorWithOrder(Math.round(Math.random()*127)); } var rr = Math.round(Math.random()*1000); var rg = Math.round(Math.random()*1000); var rb = Math.round(Math.random()*1000); console.log("random red: "+ rr); console.log("random green: "+ rg); console.log("random blue: "+ rb); console.log("----------------------------------------------------"); $('.flat-color-gen').each(function(i, obj) { console.log(generateFlatColorWithOrder(i)); $(this).css("background-color",generateFlatColorWithOrder(i, rr, rg, rb).toString()); }); })(window.jQuery);
{ "language": "en", "url": "https://stackoverflow.com/questions/43044", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "325" }
Q: C# numeric constants I have the following C# code: byte rule = 0; ... rule = rule | 0x80; which produces the error: Cannot implicitly convert type 'int' to 'byte'. An explicit conversion exists (are you missing a cast?) [Update: first version of the question was wrong ... I misread the compiler output] Adding the cast doesn't fix the problem: rule = rule | (byte) 0x80; I need to write it as: rule |= 0x80; Which just seems weird. Why is the |= operator any different to the | operator? Is there any other way of telling the compiler to treat the constant as a byte? @ Giovanni Galbo : yes and no. The code is dealing with the programming of the flash memory in an external device, and logically represents a single byte of memory. I could cast it later, but this seemed more obvious. I guess my C heritage is showing through too much! @ Jonathon Holland : the 'as' syntax looks neater but unfortunately doesn't appear to work ... it produces: The as operator must be used with a reference type or nullable type ('byte' is a non-nullable value type) A: The term you are looking for is "Literal" and unfortunately C# does not have a byte literal. Here's a list of all C# literals. A: int rule = 0; rule |= 0x80; http://msdn.microsoft.com/en-us/library/kxszd0kx.aspx The | operator is defined for all value types. I think this will produced the intended result. The "|=" operator is an or then assign operator, which is simply shorthand for rule = rule | 0x80. One of the niftier things about C# is that it lets you do crazy things like abuse value types simply based on their size. An 'int' is exactly the same as a byte, except the compiler will throw warnings if you try and use them as both at the same time. Simply sticking with one (in this case, int) works well. If you're concerned about 64bit readiness, you can specify int32, but all ints are int32s, even running in x64 mode. A: C# does not have a literal suffix for byte. u = uint, l = long, ul = ulong, f = float, m = decimal, but no byte. You have to cast it. A: According to the ECMA Specification, pg 72 there is no byte literal. Only integer literals for the types: int, uint, long, and ulong. A: Almost five years on and nobody has actually answered the question. A couple of answers claim that the problem is the lack of a byte literal, but this is irrelevant. If you calculate (byte1 | byte2) the result is of type int. Even if "b" were a literal suffix for byte the type of (23b | 32b) would still be int. The accepted answer links to an MSDN article claiming that operator| is defined for all integral types, but this isn't true either. operator| is not defined on byte so the compiler uses its usual overload resolution rules to pick the version that's defined on int. Hence, if you want to assign the result to a byte you need to cast it: rule = (byte)(rule | 0x80); The question remains, why does rule |= 0x80; work? Because the C# specification has a special rule for compound assignment that allows you to omit the explicit conversion. In the compound assignment x op= y the rule is: if the selected operator is a predefined operator, if the return type of the selected operator is explicitly convertible to the type of x, and if y is implicitly convertible to the type of x or the operator is a shift operator, then the operation is evaluated as x = (T)(x op y), where T is the type of x, except that x is evaluated only once. A: This works: rule = (byte)(rule | 0x80); Apparently the expression 'rule | 0x80' returns an int even if you define 0x80 as 'const byte 0x80'. A: Looks like you may just have to do it the ugly way: http://msdn.microsoft.com/en-us/library/5bdb6693.aspx. A: Unfortunately, your only recourse is to do it just the way you have. There is no suffix to mark the literal as a byte. The | operator does not provide for implicit conversion as an assignment (i.e. initialization) would. A: Apparently the expression 'rule | 0x80' returns an int even if you define 0x80 as 'const byte 0x80'. I think the rule is numbers like 0x80 defaults to int unless you include a literal suffix. So for the expression rule | 0x80, the result will be an int since 0x80 is an int and rule (which is a byte) can safely be converted to int. A: According to the C standard, bytes ALWAYS promote to int in expressions, even constants. However, as long as both values are UNSIGNED, the high-order bits will be discarded so the operation should return the correct value. Similarly, floats promote to double, etc. Pull out of copy of K&R. It's all in there.
{ "language": "en", "url": "https://stackoverflow.com/questions/43051", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "19" }
Q: Best way to multi-thread? What is the best way to multi-thread in the C language? I want something that is very efficient and not a CPU hog. Thanks. A: The correct (standard) way to do this on C and Windows is with __beginthreadex. This is usually preferred to calling CreateThread directly as CreateThread doesn't init C runtime support for the thread. So if you create a thread using CreateThread, and call a CRT function, bad stuff can/will happen. Note that __beginthreadex calls CreateThread internally, but performs some other work behind the scenes. A: If you're on a UNIX-based platform (Linux or Mac OS X) your best option is POSIX threads. They're the standard cross-platform way to multithread in a POSIX environment. They can also be used in Windows, but there are probably better (more native) solutions for that platform. A: Your question is a bit general to answer effectively. You might look into such things as: CreateThread in the windows SDK boost::thread
{ "language": "en", "url": "https://stackoverflow.com/questions/43086", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-7" }
Q: How can I get a commit message from a bzr post-commit hook? I'm trying to write a bzr post-commit hook for my private bugtracker, but I'm stuck at the function signature of post_commit(local, master, old_revno, old_revid, new_revno, mew_revid) How can I extract the commit message for the branch from this with bzrlib in Python? A: And the answer is like so: def check_commit_msg(local, master, old_revno, old_revid, new_revno, new_revid): branch = local or master revision = branch.repository.get_revision(new_revid) print revision.message local and master are Branch objects, so once you have a revision, it's easy to extract the message.
{ "language": "en", "url": "https://stackoverflow.com/questions/43099", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: LINQ to SQL for self-referencing tables? I have a self referencing Categories table. Each Category has a CategoryID, ParentCategoryID, CategoryName, etc. And each category can have any number of sub categories, and each of those sub categories can have any number of sub categories, and so and and so forth. So basically the tree can be X levels deep. Then Products are associated to leaf (sub) Categories. Is there a way to get all the Products for any given Category (which would be all the products associated to all its leaf descendants) using LINQ to SQL? This feels like a recursive problem. Is it better to used a Stored Procedure instead? A: I don't think linq-to-sql has a good answer to this problem. Since you are using sql server 2005 you can use CTEs to do hierarchical queries. Either a stored procedure or an inline query (using DataContext.ExecuteQuery) will do the trick. A: Well here is a terrible rushed implementation using LINQ. Don't use this :-) public IQueryable GetCategories(Category parent) { var cats = (parent.Categories); foreach (Category c in cats ) { cats = cats .Concat(GetCategories(c)); } return a; } A: The performant approach is to create an insert/modify/delete trigger which maintains an entirely different table which contains node-ancestor pairs for all ancestors of all nodes. This way, the lookup is O(N). To use it for getting all products belonging to a node and all of its descendants, you can just select all category nodes which have your target node as an ancestor. After this, you simply select any products belonging to any of these categories. A: The way I handle this is by using some extension methods (filters). I've written up some sample code from a project I have implemented this on. Look specifically at the lines where I'm populating a ParentPartner object and a SubPartners List. public IQueryable<Partner> GetPartners() { return from p in db.Partners select new Partner { PartnerId = p.PartnerId, CompanyName = p.CompanyName, Address1 = p.Address1, Address2 = p.Address2, Website = p.Website, City = p.City, State = p.State, County = p.County, Country = p.Country, Zip = p.Zip, ParentPartner = GetPartners().WithPartnerId(p.ParentPartnerId).ToList().SingleOrDefault(), SubPartners = GetPartners().WithParentPartnerId(p.PartnerId).ToList() }; } public static IQueryable<Partner> WithPartnerId(this IQueryable<Partner> qry, int? partnerId) { return from t in qry where t.PartnerId == partnerId select t; } public static IQueryable<Partner> WithParentPartnerId(this IQueryable<Partner> qry, int? parentPartnerId) { return from p in qry where p.ParentPartner.PartnerId == parentPartnerId select p; }
{ "language": "en", "url": "https://stackoverflow.com/questions/43111", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How can I run an external program from C and parse its output? I've got a utility that outputs a list of files required by a game. How can I run that utility within a C program and grab its output so I can act on it within the same program? UPDATE: Good call on the lack of information. The utility spits out a series of strings, and this is supposed to be portable across Mac/Windows/Linux. Please note, I'm looking for a programmatic way to execute the utility and retain its output (which goes to stdout). A: As others have pointed out, popen() is the most standard way. And since no answer provided an example using this method, here it goes: #include <stdio.h> #define BUFSIZE 128 int parse_output(void) { char *cmd = "ls -l"; char buf[BUFSIZE]; FILE *fp; if ((fp = popen(cmd, "r")) == NULL) { printf("Error opening pipe!\n"); return -1; } while (fgets(buf, BUFSIZE, fp) != NULL) { // Do whatever you want here... printf("OUTPUT: %s", buf); } if (pclose(fp)) { printf("Command not found or exited with error status\n"); return -1; } return 0; } Sample output: OUTPUT: total 16 OUTPUT: -rwxr-xr-x 1 14077 14077 8832 Oct 19 04:32 a.out OUTPUT: -rw-r--r-- 1 14077 14077 1549 Oct 19 04:32 main.c A: Well, assuming you're on a command line in a windows environment, you can use pipes or command line redirects. For instance, commandThatOutputs.exe > someFileToStoreResults.txt or commandThatOutputs.exe | yourProgramToProcessInput.exe Within your program, you could use the C standard input functions to read the other programs output (scanf, etc.): http://irc.essex.ac.uk/www.iota-six.co.uk/c/c1_standard_input_and_output.asp . You could also use the file example and use fscanf. This should also work in Unix/Linux. This is a very generic question, you may want to include more details, like what type of output it is (just text, or a binary file?) and how you want to process it. Edit: Hooray clarification! Redirecting STDOUT looks to be troublesome, I've had to do it in .NET, and it gave me all sorts of headaches. It looks like the proper C way is to spawn a child process, get a file pointer, and all of a sudden my head hurts. So heres a hack that uses temporary files. It's simple, but it should work. This will work well if speed isn't an issue (hitting the disk is slow), or if it's throw-away. If you're building an enterprise program, looking into the STDOUT redirection is probably best, using what other people recommended. #include <stdlib.h> #include <stdio.h> int main(int argc, char* argv[]) { FILE * fptr; // file holder char c; // char buffer system("dir >> temp.txt"); // call dir and put it's contents in a temp using redirects. fptr = fopen("temp.txt", "r"); // open said file for reading. // oh, and check for fptr being NULL. while(1){ c = fgetc(fptr); if(c!= EOF) printf("%c", c); // do what you need to. else break; // exit when you hit the end of the file. } fclose(fptr); // don't call this is fptr is NULL. remove("temp.txt"); // clean up getchar(); // stop so I can see if it worked. } Make sure to check your file permissions: right now this will simply throw the file in the same directory as an exe. You might want to look into using /tmp in nix, or C:\Users\username\Local Settings\Temp in Vista, or C:\Documents and Settings\username\Local Settings\Temp in 2K/XP. I think the /tmp will work in OSX, but I've never used one. A: For simple problems in Unix-ish environments try popen(). From the man page: The popen() function opens a process by creating a pipe, forking and invoking the shell. If you use the read mode this is exactly what you asked for. I don't know if it is implemented in Windows. For more complicated problems you want to look up inter-process communication. A: In Linux and OS X, popen() really is your best bet, as dmckee pointed out, since both OSs support that call. In Windows, this should help: http://msdn.microsoft.com/en-us/library/ms682499.aspx A: MSDN documentation says If used in a Windows program, the _popen function returns an invalid file pointer that causes the program to stop responding indefinitely. _popen works properly in a console application. To create a Windows application that redirects input and output, see Creating a Child Process with Redirected Input and Output in the Windows SDK. A: popen is supported on Windows, see here: http://msdn.microsoft.com/en-us/library/96ayss4b.aspx If you want it to be cross-platform, popen is the way to go. A: You can use system() as in: system("ls song > song.txt"); where ls is the command name for listing the contents of the folder song and song is a folder in the current directory. Resulting file song.txt will be created in the current directory. A: //execute external process and read exactly binary or text output //can read image from Zip file for example string run(const char* cmd){ FILE* pipe = popen(cmd, "r"); if (!pipe) return "ERROR"; char buffer[262144]; string data; string result; int dist=0; int size; //TIME_START while(!feof(pipe)) { size=(int)fread(buffer,1,262144, pipe); //cout<<buffer<<" size="<<size<<endl; data.resize(data.size()+size); memcpy(&data[dist],buffer,size); dist+=size; } //TIME_PRINT_ pclose(pipe); return data; }
{ "language": "en", "url": "https://stackoverflow.com/questions/43116", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "87" }
Q: IList.Cast() returns error, syntax looks ok public static IList<T> LoadObjectListAll<T>() { ISession session = CheckForExistingSession(); var cfg = new NHibernate.Cfg.Configuration().Configure(); var returnList = session.CreateCriteria(typeof(T)); var list = returnList.List(); var castList = list.Cast<typeof(T)>(); return castList; } So, I'm getting a build error where I am casting the "list" element to a generic IList .... can anyone see a glaring error here? A: T is not a type nor a System.Type. T is a type parameter. typeof(T) returns the type of T. The typeof operator does not act on an object, it returns the Type object of a type. http://msdn.microsoft.com/en-us/library/58918ffs.aspx @John is correct in answering your direct question. But the NHibernate code there is a little off. You shouldn't be configuring the ISessionFactory after getting the ISession, for example. public static T[] LoadObjectListAll() { var session = GetNewSession(); var criteria = session.CreateCriteria(typeof(T)); var results = criteria.List<T>(); return results.ToArray(); } A: I think var castList = list.Cast<typeof(T)>(); should be var castList = list.Cast<T>(); @Jon Limjap The most glaring error I can see is that an IList is definitely different from an IList<T>. An IList is non-generic (e.g., ArrayList). The original question was already using an IList<T>. It was removed when someone edited the formatting. Probably a problem with Markdown. Fixed now. A: T is already a type parameter, you don't need to call typeof on it. TypeOf takes a type and returns its type parameter. A: The IList is an IList<T>, it just got fubared by markdown when she posted it. I tried to format it, but I missed escaping the <T>..Fixing that now. A: CLI only supports generic arguments for covariance and contravariance when using delegates, but when using generics there are some limitations, for example, you can cast a string to an object so most people will assume that you can do the same with List to a List but you can't do that because there is no covariance between generic parameters however you can simulate covariance as you can see in this article. So it depends on the runtime type that it is generated by the abstract factory. That reads like a markov chain... Bravo. A: "The original question was already using an IList<T>. It was removed when someone edited the formatting. Probably a problem with Markdown." Thats what i saw but it was edited by someone and that's the reason why I put my explanation about covariance but for some reason i was marked down to -1. A: @Jonathan Holland T is already a type parameter, you don't need to call typeof on it. TypeOf takes a type and returns its type parameter. typeof "takes" a type and returns its System.Type A: You have too many temporary variables which are confusing instead of var returnList = session.CreateCriteria(typeof(T)); var list = returnList.List(); var castList = list.Cast<typeof(T)>(); return castList; Just do return session.CreateCriteria(typeof(T)).List().Cast<T>(); A: @Jon and @Jonathan is correct, but you also have to change the return type to IList<T> also. Unless that is just a markdown bug. @Jonathan, figured that was the case. I am not sure what version of nHibernate you are using. I haven't tried the gold release of 2.0 yet, but you could clean the method up some, by removing some lines: public static IList<T> LoadObjectListAll() { ISession session = CheckForExistingSession(); // Not sure if you can configure a session after retrieving it. CheckForExistingSession should have this logic. // var cfg = new NHibernate.Cfg.Configuration().Configure(); var criteria = session.CreateCriteria(typeof(T)); return criteria.List<T>(); } A: CLI only supports generic arguments for covariance and contravariance when using delegates, but when using generics there are some limitations, for example, you can cast a string to an object so most people will assume that you can do the same with List<string> to a List<object> but you can't do that because there is no covariance between generic parameters however you can simulate covariance as you can see in this article. So it depends on the runtime type that it is generated by the abstract factory. A: The most glaring error I can see is that an IList is definitely different from an IList<T>. An IList is non-generic (e.g., ArrayList). So your method signature should be: public static IList<T> LoadObjectListAll()
{ "language": "en", "url": "https://stackoverflow.com/questions/43126", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Is there a difference between :: and . when calling class methods in Ruby? Simple question, but one that I've been curious about...is there a functional difference between the following two commands? String::class String.class They both do what I expect -- that is to say they return Class -- but what is the difference between using the :: and the .? I notice that on those classes that have constants defined, IRB's auto-completion will return the constants as available options when you press tab after :: but not after ., but I don't know what the reason for this is... A: The . operator basically says "send this message to the object". In your example it is calling that particular member. The :: operator "drills down" to the scope defined to the left of the operator, and then calls the member defined on the right side of operator. When you use :: you have to be referencing members that are defined. When using . you are simply sending a message to the object. Because that message could be anything, auto-completion does not work for . while it does for ::. A: Actually, auto-completion does work for .. The completion options are found by calling #methods on the object. You can see this for yourself by overriding Object.methods: >> def Object.methods; ["foo", "bar"]; end => nil >> Object.[TAB] Object.foo Object.bar >> Object. Note that this only works when the expression to the left of the . is a literal. Otherwise, getting the object to call #methods on would involve evaluating the left-hand side, which could have side-effects. You can see this for yourself as well: [continuing from above...] >> def Object.baz; Object; end => nil >> Object.baz.[TAB] Display all 1022 possibilities? (y or n) We add a method #baz to Object which returns Object itself. Then we auto-complete to get the methods we can call on Object.baz. If IRB called Object.baz.methods, it would get the same thing as Object.methods. Instead, IRB has 1022 suggestions. I'm not sure where they come from, but it's clearly a generic list which isn't actually based on context. The :: operator is (also) used for getting a module's constants, while . is not. That's why HTTP will show up in the completion for Net::, but not for Net.. Net.HTTP isn't correct, but Net::HTTP is.
{ "language": "en", "url": "https://stackoverflow.com/questions/43134", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "26" }
Q: Easy way to write contents of a Java InputStream to an OutputStream I was surprised to find today that I couldn't track down any simple way to write the contents of an InputStream to an OutputStream in Java. Obviously, the byte buffer code isn't difficult to write, but I suspect I'm just missing something which would make my life easier (and the code clearer). So, given an InputStream in and an OutputStream out, is there a simpler way to write the following? byte[] buffer = new byte[1024]; int len = in.read(buffer); while (len != -1) { out.write(buffer, 0, len); len = in.read(buffer); } A: There's no way to do this a lot easier with JDK methods, but as Apocalisp has already noted, you're not the only one with this idea: You could use IOUtils from Jakarta Commons IO, it also has a lot of other useful things, that IMO should actually be part of the JDK... A: Using Java7 and try-with-resources, comes with a simplified and readable version. try(InputStream inputStream = new FileInputStream("C:\\mov.mp4"); OutputStream outputStream = new FileOutputStream("D:\\mov.mp4")) { byte[] buffer = new byte[10*1024]; for (int length; (length = inputStream.read(buffer)) != -1; ) { outputStream.write(buffer, 0, length); } } catch (FileNotFoundException exception) { exception.printStackTrace(); } catch (IOException ioException) { ioException.printStackTrace(); } A: Here comes how I'm doing with a simplest for loop. private void copy(final InputStream in, final OutputStream out) throws IOException { final byte[] b = new byte[8192]; for (int r; (r = in.read(b)) != -1;) { out.write(b, 0, r); } } A: Using Guava's ByteStreams.copy(): ByteStreams.copy(inputStream, outputStream); A: As WMR mentioned, org.apache.commons.io.IOUtils from Apache has a method called copy(InputStream,OutputStream) which does exactly what you're looking for. So, you have: InputStream in; OutputStream out; IOUtils.copy(in,out); in.close(); out.close(); ...in your code. Is there a reason you're avoiding IOUtils? A: Use Commons Net's Util class: import org.apache.commons.net.io.Util; ... Util.copyStream(in, out); A: I use BufferedInputStream and BufferedOutputStream to remove the buffering semantics from the code try (OutputStream out = new BufferedOutputStream(...); InputStream in = new BufferedInputStream(...))) { int ch; while ((ch = in.read()) != -1) { out.write(ch); } } A: If you are using Java 7, Files (in the standard library) is the best approach: /* You can get Path from file also: file.toPath() */ Files.copy(InputStream in, Path target) Files.copy(Path source, OutputStream out) Edit: Of course it's just useful when you create one of InputStream or OutputStream from file. Use file.toPath() to get path from file. To write into an existing file (e.g. one created with File.createTempFile()), you'll need to pass the REPLACE_EXISTING copy option (otherwise FileAlreadyExistsException is thrown): Files.copy(in, target, StandardCopyOption.REPLACE_EXISTING) A: Simple Function If you only need this for writing an InputStream to a File then you can use this simple function: private void copyInputStreamToFile( InputStream in, File file ) { try { OutputStream out = new FileOutputStream(file); byte[] buf = new byte[1024]; int len; while((len=in.read(buf))>0){ out.write(buf,0,len); } out.close(); in.close(); } catch (Exception e) { e.printStackTrace(); } } A: A IMHO more minimal snippet (that also more narrowly scopes the length variable): byte[] buffer = new byte[2048]; for (int n = in.read(buffer); n >= 0; n = in.read(buffer)) out.write(buffer, 0, n); As a side note, I don't understand why more people don't use a for loop, instead opting for a while with an assign-and-test expression that is regarded by some as "poor" style. A: This is my best shot!! And do not use inputStream.transferTo(...) because is too generic. Your code performance will be better if you control your buffer memory. public static void transfer(InputStream in, OutputStream out, int buffer) throws IOException { byte[] read = new byte[buffer]; // Your buffer size. while (0 < (buffer = in.read(read))) out.write(read, 0, buffer); } I use it with this (improvable) method when I know in advance the size of the stream. public static void transfer(int size, InputStream in, OutputStream out) throws IOException { transfer(in, out, size > 0xFFFF ? 0xFFFF // 16bits 65,536 : size > 0xFFF ? 0xFFF// 12bits 4096 : size < 0xFF ? 0xFF // 8bits 256 : size ); } A: Java 9 Since Java 9, InputStream provides a method called transferTo with the following signature: public long transferTo(OutputStream out) throws IOException As the documentation states, transferTo will: Reads all bytes from this input stream and writes the bytes to the given output stream in the order that they are read. On return, this input stream will be at end of stream. This method does not close either stream. This method may block indefinitely reading from the input stream, or writing to the output stream. The behavior for the case where the input and/or output stream is asynchronously closed, or the thread interrupted during the transfer, is highly input and output stream specific, and therefore not specified So in order to write contents of a Java InputStream to an OutputStream, you can write: input.transferTo(output); A: The JDK uses the same code so it seems like there is no "easier" way without clunky third party libraries (which probably don't do anything different anyway). The following is directly copied from java.nio.file.Files.java: // buffer size used for reading and writing private static final int BUFFER_SIZE = 8192; /** * Reads all bytes from an input stream and writes them to an output stream. */ private static long copy(InputStream source, OutputStream sink) throws IOException { long nread = 0L; byte[] buf = new byte[BUFFER_SIZE]; int n; while ((n = source.read(buf)) > 0) { sink.write(buf, 0, n); nread += n; } return nread; } A: For those who use Spring framework there is a useful StreamUtils class: StreamUtils.copy(in, out); The above does not close the streams. If you want the streams closed after the copy, use FileCopyUtils class instead: FileCopyUtils.copy(in, out); A: I think it's better to use a large buffer, because most of the files are greater than 1024 bytes. Also it's a good practice to check the number of read bytes to be positive. byte[] buffer = new byte[4096]; int n; while ((n = in.read(buffer)) > 0) { out.write(buffer, 0, n); } out.close(); A: Not very readable, but effective, has no dependencies and runs with any java version byte[] buffer=new byte[1024]; for(int n; (n=inputStream.read(buffer))!=-1; outputStream.write(buffer,0,n)); A: PipedInputStream and PipedOutputStream should only be used when you have multiple threads, as noted by the Javadoc. Also, note that input streams and output streams do not wrap any thread interruptions with IOExceptions... So, you should consider incorporating an interruption policy to your code: byte[] buffer = new byte[1024]; int len = in.read(buffer); while (len != -1) { out.write(buffer, 0, len); len = in.read(buffer); if (Thread.interrupted()) { throw new InterruptedException(); } } This would be an useful addition if you expect to use this API for copying large volumes of data, or data from streams that get stuck for an intolerably long time. A: I think this will work, but make sure to test it... minor "improvement", but it might be a bit of a cost at readability. byte[] buffer = new byte[1024]; int len; while ((len = in.read(buffer)) != -1) { out.write(buffer, 0, len); } A: PipedInputStream and PipedOutputStream may be of some use, as you can connect one to the other. A: Another possible candidate are the Guava I/O utilities: http://code.google.com/p/guava-libraries/wiki/IOExplained I thought I'd use these since Guava is already immensely useful in my project, rather than adding yet another library for one function. A: I used ByteStreamKt.copyTo(src, dst, buffer.length) method Here is my code public static void replaceCurrentDb(Context context, Uri newDbUri) { try { File currentDb = context.getDatabasePath(DATABASE_NAME); if (currentDb.exists()) { InputStream src = context.getContentResolver().openInputStream(newDbUri); FileOutputStream dst = new FileOutputStream(currentDb); final byte[] buffer = new byte[8 * 1024]; ByteStreamsKt.copyTo(src, dst, buffer.length); src.close(); dst.close(); Toast.makeText(context, "SUCCESS! Your selected file is set as current menu.", Toast.LENGTH_LONG).show(); } else Log.e("DOWNLOAD:::: Database", " fail, database not found"); } catch (IOException e) { Toast.makeText(context, "Data Download FAIL.", Toast.LENGTH_LONG).show(); Log.e("DOWNLOAD FAIL!!!", "fail, reason:", e); } } A: you can use this method public static void copyStream(InputStream is, OutputStream os) { final int buffer_size=1024; try { byte[] bytes=new byte[buffer_size]; for(;;) { int count=is.read(bytes, 0, buffer_size); if(count==-1) break; os.write(bytes, 0, count); } } catch(Exception ex){} } A: public static boolean copyFile(InputStream inputStream, OutputStream out) { byte buf[] = new byte[1024]; int len; long startTime=System.currentTimeMillis(); try { while ((len = inputStream.read(buf)) != -1) { out.write(buf, 0, len); } long endTime=System.currentTimeMillis()-startTime; Log.v("","Time taken to transfer all bytes is : "+endTime); out.close(); inputStream.close(); } catch (IOException e) { return false; } return true; } A: Try Cactoos: new LengthOf(new TeeInput(input, output)).value(); More details here: http://www.yegor256.com/2017/06/22/object-oriented-input-output-in-cactoos.html
{ "language": "en", "url": "https://stackoverflow.com/questions/43157", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "496" }
Q: What are some resources for getting started in operating system development? One thing I've always wanted to do is develop my very own operating system (not necessarily fancy like Linux or Windows, but better than a simple boot loader which I've already done). I'm having a hard time finding resources/guides that take you past writing a simple "Hello World" OS. I know lots of people will probably recommend I look at Linux or BSD; but the code base for systems like that is (presumably) so big that I wouldn't know where to start. Any suggestions? Update: To make it easier for people who land on this post through Google here are some OS development resources: * *Writing Your Own Operating System (Thanks Adam) *Linux From Scratch (Thanks John) *SharpOS (C# Operating System) (Thanks lomaxx) *Minix3 and Minix2 (Thanks Mike) *OS Dev Wiki and Forums (Thanks Steve) *BonaFide (Thanks Steve) *Bran (Thanks Steve) *Roll your own toy UNIX-clone OS (Thanks Steve) *Broken Thorn OS Development Series Other resources: I found a nice resource named MikeOS, "MikeOS is a learning tool to demonstrate how simple OSes work. It uses 16-bit real mode for BIOS access, so that it doesn't need complex drivers" Updated 11/14/08 I found some resources at Freebyte's Guide to...Free and non-free Operating Systems that links to kits such as OSKit and ExOS library. These seem super useful in getting started in OS development. Updated 2/23/09 Ric Tokyo recommended nanoos in this question. Nanoos is an OS written in C++. Updated 3/9/09 Dinah provided some useful Stack Overflow discussion of aspiring OS developers: Roadblocks in creating a custom operating system discusses what pitfalls you might encounter while developing an OS and OS Development is a more general discussion. Updated 7/9/09 LB provided a link to the Pintos Project, an education OS designed for students learning OS development. Updated 7/27/09 (Still going strong!) I stumbled upon an online OS course from Berkley featuring 23 lectures. TomOS is a fork of MikeOS that includes a little memory manager and mouse support. As MikeOS, it is designed to be an educational project. It is written in NASM assembler. Updated 8/4/09 I found the slides and other materials to go along with the online Berkeley lectures listed above. Updated 8/23/09 All questions tagged osdev on stackoverflow OS/161 is an academic OS written in c that runs on a simulated hardware. This OS is similar in Nachos. Thanks Novelocrat! tangurena recommends http://en.wikipedia.org/wiki/MicroC/OS-II, an OS designed for embedded systems. There is a companion book as well. Linux Kernel Development by Robert Love is suggested by Anders. It is a "widely acclaimed insider's look at the Linux kernel." Updated 9/18/2009 Thanks Tim S. Van Haren for telling us about Cosmos, an OS written entirely in c#. tgiphil tells us about Managed Operating System Alliance (MOSA) Framework, "a set of tools, specifications and source code to foster development of managed operating systems based on the Common Intermediate Language." Update 9/24/2009 Steve found a couple resources for development on windows using Visual Studio, check out BrokenThorn's guide setup with VS 2005 or OSDev's VS Section. Updated 9/5/2012 kerneltrap.org is no longer available. The linux kernel v0.01 is available from kernel.org Updated 12/21/2012 A basic OS development tutorial designed to be a semester's project. It guides you through to build an OS with basic components. Very good start for beginners. Related paper. Thanks Srujan! Updated 11/15/2013 Writing a Simple Operating System From Scratch. Thanks James Moore! Updated 12/8/2013 How to make a computer operating system Thanks ddtoni! Updated 3/18/2014 ToAruOS an OS built mostly from scratch, including GUI Updated Sept 12 2016 Writing your own Toy Operating System Updated Dec 10 2016 Writing a Simple Operating System —from Scratch (thank you @Tyler C) A: There are a lot of links after this brief overview of what is involved in writing an OS for the X86 platform. The link that appears to be most promising (www.nondot.org/sabre/os/articles) is no longer available, so you'll need to poke through the Archive.org version to read it. At the end of the day the bootloader takes the machine code of the kernel, puts it in memory, and jumps to it. You can put any machine code in the kernel that you want, but most C programs expect an OS so you'll need to tell your compiler that it won't have all that, or the bootloader has to create some of it. The kernel then does all the heavy lifting, and I suspect it's the example kernel you want. But there's a long way to go between having a kernel that says, "Hello world" to having a kernel that loads a command interpretor, provides disk services, and loads and manages programs. You might want to consider subscribing to ACM to get access to their older literature - there are lots of articles in the late 80's and early 90's in early computing magazines about how to create alternative OSs. There are likely books that are out of print from this era as well. You might be able to get the same information for free by looking up the indexes of those magazines (which are available on that site - click "index" near the magazine name) and then asking around for people with a copy. Lastly, I know that usenet is dead (for so sayeth the prophets of internet doom) but you'll find that many of the craggy old experts from that era still live there. You should search google groups (they have dejanews's old repository) and I expect you'll find many people asking the same questions a decade or 1.5 ago that you're asking now. You may even run across Linus Torvalds' many queries for help as he was developing linux originally. If searches don't bring anything up, ask in the appropriate newsgroup (probably starts with comp.arch, but search for ones with OS in the name). A: Just coming from another question. I'd like to mention Pintos... I remembered my OS course with Nachos and Pintos seems to be the same kind of thing that can run on x86. A: I found Robert Love's Linux Kernel Development quite interesting. It tells you about how the different subsystems in the Linux kernel works in a very down-to-earth way. Since the source is available Linux is a prime candidate for something to hack on. A: Here are some other Stack Overflow pages worth incorporating into this discussion: Roadblocks in creating a custom operating system Developing an operating system for the x86 architecture A: My operating systems course in undergrad had us building a number of subsystems for OS/161, a simple, BSD-like kernel that provides some of the basics while leaving the freedom to explore various design space decisions in implementing higher-level services. A: Start hacking away at Minix. It's a lot smaller than Linux (obviously) and it's designed with teaching purposes in mind (some, at least). Not Minix 3 though, that's a whole different story. A: Already answer, but when I took Operating Systems in college we started with an early linux kernel and added simplistic modern features (basic file systems, virtual memory, multitasking, mutexes). Good fun. You get to skip some of the REALLY crazy low level assembly only stuff for mucking w/ protected mode and page tables while still learned some of the guts. http://kerneltrap.org/node/14002 http://kerneltrap.org/files/linux-0.01.tar.bz2 A: I would like to include this repo How-to-Make-a-Computer-Operating-System by Samy Pesse. Is a work-in-progress. Very interesting. A: You might want to look at linuxfromscratch. Linux From Scratch (LFS) is a project that provides you with step-by-step instructions for building your own custom Linux system, entirely from source code. A: A simple and basic OS development tutorial designed to be a semester's project. It guides you through to build an OS with basic components. Very good start for beginners. Related paper is here. A: Minix is a lot smaller, and designed for learning purposes, and the book to go with it is a good one too. Update: I guess Minix 3 is a bit of a different goal, but Minix 2 (and of course the first version) were for teaching purposes. A: As someone who has written a real-time multi-tasking operating system from scratch... keyboard debounce routine, keyboard driver, disk driver, video driver, file system, and finally a boot-loader - and that's just to launch it for the first time with nothing to do! ... I cannot emphasize enough how important it is to get familiar with the hardware! This is especially so if you really want to do it all yourself instead of just picking up a primitive system someone else has already laid out for you. For example, contact Intel and ask them for a CPU card for your type of CPU! This will lay it out for you - the "pin-outs", interrupts, opcodes, you name it! Remember the hardware makes it all possible. Study the hardware. You won't regret it. . A: One reasonably simple OS to study would be µC/OS. The book has a floppy with the source on it. http://en.wikipedia.org/wiki/MicroC/OS-II A: Check out the Managed Operating System Alliance (MOSA) Project at www.mosa-project.org. They are designing an AOT/JIT compiler and fully managed operating system in C#. Some of the developers are from the inactive SharpOS project. A: I've toyed with Cosmos, which is "an operating system project implemented completely in CIL compliant languages." It's written in C#, so that was right up my alley. For someone like myself who has never attempted to build an operating system, it was actually pretty cool to be able to get a "Hello World" operating system running in no time. A: Check out this site: http://osix.net/modules/article/?id=359 A: As mentioned above, the OSDev Wiki is (by far) the best source for OS development. For those of you who speak German, the lowlevel.eu Wiki is also great. Something relatively unknown Incitatus OS, a simple kernel with a tiny set of userspace apps. It's great to use for getting into the complicated topic of OS development. A: Movitz is a Lisp environment written in Common Lisp and running "on the metal". Unfortunately, some links on the Movitz main page deny access, but you can find instructions on how to download and compile the source code from the trac page. Also, a ready image can be found on the archive of this page. IMHO this is utmost interesting, as it brings back the Lisp machine concept on the currently available hardware. It failed commercially, but this does not prove to me that the idea was bad. The Unix haters handbook is a fun book that semi-seriously berates the concept of Unix and its derivatives. Many sections argument about how better the Lisp machine concept was. A: Here's a paper called "Writing a Simple Operating System From Scratch". It covers writing a bootloader, entering x86-32 protected mode, and writing a basic kernel in C. It seems to do a good job at explaining everything in detail. A: The x86 JS simulator and ARM simulator can also be very useful to understand how different pieces hardware works and make tests without exiting your favourite browser. A: Write a microcontroller OS. I recommend an x86 based microcontroller. A modern OS is just huge. Learn the basics first. A: I wish there was one place to get all of the info about developing your own OS. The closest to come to that is OS Dev Wiki and Forums. They offer a ton of good information regarding the setup, development, and device hardware information. Also there are some great tutorials at BoneFide, I've used the getting started tutorial by Bran, and am now looking at a more recent one based on his called Roll your own toy UNIX-clone OS. I second checking out: "Operating Systems : Design and Implementation" And if you want to develop on Windows, check out jolson's blog post. Edit: For development on windows using Visual Studio, check out BrokenThorn's guide or OSDev's wiki. A: An excellent resource is the material of the MIT course 6.828: Operating System Engineering. XV6 - simple Unix-like teaching OS written in ANSI C for x86 http://pdos.csail.mit.edu/6.828/2012/xv6.html XV6 source - as a printed booklet with line numbers http://pdos.csail.mit.edu/6.828/2012/xv6/xv6-rev7.pdf XV6 book - explains the main ideas of os design http://pdos.csail.mit.edu/6.828/2012/xv6/book-rev7.pdf The material is compact: 92 pages source and 96 pages commentary. I like it more than the Minix book! It's a true gem! A: you also might want to take a look at SharpOS which is an operating system that they're writing in c#. A: There are good resources for operating system fundamentals in books. Since there isn't much call to create new OS's from scratch you won't find a ton of hobbyist type information on the internet. I recommend the standard text book, "Modern Operating Systems" by Tanenbaum. You may also be able to find "Operating System Elements" by Calingaert useful - it's a thin overview of a book which give a rough sketch of what an OS is from a designer's standpoint. If you have any interest in real time systems (and you should at least understand the differences and reasons for real time OS's) then I'd also recommend "MicroC/OS-II" by Labrosse. Edit: Can you specify what you mean by "more technical"? These books give pseudo code implementation details, but are you looking for an example OS, or code snippets for a particular machine/language? -Adam A: Intresting Question for the programmers. See it will take long long long time to build OS like Windows or Mac but if you want build a simple ones then you can try your best * *You need to focus on Assembly Language,C and C++. You should be expert in these languages. *First read a good book on how OS works[Google it], then read all the info from Wiki OS *Search in youtube "How to create your own OS in Assembly Language" watch the video, Eg. Video *Download Linux OS source code and compile it yourself and try to modify the code yourself *Now you are an experienced OS editor now download Minix and QNX and start developing with them and get their docs from here Minix Doc and QNX Doc Now you have gained the master degree(Not completely just a little more to go) in creating OS now distribute this knownledge to your freinds and with their help try to create an OS as powerful as Mac, Linux or Windows A: When you have made a basic operating system it's actually hard to continue because there isn't many ressources on making GUIs or porting libraries. But i think taking a look at ToAruOS would help a lot! The code under the surface of that OS is so damn simple! but at the same time he has ported things like cairo, python, (not yet but soon) sdl, made share memory and he has also made his own widget toolkit. It's all written in C. Another interesting OS would be pedigreeOS. It's made by JamesM (the man behind jamesM's kernel tutorial. While it has more features than ToaruOS it's also bigger and more confusing. But anyway these 2 OS will help you a lot especially ToAruOS. A: When I started working on my basic operating systems I needed a basic guide like Stepping stones for a basic operating system. It helped me not loose my head. That if you want to make it from absolutely nothing (pure assembly code)
{ "language": "en", "url": "https://stackoverflow.com/questions/43180", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "609" }
Q: Mixing C/C++ Libraries Is it possible for gcc to link against a library that was created with Visual C++? If so, are there any conflicts/problems that might arise from doing so? A: Some of the comments in the answers here are slightly too generalistic. Whilst no, in the specific case mentioned gcc binaries won't link with a VC++ library (AFAIK). The actual means of interlinking code/libraries is a question of the ABI standard being used. An increasingly common standard in the embedded world is the EABI (or ARM ABI) standard (based on work done during Itanium development http://www.codesourcery.com/cxx-abi/). If compilers are EABI compliant they can produce executables and libraries which will work with each other. An example of multiple toolchains working together is ARM's RVCT compiler which produces binaries which will work with GCC ARM ABI binaries. (The code sourcery link is down at the moment but can be google cached) A: I would guess not. Usually c++ compilers have quite different methods of name-mangling which means that the linkers will fail to find the correct symbols. This is a good thing by the way, because C++ compilers are allowed by the standard to have much greater levels of incompatibility than just this that will cause your program to crash, die, eat puppies and smear paint all over the wall. Usual schemes to work around this usually involve language independent techniques like COM or CORBA. A simpler sanctified method is to use C "wrappers" around your C++ code. A: It is not possible. It's usually not even possible to link libraries produced by different versions of the same compiler. A: No. Plain and simple :-) A: Yes, if you make it a dynamic link and make the interface c-style. lib.exe will generate import libraries which are compatible with the gcc toolchain. That will resolve your linking problems. However that is just the start of the problem. Your larger problems will be things like exceptions, and memory allocation. * *You must ensure that no exception cross from VC++ to gcc code, there are no guarantees of compatibility. *Every object from the VC++ library will need to live on the heap because: *Do not mix gcc new/delete with anything from VC++, bad things will happen. This goes for object construction on the stack too. However, if you make an interface like create_some_obj()/delete_some_obj() you do not end up using gcc new to construct VC++ objects. Maybe make a small handler object that handles construction and destruction. This way you preserve RAII, but still use the c-interface for the true interface. *Calling convention must be correct. In VC++ there is cdecl and stdcall. If gcc tried to call an imported function with the wrong calling type, bad things will happen. The bottom line is keep a simple interface that is ANSI C compliant, and you should be fine. The fact that crazy C++ goes on behind is okay, as long as it is contained. Oh and make sure all the code is re-entrant, or you risk opening a whole nother can-o-worms.
{ "language": "en", "url": "https://stackoverflow.com/questions/43194", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Hyper V to Virtual PC I am currently using Windows Server 2008 Standard and have several Hyper V machines. These are development VM's and I want to now switch back Vista x64 because I am missing Aero. I know Windows Server 2008 can have aero but the host performance is very very bad when I run VM in Hyper V. I want to export my Hyper V machines so that I can use it in Virtual PC. Anyone know an easy way? A: If you have built them as Hyper-V machines, I don't think you can go back. There are serious differences in the HAL for Virtual PC and Hyper-V. You can move a VPC to Hyper-V permanantly by removing the VPC add-ins ans adding the Hyper-V integration drivers/services and re-detecting the hardware. A VPC can run in Hyper-V just fine, don't add the machine drivers for Hyper-V and you can go back to VPC with no problem. A: VPC to Hyper-V is one way. A: Hyper-V is designed to be used on the server, obviously. Whereas VirtualPC is designed for the end user. Hyper-V will give you more control, and the ability to create and restore snapshots. However, it does not have a direct console interface to the VM, you would use a browser to access the console. I would go Hyper-V, but it really depends on what you're using your VMs for. Luckily, they share the same format for virtual disks, so you can try it out with your existing VMs. A: You should review Windows 2008 R2 SP1 upgrade with RemoteFX, it comes with a new video driver for VM's that allow 3D, extended desktops and more. It will help resolve some of the issues you are seeing today. Both the Host server and VM need to be running SP1 of Windows 2008 R2. http://blogs.technet.com/b/virtualization/archive/2010/03/18/explaining-microsoft-remotefx.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/43196", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Internationalized page properties in Tapestry 4.1.2 The login page in my Tapestry application has a property in which the password the user types in is stored, which is then compared against the value from the database. If the user enters a password with multi-byte characters, such as: áéíóú ...an inspection of the return value of getPassword() (the abstract method for the corresponding property) gives: áéíóú Clearly, that's not encoded properly. Yet Firebug reports that the page is served up in UTF-8, so presumably the form submission request would also be encoded in UTF-8. Inspecting the value as it comes from the database produces the correct string, so it wouldn't appear to be an OS or IDE encoding issue. I have not overridden Tapestry's default value for org.apache.tapestry.output-encoding in the .application file, and the Tapestry 4 documentation indicates that the default value for the property is UTF-8. So why does Tapestry appear to botch the encoding when setting the property? Relevant code follows: Login.html <html jwcid="@Shell" doctype='html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"' ...> <body jwcid="@Body"> ... <form jwcid="@Form" listener="listener:attemptLogin" ...> ... <input jwcid="password"/> ... </form> ... </body> </html> Login.page <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE page-specification PUBLIC "-//Apache Software Foundation//Tapestry Specification 4.0//EN" "http://jakarta.apache.org/tapestry/dtd/Tapestry_4_0.dtd"> <page-specification class="mycode.Login"> ... <property name="password" /> ... <component id="password" type="TextField"> <binding name="value" value="password"/> <binding name="hidden" value="true"/> ... </component> ... </page-specification> Login.java ... public abstract class Login extends BasePage { ... public abstract String getPassword(); ... public void attemptLogin() { // At this point, inspecting getPassword() returns // the incorrectly encoded String. } ... } Updates @Jan Soltis: Well, if I inspect the value that comes from the database, it displays the correct string, so it would seem that my editor, OS and database are all encoding the value correctly. I've also checked my .application file; it does not contain an org.apache.tapestry.output-encoding entry, and the Tapestry 4 documentation indicates that the default value for this property is UTF-8. I have updated the description above to reflect the answers to your questions. @myself: Solution found. A: Everything seems to be correct. Are you really sure getPassword() returns garbage? Isn't it someone else (your editor, OS, database,...) that doesn't know that it's a unicode string when it displays it to you while the password may be perfectly okay? What exactly makes you think it's a garbage? I would also make sure there's no strange encoding set in the .application config file <meta key="org.apache.tapestry.output-encoding" value="some strange encoding"/> A: I found the problem. Tomcat was mangling the parameters before Tapestry or my page class even had a crack at it. Creating a servlet filter that enforced the desired character encoding fixed it. CharacterEncodingFilter.java package mycode; import java.io.IOException; import javax.servlet.*; /** * Allows you to enforce a particular character encoding on incoming requests. * @author Robert J. Walker */ public class CharacterEncodingFilter implements Filter { private static final String ENCODINGPARAM = "encoding"; private String encoding; public void init(FilterConfig config) throws ServletException { encoding = config.getInitParameter(ENCODINGPARAM); if (encoding != null) { encoding = encoding.trim(); } } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { request.setCharacterEncoding(encoding); chain.doFilter(request, response); } public void destroy() { // do nothing } } web.xml <web-app> ... <filter> <filter-name>characterEncoding</filter-name> <filter-class>mycode.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>characterEncoding</filter-name> <url-pattern>/app/*</url-pattern> </filter-mapping> ... </web-app>
{ "language": "en", "url": "https://stackoverflow.com/questions/43199", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Categories of controllers in MVC Routing? (Duplicate Controller names in separate Namespaces) I'm looking for some examples or samples of routing for the following sort of scenario: The general example of doing things is: {controller}/{action}/{id} So in the scenario of doing a product search for a store you'd have: public class ProductsController: Controller { public ActionResult Search(string id) // id being the search string { ... } } Say you had a few stores to do this and you wanted that consistently, is there any way to then have: {category}/{controller}/{action}/{id} So that you could have a particular search for a particular store, but use a different search method for a different store? (If you required the store name to be a higher priority than the function itself in the url) Or would it come down to: public class ProductsController: Controller { public ActionResult Search(int category, string id) // id being the search string { if(category == 1) return Category1Search(); if(category == 2) return Category2Search(); ... } } It may not be a great example, but basically the idea is to use the same controller name and therefore have a simple URL across a few different scenarios, or are you kind of stuck with requiring unique controller names, and no way to put them in slightly different namespaces/directories? Edit to add: The other reason I want this is because I might want a url that has the categories, and that certain controllers will only work under certain categories. IE: /this/search/items/search+term <-- works /that/search/items/search+term <-- won't work - because the search controller isn't allowed. A: I actually found it not even by searching, but by scanning through the ASP .NET forums in this question. Using this you can have the controllers of the same name under any part of the namespace, so long as you qualify which routes belong to which namespaces (you can have multiple namespaces per routes if you need be!) But from here, you can put in a directory under your controller, so if your controller was "MyWebShop.Controllers", you'd put a directory of "Shop1" and the namespace would be "MyWebShop.Controllers.Shop1" Then this works: public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); var shop1namespace = new RouteValueDictionary(); shop1namespace.Add("namespaces", new HashSet<string>(new string[] { "MyWebShop.Controllers.Shop1" })); routes.Add("Shop1", new Route("Shop1/{controller}/{action}/{id}", new MvcRouteHandler()) { Defaults = new RouteValueDictionary(new { action = "Index", id = (string)null }), DataTokens = shop1namespace }); var shop2namespace = new RouteValueDictionary(); shop2namespace.Add("namespaces", new HashSet<string>(new string[] { "MyWebShop.Controllers.Shop2" })); routes.Add("Shop2", new Route("Shop2/{controller}/{action}/{id}", new MvcRouteHandler()) { Defaults = new RouteValueDictionary(new { action = "Index", id = (string)null }), DataTokens = shop2namespace }); var defaultnamespace = new RouteValueDictionary(); defaultnamespace.Add("namespaces", new HashSet<string>(new string[] { "MyWebShop.Controllers" })); routes.Add("Default", new Route("{controller}/{action}/{id}", new MvcRouteHandler()) { Defaults = new RouteValueDictionary(new { controller = "Home", action = "Index", id = "" }), DataTokens = defaultnamespace }); } The only other thing is that it will reference a view still in the base directory, so if you put the view into directories to match, you will have to put the view name in when you return it inside the controller. A: The best way to do this without any compromises would be to implement your own ControllerFactory by inheriting off of IControllerFactory. The CreateController method that you will implement handles creating the controller instance to handle the request by the RouteHandler and the ControllerActionInvoker. The convention is to use the name of the controller, when creating it, therefore you will need to override this functionality. This will be where you put your custom logic for creating the controller based on the route since you will have multiple controllers with the same name, but in different folders. Then you will need to register your custom controller factory in the application startup, just like your routes. Another area you will need to take into consideration is finding your views when creating the controller. If you plan on using the same view for all of them, then you shouldn't have to do anything different than the convention being used. If you plan on organizing your views also, then you will need to create your own ViewLocator also and assign it to the controller when creating it in your controller factory. To get an idea of code, there are a few questions I have answered on SO that relate to this question, but this one is different to some degree, because the controller names will be the same. I included links for reference. * *Views in separate assemblies in ASP.NET MVC *asp.net mvc - subfolders Another route, but may require some compromises will be to use the new AcceptVerbs attribute. Check this question out for more details. I haven't played with this new functionality yet, but it could be another route.
{ "language": "en", "url": "https://stackoverflow.com/questions/43201", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How do I change Simulink xPC target serial comm speed on the fly I have an xPC target application that talks to a device over RS-232. I am using the xPC serial block for this. To talk to this device I first have to start at a default speed, say, 9600 bps, request a change of speed to, say 57600 bps, then change the speed on my side to match it. The problem with the xPC block is that it forces you to choose a specific speed before running, and can't change it at run time. Is there a way/trick/hack to do this? A: Here is my take so far. I don't think it can be done using existing Simulink blocks. I think I am going to have to take the xpcserial C code that comes with Matlab, take the code that sets the RS-232 speed, and wrap it in my own S-function. A: I agree with you: I don't think it can be done, I'm afraid. On further reflection, I've realised that in my xPC system, I get a compilation warning telling me that the blocks I'm using don't support sample time changes during runtime; this implies that it's not impossible in general… A: Ian, What I've done before on this stuff is just modify the registers behind XPC target's back. It's ugly, but xPCTarget is ugly in the first place. Try modify Line Control Register and set the divisors directly -- all you need is the serial port IO address, and you know that. It's worth a shot anyway, you're going to have to do it anyway.
{ "language": "en", "url": "https://stackoverflow.com/questions/43211", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I reference a javascript file? I'm working on a C#/ASP.NET project that has all the javascript files in a /Javascript folder. If I refer to the JS file using this syntax: src="/Javascript/jsfile.js" then the file is correctly picked up if the project is deployed to the root of the URL. However, if this "web site" is deployed to a sub-folder of the main url this won't work. So the solution could be to use relative urls - but there's a problem with that as well because the master pages reference many of the javascript files and these master pages can be used by pages in the root and in subfolders many levels deep. Does anybody have any ideas for resolving this? A: Try something like this in the Master Page: <script type="text/javascript" src="<%= Response.ApplyAppPathModifier("~/javascript/globaljs.aspx") %>"></script> For whatever reason, I've found the browsers to be quite finicky about the final tag, so just ending the tag with /> doesn't seem to work. A: The brand-new version of ASP.NET (3.5 SP1) has a nifty feature called CompositeScript. This allows you to use a ScriptManager to reference lots of tiny little .js files server-side and have them delivered as a single .js file to the client. Good for the client since it only has to download one file. Good for you since you can maintain the files however you want on the server side. <asp:ScriptManager ID="ScriptManager1" EnablePartialRendering="True" runat="server"> <Scripts> <asp:ScriptReference Assembly="SampleControl" Name="SampleControl.UpdatePanelAnimation.js" /> </Scripts> </asp:ScriptManager> A: If you reference the JS-file in a section that is "runat=server" you could write src="~/Javascript/jsfile.js" and it will always work. You could also do this in your Page_Load (In your masterpage): Page.ClientScript.RegisterClientScriptInclude("myJsFile", Page.ResolveClientUrl("~/Javascript/jsfile.js")) A: @Jared: IE needs that /script . FF doesn't care. A: You might want to take a look at FileResolver. It's an HTTP Handler that allows you to do this: <link rel="stylesheet" href="~/resources/stylesheet.css.ashx" /> And have the tilde (as well as any tildes within the file) expanded properly.
{ "language": "en", "url": "https://stackoverflow.com/questions/43218", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Running a Simulink xPC block at a faster rate than the continuous rate I have a Simulink xPC target application that has blocks with discrete states at several different sample rates and some sections using continuous states. My intention on keeping the continuous states is for better numerical integration. What creates the problem: One block is reading a device at a very fast rate (500 hz). The rest of the application can and should run at a slower rate (say, 25 or 50 Hz) because it would be overkill to run it at the highest rate, and because the processor simply cannot squeeze a full application cycle into the .002 secs of the faster rate. So I need both rates. However, the continuous states run by definition in Simulink at the faster discrete rate of the whole application! This means everywhere I have continuous states now they're forced to run at 500 Hz when 25 Hz would do! Is there a way to force the continuous states in xPC target to a rate that is not the fastest in the application? Or alternatively, is there a way to allow certain block to run at a faster speed than the rest of the application? A: You are thinking about continuous solvers in the wrong way - continuous doesn't only mean that it's run as fast as possible - it uses a fundamentally different algorithm to solve the equations than discrete. Due to this, they must be run at least as fast as the discrete solvers. From Using Simulink: Continuous solvers use numerical integration to compute a model's continuous states at the current time step from the states at previous time steps and the state derivatives. Continuous solvers rely on the model's blocks to compute the values of the model's discrete states at each time step. Mathematicians have developed a wide variety of numerical integration techniques for solving the ordinary differential equations (ODEs) that represent the continuous states of dynamic systems. Simulink provides an extensive set of fixed-step and variable-step continuous solvers, each implementing a specific ODE solution method (see Solvers). Discrete solvers exist primarily to solve purely discrete models. They compute the next simulation time step for a model and nothing else. They do not compute continuous states and they rely on the model's blocks to update the model's discrete states. So the upshot is that no it's not good enough to have the continuous run more slowly than the fastest discrete solvers - otherwise they are, by definition, not continuous. You should reconsider why you are specifying them as continuous. What are you trying to accomplish by slowing down the continuous solvers? Is this a simulation time/performance issue? -Adam A: My take on this is that it cannot be done. One way to approach this is to replace the continuous states by discrete ones (perhaps at an intermediate rate, say 100 Hz), and cross my fingers that the loss of precision is bearable. Maybe it's possible to isolate a block and run it separately at a faster rate somehow, but I don't know. A: Truly continuous computation is impossible in a digital processor such as your computer's. What MATLAB/Simulink means by "continuous" is "I will (dynamically) try to guess what discrete step size is small enough so that discretization error is very small in your application". If you already know, by knowing your application, that 20ms (50Hz) would be small enough, then use discrete - 50Hz.
{ "language": "en", "url": "https://stackoverflow.com/questions/43223", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How do I calculate a trendline for a graph? Google is not being my friend - it's been a long time since my stats class in college...I need to calculate the start and end points for a trendline on a graph - is there an easy way to do this? (working in C# but whatever language works for you) A: Thanks to all for your help - I was off this issue for a couple of days and just came back to it - was able to cobble this together - not the most elegant code, but it works for my purposes - thought I'd share if anyone else encounters this issue: public class Statistics { public Trendline CalculateLinearRegression(int[] values) { var yAxisValues = new List<int>(); var xAxisValues = new List<int>(); for (int i = 0; i < values.Length; i++) { yAxisValues.Add(values[i]); xAxisValues.Add(i + 1); } return new Trendline(yAxisValues, xAxisValues); } } public class Trendline { private readonly IList<int> xAxisValues; private readonly IList<int> yAxisValues; private int count; private int xAxisValuesSum; private int xxSum; private int xySum; private int yAxisValuesSum; public Trendline(IList<int> yAxisValues, IList<int> xAxisValues) { this.yAxisValues = yAxisValues; this.xAxisValues = xAxisValues; this.Initialize(); } public int Slope { get; private set; } public int Intercept { get; private set; } public int Start { get; private set; } public int End { get; private set; } private void Initialize() { this.count = this.yAxisValues.Count; this.yAxisValuesSum = this.yAxisValues.Sum(); this.xAxisValuesSum = this.xAxisValues.Sum(); this.xxSum = 0; this.xySum = 0; for (int i = 0; i < this.count; i++) { this.xySum += (this.xAxisValues[i]*this.yAxisValues[i]); this.xxSum += (this.xAxisValues[i]*this.xAxisValues[i]); } this.Slope = this.CalculateSlope(); this.Intercept = this.CalculateIntercept(); this.Start = this.CalculateStart(); this.End = this.CalculateEnd(); } private int CalculateSlope() { try { return ((this.count*this.xySum) - (this.xAxisValuesSum*this.yAxisValuesSum))/((this.count*this.xxSum) - (this.xAxisValuesSum*this.xAxisValuesSum)); } catch (DivideByZeroException) { return 0; } } private int CalculateIntercept() { return (this.yAxisValuesSum - (this.Slope*this.xAxisValuesSum))/this.count; } private int CalculateStart() { return (this.Slope*this.xAxisValues.First()) + this.Intercept; } private int CalculateEnd() { return (this.Slope*this.xAxisValues.Last()) + this.Intercept; } } A: OK, here's my best pseudo math: The equation for your line is: Y = a + bX Where: b = (sum(x*y) - sum(x)sum(y)/n) / (sum(x^2) - sum(x)^2/n) a = sum(y)/n - b(sum(x)/n) Where sum(xy) is the sum of all x*y etc. Not particularly clear I concede, but it's the best I can do without a sigma symbol :) ... and now with added Sigma b = (Σ(xy) - (ΣxΣy)/n) / (Σ(x^2) - (Σx)^2/n) a = (Σy)/n - b((Σx)/n) Where Σ(xy) is the sum of all x*y etc. and n is the number of points A: Regarding a previous answer if (B) y = offset + slope*x then (C) offset = y/(slope*x) is wrong (C) should be: offset = y-(slope*x) See: http://zedgraph.org/wiki/index.php?title=Trend A: If you have access to Excel, look in the "Statistical Functions" section of the Function Reference within Help. For straight-line best-fit, you need SLOPE and INTERCEPT and the equations are right there. Oh, hang on, they're also defined online here: http://office.microsoft.com/en-us/excel/HP052092641033.aspx for SLOPE, and there's a link to INTERCEPT. OF course, that assumes MS don't move the page, in which case try Googling for something like "SLOPE INTERCEPT EQUATION Excel site:microsoft.com" - the link given turned out third just now. A: I converted Matt's code to Java so I could use it in Android with the MPAndroidChart library. Also used double values instead of integer values: ArrayList<Entry> yValues2 = new ArrayList<>(); ArrayList<Double > xAxisValues = new ArrayList<Double>(); ArrayList<Double> yAxisValues = new ArrayList<Double>(); for (int i = 0; i < readings.size(); i++) { r = readings.get(i); yAxisValues.add(r.value); xAxisValues.add((double)i + 1); } TrendLine tl = new TrendLine(yAxisValues, xAxisValues); //Create the y values for the trend line double currY = tl.Start; for (int i = 0; i < readings.size(); ++ i) { yValues2.add(new Entry(i, (float) currY)); currY = currY + tl.Slope; } ... public class TrendLine { private ArrayList<Double> xAxisValues = new ArrayList<Double>(); private ArrayList<Double> yAxisValues = new ArrayList<Double>(); private int count; private double xAxisValuesSum; private double xxSum; private double xySum; private double yAxisValuesSum; public TrendLine(ArrayList<Double> yAxisValues, ArrayList<Double> xAxisValues) { this.yAxisValues = yAxisValues; this.xAxisValues = xAxisValues; this.Initialize(); } public double Slope; public double Intercept; public double Start; public double End; private double getArraySum(ArrayList<Double> arr) { double sum = 0; for (int i = 0; i < arr.size(); ++i) { sum = sum + arr.get(i); } return sum; } private void Initialize() { this.count = this.yAxisValues.size(); this.yAxisValuesSum = getArraySum(this.yAxisValues); this.xAxisValuesSum = getArraySum(this.xAxisValues); this.xxSum = 0; this.xySum = 0; for (int i = 0; i < this.count; i++) { this.xySum += (this.xAxisValues.get(i)*this.yAxisValues.get(i)); this.xxSum += (this.xAxisValues.get(i)*this.xAxisValues.get(i)); } this.Slope = this.CalculateSlope(); this.Intercept = this.CalculateIntercept(); this.Start = this.CalculateStart(); this.End = this.CalculateEnd(); } private double CalculateSlope() { try { return ((this.count*this.xySum) - (this.xAxisValuesSum*this.yAxisValuesSum))/((this.count*this.xxSum) - (this.xAxisValuesSum*this.xAxisValuesSum)); } catch (Exception e) { return 0; } } private double CalculateIntercept() { return (this.yAxisValuesSum - (this.Slope*this.xAxisValuesSum))/this.count; } private double CalculateStart() { return (this.Slope*this.xAxisValues.get(0)) + this.Intercept; } private double CalculateEnd() { return (this.Slope*this.xAxisValues.get(this.xAxisValues.size()-1)) + this.Intercept; } } A: Given that the trendline is straight, find the slope by choosing any two points and calculating: (A) slope = (y1-y2)/(x1-x2) Then you need to find the offset for the line. The line is specified by the equation: (B) y = offset + slope*x So you need to solve for offset. Pick any point on the line, and solve for offset: (C) offset = y - (slope*x) Now you can plug slope and offset into the line equation (B) and have the equation that defines your line. If your line has noise you'll have to decide on an averaging algorithm, or use curve fitting of some sort. If your line isn't straight then you'll need to look into Curve fitting, or Least Squares Fitting - non trivial, but do-able. You'll see the various types of curve fitting at the bottom of the least squares fitting webpage (exponential, polynomial, etc) if you know what kind of fit you'd like. Also, if this is a one-off, use Excel. A: Here is a very quick (and semi-dirty) implementation of Bedwyr Humphreys's answer. The interface should be compatible with @matt's answer as well, but uses decimal instead of int and uses more IEnumerable concepts to hopefully make it easier to use and read. Slope is b, Intercept is a public class Trendline { public Trendline(IList<decimal> yAxisValues, IList<decimal> xAxisValues) : this(yAxisValues.Select((t, i) => new Tuple<decimal, decimal>(xAxisValues[i], t))) { } public Trendline(IEnumerable<Tuple<Decimal, Decimal>> data) { var cachedData = data.ToList(); var n = cachedData.Count; var sumX = cachedData.Sum(x => x.Item1); var sumX2 = cachedData.Sum(x => x.Item1 * x.Item1); var sumY = cachedData.Sum(x => x.Item2); var sumXY = cachedData.Sum(x => x.Item1 * x.Item2); //b = (sum(x*y) - sum(x)sum(y)/n) // / (sum(x^2) - sum(x)^2/n) Slope = (sumXY - ((sumX * sumY) / n)) / (sumX2 - (sumX * sumX / n)); //a = sum(y)/n - b(sum(x)/n) Intercept = (sumY / n) - (Slope * (sumX / n)); Start = GetYValue(cachedData.Min(a => a.Item1)); End = GetYValue(cachedData.Max(a => a.Item1)); } public decimal Slope { get; private set; } public decimal Intercept { get; private set; } public decimal Start { get; private set; } public decimal End { get; private set; } public decimal GetYValue(decimal xValue) { return Intercept + Slope * xValue; } } A: This is the way i calculated the slope: Source: http://classroom.synonym.com/calculate-trendline-2709.html class Program { public double CalculateTrendlineSlope(List<Point> graph) { int n = graph.Count; double a = 0; double b = 0; double bx = 0; double by = 0; double c = 0; double d = 0; double slope = 0; foreach (Point point in graph) { a += point.x * point.y; bx = point.x; by = point.y; c += Math.Pow(point.x, 2); d += point.x; } a *= n; b = bx * by; c *= n; d = Math.Pow(d, 2); slope = (a - b) / (c - d); return slope; } } class Point { public double x; public double y; } A: Here's what I ended up using. public class DataPoint<T1,T2> { public DataPoint(T1 x, T2 y) { X = x; Y = y; } [JsonProperty("x")] public T1 X { get; } [JsonProperty("y")] public T2 Y { get; } } public class Trendline { public Trendline(IEnumerable<DataPoint<long, decimal>> dataPoints) { int count = 0; long sumX = 0; long sumX2 = 0; decimal sumY = 0; decimal sumXY = 0; foreach (var dataPoint in dataPoints) { count++; sumX += dataPoint.X; sumX2 += dataPoint.X * dataPoint.X; sumY += dataPoint.Y; sumXY += dataPoint.X * dataPoint.Y; } Slope = (sumXY - ((sumX * sumY) / count)) / (sumX2 - ((sumX * sumX) / count)); Intercept = (sumY / count) - (Slope * (sumX / count)); } public decimal Slope { get; private set; } public decimal Intercept { get; private set; } public decimal Start { get; private set; } public decimal End { get; private set; } public decimal GetYValue(decimal xValue) { return Slope * xValue + Intercept; } } My data set is using a Unix timestamp for the x-axis and a decimal for the y. Change those datatypes to fit your need. I do all the sum calculations in one iteration for the best possible performance. A: Thank You so much for the solution, I was scratching my head. Here's how I applied the solution in Excel. I successfully used the two functions given by MUHD in Excel: a = (sum(x*y) - sum(x)sum(y)/n) / (sum(x^2) - sum(x)^2/n) b = sum(y)/n - b(sum(x)/n) (careful my a and b are the b and a in MUHD's solution). - Made 4 columns, for example: NB: my values y values are in B3:B17, so I have n=15; my x values are 1,2,3,4...15. 1. Column B: Known x's 2. Column C: Known y's 3. Column D: The computed trend line 4. Column E: B values * C values (E3=B3*C3, E4=B4*C4, ..., E17=B17*C17) 5. Column F: x squared values I then sum the columns B,C and E, the sums go in line 18 for me, so I have B18 as sum of Xs, C18 as sum of Ys, E18 as sum of X*Y, and F18 as sum of squares. To compute a, enter the followin formula in any cell (F35 for me): F35=(E18-(B18*C18)/15)/(F18-(B18*B18)/15) To compute b (in F36 for me): F36=C18/15-F35*(B18/15) Column D values, computing the trend line according to the y = ax + b: D3=$F$35*B3+$F$36, D4=$F$35*B4+$F$36 and so on (until D17 for me). Select the column datas (C2:D17) to make the graph. HTH. A: If anyone needs the JS code for calculating the trendline of many points on a graph, here's what worked for us in the end: /**@typedef {{ * x: Number; * y:Number; * }} Point * @param {Point[]} data * @returns {Function} */ function _getTrendlineEq(data) { const xySum = data.reduce((acc, item) => { const xy = item.x * item.y acc += xy return acc }, 0) const xSum = data.reduce((acc, item) => { acc += item.x return acc }, 0) const ySum = data.reduce((acc, item) => { acc += item.y return acc }, 0) const aTop = (data.length * xySum) - (xSum * ySum) const xSquaredSum = data.reduce((acc, item) => { const xSquared = item.x * item.x acc += xSquared return acc }, 0) const aBottom = (data.length * xSquaredSum) - (xSum * xSum) const a = aTop / aBottom const bTop = ySum - (a * xSum) const b = bTop / data.length return function trendline(x) { return a * x + b } } It takes an array of (x,y) points and returns the function of a y given a certain x Have fun :) A: Here's a working example in golang. I searched around and found this page and converted this over to what I needed. Hope someone else can find it useful. // https://classroom.synonym.com/calculate-trendline-2709.html package main import ( "fmt" "math" ) func main() { graph := [][]float64{ {1, 3}, {2, 5}, {3, 6.5}, } n := len(graph) // get the slope var a float64 var b float64 var bx float64 var by float64 var c float64 var d float64 var slope float64 for _, point := range graph { a += point[0] * point[1] bx += point[0] by += point[1] c += math.Pow(point[0], 2) d += point[0] } a *= float64(n) // 97.5 b = bx * by // 87 c *= float64(n) // 42 d = math.Pow(d, 2) // 36 slope = (a - b) / (c - d) // 1.75 // calculating the y-intercept (b) of the Trendline var e float64 var f float64 e = by // 14.5 f = slope * bx // 10.5 intercept := (e - f) / float64(n) // (14.5 - 10.5) / 3 = 1.3 // output fmt.Println(slope) fmt.Println(intercept) }
{ "language": "en", "url": "https://stackoverflow.com/questions/43224", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "52" }
Q: How does Web Routing Work? I need a good understanding of the inner workings of System.Web.Routing. Usually we define the RoutesTable. But how does it do the routing? The reason I'm asking it is that I want to pass the routing to subapps. What I want to see working is a way of passing the current request to mvc apps that work in other AppDomains. Just to make it clear this is what I'm imagining I have a MVC APP that only has the barebone Global.asax and that loads in other app domains some dlls that are mvc apps.. and the comunication is done through a transparent proxy created through _appDomain.CreateInstanceAndUnwrap(...). Hope this is clear enough. Edit: from what I can tell the codebehind Default.aspx is invoked on the first page reguest and that starts the MvcHttpHandler that does all the voodoo of displaying the pages we are requesting. So it might just be a matter of passing the http context. If you have any ideas on matter please post your thoughts.
{ "language": "en", "url": "https://stackoverflow.com/questions/43243", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: T-SQL stored procedure that accepts multiple Id values Is there a graceful way to handle passing a list of ids as a parameter to a stored procedure? For instance, I want departments 1, 2, 5, 7, 20 returned by my stored procedure. In the past, I have passed in a comma delimited list of ids, like the below code, but feel really dirty doing it. SQL Server 2005 is my only applicable limitation I think. create procedure getDepartments @DepartmentIds varchar(max) as declare @Sql varchar(max) select @Sql = 'select [Name] from Department where DepartmentId in (' + @DepartmentIds + ')' exec(@Sql) A: You could use XML. E.g. declare @xmlstring as varchar(100) set @xmlstring = '<args><arg value="42" /><arg2>-1</arg2></args>' declare @docid int exec sp_xml_preparedocument @docid output, @xmlstring select [id],parentid,nodetype,localname,[text] from openxml(@docid, '/args', 1) The command sp_xml_preparedocument is built in. This would produce the output: id parentid nodetype localname text 0 NULL 1 args NULL 2 0 1 arg NULL 3 2 2 value NULL 5 3 3 #text 42 4 0 1 arg2 NULL 6 4 3 #text -1 which has all (more?) of what you you need. A: One method you might want to consider if you're going to be working with the values a lot is to write them to a temporary table first. Then you just join on it like normal. This way, you're only parsing once. It's easiest to use one of the 'Split' UDFs, but so many people have posted examples of those, I figured I'd go a different route ;) This example will create a temporary table for you to join on (#tmpDept) and fill it with the department id's that you passed in. I'm assuming you're separating them with commas, but you can -- of course -- change it to whatever you want. IF OBJECT_ID('tempdb..#tmpDept', 'U') IS NOT NULL BEGIN DROP TABLE #tmpDept END SET @DepartmentIDs=REPLACE(@DepartmentIDs,' ','') CREATE TABLE #tmpDept (DeptID INT) DECLARE @DeptID INT IF IsNumeric(@DepartmentIDs)=1 BEGIN SET @DeptID=@DepartmentIDs INSERT INTO #tmpDept (DeptID) SELECT @DeptID END ELSE BEGIN WHILE CHARINDEX(',',@DepartmentIDs)>0 BEGIN SET @DeptID=LEFT(@DepartmentIDs,CHARINDEX(',',@DepartmentIDs)-1) SET @DepartmentIDs=RIGHT(@DepartmentIDs,LEN(@DepartmentIDs)-CHARINDEX(',',@DepartmentIDs)) INSERT INTO #tmpDept (DeptID) SELECT @DeptID END END This will allow you to pass in one department id, multiple id's with commas in between them, or even multiple id's with commas and spaces between them. So if you did something like: SELECT Dept.Name FROM Departments JOIN #tmpDept ON Departments.DepartmentID=#tmpDept.DeptID ORDER BY Dept.Name You would see the names of all of the department IDs that you passed in... Again, this can be simplified by using a function to populate the temporary table... I mainly did it without one just to kill some boredom :-P -- Kevin Fairchild A: Erland Sommarskog has maintained the authoritative answer to this question for the last 16 years: Arrays and Lists in SQL Server. There are at least a dozen ways to pass an array or list to a query; each has their own unique pros and cons. * *Table-Valued Parameters. SQL Server 2008 and higher only, and probably the closest to a universal "best" approach. *The Iterative Method. Pass a delimited string and loop through it. *Using the CLR. SQL Server 2005 and higher from .NET languages only. *XML. Very good for inserting many rows; may be overkill for SELECTs. *Table of Numbers. Higher performance/complexity than simple iterative method. *Fixed-length Elements. Fixed length improves speed over the delimited string *Function of Numbers. Variations of Table of Numbers and fixed-length where the number are generated in a function rather than taken from a table. *Recursive Common Table Expression (CTE). SQL Server 2005 and higher, still not too complex and higher performance than iterative method. *Dynamic SQL. Can be slow and has security implications. *Passing the List as Many Parameters. Tedious and error prone, but simple. *Really Slow Methods. Methods that uses charindex, patindex or LIKE. I really can't recommend enough to read the article to learn about the tradeoffs among all these options. A: A superfast XML Method, if you want to use a stored procedure and pass the comma separated list of Department IDs : Declare @XMLList xml SET @XMLList=cast('<i>'+replace(@DepartmentIDs,',','</i><i>')+'</i>' as xml) SELECT x.i.value('.','varchar(5)') from @XMLList.nodes('i') x(i)) All credit goes to Guru Brad Schulz's Blog A: Yeah, your current solution is prone to SQL injection attacks. The best solution that I've found is to use a function that splits text into words (there are a few posted here, or you can use this one from my blog) and then join that to your table. Something like: SELECT d.[Name] FROM Department d JOIN dbo.SplitWords(@DepartmentIds) w ON w.Value = d.DepartmentId
{ "language": "en", "url": "https://stackoverflow.com/questions/43249", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "147" }
Q: Measuring exception handling overhead in C++ What is the best way to measure exception handling overhead/performance in C++? Please give standalone code samples. I'm targeting Microsoft Visual C++ 2008 and gcc. I need to get results from the following cases: * *Overhead when there are no try/catch blocks *Overhead when there are try/catch blocks but exceptions are not thrown *Overhead when exceptions are thrown A: Here's the measuring code I came up with. Do you see any problems with it? Works on Linux and Windows so far, compile with: g++ exception_handling.cpp -o exception_handling [ -O2 ] or for example Visual C++ Express. To get the base case ("exception support removed from the language altogether"), use: g++ exception_handling.cpp -o exception_handling [ -O2 ] -fno-exceptions -DNO_EXCEPTIONS or similar settings in MSVC. Some preliminary results here. They are probably all hokey because of varying machine load, but they do give some idea about the relative exception handling overhead. (Executive summary: none or little when no exceptions are thrown, huge when they actually are thrown.) #include <stdio.h> // Timer code #if defined(__linux__) #include <sys/time.h> #include <time.h> double time() { timeval tv; gettimeofday(&tv, 0); return 1.0 * tv.tv_sec + 0.000001 * tv.tv_usec; } #elif defined(_WIN32) #include <windows.h> double get_performance_frequency() { unsigned _int64 frequency; QueryPerformanceFrequency((LARGE_INTEGER*) &frequency); // just assume it works return double(frequency); } double performance_frequency = get_performance_frequency(); double time() { unsigned _int64 counter; QueryPerformanceCounter((LARGE_INTEGER*) &counter); return double(counter) / performance_frequency; } #else # error time() not implemented for your platform #endif // How many times to repeat the whole test const int repeats = 10; // How many times to iterate one case const int times = 1000000; // Trick optimizer to not remove code int result = 0; // Case 1. No exception thrown nor handled. void do_something() { ++result; } void case1() { do_something(); } // Case 2. No exception thrown, but handler installed #ifndef NO_EXCEPTIONS void do_something_else() { --result; } void case2() { try { do_something(); } catch (int exception) { do_something_else(); } } // Case 3. Exception thrown and caught void do_something_and_throw() { throw ++result; } void case3() { try { do_something_and_throw(); } catch (int exception) { result = exception; } } #endif // !NO_EXCEPTIONS void (*tests[])() = { case1, #ifndef NO_EXCEPTIONS case2, case3 #endif // !NO_EXCEPTIONS }; int main() { #ifdef NO_EXCEPTIONS printf("case0\n"); #else printf("case1\tcase2\tcase3\n"); #endif for (int repeat = 0; repeat < repeats; ++repeat) { for (int test = 0; test < sizeof(tests)/sizeof(tests[0]); ++test) { double start = time(); for (int i = 0; i < times; ++i) tests[test](); double end = time(); printf("%f\t", (end - start) * 1000000.0 / times); } printf("\n"); } return result; // optimizer is happy - we produce a result } A: Section 5.4 of the draft Technical Report on C++ Performance is entirely devoted to the overhead of exceptions. A: Kevin Frei talks about exception handling performance cost in his speech "The Cost of C++ Exception Handling on Windows". (Under "Summary & Conclusions" there is one list item that says "[Exception handling performance cost is] not always measurable".) A: There's no really good way to meassure that in code. You would need to use a a profiler. This won't show you directly how much time is spent with exception handling but with a little bit of research you will find out which of the runtime methods deal with exceptions (for example for VC++.NET it's __cxx_exc[...]). Add their times up and you have the overhead. In our project we used vTunes from Intel which works with both Visual C++ and gcc. Edit: Well, if you just need a generic number that might work. Thought you had an actual application to profile where you can't just turn off exceptions. A: Another note on exception handling performance: simple tests don't take caching into account. The try-code and the catch-code are both so small that everything fits in the instruction and data caches. But compilers may try to move the catch-code far away from the try-code, which reduces the amount of code to keep in cache normally, thus enhancing performance. If you compare exception handling to traditional C-style return-value checking, this caching effect should be taken into account as well (the question is usually ignored in discussions). Carl A: As a suggestion: don't bother too much with the overhead when exceptions are thrown. Exception handling implementations usually make not throwing fast and catching slow. That's ok since those cases are, well, exceptional. Carl A: Won't the answer depend on what cleanup has to happen as a result of a throw? If an excpetion is thrown that causes a whole load of objects to go out of scope up the stack, then that will add to the overhead. In other words, I'm not sure if there is a an answer to the 3rd question that is independent of the specifics of the code. A: Full details on how g++ handles exceptions is shown here. It describes it as being for the Itanium architecture, however the general techniques used are the same. It won't tell you exact overhead in terms of time, however you can glean what the rough code overhead will be.
{ "language": "en", "url": "https://stackoverflow.com/questions/43253", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: Can Database and transaction logs on the same drive cause problems? Can we have the database and transaction logs on the same drive? What will be its consequences if it is not recommended? A: The only downside is that it causes more thrashing on the disk, so worse performance. A single write will require 2 seeks (between: write transaction log, write data, commit log). Having the transaction log on a separate disk means as few as zero seeks, because the drive heads can remain on the transaction log and the data. A: The problem with having both on the same drive is that if the drive fails you lose both. If they are on different drives and the drive containing the data fails you can apply the log to the last backup so you don't lose any data. A: An company I worked for earlier had transaction logs and datafiles side by side on the same drive, in the same folder on several servers. This didn't cause any problems datawise. As others have noted it may well have impact on performance. And if you lose the drive you lose both. A: Just to add briefly to Ted Percival's comment above... A hard disk drive will perform fastest if it is doing sequential writes or sequential reads, because the drive head doesn't need to move around. SQL Server log files happen to be sequential, so if you dedicate a hard drive to ONLY the logs, you will see a noticeable performance improvement. That said, for smaller databases where performance is not an issue, it doesn't matter. And as for Nir's comment on drive failures -- hopefully you are handling that at a lower level, by putting both your data and logs on RAID arrays. A: In some scenarios you don't need transaction log at all. In that case you can switch database to Simple Recovery Mode and you gain performance and simpler administration benefits.
{ "language": "en", "url": "https://stackoverflow.com/questions/43259", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Good resources for writing console style applications for Windows? For certain programs nothing beats the command line. Unfortunately, I have never seen good documentation or examples on how to write console applications that go beyond "Hello World". I'm interested in making console apps like Vim or Emacs. Well not exactly like Vim or Emacs but one that takes over the entire command prompt while it is in use and then after you exit it leaves no trace behind. I know that on Unix there is the curses library but for Windows? ... A: PDCurses works on Win32. A: I found List of Console Functions on msdn, PDCurses, and The Console Module. A: In Windows or DOS, I used the conio library from Borland. It's very old but fine enough for a beginner like me. A: You can certainly write that kind of application with Delphi, which has reasonable commandline support. People often overlook that Delphi can build any kind of Windows executable, not just GUI apps. I don't know off-hand if the free 'Turbo' edition of Delphi has anything cobbled into it to PREVENT you from using it to build console apps - I would have thought it would be fine for this kind of thing. A: You could also try Free Pascal. It is a free ((L)GPL) Object Pascal compiler which is compatible with the Delphi-compiler. It has an console-based IDE, which proves that you can make very good console-applications with it, and which you can use as an example. If you want to use a graphical IDE to build your console-application, you can download the Lazarus IDE. As a bonus your application will run on Windows (32/64 bit), Linux, Mac OS X, FreeBSD, Solaris etc... A: There is a small but good tutorial on using C++ for the Windows console at www.benryves.com/tutorials/?t=winconsole&c=all going as far as coding a simple painting program. A: As Robsoft says Delphi would be a good start. There is Turbo Delphi (Pascal based) or Turbo C++ both free editions. web site here. http://www.turboexplorer.com/ A: Check out some of the mono libs. They have a great one to parse command line arguments but can't remember the namespace. Miguel just posted some terminal code as well. A: For ncurses-like library/framework on Windows, I'll highly suggest to get your hand dirty with PDCurses. If you trying/using C#, there's Curses-Sharp. A: This is the best tool for it I've ever seen!! 1) Create any application using VB6 IDE 2) Convert it to Console Application, using THIS!
{ "language": "en", "url": "https://stackoverflow.com/questions/43267", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Comparing two byte arrays in .NET How can I do this fast? Sure I can do this: static bool ByteArrayCompare(byte[] a1, byte[] a2) { if (a1.Length != a2.Length) return false; for (int i=0; i<a1.Length; i++) if (a1[i]!=a2[i]) return false; return true; } But I'm looking for either a BCL function or some highly optimized proven way to do this. java.util.Arrays.equals((sbyte[])(Array)a1, (sbyte[])(Array)a2); works nicely, but it doesn't look like that would work for x64. Note my super-fast answer here. A: Edit: modern fast way is to use a1.SequenceEquals(a2) User gil suggested unsafe code which spawned this solution: // Copyright (c) 2008-2013 Hafthor Stefansson // Distributed under the MIT/X11 software license // Ref: http://www.opensource.org/licenses/mit-license.php. static unsafe bool UnsafeCompare(byte[] a1, byte[] a2) { unchecked { if(a1==a2) return true; if(a1==null || a2==null || a1.Length!=a2.Length) return false; fixed (byte* p1=a1, p2=a2) { byte* x1=p1, x2=p2; int l = a1.Length; for (int i=0; i < l/8; i++, x1+=8, x2+=8) if (*((long*)x1) != *((long*)x2)) return false; if ((l & 4)!=0) { if (*((int*)x1)!=*((int*)x2)) return false; x1+=4; x2+=4; } if ((l & 2)!=0) { if (*((short*)x1)!=*((short*)x2)) return false; x1+=2; x2+=2; } if ((l & 1)!=0) if (*((byte*)x1) != *((byte*)x2)) return false; return true; } } } which does 64-bit based comparison for as much of the array as possible. This kind of counts on the fact that the arrays start qword aligned. It'll work if not qword aligned, just not as fast as if it were. It performs about seven timers faster than the simple `for` loop. Using the J# library performed equivalently to the original `for` loop. Using .SequenceEqual runs around seven times slower; I think just because it is using IEnumerator.MoveNext. I imagine LINQ-based solutions being at least that slow or worse. A: I would use unsafe code and run the for loop comparing Int32 pointers. Maybe you should also consider checking the arrays to be non-null. A: You can use Enumerable.SequenceEqual method. using System; using System.Linq; ... var a1 = new int[] { 1, 2, 3}; var a2 = new int[] { 1, 2, 3}; var a3 = new int[] { 1, 2, 4}; var x = a1.SequenceEqual(a2); // true var y = a1.SequenceEqual(a3); // false If you can't use .NET 3.5 for some reason, your method is OK. Compiler\run-time environment will optimize your loop so you don't need to worry about performance. A: If you look at how .NET does string.Equals, you see that it uses a private method called EqualsHelper which has an "unsafe" pointer implementation. .NET Reflector is your friend to see how things are done internally. This can be used as a template for byte array comparison which I did an implementation on in blog post Fast byte array comparison in C#. I also did some rudimentary benchmarks to see when a safe implementation is faster than the unsafe. That said, unless you really need killer performance, I'd go for a simple fr loop comparison. A: For those of you that care about order (i.e. want your memcmp to return an int like it should instead of nothing), .NET Core 3.0 (and presumably .NET Standard 2.1 aka .NET 5.0) will include a Span.SequenceCompareTo(...) extension method (plus a Span.SequenceEqualTo) that can be used to compare two ReadOnlySpan<T> instances (where T: IComparable<T>). In the original GitHub proposal, the discussion included approach comparisons with jump table calculations, reading a byte[] as long[], SIMD usage, and p/invoke to the CLR implementation's memcmp. Going forward, this should be your go-to method for comparing byte arrays or byte ranges (as should using Span<byte> instead of byte[] for your .NET Standard 2.1 APIs), and it is sufficiently fast enough that you should no longer care about optimizing it (and no, despite the similarities in name it does not perform as abysmally as the horrid Enumerable.SequenceEqual). #if NETCOREAPP3_0_OR_GREATER // Using the platform-native Span<T>.SequenceEqual<T>(..) public static int Compare(byte[] range1, int offset1, byte[] range2, int offset2, int count) { var span1 = range1.AsSpan(offset1, count); var span2 = range2.AsSpan(offset2, count); return span1.SequenceCompareTo(span2); // or, if you don't care about ordering // return span1.SequenceEqual(span2); } #else // The most basic implementation, in platform-agnostic, safe C# public static bool Compare(byte[] range1, int offset1, byte[] range2, int offset2, int count) { // Working backwards lets the compiler optimize away bound checking after the first loop for (int i = count - 1; i >= 0; --i) { if (range1[offset1 + i] != range2[offset2 + i]) { return false; } } return true; } #endif A: I did some measurements using attached program .net 4.7 release build without the debugger attached. I think people have been using the wrong metric since what you are about if you care about speed here is how long it takes to figure out if two byte arrays are equal. i.e. throughput in bytes. StructuralComparison : 4.6 MiB/s for : 274.5 MiB/s ToUInt32 : 263.6 MiB/s ToUInt64 : 474.9 MiB/s memcmp : 8500.8 MiB/s As you can see, there's no better way than memcmp and it's orders of magnitude faster. A simple for loop is the second best option. And it still boggles my mind why Microsoft cannot simply include a Buffer.Compare method. [Program.cs]: using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; namespace memcmp { class Program { static byte[] TestVector(int size) { var data = new byte[size]; using (var rng = new System.Security.Cryptography.RNGCryptoServiceProvider()) { rng.GetBytes(data); } return data; } static TimeSpan Measure(string testCase, TimeSpan offset, Action action, bool ignore = false) { var t = Stopwatch.StartNew(); var n = 0L; while (t.Elapsed < TimeSpan.FromSeconds(10)) { action(); n++; } var elapsed = t.Elapsed - offset; if (!ignore) { Console.WriteLine($"{testCase,-16} : {n / elapsed.TotalSeconds,16:0.0} MiB/s"); } return elapsed; } [DllImport("msvcrt.dll", CallingConvention = CallingConvention.Cdecl)] static extern int memcmp(byte[] b1, byte[] b2, long count); static void Main(string[] args) { // how quickly can we establish if two sequences of bytes are equal? // note that we are testing the speed of different comparsion methods var a = TestVector(1024 * 1024); // 1 MiB var b = (byte[])a.Clone(); // was meant to offset the overhead of everything but copying but my attempt was a horrible mistake... should have reacted sooner due to the initially ridiculous throughput values... // Measure("offset", new TimeSpan(), () => { return; }, ignore: true); var offset = TimeZone.Zero Measure("StructuralComparison", offset, () => { StructuralComparisons.StructuralEqualityComparer.Equals(a, b); }); Measure("for", offset, () => { for (int i = 0; i < a.Length; i++) { if (a[i] != b[i]) break; } }); Measure("ToUInt32", offset, () => { for (int i = 0; i < a.Length; i += 4) { if (BitConverter.ToUInt32(a, i) != BitConverter.ToUInt32(b, i)) break; } }); Measure("ToUInt64", offset, () => { for (int i = 0; i < a.Length; i += 8) { if (BitConverter.ToUInt64(a, i) != BitConverter.ToUInt64(b, i)) break; } }); Measure("memcmp", offset, () => { memcmp(a, b, a.Length); }); } } } A: Couldn't find a solution I'm completely happy with (reasonable performance, but no unsafe code/pinvoke) so I came up with this, nothing really original, but works: /// <summary> /// /// </summary> /// <param name="array1"></param> /// <param name="array2"></param> /// <param name="bytesToCompare"> 0 means compare entire arrays</param> /// <returns></returns> public static bool ArraysEqual(byte[] array1, byte[] array2, int bytesToCompare = 0) { if (array1.Length != array2.Length) return false; var length = (bytesToCompare == 0) ? array1.Length : bytesToCompare; var tailIdx = length - length % sizeof(Int64); //check in 8 byte chunks for (var i = 0; i < tailIdx; i += sizeof(Int64)) { if (BitConverter.ToInt64(array1, i) != BitConverter.ToInt64(array2, i)) return false; } //check the remainder of the array, always shorter than 8 bytes for (var i = tailIdx; i < length; i++) { if (array1[i] != array2[i]) return false; } return true; } Performance compared with some of the other solutions on this page: Simple Loop: 19837 ticks, 1.00 *BitConverter: 4886 ticks, 4.06 UnsafeCompare: 1636 ticks, 12.12 EqualBytesLongUnrolled: 637 ticks, 31.09 P/Invoke memcmp: 369 ticks, 53.67 Tested in linqpad, 1000000 bytes identical arrays (worst case scenario), 500 iterations each. A: It seems that EqualBytesLongUnrolled is the best from the above suggested. Skipped methods (Enumerable.SequenceEqual,StructuralComparisons.StructuralEqualityComparer.Equals), were not-patient-for-slow. On 265MB arrays I have measured this: Host Process Environment Information: BenchmarkDotNet.Core=v0.9.9.0 OS=Microsoft Windows NT 6.2.9200.0 Processor=Intel(R) Core(TM) i7-3770 CPU 3.40GHz, ProcessorCount=8 Frequency=3323582 ticks, Resolution=300.8802 ns, Timer=TSC CLR=MS.NET 4.0.30319.42000, Arch=64-bit RELEASE [RyuJIT] GC=Concurrent Workstation JitModules=clrjit-v4.6.1590.0 Type=CompareMemoriesBenchmarks Mode=Throughput Method | Median | StdDev | Scaled | Scaled-SD | ----------------------- |------------ |---------- |------- |---------- | NewMemCopy | 30.0443 ms | 1.1880 ms | 1.00 | 0.00 | EqualBytesLongUnrolled | 29.9917 ms | 0.7480 ms | 0.99 | 0.04 | msvcrt_memcmp | 30.0930 ms | 0.2964 ms | 1.00 | 0.03 | UnsafeCompare | 31.0520 ms | 0.7072 ms | 1.03 | 0.04 | ByteArrayCompare | 212.9980 ms | 2.0776 ms | 7.06 | 0.25 | OS=Windows Processor=?, ProcessorCount=8 Frequency=3323582 ticks, Resolution=300.8802 ns, Timer=TSC CLR=CORE, Arch=64-bit ? [RyuJIT] GC=Concurrent Workstation dotnet cli version: 1.0.0-preview2-003131 Type=CompareMemoriesBenchmarks Mode=Throughput Method | Median | StdDev | Scaled | Scaled-SD | ----------------------- |------------ |---------- |------- |---------- | NewMemCopy | 30.1789 ms | 0.0437 ms | 1.00 | 0.00 | EqualBytesLongUnrolled | 30.1985 ms | 0.1782 ms | 1.00 | 0.01 | msvcrt_memcmp | 30.1084 ms | 0.0660 ms | 1.00 | 0.00 | UnsafeCompare | 31.1845 ms | 0.4051 ms | 1.03 | 0.01 | ByteArrayCompare | 212.0213 ms | 0.1694 ms | 7.03 | 0.01 | A: If you are not opposed to doing it, you can import the J# assembly "vjslib.dll" and use its Arrays.equals(byte[], byte[]) method... Don't blame me if someone laughs at you though... EDIT: For what little it is worth, I used Reflector to disassemble the code for that, and here is what it looks like: public static bool equals(sbyte[] a1, sbyte[] a2) { if (a1 == a2) { return true; } if ((a1 != null) && (a2 != null)) { if (a1.Length != a2.Length) { return false; } for (int i = 0; i < a1.Length; i++) { if (a1[i] != a2[i]) { return false; } } return true; } return false; } A: For comparing short byte arrays the following is an interesting hack: if(myByteArray1.Length != myByteArray2.Length) return false; if(myByteArray1.Length == 8) return BitConverter.ToInt64(myByteArray1, 0) == BitConverter.ToInt64(myByteArray2, 0); else if(myByteArray.Length == 4) return BitConverter.ToInt32(myByteArray2, 0) == BitConverter.ToInt32(myByteArray2, 0); Then I would probably fall out to the solution listed in the question. It'd be interesting to do a performance analysis of this code. A: I have not seen many linq solutions here. I am not sure of the performance implications, however I generally stick to linq as rule of thumb and then optimize later if necessary. public bool CompareTwoArrays(byte[] array1, byte[] array2) { return !array1.Where((t, i) => t != array2[i]).Any(); } Please do note this only works if they are the same size arrays. an extension could look like so public bool CompareTwoArrays(byte[] array1, byte[] array2) { if (array1.Length != array2.Length) return false; return !array1.Where((t, i) => t != array2[i]).Any(); } A: .NET 3.5 and newer have a new public type, System.Data.Linq.Binary that encapsulates byte[]. It implements IEquatable<Binary> that (in effect) compares two byte arrays. Note that System.Data.Linq.Binary also has implicit conversion operator from byte[]. MSDN documentation:System.Data.Linq.Binary Reflector decompile of the Equals method: private bool EqualsTo(Binary binary) { if (this != binary) { if (binary == null) { return false; } if (this.bytes.Length != binary.bytes.Length) { return false; } if (this.hashCode != binary.hashCode) { return false; } int index = 0; int length = this.bytes.Length; while (index < length) { if (this.bytes[index] != binary.bytes[index]) { return false; } index++; } } return true; } Interesting twist is that they only proceed to byte-by-byte comparison loop if hashes of the two Binary objects are the same. This, however, comes at the cost of computing the hash in constructor of Binary objects (by traversing the array with for loop :-) ). The above implementation means that in the worst case you may have to traverse the arrays three times: first to compute hash of array1, then to compute hash of array2 and finally (because this is the worst case scenario, lengths and hashes equal) to compare bytes in array1 with bytes in array 2. Overall, even though System.Data.Linq.Binary is built into BCL, I don't think it is the fastest way to compare two byte arrays :-|. A: P/Invoke powers activate! [DllImport("msvcrt.dll", CallingConvention=CallingConvention.Cdecl)] static extern int memcmp(byte[] b1, byte[] b2, long count); static bool ByteArrayCompare(byte[] b1, byte[] b2) { // Validate buffers are the same length. // This also ensures that the count does not exceed the length of either buffer. return b1.Length == b2.Length && memcmp(b1, b2, b1.Length) == 0; } A: I posted a similar question about checking if byte[] is full of zeroes. (SIMD code was beaten so I removed it from this answer.) Here is fastest code from my comparisons: static unsafe bool EqualBytesLongUnrolled (byte[] data1, byte[] data2) { if (data1 == data2) return true; if (data1.Length != data2.Length) return false; fixed (byte* bytes1 = data1, bytes2 = data2) { int len = data1.Length; int rem = len % (sizeof(long) * 16); long* b1 = (long*)bytes1; long* b2 = (long*)bytes2; long* e1 = (long*)(bytes1 + len - rem); while (b1 < e1) { if (*(b1) != *(b2) || *(b1 + 1) != *(b2 + 1) || *(b1 + 2) != *(b2 + 2) || *(b1 + 3) != *(b2 + 3) || *(b1 + 4) != *(b2 + 4) || *(b1 + 5) != *(b2 + 5) || *(b1 + 6) != *(b2 + 6) || *(b1 + 7) != *(b2 + 7) || *(b1 + 8) != *(b2 + 8) || *(b1 + 9) != *(b2 + 9) || *(b1 + 10) != *(b2 + 10) || *(b1 + 11) != *(b2 + 11) || *(b1 + 12) != *(b2 + 12) || *(b1 + 13) != *(b2 + 13) || *(b1 + 14) != *(b2 + 14) || *(b1 + 15) != *(b2 + 15)) return false; b1 += 16; b2 += 16; } for (int i = 0; i < rem; i++) if (data1 [len - 1 - i] != data2 [len - 1 - i]) return false; return true; } } Measured on two 256MB byte arrays: UnsafeCompare : 86,8784 ms EqualBytesSimd : 71,5125 ms EqualBytesSimdUnrolled : 73,1917 ms EqualBytesLongUnrolled : 39,8623 ms A: I thought about block-transfer acceleration methods built into many graphics cards. But then you would have to copy over all the data byte-wise, so this doesn't help you much if you don't want to implement a whole portion of your logic in unmanaged and hardware-dependent code... Another way of optimization similar to the approach shown above would be to store as much of your data as possible in a long[] rather than a byte[] right from the start, for example if you are reading it sequentially from a binary file, or if you use a memory mapped file, read in data as long[] or single long values. Then, your comparison loop will only need 1/8th of the number of iterations it would have to do for a byte[] containing the same amount of data. It is a matter of when and how often you need to compare vs. when and how often you need to access the data in a byte-by-byte manner, e.g. to use it in an API call as a parameter in a method that expects a byte[]. In the end, you only can tell if you really know the use case... A: Span<T> offers an extremely competitive alternative without having to throw confusing and/or non-portable fluff into your own application's code base: // byte[] is implicitly convertible to ReadOnlySpan<byte> static bool ByteArrayCompare(ReadOnlySpan<byte> a1, ReadOnlySpan<byte> a2) { return a1.SequenceEqual(a2); } The (guts of the) implementation as of .NET 6.0.4 can be found here. I've revised @EliArbel's gist to add this method as SpansEqual, drop most of the less interesting performers in others' benchmarks, run it with different array sizes, output graphs, and mark SpansEqual as the baseline so that it reports how the different methods compare to SpansEqual. The below numbers are from the results, lightly edited to remove "Error" column. | Method | ByteCount | Mean | StdDev | Ratio | RatioSD | |-------------- |----------- |-------------------:|----------------:|------:|--------:| | SpansEqual | 15 | 2.074 ns | 0.0233 ns | 1.00 | 0.00 | | LongPointers | 15 | 2.854 ns | 0.0632 ns | 1.38 | 0.03 | | Unrolled | 15 | 12.449 ns | 0.2487 ns | 6.00 | 0.13 | | PInvokeMemcmp | 15 | 7.525 ns | 0.1057 ns | 3.63 | 0.06 | | | | | | | | | SpansEqual | 1026 | 15.629 ns | 0.1712 ns | 1.00 | 0.00 | | LongPointers | 1026 | 46.487 ns | 0.2938 ns | 2.98 | 0.04 | | Unrolled | 1026 | 23.786 ns | 0.1044 ns | 1.52 | 0.02 | | PInvokeMemcmp | 1026 | 28.299 ns | 0.2781 ns | 1.81 | 0.03 | | | | | | | | | SpansEqual | 1048585 | 17,920.329 ns | 153.0750 ns | 1.00 | 0.00 | | LongPointers | 1048585 | 42,077.448 ns | 309.9067 ns | 2.35 | 0.02 | | Unrolled | 1048585 | 29,084.901 ns | 428.8496 ns | 1.62 | 0.03 | | PInvokeMemcmp | 1048585 | 30,847.572 ns | 213.3162 ns | 1.72 | 0.02 | | | | | | | | | SpansEqual | 2147483591 | 124,752,376.667 ns | 552,281.0202 ns | 1.00 | 0.00 | | LongPointers | 2147483591 | 139,477,269.231 ns | 331,458.5429 ns | 1.12 | 0.00 | | Unrolled | 2147483591 | 137,617,423.077 ns | 238,349.5093 ns | 1.10 | 0.00 | | PInvokeMemcmp | 2147483591 | 138,373,253.846 ns | 288,447.8278 ns | 1.11 | 0.01 | I was surprised to see SpansEqual not come out on top for the max-array-size methods, but the difference is so minor that I don't think it'll ever matter. After refreshing to run on .NET 6.0.4 with my newer hardware, SpansEqual now comfortably outperforms all others at all array sizes. My system info: BenchmarkDotNet=v0.13.1, OS=Windows 10.0.22000 AMD Ryzen 9 5900X, 1 CPU, 24 logical and 12 physical cores .NET SDK=6.0.202 [Host] : .NET 6.0.4 (6.0.422.16404), X64 RyuJIT DefaultJob : .NET 6.0.4 (6.0.422.16404), X64 RyuJIT A: There's a new built-in solution for this in .NET 4 - IStructuralEquatable static bool ByteArrayCompare(byte[] a1, byte[] a2) { return StructuralComparisons.StructuralEqualityComparer.Equals(a1, a2); } A: using System.Linq; //SequenceEqual byte[] ByteArray1 = null; byte[] ByteArray2 = null; ByteArray1 = MyFunct1(); ByteArray2 = MyFunct2(); if (ByteArray1.SequenceEqual<byte>(ByteArray2) == true) { MessageBox.Show("Match"); } else { MessageBox.Show("Don't match"); } A: Let's add one more! Recently Microsoft released a special NuGet package, System.Runtime.CompilerServices.Unsafe. It's special because it's written in IL, and provides low-level functionality not directly available in C#. One of its methods, Unsafe.As<T>(object) allows casting any reference type to another reference type, skipping any safety checks. This is usually a very bad idea, but if both types have the same structure, it can work. So we can use this to cast a byte[] to a long[]: bool CompareWithUnsafeLibrary(byte[] a1, byte[] a2) { if (a1.Length != a2.Length) return false; var longSize = (int)Math.Floor(a1.Length / 8.0); var long1 = Unsafe.As<long[]>(a1); var long2 = Unsafe.As<long[]>(a2); for (var i = 0; i < longSize; i++) { if (long1[i] != long2[i]) return false; } for (var i = longSize * 8; i < a1.Length; i++) { if (a1[i] != a2[i]) return false; } return true; } Note that long1.Length would still return the original array's length, since it's stored in a field in the array's memory structure. This method is not quite as fast as other methods demonstrated here, but it is a lot faster than the naive method, doesn't use unsafe code or P/Invoke or pinning, and the implementation is quite straightforward (IMO). Here are some BenchmarkDotNet results from my machine: BenchmarkDotNet=v0.10.3.0, OS=Microsoft Windows NT 6.2.9200.0 Processor=Intel(R) Core(TM) i7-4870HQ CPU 2.50GHz, ProcessorCount=8 Frequency=2435775 Hz, Resolution=410.5470 ns, Timer=TSC [Host] : Clr 4.0.30319.42000, 64bit RyuJIT-v4.6.1637.0 DefaultJob : Clr 4.0.30319.42000, 64bit RyuJIT-v4.6.1637.0 Method | Mean | StdDev | ----------------------- |-------------- |---------- | UnsafeLibrary | 125.8229 ns | 0.3588 ns | UnsafeCompare | 89.9036 ns | 0.8243 ns | JSharpEquals | 1,432.1717 ns | 1.3161 ns | EqualBytesLongUnrolled | 43.7863 ns | 0.8923 ns | NewMemCmp | 65.4108 ns | 0.2202 ns | ArraysEqual | 910.8372 ns | 2.6082 ns | PInvokeMemcmp | 52.7201 ns | 0.1105 ns | I've also created a gist with all the tests. A: I developed a method that slightly beats memcmp() (plinth's answer) and very slighly beats EqualBytesLongUnrolled() (Arek Bulski's answer) on my PC. Basically, it unrolls the loop by 4 instead of 8. Update 30 Mar. 2019: Starting in .NET core 3.0, we have SIMD support! This solution is fastest by a considerable margin on my PC: #if NETCOREAPP3_0 using System.Runtime.Intrinsics.X86; #endif … public static unsafe bool Compare(byte[] arr0, byte[] arr1) { if (arr0 == arr1) { return true; } if (arr0 == null || arr1 == null) { return false; } if (arr0.Length != arr1.Length) { return false; } if (arr0.Length == 0) { return true; } fixed (byte* b0 = arr0, b1 = arr1) { #if NETCOREAPP3_0 if (Avx2.IsSupported) { return Compare256(b0, b1, arr0.Length); } else if (Sse2.IsSupported) { return Compare128(b0, b1, arr0.Length); } else #endif { return Compare64(b0, b1, arr0.Length); } } } #if NETCOREAPP3_0 public static unsafe bool Compare256(byte* b0, byte* b1, int length) { byte* lastAddr = b0 + length; byte* lastAddrMinus128 = lastAddr - 128; const int mask = -1; while (b0 < lastAddrMinus128) // unroll the loop so that we are comparing 128 bytes at a time. { if (Avx2.MoveMask(Avx2.CompareEqual(Avx.LoadVector256(b0), Avx.LoadVector256(b1))) != mask) { return false; } if (Avx2.MoveMask(Avx2.CompareEqual(Avx.LoadVector256(b0 + 32), Avx.LoadVector256(b1 + 32))) != mask) { return false; } if (Avx2.MoveMask(Avx2.CompareEqual(Avx.LoadVector256(b0 + 64), Avx.LoadVector256(b1 + 64))) != mask) { return false; } if (Avx2.MoveMask(Avx2.CompareEqual(Avx.LoadVector256(b0 + 96), Avx.LoadVector256(b1 + 96))) != mask) { return false; } b0 += 128; b1 += 128; } while (b0 < lastAddr) { if (*b0 != *b1) return false; b0++; b1++; } return true; } public static unsafe bool Compare128(byte* b0, byte* b1, int length) { byte* lastAddr = b0 + length; byte* lastAddrMinus64 = lastAddr - 64; const int mask = 0xFFFF; while (b0 < lastAddrMinus64) // unroll the loop so that we are comparing 64 bytes at a time. { if (Sse2.MoveMask(Sse2.CompareEqual(Sse2.LoadVector128(b0), Sse2.LoadVector128(b1))) != mask) { return false; } if (Sse2.MoveMask(Sse2.CompareEqual(Sse2.LoadVector128(b0 + 16), Sse2.LoadVector128(b1 + 16))) != mask) { return false; } if (Sse2.MoveMask(Sse2.CompareEqual(Sse2.LoadVector128(b0 + 32), Sse2.LoadVector128(b1 + 32))) != mask) { return false; } if (Sse2.MoveMask(Sse2.CompareEqual(Sse2.LoadVector128(b0 + 48), Sse2.LoadVector128(b1 + 48))) != mask) { return false; } b0 += 64; b1 += 64; } while (b0 < lastAddr) { if (*b0 != *b1) return false; b0++; b1++; } return true; } #endif public static unsafe bool Compare64(byte* b0, byte* b1, int length) { byte* lastAddr = b0 + length; byte* lastAddrMinus32 = lastAddr - 32; while (b0 < lastAddrMinus32) // unroll the loop so that we are comparing 32 bytes at a time. { if (*(ulong*)b0 != *(ulong*)b1) return false; if (*(ulong*)(b0 + 8) != *(ulong*)(b1 + 8)) return false; if (*(ulong*)(b0 + 16) != *(ulong*)(b1 + 16)) return false; if (*(ulong*)(b0 + 24) != *(ulong*)(b1 + 24)) return false; b0 += 32; b1 += 32; } while (b0 < lastAddr) { if (*b0 != *b1) return false; b0++; b1++; } return true; } A: Sorry, if you're looking for a managed way you're already doing it correctly and to my knowledge there's no built in method in the BCL for doing this. You should add some initial null checks and then just reuse it as if it where in BCL. A: I settled on a solution inspired by the EqualBytesLongUnrolled method posted by ArekBulski with an additional optimization. In my instance, array differences in arrays tend to be near the tail of the arrays. In testing, I found that when this is the case for large arrays, being able to compare array elements in reverse order gives this solution a huge performance gain over the memcmp based solution. Here is that solution: public enum CompareDirection { Forward, Backward } private static unsafe bool UnsafeEquals(byte[] a, byte[] b, CompareDirection direction = CompareDirection.Forward) { // returns when a and b are same array or both null if (a == b) return true; // if either is null or different lengths, can't be equal if (a == null || b == null || a.Length != b.Length) return false; const int UNROLLED = 16; // count of longs 'unrolled' in optimization int size = sizeof(long) * UNROLLED; // 128 bytes (min size for 'unrolled' optimization) int len = a.Length; int n = len / size; // count of full 128 byte segments int r = len % size; // count of remaining 'unoptimized' bytes // pin the arrays and access them via pointers fixed (byte* pb_a = a, pb_b = b) { if (r > 0 && direction == CompareDirection.Backward) { byte* pa = pb_a + len - 1; byte* pb = pb_b + len - 1; byte* phead = pb_a + len - r; while(pa >= phead) { if (*pa != *pb) return false; pa--; pb--; } } if (n > 0) { int nOffset = n * size; if (direction == CompareDirection.Forward) { long* pa = (long*)pb_a; long* pb = (long*)pb_b; long* ptail = (long*)(pb_a + nOffset); while (pa < ptail) { if (*(pa + 0) != *(pb + 0) || *(pa + 1) != *(pb + 1) || *(pa + 2) != *(pb + 2) || *(pa + 3) != *(pb + 3) || *(pa + 4) != *(pb + 4) || *(pa + 5) != *(pb + 5) || *(pa + 6) != *(pb + 6) || *(pa + 7) != *(pb + 7) || *(pa + 8) != *(pb + 8) || *(pa + 9) != *(pb + 9) || *(pa + 10) != *(pb + 10) || *(pa + 11) != *(pb + 11) || *(pa + 12) != *(pb + 12) || *(pa + 13) != *(pb + 13) || *(pa + 14) != *(pb + 14) || *(pa + 15) != *(pb + 15) ) { return false; } pa += UNROLLED; pb += UNROLLED; } } else { long* pa = (long*)(pb_a + nOffset); long* pb = (long*)(pb_b + nOffset); long* phead = (long*)pb_a; while (phead < pa) { if (*(pa - 1) != *(pb - 1) || *(pa - 2) != *(pb - 2) || *(pa - 3) != *(pb - 3) || *(pa - 4) != *(pb - 4) || *(pa - 5) != *(pb - 5) || *(pa - 6) != *(pb - 6) || *(pa - 7) != *(pb - 7) || *(pa - 8) != *(pb - 8) || *(pa - 9) != *(pb - 9) || *(pa - 10) != *(pb - 10) || *(pa - 11) != *(pb - 11) || *(pa - 12) != *(pb - 12) || *(pa - 13) != *(pb - 13) || *(pa - 14) != *(pb - 14) || *(pa - 15) != *(pb - 15) || *(pa - 16) != *(pb - 16) ) { return false; } pa -= UNROLLED; pb -= UNROLLED; } } } if (r > 0 && direction == CompareDirection.Forward) { byte* pa = pb_a + len - r; byte* pb = pb_b + len - r; byte* ptail = pb_a + len; while(pa < ptail) { if (*pa != *pb) return false; pa++; pb++; } } } return true; } A: This is almost certainly much slower than any other version given here, but it was fun to write. static bool ByteArrayEquals(byte[] a1, byte[] a2) { return a1.Zip(a2, (l, r) => l == r).All(x => x); } A: This is similar to others, but the difference here is that there is no falling through to the next highest number of bytes I can check at once, e.g. if I have 63 bytes (in my SIMD example) I can check the equality of the first 32 bytes, and then the last 32 bytes, which is faster than checking 32 bytes, 16 bytes, 8 bytes, and so on. The first check you enter is the only check you will need to compare all of the bytes. This does come out on top in my tests, but just by a hair. The following code is exactly how I tested it in airbreather/ArrayComparePerf.cs. public unsafe bool SIMDNoFallThrough() #requires System.Runtime.Intrinsics.X86 { if (a1 == null || a2 == null) return false; int length0 = a1.Length; if (length0 != a2.Length) return false; fixed (byte* b00 = a1, b01 = a2) { byte* b0 = b00, b1 = b01, last0 = b0 + length0, last1 = b1 + length0, last32 = last0 - 31; if (length0 > 31) { while (b0 < last32) { if (Avx2.MoveMask(Avx2.CompareEqual(Avx.LoadVector256(b0), Avx.LoadVector256(b1))) != -1) return false; b0 += 32; b1 += 32; } return Avx2.MoveMask(Avx2.CompareEqual(Avx.LoadVector256(last0 - 32), Avx.LoadVector256(last1 - 32))) == -1; } if (length0 > 15) { if (Sse2.MoveMask(Sse2.CompareEqual(Sse2.LoadVector128(b0), Sse2.LoadVector128(b1))) != 65535) return false; return Sse2.MoveMask(Sse2.CompareEqual(Sse2.LoadVector128(last0 - 16), Sse2.LoadVector128(last1 - 16))) == 65535; } if (length0 > 7) { if (*(ulong*)b0 != *(ulong*)b1) return false; return *(ulong*)(last0 - 8) == *(ulong*)(last1 - 8); } if (length0 > 3) { if (*(uint*)b0 != *(uint*)b1) return false; return *(uint*)(last0 - 4) == *(uint*)(last1 - 4); } if (length0 > 1) { if (*(ushort*)b0 != *(ushort*)b1) return false; return *(ushort*)(last0 - 2) == *(ushort*)(last1 - 2); } return *b0 == *b1; } } If no SIMD is preferred, the same method applied to the the existing LongPointers algorithm: public unsafe bool LongPointersNoFallThrough() { if (a1 == null || a2 == null || a1.Length != a2.Length) return false; fixed (byte* p1 = a1, p2 = a2) { byte* x1 = p1, x2 = p2; int l = a1.Length; if ((l & 8) != 0) { for (int i = 0; i < l / 8; i++, x1 += 8, x2 += 8) if (*(long*)x1 != *(long*)x2) return false; return *(long*)(x1 + (l - 8)) == *(long*)(x2 + (l - 8)); } if ((l & 4) != 0) { if (*(int*)x1 != *(int*)x2) return false; x1 += 4; x2 += 4; return *(int*)(x1 + (l - 4)) == *(int*)(x2 + (l - 4)); } if ((l & 2) != 0) { if (*(short*)x1 != *(short*)x2) return false; x1 += 2; x2 += 2; return *(short*)(x1 + (l - 2)) == *(short*)(x2 + (l - 2)); } return *x1 == *x2; } } A: The short answer is this: public bool Compare(byte[] b1, byte[] b2) { return Encoding.ASCII.GetString(b1) == Encoding.ASCII.GetString(b2); } In such a way you can use the optimized .NET string compare to make a byte array compare without the need to write unsafe code. This is how it is done in the background: private unsafe static bool EqualsHelper(String strA, String strB) { Contract.Requires(strA != null); Contract.Requires(strB != null); Contract.Requires(strA.Length == strB.Length); int length = strA.Length; fixed (char* ap = &strA.m_firstChar) fixed (char* bp = &strB.m_firstChar) { char* a = ap; char* b = bp; // Unroll the loop #if AMD64 // For the AMD64 bit platform we unroll by 12 and // check three qwords at a time. This is less code // than the 32 bit case and is shorter // pathlength. while (length >= 12) { if (*(long*)a != *(long*)b) return false; if (*(long*)(a+4) != *(long*)(b+4)) return false; if (*(long*)(a+8) != *(long*)(b+8)) return false; a += 12; b += 12; length -= 12; } #else while (length >= 10) { if (*(int*)a != *(int*)b) return false; if (*(int*)(a+2) != *(int*)(b+2)) return false; if (*(int*)(a+4) != *(int*)(b+4)) return false; if (*(int*)(a+6) != *(int*)(b+6)) return false; if (*(int*)(a+8) != *(int*)(b+8)) return false; a += 10; b += 10; length -= 10; } #endif // This depends on the fact that the String objects are // always zero terminated and that the terminating zero is not included // in the length. For odd string sizes, the last compare will include // the zero terminator. while (length > 0) { if (*(int*)a != *(int*)b) break; a += 2; b += 2; length -= 2; } return (length <= 0); } } A: Since many of the fancy solutions above don't work with UWP and because I love Linq and functional approaches I pressent you my version to this problem. To escape the comparison when the first difference occures, I chose .FirstOrDefault() public static bool CompareByteArrays(byte[] ba0, byte[] ba1) => !(ba0.Length != ba1.Length || Enumerable.Range(1,ba0.Length) .FirstOrDefault(n => ba0[n] != ba1[n]) > 0); A: If you are looking for a very fast byte array equality comparer, I suggest you take a look at this STSdb Labs article: Byte array equality comparer. It features some of the fastest implementations for byte[] array equality comparing, which are presented, performance tested and summarized. You can also focus on these implementations: BigEndianByteArrayComparer - fast byte[] array comparer from left to right (BigEndian) BigEndianByteArrayEqualityComparer - - fast byte[] equality comparer from left to right (BigEndian) LittleEndianByteArrayComparer - fast byte[] array comparer from right to left (LittleEndian) LittleEndianByteArrayEqualityComparer - fast byte[] equality comparer from right to left (LittleEndian) A: Use SequenceEquals for this to comparison.
{ "language": "en", "url": "https://stackoverflow.com/questions/43289", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "627" }
Q: How to generate urls in django In Django's template language, you can use {% url [viewname] [args] %} to generate a URL to a specific view with parameters. How can you programatically do the same in Python code? What I need is to create a list of menu items where each item has name, URL, and an active flag (whether it's the current page or not). This is because it will be a lot cleaner to do this in Python than the template language. A: For Python3 and Django 2: from django.urls import reverse url = reverse('my_app:endpoint', kwargs={'arg1': arg_1}) A: If you need to use something similar to the {% url %} template tag in your code, Django provides the django.core.urlresolvers.reverse(). The reverse function has the following signature: reverse(viewname, urlconf=None, args=None, kwargs=None) https://docs.djangoproject.com/en/dev/ref/urlresolvers/ At the time of this edit the import is django.urls import reverse A: Be aware that using reverse() requires that your urlconf module is 100% error free and can be processed - iow no ViewDoesNotExist errors or so, or you get the dreaded NoReverseMatch exception (errors in templates usually fail silently resulting in None). A: I'm using two different approaches in my models.py. The first is the permalink decorator: from django.db.models import permalink def get_absolute_url(self): """Construct the absolute URL for this Item.""" return ('project.app.views.view_name', [str(self.id)]) get_absolute_url = permalink(get_absolute_url) You can also call reverse directly: from django.core.urlresolvers import reverse def get_absolute_url(self): """Construct the absolute URL for this Item.""" return reverse('project.app.views.view_name', None, [str(self.id)])
{ "language": "en", "url": "https://stackoverflow.com/questions/43290", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "36" }
Q: Setting Variable Types in PHP I know that I can do something like $int = (int)99; //(int) has a maximum or 99 To set the variable $int to an integer and give it a value of 99. Is there a way to set the type to something like LongBlob in MySQL for LARGE Integers in PHP? A: No. PHP does what is called automatic type conversion. In your example $int = (int)123; the "(int)" just assures that at that exact moment 123 will be handled as an int. I think your best bet would be to use a class to provide some sort of type safety. A: No, the type LongBlob is specific to MySQL. In PHP it is seen as binary data (usually characters), if you tried to convert it to an int it would take the first 32 bits of data (platform dependent) and push that into the variable.
{ "language": "en", "url": "https://stackoverflow.com/questions/43291", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Can I write native iPhone apps using Python? Using PyObjC, you can use Python to write Cocoa applications for OS X. Can I write native iPhone apps using Python and if so, how? A: You can use PyObjC on the iPhone as well, due to the excellent work by Jay Freeman (saurik). See iPhone Applications in Python. Note that this requires a jailbroken iPhone at the moment. A: The iPhone SDK agreement is also rather vague about whether you're even allowed to run scripting languages (outside of a WebView's Javascript). My reading is that it is OK - as long as none of the scripts you execute are downloaded from the network (so pre-installed and user-edited scripts seem to be OK). IANAL etc etc. A: Not currently, currently the only languages available to access the iPhone SDK are C/C++, Objective C and Swift. There is no technical reason why this could not change in the future but I wouldn't hold your breath for this happening in the short term. That said, Objective-C and Swift really are not too scary... 2016 edit Javascript with NativeScript framework is available to use now. A: BeeWare is an open source framework for authoring native iOS & Android apps. A: 2019 Update: While Python-iOS development is relatively immature and likely will prevent (afaik) your app from having native UI and functionality that could be achieved in an Apple-supported development language, Apple now seems to allow embedding Python interpreters in Native Swift/Obj-C apps. This supports importing Python libraries and running Python scripts (even with supplied command-line arguments) directly from your Native Swift/Obj-C code. My company is actually wrapping our infrastructure (originally written in Python) in a native iOS application! It works very well and communication between the parts can be easily achieved via a client-server model. Here is a nice library by Beeware with a cookiecutter template if you want to try and run Python scripts in your iOS app: https://github.com/beeware/Python-Apple-support/tree/3.6. A: It seems this is now something developers are allowed to do: the iOS Developer Agreement was changed yesterday and appears to have been ammended in a such a way as to make embedding a Python interpretter in your application legal: SECTION 3.3.2 — INTERPRETERS Old: 3.3.2 An Application may not itself install or launch other executable code by any means, including without limitation through the use of a plug-in architecture, calling other frameworks, other APIs or otherwise. Unless otherwise approved by Apple in writing, no interpreted code may be downloaded or used in an Application except for code that is interpreted and run by Apple’s Documented APIs and built-in interpreter(s). Notwithstanding the foregoing, with Apple’s prior written consent, an Application may use embedded interpreted code in a limited way if such use is solely for providing minor features or functionality that are consistent with the intended and advertised purpose of the Application. New: 3.3.2 An Application may not download or install executable code. Interpreted code may only be used in an Application if all scripts, code and interpreters are packaged in the Application and not downloaded. The only exception to the foregoing is scripts and code downloaded and run by Apple’s built-in WebKit framework. A: Yes you can. You write your code in tinypy (which is restricted Python), then use tinypy to convert it to C++, and finally compile this with XCode into a native iPhone app. Phil Hassey has published a game called Elephants! using this approach. Here are more details, http://www.philhassey.com/blog/2009/12/23/elephants-is-free-on-the-app-store/ A: Yes, nowadays you can develop apps for iOS in Python. There are two frameworks that you may want to checkout: Kivy and PyMob. Please consider the answers to this question too, as they are more up-to-date than this one. A: An update to the iOS Developer Agreement means that you can use whatever you like, as long as you meet the developer guidelines. Section 3.3.1, which restricted what developers could use for iOS development, has been entirely removed. Source: http://daringfireball.net/2010/09/app_store_guidelines A: Pythonista has an Export to Xcode feature that allows you to export your Python scripts as Xcode projects that build standalone iOS apps. https://github.com/ColdGrub1384/Pyto is also worth looking into. A: Technically, as long as the interpreted code ISN'T downloaded (excluding JavaScript), the app may be approved. Rhomobiles "Rhodes" framework does just that, bundling mobile Ruby, a lightweight version of Rails, and your app for distribution via the app-store. Because both the interpreter and the interpreted code are packaged into the final application - Apple doesn't find it objectionable. http://rhomobile.com/products/rhodes/ Even after the latest apple press release - rhodes apps (mobile ruby) are still viable on the app-store. I'd find it hard to believe that tinyPy or pyObjC wouldn't find a place if there is a willing developer community. A: You can do this with PyObjC, with a jailbroken phone of course. But if you want to get it into the App Store, they will not allow it because it "interprets code." However, you may be able to use Shed Skin, although I'm not aware of anyone doing this. I can't think of any good reason to do this though, as you lose dynamic typing, and might as well use ObjC. A: The only significant "external" language for iPhone development that I'm aware of with semi-significant support in terms of frameworks and compatibility is MonoTouch, a C#/.NET environment for developing on the iPhone. A: I think it was not possible earlier but I recently heard about PyMob, which seems interesting because the apps are written in Python and the final outputs are native source codes in various platforms (Obj-C for iOS, Java for Android etc). This is certainly quite unique. This webpage explains it in more detail. I haven't given it a shot yet, but will take a look soon.
{ "language": "en", "url": "https://stackoverflow.com/questions/43315", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "96" }
Q: NHibernate ISession Flush: Where and when to use it, and why? One of the things that get me thoroughly confused is the use of session.Flush,in conjunction with session.Commit, and session.Close. Sometimes session.Close works, e.g., it commits all the changes that I need. I know I need to use commit when I have a transaction, or a unit of work with several creates/updates/deletes, so that I can choose to rollback if an error occurs. But sometimes I really get stymied by the logic behind session.Flush. I have seen examples where you have a session.SaveOrUpdate() followed by a flush, but when I remove Flush it works fine anyway. Sometimes I run into errors on the Flush statement saying that the session timed out, and removing it made sure that I didn't run into that error. Does anyone have a good guideline as to where or when to use a Flush? I've checked out the NHibernate documentation for this, but I still can't find a straightforward answer. A: Briefly: * *Always use transactions *Don't use Close(), instead wrap your calls on an ISession inside a using statement or manage the lifecycle of your ISession somewhere else. From the documentation: From time to time the ISession will execute the SQL statements needed to synchronize the ADO.NET connection's state with the state of objects held in memory. This process, flush, occurs by default at the following points * *from some invocations of Find() or Enumerable() *from NHibernate.ITransaction.Commit() *from ISession.Flush() The SQL statements are issued in the following order * *all entity insertions, in the same order the corresponding objects were saved using ISession.Save() *all entity updates *all collection deletions *all collection element deletions, updates and insertions *all collection insertions *all entity deletions, in the same order the corresponding objects were deleted using ISession.Delete() (An exception is that objects using native ID generation are inserted when they are saved.) Except when you explicity Flush(), there are absolutely no guarantees about when the Session executes the ADO.NET calls, only the order in which they are executed. However, NHibernate does guarantee that the ISession.Find(..) methods will never return stale data; nor will they return the wrong data. It is possible to change the default behavior so that flush occurs less frequently. The FlushMode class defines three different modes: only flush at commit time (and only when the NHibernate ITransaction API is used), flush automatically using the explained routine, or never flush unless Flush() is called explicitly. The last mode is useful for long running units of work, where an ISession is kept open and disconnected for a long time. ... Also refer to this section: Ending a session involves four distinct phases: * *flush the session *commit the transaction *close the session *handle exceptions Flushing the Session If you happen to be using the ITransaction API, you don't need to worry about this step. It will be performed implicitly when the transaction is committed. Otherwise you should call ISession.Flush() to ensure that all changes are synchronized with the database. Committing the database transaction If you are using the NHibernate ITransaction API, this looks like: tx.Commit(); // flush the session and commit the transaction If you are managing ADO.NET transactions yourself you should manually Commit() the ADO.NET transaction. sess.Flush(); currentTransaction.Commit(); If you decide not to commit your changes: tx.Rollback(); // rollback the transaction or: currentTransaction.Rollback(); If you rollback the transaction you should immediately close and discard the current session to ensure that NHibernate's internal state is consistent. Closing the ISession A call to ISession.Close() marks the end of a session. The main implication of Close() is that the ADO.NET connection will be relinquished by the session. tx.Commit(); sess.Close(); sess.Flush(); currentTransaction.Commit(); sess.Close(); If you provided your own connection, Close() returns a reference to it, so you can manually close it or return it to the pool. Otherwise Close() returns it to the pool. A: Starting in NHibernate 2.0, transactions are required for DB operations. Therefore, the ITransaction.Commit() call will handle any necessary flushing. If for some reason you aren't using NHibernate transactions, then there will be no auto-flushing of the session. A: From time to time the ISession will execute the SQL statements needed to synchronize the ADO.NET connection's state with the state of objects held in memory. And always use using (var transaction = session.BeginTransaction()) { transaction.Commit(); } after the changes are committed than this changes to save into database we use transaction.Commit(); A: Here are two examples of my code where it would fail without session.Flush(): http://www.lucidcoding.blogspot.co.uk/2012/05/changing-type-of-entity-persistence.html at the end of this, you can see a section of code where I set identity insert on, save the entity then flush, then set identity insert off. Without this flush it seemed to be setting identity insert on and off then saving the entity. The use of Flush() gave me more control over what was going on. Here is another example: Sending NServiceBus message inside TransactionScope I don't fully understand why on this one, but Flush() prevented my error from happening.
{ "language": "en", "url": "https://stackoverflow.com/questions/43320", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "189" }
Q: Worth switching to zsh for casual use? The default shell in Mac OS X is bash, which I'm generally happy to be using. I just take it for granted. It would be really nice if it auto-completed more stuff, though, and I've heard good things about zsh in this regard. But I don't really have the inclination to spend hours fiddling with settings to improve my command line usage by a tiny amount, since my life on the command line isn't that bad. (As I understand it, bash can also be configured to auto-complete more cleverly. It's the configuring I'm not all that keen on.) Will switching to zsh, even in a small number cases, make my life easier? Or is it only a better shell if you put in the time to learn why it's better? (Examples would be nice, too :) ) @Rodney Amato & @Vulcan Eager give two good reasons to respectively stick to bash and switch to zsh. Looks like I'll have to investigate both! Oh well :) Is there anyone with an opinion from both sides of the argument? A: Personally, I love zsh. Generally, you probably won't notice the difference between it and bash, until you want to quickly do things like recursive globbing: * ***/*.c for example. Or use suffix aliases to associate specific progs with different suffixes, so that you can "execute" them directly. The below alias lets you "run" a C source file at the prompt by simply typing ./my_program.c – which will work exactly as if you typed vim ./my_program.c. (Sort of the equivalent to double clicking on the icon of a file.) * *alias -s c=vim Or print the names of files modified today: * *print *(e:age today now:) You can probably do all of these things in bash, but my experience with zsh is that if there's something I want to do, I can probably find it in zsh-lovers. I also find the book 'From Bash to Z-Shell' really useful. Playing with the mind bogglingly large number of options is good fun too! A: For casual use you are probably better off sticking with bash and just installing bash completion. Installing it is pretty easy, grab the bash-completion-20060301.tar.gz from http://www.caliban.org/bash/index.shtml#completion and extract it with tar -xzvf bash-completion-20060301.tar.gz then copy the bash_completion/bash_completion file to /etc with sudo cp bash_completion/bash_completion /etc which will prompt you for your password. You probably will want to make a /etc/bash_completion.d directory for any additional completion scripts (for instance I have the git completion script in there). Once this is done the last step is to make sure the .bash_profile file in your home directory has if [ -f /etc/bash_completion ]; then . /etc/bash_completion fi in it to load the completion file when you login. To test it just open a new terminal, and try completing on cvs and it should show you the cvs options in the list of completions. A: zsh has a console gui configuration thing. You can set it up pretty quickly and easily without having to fiddle with configuration files. I don't think you will need much time to set it up, probably 10 seconds with just using defaults, so go ahead and try it out. A: Switch to zsh. You will have access to: * *zmv: You can do: zmv '(*).mp3' '$1.wma' for thousands of files. *zcalc: Extremely comfortable calculator, better than bc. *zparseopts: One-liner for parsing arbitrary complex options given to your script. *autopushd: You can always do popd after cd to change back to your previous directory. *Floating point support. It is needed from time to time. *Hashes support. Sometimes they are just a key feature. A: Staale is talking about a wizard like program (CUI) which autoruns the first time you run zsh. Just answer some questions, view/change the defaults and its configured for you. IBM developerWorks has great resources on zsh. I have not used very advanced features and so far I have not come across serious differences which should hamper someone coming from bash. Some examples: * *!?pattern<Tab> will autocomplete to the last command in history matching pattern. Very useful. *You can configure a prompt on the RHS. One use is to keep a fixed width prompt on the left hand side so all commands line up nicely while displaying the pwd (or anything of variable width) as the right hand side prompt. *You can redirect input from multiple files (yet to try this): cat < file1 < file2 < file3 A: If all you want to use ZSH for is better completion, the configuration is pretty easy. Place this in your ~/.zshrc: autoload -U zutil # [1] autoload -U compinit # [2] autoload -U complist # [3] compinit However, it's worth checking out all the other great features of the ZSH. The above example will give you a pretty plain prompt with good completion. If you don't want to fiddle with configurations, but want to see what ZSH can do for you, Google for "zshrc" and you will get some ready to use configurations to get started. * *[1]: http://zsh.sourceforge.net/Doc/Release/Zsh-Modules.html#The-zsh_002fzutil-Module *[2]: http://zsh.sourceforge.net/Doc/Release/Completion-System.html#Initialization *[3]: http://zsh.sourceforge.net/Doc/Release/Zsh-Modules.html#The-zsh_002fcomplist-Module
{ "language": "en", "url": "https://stackoverflow.com/questions/43321", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "193" }
Q: What's safe for a C++ plug-in system? Plug-in systems in C++ are hard because the ABI is not properly defined, and each compiler (or version thereof) follows its own rules. However, COM on Windows shows that it's possible to create a minimal plug-in system that allows programmers with different compilers to create plug-ins for a host application using a simple interface. Let's be practical, and leave the C++ standard, which is not very helpful in this respect, aside for a minute. If I want to write an app for Windows and Mac (and optionally Linux) that supports C++ plug-ins, and if I want to give plug-in authors a reasonably large choice of compilers (say less than 2 year old versions of Visual C++, GCC or Intel's C++ compiler), what features of C++ could I count on? Of course, I assume that plug-ins would be written for a specific platform. Off the top of my head, here are some C++ features I can think of, with what I think is the answer: * *vtable layout, to use objects through abstract classes? (yes) *built-in types, pointers? (yes) *structs, unions? (yes) *exceptions? (no) *extern "C" functions? (yes) *stdcall non-extern "C" functions with built-in parameter types? (yes) *non-stdcall non-extern "C" functions with user-defined parameter types? (no) I would appreciate any experience you have in that area that you could share. If you know of any moderately successful app that has a C++ plug-in system, that's cool too. Carl A: You might also want to consider replacing the conventional plugin interface by a scripting interface. There are some very good bindings for several scripting languages in C/C++ that have already solved your problem. It might not be a bad idea to build on top of them. For example, have a look at Boost.Python. A: Qt has a very nice system for plugins that I've used in the past. It uses Qt's meta-object system to overcome many of the problems typically found when trying to develop C++ plugins. One example is how Q_DECLARE_INTERFACE works, to prevent you from using an incompatible plugin. Another is the build key, to make sure you load the correct plugin for your architecture, OS, compiler. If you don't use Qt's plugin system, these are things you will have to worry about and invent solutions for on your own. It's not necessarily rocket science, and I'm not saying you'd fail at it, but the guys at Trolltech are pretty smart and have spent a while thinking about it, and I'd rather use what they created than reinvent the wheel myself. Another example is that RTTI typically doesn't work across DLL boundaries, but when using Qt, things like qobject_cast which rely on the meta-object system do work across DLL boundaries. A: I think you are safe creating a plugin system based on: * *Packaging of plugin functionality into library (.dll, .so, etc.) *Requiring that the plugin expose key C-language exports. *Requiring that the plugin implement (and return a pointer/reference to) an abstract C++ interface. Probably the most successful C++ plugin system: good old Adobe Photoshop. And if not that, one of the virtual synth formats such as VSTi etc. A: The book Imperfect C++ by Matthew Wilson has a nice info about this. The advice in the seems to be: as long as you use the same (or equivelant) compiler, you can use C++, otherwise you're better of using C as an interface on top of your C++ code. A: Dr Dobb's Journal has an article Building Your Own Plugin Framework: Part 1 which is pretty good reading on the subject. It is the start of a series of articles which covers the architecture, development, and deployment of a C/C++ cross-platform plugin framework. A: I have my own game engine that has a C++ plug-in system. I have some code in header files so it gets put into the plugin's compilation unit. Larger functions that live in the main engine are called via an exported C function (plugin calls MyObject_somefunction(MyObject *obj) which in the engine just calls obj->somefunction()). If calling a C function is ugly for your taste, then with some header trickery, when the header is included in the plugin, have the member function #defined to call the C function: #if defined(IN_THE_PLUGIN) void MyObject::somefunction() { MyObject_somefunction(this); } #endif Virtual functions either have to be pure or the code lives in the header file. If I'm not inheriting from a class and merely just instancing one, virtual function code can live in the engine, but then the class must export some C functions for creating and destroying the object that is called from the plugin. Basically, the tricks that I have used, with the goal being to maintain total platform independence, just amount to C exports and header file tricks. A: ACE has a cross platform plug-in architecture. Check out: * *ACE DLL *ACE DLL Manager I would suggest checking out the book The ACE Programmer's Guide A: Firefox runs on XPCOM (http://www.mozilla.org/projects/xpcom/). It's inspired by Microsoft COM but it's multiplatform.
{ "language": "en", "url": "https://stackoverflow.com/questions/43322", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "48" }
Q: Can I put an ASP.Net session ID in a hidden form field? I'm using the Yahoo Uploader, part of the Yahoo UI Library, on my ASP.Net website to allow users to upload files. For those unfamiliar, the uploader works by using a Flash applet to give me more control over the FileOpen dialog. I can specify a filter for file types, allow multiple files to be selected, etc. It's great, but it has the following documented limitation: Because of a known Flash bug, the Uploader running in Firefox in Windows does not send the correct cookies with the upload; instead of sending Firefox cookies, it sends Internet Explorer’s cookies for the respective domain. As a workaround, we suggest either using a cookieless upload method or appending document.cookie to the upload request. So, if a user is using Firefox, I can't rely on cookies to persist their session when they upload a file. I need their session because I need to know who they are! As a workaround, I'm using the Application object thusly: Guid UploadID = Guid.NewGuid(); Application.Add(Guid.ToString(), User); So, I'm creating a unique ID and using it as a key to store the Page.User object in the Application scope. I include that ID as a variable in the POST when the file is uploaded. Then, in the handler that accepts the file upload, I grab the User object thusly: IPrincipal User = (IPrincipal)Application[Request.Form["uploadid"]]; This actually works, but it has two glaring drawbacks: * *If IIS, the app pool, or even just the application is restarted between the time the user visits the upload page, and actually uploads a file, their "uploadid" is deleted from application scope and the upload fails because I can't authenticate them. *If I ever scale to a web farm (possibly even a web garden) scenario, this will completely break. I might not be worried, except I do plan on scaling this app in the future. Does anyone have a better way? Is there a way for me to pass the actual ASP.Net session ID in a POST variable, then use that ID at the other end to retrieve the session? I know I can get the session ID through Session.SessionID, and I know how to use YUI to post it to the next page. What I don't know is how to use that SessionID to grab the session from the state server. Yes, I'm using a state server to store the sessions, so they persist application/IIS restarts, and will work in a web farm scenario. A: Here is a post from the maintainer of SWFUpload which explains how to load the session from an ID stored in Request.Form. I imagine the same thing would work for the Yahoo component. Note the security disclaimers at the bottom of the post. By including a Global.asax file and the following code you can override the missing Session ID cookie: using System; using System.Web; public class Global_asax : System.Web.HttpApplication { private void Application_BeginRequest(object sender, EventArgs e) { /* Fix for the Flash Player Cookie bug in Non-IE browsers. Since Flash Player always sends the IE cookies even in FireFox we have to bypass the cookies by sending the values as part of the POST or GET and overwrite the cookies with the passed in values. The theory is that at this point (BeginRequest) the cookies have not been ready by the Session and Authentication logic and if we update the cookies here we'll get our Session and Authentication restored correctly */ HttpRequest request = HttpContext.Current.Request; try { string sessionParamName = "ASPSESSID"; string sessionCookieName = "ASP.NET_SESSIONID"; string sessionValue = request.Form[sessionParamName] ?? request.QueryString[sessionParamName]; if (sessionValue != null) { UpdateCookie(sessionCookieName, sessionValue); } } catch (Exception ex) { // TODO: Add logging here. } try { string authParamName = "AUTHID"; string authCookieName = FormsAuthentication.FormsCookieName; string authValue = request.Form[authParamName] ?? request.QueryString[authParamName]; if (authValue != null) { UpdateCookie(authCookieName, authValue); } } catch (Exception ex) { // TODO: Add logging here. } } private void UpdateCookie(string cookieName, string cookieValue) { HttpCookie cookie = HttpContext.Current.Request.Cookies.Get(cookieName); if (cookie == null) { HttpCookie newCookie = new HttpCookie(cookieName, cookieValue); Response.Cookies.Add(newCookie); } else { cookie.Value = cookieValue; HttpContext.Current.Request.Cookies.Set(cookie); } } } Security Warning: Don't just copy and paste this code in to your ASP.Net application without knowing what you are doing. It introduces security issues and possibilities of Cross-site Scripting. A: Relying on this blog post, here's a function that should get you the session for any user based on the session ID, though it's not pretty: public SessionStateStoreData GetSessionById(string sessionId) { HttpApplication httpApplication = HttpContext.ApplicationInstance; // Black magic #1: getting to SessionStateModule HttpModuleCollection httpModuleCollection = httpApplication.Modules; SessionStateModule sessionHttpModule = httpModuleCollection["Session"] as SessionStateModule; if (sessionHttpModule == null) { // Couldn't find Session module return null; } // Black magic #2: getting to SessionStateStoreProviderBase through reflection FieldInfo fieldInfo = typeof(SessionStateModule).GetField("_store", BindingFlags.NonPublic | BindingFlags.Instance); SessionStateStoreProviderBase sessionStateStoreProviderBase = fieldInfo.GetValue(sessionHttpModule) as SessionStateStoreProviderBase; if (sessionStateStoreProviderBase == null) { // Couldn't find sessionStateStoreProviderBase return null; } // Black magic #3: generating dummy HttpContext out of the thin air. sessionStateStoreProviderBase.GetItem in #4 needs it. SimpleWorkerRequest request = new SimpleWorkerRequest("dummy.html", null, new StringWriter()); HttpContext context = new HttpContext(request); // Black magic #4: using sessionStateStoreProviderBase.GetItem to fetch the data from session with given Id. bool locked; TimeSpan lockAge; object lockId; SessionStateActions actions; SessionStateStoreData sessionStateStoreData = sessionStateStoreProviderBase.GetItem( context, sessionId, out locked, out lockAge, out lockId, out actions); return sessionStateStoreData; } A: You can get your current SessionID from the following code: string sessionId = HttpContext.Current.Session.SessionID; Then you can feed that into a hidden field maybe and then access that value through YUI. It's just a get, so you hopefully won't have any scaling problems. Security-problems though, that I don't know. A: The ASP.Net Session ID is stored in Session.SessionID so you could set that in a hidden field and then post it to the next page. I think, however, that if the application restarts, the sessionID will expire if you do not store your sessions in sql server.
{ "language": "en", "url": "https://stackoverflow.com/questions/43324", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: What are options available to get cron's results and how to set them up? I know that default cron's behavior is to send normal and error output to cron's owner local email box. Is there other ways to get theses results (for example to send it by email to a bunch of people, to store them somewhere, and so on) ? A: To email the output to a different email address just add the line MAILTO="[email protected]" To the crontab before the command A: You could chuck file redirection onto either the command shown or the actual command in the crontab for both stdout and stderr - like command > /tmp/log.txt 2>&1 . If you want several users to receive this log, you could insert a MAILTO=nameofmailinglist at the top of you cron file. A: The cron line is just like any other unix command line so you can redirect output to another program. Ie. * * * * * /path/my/command > /my/email/script 2&>1 A: This may be an unnecessary addition, but to qualify the redirection commands: > redirects standard output 2 is a Bourne shell specific term that means standard error 1 is a Bourne shell specific term that means standard output 2>&1 means redirect the standard error to standard output Also see the following useful article Standard Input and Output Redirection A: As far as I see it you've got three options: * *Redirect the output: either to a file, or to a program that will email the results as you want them *Use MAILTO in cron, and redirect the email to any other single address for all your cron jobs. *Do the redirection in your mail server or client, after cron has sent it.
{ "language": "en", "url": "https://stackoverflow.com/questions/43349", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: How do you reference a bitmap on the stage in actionscript? How do you reference a bitmap on the stage in flash using actionscript 3? I have a bitmap on the stage in flash and at the end of the movie I would like to swap it out for the next in the sequence before the movie loops. in my library i have 3 images, exported for actionscript, with the class name img1/img2/img3. here is how my layers in flash are set out. layer 5 : mask2:MovieClip layer 4 : img2:Bitmap layer 3 : mask1:MovieClip layer 2 : img1:Bitmap layer 1 : background:Bitmap at the end of the movie I would like to swap img1 with img2, so the movie loops seamlessly, then ideally swap img2 (on layer 4) with img3 and so on until I get to the end of my images. but I can not find out how to reference the images that have already been put on the stage (in design time), any one have any idea of how to do this? The end movie will hopefully load images dynamically from the web server (I have the code for this bit) and display them as well as img1/img2/img3. Any help would be appreciated. EDIT: @81bronco , I tried this but the instance name is greyed out for graphics, it will only allow me to do it with movieclips and buttons. I half got it to work by turning them into moveclips, and clearing the images in the moveclip out before adding a new one (using something simpler to what vanhornRF suggested), but for some odd reason when the mask kicks in the images I cleared out come back for the mask animation. A: To reference something on the stage, you need to give the stage instance a name - not give the symbol in the library a class name. Click on the item on the stage and look at the properties panel. There should be a text entry box just above the entry boxes for the item's dimensions. Enter a name there. Elsewhere in your code, you can then refer to that item on stage by it's instance name. A: It should be something like this: imageHolder.removeChild( imageIndex ) or imageHolder.removeChildByName( imageName ) and after that imageHolder.addChild( newImage ) A: I would probably do something like this in your document class for(var i:int=0; i<numChildren; i++){ trace(getChildAt(i),"This is the child at position "+i); } I do this because I still code in the flash IDE and its debugger is so very painful to get working most of the time it's easier to just trace variables out, so you can either use that for loop to print the object names of the items currently on your stage, or use a debugger program to find the objects as well. Now that you have the children and at what index they actually are at within the stage, you can reference them by calling getChildAt(int), you can removeChildAt(int), you can addChildAt(displayObject, int) and swapChildrenAt(int, int). The int in these arguments would represent the index position that was returned by your trace statement and the displayObject would obviously just represent anything you wanted to add to the stage or parent DisplayObject. Using those 4 commands you should be able to freely re-arrange any movieclips you have on stage so that they will appear to transition seamlessly. @81bronco One should definitely name your assets on stage if you want to uniquely reference them specifically to avoid any confusion if there ends up being a lot of items on stage A: Hey Re0sless, when you remove those items from the stage do they have any event listeners attached to them, any timers or loaders? Any of those things can make an object stick around in flash's memory and not remove properly. Also on top of just removing the item, perhaps try nulling it as well? Sometimes that helps in clearing out its references so it can be properly destroyed. Of course it could also be something silly like removing the item at one instance doesn't remove the item from future frames as well, but I really don't think that's the case.
{ "language": "en", "url": "https://stackoverflow.com/questions/43354", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: A python web application framework for tight DB/GUI coupling? I'm a firm believer of the heretic thought of tight coupling between the backend and frontend: I want existing, implied knowledge about a backend to be automatically made use of when generating user interfaces. E.g., if a VARCHAR column has a maximum with of 20 characters, there GUIs should automatically constrain the user from typing more than 20 characters in a related form field. And I have strong antipathy to ORMs which want to define my database tables, or are based on some hack where every table needs to have extra numeric ID columns because of the ORM. I've looked a bit into Python database frameworks and I think I can conclude the SQLAlchemy fits best to my mentality. Now, I need to find a web application framework which fits naturally with SQLAlchemy (or an equivalent) and perhaps even with my appetite for coupling. With "web application framework", I mean products/project such as Pyhons, Django, TurboGears, web2py, etc. E.g., it should ideally be able to: * *automatically select a suitable form widget for data entering a given column if told to do so; e.g., if the column has a foreign key to a column with 10 different values, widget should display the 10 possible values as a dropdown *auto-generate javascript form validation code which gives the end-user quick error feedback if a string is entered into a field which is about to end up in an INTEGER column, etc *auto-generate a calendar widget for data which will end up in a DATE column *hint NOT NULL constraints as javascript which complains about empty or whitespace-only data in a related input field *generate javascript validation code which matches relevant (simple) CHECK-constraints *make it easy to avoid SQL injection, by using prepared statements and/or validation of externally derived data *make it easy to avoid cross site scripting by automatically escape outgoing strings when appropriate *make use of constraint names to generate somewhat user friendly error messages in case a constrataint is violated All this should happen dynamically, so table adjustments are automatically reflected on the frontend - probably with a caching mechanism, so that all the model introspection wouldn't kill performance. In other words, I don't want to repeat my model definition in an XML file (or alike) when it has already been carefully been defined in my database. Does such a framework exist for Python (or for any language, for that matter)? If not: Which of the several Python web application frameworks will be least in the way if I were to add parts of the above features myself? A: web2py does most of what you ask: Based on a field type and its validators it will render the field with the appropriate widget. You can override with db.table.field.widget=... and use a third party widget. web2py has js to blocks the user from entering a non-integer in a integer field or a non-double in a double field. time, date and datetime fields have their own pickers. These js validation work with (not instead) of server side validation. There is IS_EMPTY_OR(...) validator. The DAL prevents SQL injections since everthing is escaped when goes in the DB. web2py prevents XSS because in {{=variable}}, 'variable' is escaped unless specified otherwise {{=XML(variable)}} or {{=XML(variable,sanitize=True)}} Error messages are arguments of validators for example db.table.field.requires=IS_NOT_EMPTY(error_message=T('hey! write something in here')) T is for internationalization. A: You should have a look at django and especially its newforms and admin modules. The newforms module provides a nice possibility to do server side validation with automated generation of error messages/pages for the user. Adding ajax validation is also possible A: I believe that Django models does not support composite primary keys (see documentation). But perhaps you can use SQLAlchemy in Django? A google search indicates that you can. I have not used Django, so I don't know. I suggest you take a look at: * *ToscaWidgets *DBSprockets, including DBMechanic *Catwalk. Catwalk is an application for TurboGears 1.0 that uses SQLObject, not SQLAlchemy. Also check out this blog post and screencast. *FastData. Also uses SQLObject. *formalchemy *Rum I do not have any deep knowledge of any of the projects above. I am just in the process of trying to add something similar to one of my own applications as what the original question mentions. The above list is simply a list of interesting projects that I have stumbled across. As to web application frameworks for Python, I recommend TurboGears 2. Not that I have any experience with any of the other frameworks, I just like TurboGears... If the original question's author finds a solution that works well, please update or answer this thread. A: TurboGears currently uses SQLObject by default but you can use it with SQLAlchemy. They are saying that the next major release of TurboGears (1.1) will use SQLAlchemy by default. A: I know that you specificity ask for a framework but I thought I would let you know about what I get up to here. I have just undergone converting my company's web application from a custom in-house ORM layer into sqlAlchemy so I am far from an expert but something that occurred to me was that sqlAlchemy has types for all of the attributes it maps from the database so why not use that to help output the right html onto the page. So we use sqlAlchemy for the back end and Cheetah templates for the front end but everything in between is basically our own still. We have never managed to find a framework that does exactly what we want without compromise and prefer to get all the bits that work right for us and write the glue our selves. Step 1. For each data type sqlAlchemy.types.INTEGER etc. Add an extra function toHtml (or many maybe toHTMLReadOnly, toHTMLAdminEdit whatever) and just have that return the template for the html, now you don't even have to care what data type your displaying if you just want to spit out a whole table you can just do (as a cheetah template or what ever your templating engine is). Step 2 <table> <tr> #for $field in $dbObject.c: <th>$field.name</th> #end for </tr> <tr> #for $field in dbObject.c: <td>$field.type.toHtml($field.name, $field.value)</td> #end for </tr> </table> Using this basic method and stretching pythons introspection to its potential, in an afternoon I managed to make create read update and delete code for our whole admin section of out database, not yet with the polish of django but more then good enough for my needs. Step 3 Discovered the need for a third step just on Friday, wanted to upload files which as you know needs more then just the varchar data types default text box. No sweat, I just overrode the rows class in my table definition from VARCHAR to FilePath(VARCHAR) where the only difference was FilePath had a different toHtml method. Worked flawlessly. All that said, if there is a shrink wrapped one out there that does just what you want, use that. Disclaimer: This code was written from memory after midnight and probably wont produce a functioning web page.
{ "language": "en", "url": "https://stackoverflow.com/questions/43368", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Is there a better way of writing a git pre-commit hook to check any php file in a commit for parse errors? What I have so far is #!/bin/sh php_syntax_check() { retval=0 for i in $(git-diff-index --name-only --cached HEAD -- | grep -e '\.php$'); do if [ -f $i ]; then output=$(php -l $i) retval=$? if [ $retval -gt 0 ]; then echo "==============================================================================" echo "Unstaging $i for the commit due to the follow parse errors" echo "$output" git reset -q HEAD $i fi fi done if [ $retval -gt 0 ]; then exit $retval fi } php_syntax_check A: I'm sorry if it's offtopic, but aren't you supposed to run some kind of automated tests (which would imply that the code has no syntax errors) before doing a commit? A: If the commit is a partial commit (not all the changes in the working tree are committed), then this make give incorrect results since it tests the working copy and not the staged copy. One way to do this could be: git diff --cached --name-only --diff-filter=ACMR | xargs git checkout-index --prefix=$TMPDIR/ -- find $TMPDIR -name '*.php' -print | xargs -n 1 php -l Which would make a copy of the staged images into a scratch space and then run the test command on them there. If any of the files include other files in the build then you may have to recreate the whole staged image in the test tree and then test the changed files there (See: Git pre-commit hook : changed/added files). A: If you've got the php5-cli installed you can write your pre-commit in PHP and use the syntax your more familiar with. Just do something more like. #!/usr/bin/php <?php /* Your pre-commit check. */ ?> A: My PHP implementation of the pre-commit hook checks whether the modified files in git are 'error free' and are as per PSR2 standard using either 'php-code-sniffer' or 'php-cs-fixer' #!/usr/local/bin/php <?php /** * Collect all files which have been added, copied or * modified and store them in an array - output */ exec('git diff --cached --name-only --diff-filter=ACM', $output); $isViolated = 0; $violatedFiles = array(); // $php_cs_path = "/usr/local/bin/php-cs-fixer"; $php_cs_path = "~/.composer/vendor/bin/phpcs"; foreach ($output as $fileName) { // Consider only PHP file for processing if (pathinfo($fileName, PATHINFO_EXTENSION) == "php") { $psr_output = array(); // Put the changes to be made in $psr_output, if not as per PSR2 standard // php-cs-fixer // exec("{$php_cs_path} fix {$fileName} --rules=@PSR2 --dry-run --diff", $psr_output, $return); // php-code-sniffer exec("{$php_cs_path} --standard=PSR2 --colors -n {$fileName}", $psr_output, $return); if ($return != 0) { $isViolated = 1; $violatedFiles[] = $fileName; echo implode("\n", $psr_output), "\n"; } } } if ($isViolated == 1) { echo "\n---------------------------- IMPORTANT --------------------------------\n"; echo "\nPlease use the suggestions above to fix the code in the following file: \n"; echo " => " . implode("\n => ", $violatedFiles); echo "\n-----------------------------------------------------------------------\n\n\n"; exit(1); } else { echo "\n => Committed Successfully :-)\n\n"; exit(0); }
{ "language": "en", "url": "https://stackoverflow.com/questions/43374", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Best practices for querying with NHibernate I've come back to using NHibernate after using other technologies (CSLA and Subsonic) for a couple of years, and I'm finding the querying a bit frustrating, especially when compared to Subsonic. I was wondering what other approaches people are using? The Hibernate Query Language doesn't feel right to me, seems too much like writing SQL, which to my mind is one of the reason to use an ORM tools so I don't have to, furthermore it's all in XML, which means it's poor for refactoring, and errors will only be discovered at runtime? Criteria Queries, don't seem fluid enough. I've read that Ayende's NHibernate Query Generator, is a useful tool, is this what people are using? What else is out there? EDIT: Worth a read http://www.ayende.com/Blog/archive/2007/03/17/Implementing-Linq-for-NHibernate-A-How-To-Guide--Part.aspx A: The thing with LINQ for NHibernate is still in beta; I'm looking forward to NHibernate 2.1, where they say it will finally make the cut. I made a presentation on LINQ for NHibernate around a month ago, you might find it useful. I blogged about it here, including slides and code: LINQ for NHibernate: O/R Mapping in Visual Studio 2008 Slides and Code A: To rid yourself of the XML, try Fluent NHibernate Linq2NH isn't fully baked yet. The core team is working on a different implementation than the one in NH Contrib. It works fine for simple queries though. Use sparingly if at all for best results. As for how to query (hql vs. Criteria vs. Linq2NH), expose intention-revealing methods (GetProductsForOrder(Order order), GetCustomersThatPurchasedProduct(Product product), etc) on your repository interface and implement them in the best way. Simple queries may be easier with hql, while using the specification pattern you may find the Criteria API to be a better fit. That stuff just stays encapsulated in your repository, and if your tests pass it doesn't much matter how you implement. I've found that the Criteria API is cumbersome and limiting but flexible. HQL is more my style (and it's better than SQL - it's object based, not schema based) and seems to work better for me for simple GetX methods.. A: I use Linq for NHibernate by default. When I hit bugs or limitations, I switch to HQL. It's a clean approach if you keep all your queries together in a data access class, such as a Repository. public class CustomerRepostitory() { //LINQ for NHibernate public Customer[] FindCustomerByEmail(string email) { return (from c in _session.Linq<Customer>() where c.Email == email).FirstOrDefault(); } //HQL public Customer[] FindBestBuyers() { var q = _session.CreateQuery("...insert complex HQL here..."); return q.List<Customer>(); } } You asked about refactoring. LINQ is obviously taken care of by the IDE, so for any remaining HQL, it's fairly easy to scan these repository classes and change HQL by hand. Putting HQL in XML files is a good practice, maybe see if the ReSharper NHIbernate plugin can handle the query refactoring by now? A big improvement when writing or refactoring queries (HQL or LINQ) is to put finder methods under unit test. This way you can quickly tweak the HQL/LINQ until you get a green bar. The compile/test/feedback loop is very fast, especially if you use an in-memory database for testing. Also, if you forget to edit the HQL after refactoring, the unit tests should let you know about your broken HQL very quickly. A: An alternative to LINQ-to-NHibernate and Ayende's NHQG is to generate NHibernate Expressions/Restrictions from C#3 Expressions. This way you get a more strongly-typed Criteria API. See: * *http://bugsquash.blogspot.com/2008/03/strongly-typed-nhibernate-criteria-with.html *http://www.kowitz.net/archive/2008/08/17/what-would-nhibernate-icriteria-look-like-in-.net-3.5.aspx *http://nhibernate.info/blog/2009/01/07/typesafe-icriteria-using-lambda-expressions.html A: scrap nHibernate and go back to Subsonic if you can. In my opinion, Subsonic is a far more fluent and testable ORM/DAL. I absolutely hate HQL what's the point of a weakly typed query in an ORM? And why would I use Linq/nH/SQL when I can just use Linq to SQL and cut out a layer? nHibernate was a good ORM when Subsonic wasn't around, but now, it's just plain awful to work with in comparison. It easily takes me 2 times longer to do stuff with nHibernate vs Subsonic. Testing is a pain since nHibernate is runtime, so now I need to employ a few QA engineers to "click" around the site instead of getting a compile time error.
{ "language": "en", "url": "https://stackoverflow.com/questions/43393", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Is there a standard HTML layout with multiple CSS styles available? When it comes to web-design, I am horrible at producing anything remotely good looking. Thankfully there are a lot of free sources for design templates. However, a problem with these designs is that they just cover a single page, and not many use cases. If you take a look at CSS Zen Gardens, they have 1 single HTML file, and can radically style it differently by just changing the CSS file. Now I am wondering if there is a standard HTML layout (tags and ids), that covers alot of use cases, and can be generically themed with different CSS files like Zen Garden. What I am imagining is a set of rules off how you write your html, and what boxes, lists, menus and styles you are supposed to use. A set of standard test pages covering the various uses can be created, and a new CSS file while have to support all the different pages in a nice view. Is there any projects that covers anything similar to what I am describing? A: Check out the Grids framework from YUI. Particularly awesome is the Grid Builder. Also, they have a set of reset, base, and font CSS files that will give you a good baseline to build on. A: I generally just try to follow the guidelines set by the HTML standard itself. * *Headings go in "h" tags (so one H1 tag for the main heading, then one or more H2 tags under that etc). *Free text gets grouped in paragraphs in P tags. *Logically-grouped sections of information go in DIV tags. *Any kind of list (even menus that you eventually might want horizontally laid out) belong in list tags like UL, OL or DL. *Tables of information go in TABLE tags. DON'T use table tags for layout. *Be smart with your ID and CLASS attributes. Keep IDs unique and assign them to elements that you know represent something unique on the page, like a navigation menu or a page footer. Assign the same class to elements that are repeated but similar (which you might want to render with a similar visual style). I always start with a very plain, vertical page - just run everything I want down the page in black and white. Then I start adding CSS to make sure the bits are formatted and laid out the way I want. Take a look at the source of my home page for an example of what I'm talking about. A: I've used Bluprint CSS, it's easy and useful as you'll see. It also has some ruby scripts that allow you to change the number of columns and the distance between them. By default it's 950px for a span-24 element. A: BluePrintCSS was, from what I know, the first CSS framework. As YUI CSS Framework, It's help you to handle layout. That kind of framework will help you to build multiple CSS for your site. BluePrintCSS is a quite mature project so I encourage you to check it out.
{ "language": "en", "url": "https://stackoverflow.com/questions/43400", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Is there any way to see the progress of an ALTER TABLE statement in MySQL? For example, I issued an ALTER TABLE statement to create an index on a MEDIUMTEXT field in an InnoDB table that has 134k rows where the size of the index was 255 bytes and the average size of the data in the field is 30k. This command has been running for the last 15 minutes or so (and is the only thing running on the database). Is there any way for me to determine if it is going to finish in closer to 5 minutes, 5 hours, or 5 days? A: Very old question but at leas mysql 5.7 has a proper answer for this https://dev.mysql.com/doc/refman/5.7/en/monitor-alter-table-performance-schema.html In essence... UPDATE performance_schema.setup_instruments SET ENABLED = 'YES' WHERE NAME LIKE 'stage/innodb/alter%'; UPDATE performance_schema.setup_consumers SET ENABLED = 'YES' WHERE NAME LIKE '%stages%'; ... run the alter table ... SELECT EVENT_NAME, WORK_COMPLETED, WORK_ESTIMATED FROM performance_schema.events_stages_current; +------------------------------------------------------+----------------+----------------+ | EVENT_NAME | WORK_COMPLETED | WORK_ESTIMATED | +------------------------------------------------------+----------------+----------------+ | stage/innodb/alter table (read PK and internal sort) | 280 | 1245 | +------------------------------------------------------+----------------+----------------+ 1 row in set (0.01 sec) A: This is a pretty common request apparently - requested as far back as 2005 on bugs.mysql.com. It exists in Oracle already, and is listed as useful, but "it is not a simple thing to do, so don't expect it to be implemented soon.". Although that was 2005 :) That said, the chap who asked the original question later released a patch for MySQL 5.0, backported to 4.1, which might help you out. A: I made a query that estimates the time to finish an alter command on an innodb table. You have to run it at least twice on the same session since it compares stats from consecutive runs to make the estimatation. Don't forget to change <tableName> to the correct table name on the fourth line. It gives you two estimations. Local estimation uses only data between runs while Global estimation uses the entire transaction time. select beginsd, now(), qRuns, qTime, tName, trxStarted, trxTime, `rows`, modified, locked, hoursLeftL, estimatedEndL, modifiedPerSecL, avgRows, estimatedEndG, modifiedPerSecG, hoursLeftG from ( select (@tname:='<table>') tName, @beginsd:=sysdate() beginsd, @trxStarted:=(select trx_started from information_schema.innodb_trx where trx_query like concat('alter table %', @tname, '%')) trxStarted, @trxTime:=timediff(@beginsd, @trxStarted) trxTime, @rows:=(select table_rows from information_schema.tables where table_name like @tname) `rows`, @runs:=(ifnull(@runs, 0)+1) qRuns, @rowsSum:=(ifnull(@rowsSum, 0)+@rows), round(@avgRows:=(@rowsSum / @runs)) avgRows, @modified:=(select trx_rows_modified from information_schema.innodb_trx where trx_query like concat('alter table %', @tname, '%')) modified, @rowsLeftL:=(cast(@rows as signed) - cast(@modified as signed)) rowsLeftL, round(@rowsLeftG:=(cast(@avgRows as signed) - cast(@modified as signed)), 2) rowsLeftG, @locked:=(select trx_rows_locked from information_schema.innodb_trx where trx_query like concat('alter table %', @tname, '%')) locked, @endsd:=sysdate() endsd, -- time_to_sec(timediff(@endsd, @beginsd)) qTime, @modifiedInc:=(cast(@modified as signed) - cast(@p_modified as signed)) modifiedInc, @timeInc:=time_to_sec(timediff(@beginsd, @p_beginsd)) timeInc, round(@modifiedPerSecL:=(@modifiedInc/@timeInc)) modifiedPerSecL, round(@modifiedPerSecG:=(@modified/time_to_sec(@trxTime))) modifiedPerSecG, round(@minutesLeftL := (@rowsLeftL / @modifiedPerSecL / 60)) minutesLeftL, round(@minutesLeftG := (@rowsLeftG / @modifiedPerSecG / 60)) minutesLeftG, round(@hoursLeftL := (@minutesLeftL / 60), 2) hoursLeftL, round(@hoursLeftG := (@minutesLeftG / 60), 2) hoursLeftG, (@beginsd + INTERVAL @minutesLeftL MINUTE) estimatedEndL, (@beginsd + INTERVAL @minutesLeftG MINUTE) estimatedEndG, -- @p_rows:=@rows, @p_modified:=@modified, @p_beginsd:=@beginsd ) sq; A: I was able to perform these 2 queries and figure out how many rows remain to be moved. select count(*) from `myoriginalrable`; select count(*) from `#sql-1e8_11ae5`; this was WAY more helpful than comparing the file size on disk, because changing from myisam to innodb etc changes the row size. A: Run ls -laShr /var/lib/mysql | sort -h and you'll see files in the mysql folder something like this: -rw-r----- 1 mysql mysql 3.3G Feb 9 13:21 sql-#2088_10fa.ibd -rw-r----- 1 mysql mysql 10.2G Feb 9 13:21 posts.ibd You can see original table file and temporary target table file as it's being constructed, with human-readable sizes. Usually it will grow linearly with time, so if it's half the size of the original table, it's halfway through. The ls command will sort files by size, so both files will be near the bottom of the file list if this is a large table and you've been waiting a while. A: In the case of InnoDB tables, one can use SHOW ENGINE INNODB STATUS to find the transaction doing the ALTER TABLE and check how many row locks the TX holds. This is the number of processed rows. Explained in detail here: http://gabrielcain.com/blog/2009/08/05/mysql-alter-table-and-how-to-observe-progress/ Also MariaDB 5.3 and later has the feature to report progress for some operations (including ALTER TABLE). See: http://kb.askmonty.org/en/progress-reporting/ A: pt-online-schema-change by Percona shows remaining time estimate. By default it prints out the remaining time estimate and progress percentage every 30 seconds. It also has additional functions compared to just running the ALTER command by itself. http://www.percona.com/doc/percona-toolkit/2.1/pt-online-schema-change.html A: if anyone wants a bash solution: (the sql was not working for me) cd /var/lib/mysql/mydb TABLEFILE="MYTABLE.ibd" TEMPFILE="\#*ibd" ls -lah $TABLEFILE; ls -lah $TEMPFILE; # make sure you have only one temp file or modify the above TEMPFILE SIZE_TOTAL=$(stat -c %s $TABLEFILE); # other ways to get 1st size and time #SIZE1=1550781106; TIME1=1550781106; #SIZE1=$(stat -c %s $TEMPFILE); TIME1=$(stat -c %Z $TEMPFILE); sleep 10; SIZE1=0; TIME1=$(stat -c %X $TEMPFILE); # use file create time echo "SIZE1=$TIME1; TIME1=$TIME1"; SIZE2=$(stat -c %s $TEMPFILE); TIME2=$(stat -c %Z $TEMPFILE); DELTA_SIZE=$(( $SIZE2 - $SIZE1 )) DELTA_TIME=$(( $TIME2 - $TIME1 )) # debug last numbers should not be zero: echo $SIZE1 $SIZE2 $SIZE_TOTAL $DELTA_SIZE; echo $TIME1 $TIME2 $DELTA_TIME; SIZE_PER_SECOND=$( awk "BEGIN {print $DELTA_SIZE / $DELTA_TIME }" ); SIZE_LEFT=$(($SIZE_TOTAL - $SIZE2)); TIME_LEFT_SECONDS=$( awk "BEGIN { print ( $SIZE_LEFT / $SIZE_PER_SECOND) }" ); TIME_LEFT_MINUTES=$( awk "BEGIN { print $TIME_LEFT_SECONDS /60 }" ); TIME_LEFT=$( awk "BEGIN { printf \"%d:%02d:%2d\", int($TIME_LEFT_MINUTES /60), int($TIME_LEFT_MINUTES % 60), int($TIME_LEFT_SECONDS % 60 ) }" ); echo "TIME_LEFT = $TIME_LEFT"; echo "SIZE_LEFT = $SIZE_LEFT" "MB=" $(( $SIZE_LEFT/1024/1024 )) ; awk "BEGIN { if( $SIZE_TOTAL == $SIZE2 ) print \"mysql finished\" }" ; free -h # check free memory, sometimes it is full and it makes it slow conclusions: it takes time, a lot of time. just make sure there is ram free. and free space. like 50% of memory is not used by mysql. low ram makes the whole system work very low A: Percona Server, which is a branched version of MySQL with some enhancements, has this feature. You can observe extra columns in SHOW PROCESSLIST for ROWS_SENT and ROWS_EXAMINED. For example, if your table has 1000000 rows, and you see ROWS_EXAMINED of 650000, then it's 65% finished. See http://www.percona.com/doc/percona-server/5.6/diagnostics/process_list.html
{ "language": "en", "url": "https://stackoverflow.com/questions/43422", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "26" }
Q: How to set up a robot.txt which only allows the default page of a site Say I have a site on http://example.com. I would really like allowing bots to see the home page, but any other page need to blocked as it is pointless to spider. In other words http://example.com & http://example.com/ should be allowed, but http://example.com/anything and http://example.com/someendpoint.aspx should be blocked. Further it would be great if I can allow certain query strings to passthrough to the home page: http://example.com?okparam=true but not http://example.com?anythingbutokparam=true A: So after some research, here is what I found - a solution acceptable by the major search providers: google , yahoo & msn (I could on find a validator here) : User-Agent: * Disallow: /* Allow: /?okparam= Allow: /$ The trick is using the $ to mark the end of URL. A: Google's Webmaster Tools report that disallow always takes precedence over allow, so there's no easy way of doing this in a robots.txt file. You could accomplish this by puting a noindex,nofollow META tag in the HTML every page but the home page. A: Basic robots.txt: Disallow: /subdir/ I don't think that you can create an expression saying 'everything but the root', you have to fill in all sub directories. The query string limitation is also not possible from robots.txt. You have to do it in the background code (the processing part), or maybe with server rewrite-rules. A: Disallow: * Allow: index.ext If I remember correctly the second clause should override the first. A: As far as I know, not all the crawlers support Allow tag. One possible solution might be putting everything except the home page into another folder and disallowing that folder.
{ "language": "en", "url": "https://stackoverflow.com/questions/43427", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "23" }
Q: How do I serialize a DOM to XML text, using JavaScript, in a cross browser way? I have an XML object (loaded using XMLHTTPRequest's responseXML). I have modified the object (using jQuery) and would like to store it as text in a string. There is apparently a simple way to do it in Firefox et al: var xmlString = new XMLSerializer().serializeToString( doc ); (from rosettacode ) But how does one do it in IE6 and other browsers (without, of course, breaking Firefox)? A: You can use doc.xml in internet exlporer. You'll get something like this: function xml2Str(xmlNode) { try { // Gecko- and Webkit-based browsers (Firefox, Chrome), Opera. return (new XMLSerializer()).serializeToString(xmlNode); } catch (e) { try { // Internet Explorer. return xmlNode.xml; } catch (e) { //Other browsers without XML Serializer alert('Xmlserializer not supported'); } } return false; } Found it here.
{ "language": "en", "url": "https://stackoverflow.com/questions/43455", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "28" }
Q: How do I make the jquery dialog work with the themeroller themes? I am trying out the dialog from jquery UI. All the online demos use flora.css. I can't get the dialog to display correctly with the css file generated by the themeroller application. Am I missing something? Should these things work out of the box? Update: Thanks Brock. When I cleaned up my code to make a sample, I realized that the HTML in demo.html (that comes with the themeroller.zip) is a little too verbose. All I needed to do was give the dialog div the attribute class="ui-dialog" like this: <div id="SERVICE03_DLG" class="ui-dialog">please enter something<br><br> <label for="something">somthing:</label>&nbsp;<input name="something" id="something" type="text" maxlength="20" size="24"> </div> I'll accept your answer. Thanks for your time. A: I think it is because you have the classes different. <div id="SERVICE03_DLG" class="flora"> (flora) <div id="SERVICE03_DLG" class="ui-dialog"> (custom) Even with the flora theme, you would still use the ui-dialog class to define it as a dialog. I've done modals before and I've never even defined a class in the tag. jQueryUI should take care of that for you. Try getting rid of the class attribute or using the ui-dialog class.
{ "language": "en", "url": "https://stackoverflow.com/questions/43458", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Kerberos user authentication in Apache can anybody recommend some really good resources for how to get Apache authenticating users with Kerberos. Background reading on Kerberos would also be useful Thanks Peter A: mod_auth_kerb is a good start: http://modauthkerb.sourceforge.net/. If you need Active Directory support, look here: http://support.microsoft.com/?id=555092. A: I found mod_auth_spnego also quite okay, as it can use SSPI on windows instead of requiring MIT Kerberos. mod_spnego A: Here's an example using Active Directory as the KDC: http://oslabs.mikro-net.com/krb_apache.html A: I liked this article about configuring apache to use Kerberos: http://www.roguelynn.com/words/apache-kerberos-for-django/ (you may skip parts about django if you are not interested) EDIT: Fullblown answer It is pretty easy to configure apache to use Kerberos authentication. I am assuming you have correctly configured Kerberos on your machine. 1) Your webserver has to have keytab [1]. Bottom line, your webserver has to be able to read the keytab! 2) You have to have proper httpd module for authentication -- mod_auth_kerb: LoadModule auth_kerb_module modules/mod_auth_kerb.so 3) Then you have to tell apache about Kerberos: <Location /> AuthName "Kerberos Authentication -- this will be showed to users via BasicAuth" AuthType Kerberos KrbMethodNegotiate On KrbMethodK5Passwd Off # this is the principal from your keytab (you may lose the FQDN part) KrbServiceName HTTP/$FQDN KrbAuthRealms KERBEROS_DOMAIN Krb5KeyTab /path/to/http.keytab Require valid-user Order Deny,Allow Deny from all </Location> Then apache will pass the user to your app via REMOTE_USER HTTP header. And that's it. I also advice you to turn on debugging logging in apache during setup. Be sure that you have correct time and httpd can read keytab, that's all. [1] http://kb.iu.edu/data/aumh.html [2] Main resource: http://www.roguelynn.com/words/apache-kerberos-for-django/
{ "language": "en", "url": "https://stackoverflow.com/questions/43459", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: What't the best solution for creating subsets of a set of characters? I know 'best' is subjective, so according to you, what is the best solution for the following problem: Given a string of length n (say "abc"), generate all proper subsets of the string. So, for our example, the output would be {}, {a}, {b}, {c}, {ab}, {bc}, {ac}. {abc}. What do you think? A: You want the power set. It can be calculated recursively and inductively. ;-) A: The recursive approach -- the subsets of "abc" come in two types: those which are subsets of "bc", and those which are "a" plus a subset of "bc". So if you know the subsets of "bc", it's easy. Alternatively, a string of length n has 2^n subsets. So write two nested loops: i counts from 0 to 2^n -1 (for the subsets), and j counts from 0 to n-1 (for characters in the ith subset). Output the jth character of the string if and only if the jth bit of i is 1. (Well, you did say that "best" was subjective...) A: Interpret a number in binary representation as indicating which elements are included in the subset. Let's assume that you have 3 elements in your set. Number 4 corresponds to 0100 in binary notation, so you will interpret this as a subset of size 1 that only includes 2nd element. This way, generating all subsets is counting up to (2^n)-1 char str [] = "abc"; int n = strlen(str); // n is number of elements in your set for(int i=0; i< (1 << n); i++) { // (1 << n) is equal to 2^n for(int j=0; j<n; j++) { // For each element in the set if((i & (1 << j)) > 0) { // Check if it's included in this subset. (1 << j) sets the jth bit cout << str[j]; } } cout << endl; } A: def subsets(s): r = [] a = [False] * len(s) while True: r.append("".join([s[i] for i in range(len(s)) if a[i]])) j = 0 while a[j]: a[j] = False j += 1 if j >= len(s): return r a[j] = True print subsets("abc") A: Pardon the pseudo code... int i = 0; Results.push({}); While(i > Inset.Length) { Foreach(Set s in Results) { If(s.Length == i) { Foreach(character c in inSet) Results.push(s+c); } i++; } A: Recursive solution in C++: set<string> power_set_recursive(string input_str) { set<string> res; if(input_str.size()==0) { res.insert(""); } else if(input_str.size()==1) { res.insert(input_str.substr(0,1)); } else { for(int i=0;i<input_str.size();i++) { set<string> left_set=power_set_iterative(input_str.substr(0,i)); set<string> right_set=power_set_iterative(input_str.substr(i,input_str.size()-i)); for(set<string>::iterator it1=left_set.begin();it1!=left_set.end();it1++) { for(set<string>::iterator it2=right_set.begin();it2!=right_set.end();it2++) { string tmp=(*it1)+(*it2); sort(tmp.begin(),tmp.end()); res.insert(tmp); } } } } return res; } Iterative solution in C++: set<string> power_set_iterative(string input_str) { set<string> res; set<string> out_res; res.insert(""); set<string>::iterator res_it; for(int i=0;i<input_str.size();i++){ for(res_it=res.begin();res_it!=res.end();res_it++){ string tmp=*res_it+input_str.substr(i,1); sort(tmp.begin(),tmp.end()); out_res.insert(tmp); } res.insert(input_str.substr(i,1)); for(set<string>::iterator res_it2=out_res.begin();res_it2!=out_res.end();res_it2++){ res.insert(*res_it2); } out_res.clear(); } return res; }
{ "language": "en", "url": "https://stackoverflow.com/questions/43466", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: When is Control.DestroyHandle called? When is this called? More specifically, I have a control I'm creating - how can I release handles when the window is closed. In normal win32 I'd do it during wm_close - is DestroyHandle the .net equivalent? I don't want to destroy the window handle myself - my control is listening for events on another object and when my control is destroyed, I want to stop listening to those events. Eg: void Dispose(bool disposing) { otherObject.Event -= myEventHandler; } A: Normally DestroyHandle is being called in Dispose method. So you need to make sure that all controls are disposed to avoid resource leaks. A: Dispose does call DestroyHandle, but not always. If I close the parent window, then Windows will destroy all child windows. In this situation Dispose won't call DestroyHandle (since it is already destroyed). In other words, DestroyHandle is called to destroy the window, it is not called when the window is destroyed. The solution is to override either OnHandleDestroyed, or Dispose. I'm opting for Dispose.
{ "language": "en", "url": "https://stackoverflow.com/questions/43490", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is there a built-in method to compare collections? I would like to compare the contents of a couple of collections in my Equals method. I have a Dictionary and an IList. Is there a built-in method to do this? Edited: I want to compare two Dictionaries and two ILists, so I think what equality means is clear - if the two dictionaries contain the same keys mapped to the same values, then they're equal. A: Take a look at the Enumerable.SequenceEqual method var dictionary = new Dictionary<int, string>() {{1, "a"}, {2, "b"}}; var intList = new List<int> {1, 2}; var stringList = new List<string> {"a", "b"}; var test1 = dictionary.Keys.SequenceEqual(intList); var test2 = dictionary.Values.SequenceEqual(stringList); A: This is not directly answering your questions, but both the MS' TestTools and NUnit provide CollectionAssert.AreEquivalent which does pretty much what you want. A: As others have suggested and have noted, SequenceEqual is order-sensitive. To solve that, you can sort the dictionary by key (which is unique, and thus the sort is always stable) and then use SequenceEqual. The following expression checks if two dictionaries are equal regardless of their internal order: dictionary1.OrderBy(kvp => kvp.Key).SequenceEqual(dictionary2.OrderBy(kvp => kvp.Key)) EDIT: As pointed out by Jeppe Stig Nielsen, some object have an IComparer<T> that is incompatible with their IEqualityComparer<T>, yielding incorrect results. When using keys with such an object, you must specify a correct IComparer<T> for those keys. For example, with string keys (which exhibit this issue), you must do the following in order to get correct results: dictionary1.OrderBy(kvp => kvp.Key, StringComparer.Ordinal).SequenceEqual(dictionary2.OrderBy(kvp => kvp.Key, StringComparer.Ordinal)) A: I didn't know about Enumerable.SequenceEqual method (you learn something every day....), but I was going to suggest using an extension method; something like this: public static bool IsEqual(this List<int> InternalList, List<int> ExternalList) { if (InternalList.Count != ExternalList.Count) { return false; } else { for (int i = 0; i < InternalList.Count; i++) { if (InternalList[i] != ExternalList[i]) return false; } } return true; } Interestingly enough, after taking 2 seconds to read about SequenceEqual, it looks like Microsoft has built the function I described for you. A: .NET Lacks any powerful tools for comparing collections. I've developed a simple solution you can find at the link below: http://robertbouillon.com/2010/04/29/comparing-collections-in-net/ This will perform an equality comparison regardless of order: var list1 = new[] { "Bill", "Bob", "Sally" }; var list2 = new[] { "Bob", "Bill", "Sally" }; bool isequal = list1.Compare(list2).IsSame; This will check to see if items were added / removed: var list1 = new[] { "Billy", "Bob" }; var list2 = new[] { "Bob", "Sally" }; var diff = list1.Compare(list2); var onlyinlist1 = diff.Removed; //Billy var onlyinlist2 = diff.Added; //Sally var inbothlists = diff.Equal; //Bob This will see what items in the dictionary changed: var original = new Dictionary<int, string>() { { 1, "a" }, { 2, "b" } }; var changed = new Dictionary<int, string>() { { 1, "aaa" }, { 2, "b" } }; var diff = original.Compare(changed, (x, y) => x.Value == y.Value, (x, y) => x.Value == y.Value); foreach (var item in diff.Different) Console.Write("{0} changed to {1}", item.Key.Value, item.Value.Value); //Will output: a changed to aaa A: Enumerable.SequenceEqual Determines whether two sequences are equal by comparing their elements by using a specified IEqualityComparer(T). You can't directly compare the list & the dictionary, but you could compare the list of values from the Dictionary with the list A: In addition to the mentioned SequenceEqual, which is true if two lists are of equal length and their corresponding elements compare equal according to a comparer (which may be the default comparer, i.e. an overriden Equals()) it is worth mentioning that in .Net4 there is SetEquals on ISet objects, which ignores the order of elements and any duplicate elements. So if you want to have a list of objects, but they don't need to be in a specific order, consider that an ISet (like a HashSet) may be the right choice. A: To compare collections you can also use LINQ. Enumerable.Intersect returns all pairs that are equal. You can comparse two dictionaries like this: (dict1.Count == dict2.Count) && dict1.Intersect(dict2).Count() == dict1.Count The first comparison is needed because dict2 can contain all the keys from dict1 and more. You can also use think of variations using Enumerable.Except and Enumerable.Union that lead to similar results. But can be used to determine the exact differences between sets. A: How about this example: static void Main() { // Create a dictionary and add several elements to it. var dict = new Dictionary<string, int>(); dict.Add("cat", 2); dict.Add("dog", 3); dict.Add("x", 4); // Create another dictionary. var dict2 = new Dictionary<string, int>(); dict2.Add("cat", 2); dict2.Add("dog", 3); dict2.Add("x", 4); // Test for equality. bool equal = false; if (dict.Count == dict2.Count) // Require equal count. { equal = true; foreach (var pair in dict) { int value; if (dict2.TryGetValue(pair.Key, out value)) { // Require value be equal. if (value != pair.Value) { equal = false; break; } } else { // Require key be present. equal = false; break; } } } Console.WriteLine(equal); } Courtesy : https://www.dotnetperls.com/dictionary-equals A: For ordered collections (List, Array) use SequenceEqual for HashSet use SetEquals for Dictionary you can do: namespace System.Collections.Generic { public static class ExtensionMethods { public static bool DictionaryEquals<TKey, TValue>(this IReadOnlyDictionary<TKey, TValue> d1, IReadOnlyDictionary<TKey, TValue> d2) { if (object.ReferenceEquals(d1, d2)) return true; if (d2 is null || d1.Count != d2.Count) return false; foreach (var (d1key, d1value) in d1) { if (!d2.TryGetValue(d1key, out TValue d2value)) return false; if (!d1value.Equals(d2value)) return false; } return true; } } } (A more optimized solution will use sorting but that will require IComparable<TValue>) A: No, because the framework doesn't know how to compare the contents of your lists. Have a look at this: http://blogs.msdn.com/abhinaba/archive/2005/10/11/479537.aspx A: public bool CompareStringLists(List<string> list1, List<string> list2) { if (list1.Count != list2.Count) return false; foreach(string item in list1) { if (!list2.Contains(item)) return false; } return true; } A: There wasn't, isn't and might not be, at least I would believe so. The reason behind is collection equality is probably an user defined behavior. Elements in collections are not supposed to be in a particular order though they do have an ordering naturally, it's not what the comparing algorithms should rely on. Say you have two collections of: {1, 2, 3, 4} {4, 3, 2, 1} Are they equal or not? You must know but I don't know what's your point of view. Collections are conceptually unordered by default, until the algorithms provide the sorting rules. The same thing SQL server will bring to your attention is when you trying to do pagination, it requires you to provide sorting rules: https://learn.microsoft.com/en-US/sql/t-sql/queries/select-order-by-clause-transact-sql?view=sql-server-2017 Yet another two collections: {1, 2, 3, 4} {1, 1, 1, 2, 2, 3, 4} Again, are they equal or not? You tell me .. Element repeatability of a collection plays its role in different scenarios and some collections like Dictionary<TKey, TValue> don't even allow repeated elements. I believe these kinds of equality are application defined and the framework therefore did not provide all of the possible implementations. Well, in general cases Enumerable.SequenceEqual is good enough but it returns false in the following case: var a = new Dictionary<String, int> { { "2", 2 }, { "1", 1 }, }; var b = new Dictionary<String, int> { { "1", 1 }, { "2", 2 }, }; Debug.Print("{0}", a.SequenceEqual(b)); // false I read some answers to questions like this(you may google for them) and what I would use, in general: public static class CollectionExtensions { public static bool Represents<T>(this IEnumerable<T> first, IEnumerable<T> second) { if(object.ReferenceEquals(first, second)) { return true; } if(first is IOrderedEnumerable<T> && second is IOrderedEnumerable<T>) { return Enumerable.SequenceEqual(first, second); } if(first is ICollection<T> && second is ICollection<T>) { if(first.Count()!=second.Count()) { return false; } } first=first.OrderBy(x => x.GetHashCode()); second=second.OrderBy(x => x.GetHashCode()); return CollectionExtensions.Represents(first, second); } } That means one collection represents the other in their elements including repeated times without taking the original ordering into account. Some notes of the implementation: * *GetHashCode() is just for the ordering not for equality; I think it's enough in this case *Count() will not really enumerates the collection and directly fall into the property implementation of ICollection<T>.Count *If the references are equal, it's just Boris A: I've made my own compare method. It returns common, missing, and extra values. private static void Compare<T>(IEnumerable<T> actual, IEnumerable<T> expected, out IList<T> common, out IList<T> missing, out IList<T> extra) { common = new List<T>(); missing = new List<T>(); extra = new List<T>(); var expected_ = new LinkedList<T>( expected ); foreach (var item in actual) { if (expected_.Remove( item )) { common.Add( item ); } else { extra.Add( item ); } } foreach (var item in expected_) { missing.Add( item ); } } A: Comparing dictionaries' contents: To compare two Dictionary<K, V> objects, we can assume that the keys are unique for every value, thus if two sets of keys are equal, then the two dictionaries' contents are equal. Dictionary<K, V> dictionaryA, dictionaryB; bool areDictionaryContentsEqual = new HashSet<K>(dictionaryA.Keys).SetEquals(dictionaryB.Keys); Comparing collections' contents: To compare two ICollection<T> objects, we need to check: * *If they are of the same length. *If every T value that appears in the first collection appears an equal number of times in the second. public static bool AreCollectionContentsEqual<T>(ICollection<T> collectionA, ICollection<T> collectionB) where T : notnull { if (collectionA.Count != collectionB.Count) { return false; } Dictionary<T, int> countByValueDictionary = new(collectionA.Count); foreach(T item in collectionA) { countByValueDictionary[item] = countByValueDictionary.TryGetValue(item, out int count) ? count + 1 : 1; } foreach (T item in collectionB) { if (!countByValueDictionary.TryGetValue(item, out int count) || count < 1) { return false; } countByValueDictionary[item] = count - 1; } return true; } These solutions should be optimal since their time and memory complexities are O(n), while the solutions that use ordering/sorting have time and memory complexities greater than O(n).
{ "language": "en", "url": "https://stackoverflow.com/questions/43500", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "196" }
Q: is it possible to detect if a flash movie also contains (plays) sound? Is there a way to detect if a flash movie contains any sound or is playing any music? It would be nice if this could be done inside a webbrowser (actionscript from another flash object, javascript,..) and could be done before the flash movie starts playing. However, I have my doubts this will be possible altogether, so any other (programmable) solution is also appreciated A: Yes, on the server side for sure. Client side? I don't know. (I'm a serverside kind of guy.) On the server side, one would have to parse the file, read the header and/or look for audio frames. (I've ported a haskel FLV parser to Java for indexing purposes myself, and there are other parsing utilities out there. It is possible.) osflash.org's FLV page has the gory details. Check out the FLV Format sections's FLV Header table. FIELD DATA TYPE EXAMPLE DESCRIPTION Signature byte[3] “FLV” Always “FLV” Version uint8 “\x01” (1) Currently 1 for known FLV files Flags uint8 bitmask “\x05” (5, audio+video) Bitmask: 4 is audio, 1 is video Offset uint32-be “\x00\x00\x00\x09” (9) Total size of header (always 9 for known FLV files) EDIT: My client side coding with Flash is non-existent, but I believe there is an onMetaDataLoad event that your code could catch. That might be happening a bit late for you, but maybe it is good enough? A: Are you asking about FLV video files or Flash "movies" as in SWF? Just to clarify, an FLV is the Flash Video Format (or whatever the acronym is), a regular Flash movie/application/banner would be an SWF. These are very different file formats. A: With the ByteArray you can do pretty much what you want. Before starting playback you can analyze the bytes of the FLV header (use byteArray.readByte() and refer to the specs) to determine to check if the audio flag is on. Since the FLV header is loaded almost instantly this shouldn't cause any inconvenient delay for the user. With SWF's it's a lot tricker -- i'm pretty sure there's no easy way to determine in advance if a swf plays audio somewhere. A way to do it could be to look at what assets the SWF has defined in the library but also then the swf could just load an external audio file (or even generate it with some hacks or the new apis in Flash player 10). If the swf's are user submitted (or something similar that's out of your immediate control) I think this is a risky road..
{ "language": "en", "url": "https://stackoverflow.com/questions/43503", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: SQL Server 2005 One-way Replication In the business I work for we are discussion methods to reduce the read load on our primary database. One option that has been suggested is to have live one-way replication from our primary database to a slave database. Applications would then read from the slave database and write directly to the primary database. So... * *Application Reads From Slave *Application Writes to Primary *Primary Updates Slave Automatically What are the major pros and cons for this method? A: A few cons: * *2 points of failure *Application logic will have to take into account the delay between writing something and then reading it, since it won't be available immediately from the secondary database A strategy I have used is to send key reporting data to a secondary database nightly, de-normalizing it on the way, so that beefy queries can run on that database instead of locking up tables and stealing resources from the OLTP server. I'm not using any formal data warehousing or replication tools, rather I identify problem queries that are Ok without up-to-the-minute data and create data structures on the secondary server specifically for those queries. There are definitely pros to the "replicate everything" approach: * *You can run any ad-hoc query on the secondary, since it has all of your data *If your primary server dies, you can re-purpose the secondary quickly to take over A: We are using one-way replications, but not from the same application. Our applications are reading-writing to the master database, the data gets synchronized to the replca database, and the reporting tools are using this replica. We don't want our application to read from a different database, so in this scenario I would suggest using file groups and partitioning on the master database. Using file groups (especially on different drives) and partitioning of files and indexes can help on performance a lot.
{ "language": "en", "url": "https://stackoverflow.com/questions/43504", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How sophisticated should my Ajax code be? I have seen simple example Ajax source codes in many online tutorials. What I want to know is whether using the source code in the examples are perfectly alright or not? Is there anything more to be added to the code that goes into a real world application? What all steps are to be taken to make the application more robust and secure? Here is a sample source code I got from the web: function getChats() { xmlHttp=GetXmlHttpObject(); if (xmlHttp==null) { return; } var url="getchat.php?latest="+latest; xmlHttp.onreadystatechange=stateChanged; xmlHttp.open("GET",url,true); xmlHttp.send(null); } function GetXmlHttpObject() { var xmlHttp=null; try { xmlHttp=new XMLHttpRequest(); } catch (e) { try { xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } } return xmlHttp; } A: The code you posted is missing one important ingredient: the function stateChanged. If you don't quite understand the code you posted yourself, then what happens is when the call to getchats.php is complete, a function "stateChanged" is called and that function will be responsible for handling the response. Since the script you're calling and the function itself is prefixed with "gets" then I'm pretty sure the response is something you're going to be interested in. That aside, there are a number of ways to improve on the code you posted. I'd guess it works by declaring a single "xmlHttp" object and then making that available to every function (because if it doesn't, the stateChanged function has no way of getting the response). This is fine until you run an AJAX request before the last one (or last few) haven't replied yet, which in that case the object reference is overwritten to the latest request each time. Also, any AJAX code worth its salt provides functionality for sucess and failure (server errors, page not found, etc.) cases so that the appriopiate message can be delivered to the user. If you just want to use AJAX functionality on your website then I'd point you in the direction of jQuery or a similar framework. BUT if you actually want to understand the technology and what is happening behind the scenes, I'd continue doing what you're doing and asking specific questions as you try to build a small lightweight AJAX class on your own. This is how I done it, and although I use the jQuery framework today.. I'm still glad I know how it works behind the scenes. A: I would use a framework like DOMAssistant which has already done the hard work for you and will be more robust as well as adding extra useful features. Apart from that, you code looks like it would do the job. A: I would honestly recommend using one of the many libraries available for Ajax. I use prototype myself, while others prefer jQuery. I like prototype because it's pretty minimal. The Prototype Ajax tutorial explains it well. It also allows you to handle errors easily. new Ajax.Request('/some_url', { method:'get', onSuccess: function(transport){ var response = transport.responseText || "no response text"; alert("Success! \n\n" + response); }, onFailure: function(){ alert('Something went wrong...') } });
{ "language": "en", "url": "https://stackoverflow.com/questions/43507", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: What happened to the .Net Framework Configuration tool? Older versions of the .Net Framework used to install "Microsoft .NET Framework v1.0 / v1.1 / v2.0 Configuration" in the Control Panel, under Administrative Tools. I just noticed that there isn't a v3.0 or v3.5 version of this. Is this functionality now hiding somewhere else, or do I have to use the command-line tools instead? A: For 3.5, you must install this tool: * *http://www.microsoft.com/downloads/details.aspx?FamilyID=4377f86d-c913-4b5c-b87e-ef72e5b4e065&displaylang=en And for 3.0 you must use the 2.0 config tool. Source of Answer. A: Both 3 and 3.5 still use the Common Language Runtime of .NET Framework 2.0. So no control panel is needed, as you can still use the 2.0 control panel. A: The .NET Framework versions 3.0 and 3.5 have been built incrementally on the .NET Framework version 2.0. This version can be used to manage code access security policy for the .NET Framework 3.0, 3.5, and later versions as well. A: To sort out the confusion between the apparently conflicting answers above, this is my current understanding of the answer: * *Use the 2.0 version, as DAC and Codeslayer recommended *If you don't have the 2.0 version (mine was helpfully uninstalled when I removed VS2005 and installed VS2008), then you can either install VS2005, or download the Windows SDK, as per GateKiller's link On my PC, even downloading the SDK didn't work; it installed mscorcfg.msc but not mscorcfg.dll. Digging about in the GAC, I notice mscorcfg.dll v3.5, which confuses me even more. Anyway, there is an iffy-looking copy-dlls-and-hack-registry solution at http://home.hot.rr.com/graye/Articles/CodeAccessSecurity.htm, and that's what I'm going to try next. Wish me luck!
{ "language": "en", "url": "https://stackoverflow.com/questions/43509", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Can I prevent an inherited virtual method from being overridden in subclasses? I have some classes layed out like this class A { public virtual void Render() { } } class B : A { public override void Render() { // Prepare the object for rendering SpecialRender(); // Do some cleanup } protected virtual void SpecialRender() { } } class C : B { protected override void SpecialRender() { // Do some cool stuff } } Is it possible to prevent the C class from overriding the Render method, without breaking the following code? A obj = new C(); obj.Render(); // calls B.Render -> c.SpecialRender A: You can seal individual methods to prevent them from being overridable: public sealed override void Render() { // Prepare the object for rendering SpecialRender(); // Do some cleanup } A: Yes, you can use the sealed keyword in the B class's implementation of Render: class B : A { public sealed override void Render() { // Prepare the object for rendering SpecialRender(); // Do some cleanup } protected virtual void SpecialRender() { } } A: In B, do protected override sealed void Render() { ... } A: try sealed class B : A { protected sealed override void SpecialRender() { // do stuff } } class C : B protected override void SpecialRender() { // not valid } } Of course, I think C can get around it by being new. A: An other (better ?) way is probablby using the new keyword to prevent a particular virtual method from being overiden: class A { public virtual void Render() { } } class B : A { public override void Render() { // Prepare the object for rendering SpecialRender(); // Do some cleanup } protected virtual void SpecialRender() { } } class B2 : B { public new void Render() { } } class C : B2 { protected override void SpecialRender() { } //public override void Render() // compiler error //{ //} } A: yes. If you mark a method as Sealed then it can not be overriden in a derived class.
{ "language": "en", "url": "https://stackoverflow.com/questions/43511", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "21" }
Q: Why is Visual Studio 2005 so slow? It is slow to load anything other than a small project. It is slow to quit; it can sometimes take minutes. It can be slow to open new files. The record macro feature used to be useful. It is now so slow to start up it's almost always quicker to do it manually! More info would be helpful. How big are your solutions? What platform are you on. What 3rd party plugins are you running? What else is running on your pc? 3.2GHz P4 Hyperthreaded, 2GB RAM. Running Outlook, Perforce, IE7, directory browsers. Usually have 1-3 instances of VS running. It's much slower than VC6, say. It seems to take a long time to load projects and close down. I'm interested in if people know reasons why this happens, because of the way VS is written. Is it using .net internally and GC slows it down? A: One of the biggest culprits for Visual Studio 2005 slowness is Intellisense. This has been brought up on the MSDN forums again and again and again. What I frequently experience is that Intellisense is working nearly non-stop to "re-index" symbols (or whatever you call it). But developers at Microsoft have not been deaf to the complaints and some outgoing folks there have come up with some workarounds that have helped me and might help you: Check out this link to get a better understanding of Intellisense: Intellisense Info Then check out this link for some macros that I've had a lot of success with: Intellisense Macros With those macros, you can turn off intellisense (without renaming any DLLs), restart it, delete the ncb file (which you can do manually, but this is a convenience) and it can give you the status of Intellisense. A: it might be that you have a plugin that is misbehaving. Try the safemode switch to see if this improves performance A: One of the biggest culprits for Visual Studio 2005 slowness is Intellisense. This has been brought up on the MSDN forums again and again and again. What I frequently experience is that Intellisense is working nearly non-stop to "re-index" symbols [...] I agree. I use Visual Assist. It is much better. There is no real way to turn "Intellisense" off either. The only way I have found is to rename the DLL so when you restart VS it is not found. This works and makes VS faster. A: I tend to agree that VS is a heavyweight. Back in the day I coded in DOS using Boxer text editor and makefiles. Boxer didn't have the heavy intellisense and refactoring features, but it did better in the text editing department, had good syntax highlighting and startup/closing were instantaneous, even on a 486. ...those were the days. I would say it would be really nice to customize VS to remove all the overhead you're never going to use anyway, but I don't see that happening. A: here's ya problem: 3.2GHz P4 Hyperthreaded, 2GB RAM Hypertheaded means "doesn't actually have two CPU's, but it fakes it". If you have a process with just one thread running, then you get bad performance. It was a good short-term measure, but compared to having two REAL CPU's, it's a slow hack. I don't think that's the problem at all. The machine is plenty high spec enough to be professional C++ development machine for large projects. I can run Eclipse (which is Java, which is memory hungry and slower than native code) and this is still way faster than VS 2005. I doubled the amount of RAM from 1GB to 2GB. This helps a lot with linking large applications. We also use Incredibuild to accelerate compilation. But it's the VS app that is slow. And if you think I'm a grumpy anti-MS zealot, ask yourself why people aren't buying Vista! :) A: I'm am seeing mixed results with faster machines. Sure, faster machine, hides the poor performance quality of vs2005 but not all. Simply taking your obligatory "hello world" C/C++ program, just compile it, (CL /c helloword.cpp), #include <stdio.h> #include <windows.h> int main(char argc, char *argv[]) { printf("Hello World\n"); return 0; } I see 1 seconds compiler under Vc6 and a 6 seconds compile under VS2005. Using DEPENDS to profile the two, I see 3 areas where the 5 seconds delays and time different are taking place: ~2.5 secs with ADVAPI32.DLL, CryptGetHashParam() ~1.5 secs with OLE2.DLL, StringFromGUID2() ~1.0 secs with C2.DLL, _AbortCompilerPass() Again, this is just a compile, not a link. The VC8+ compiler executables/dlls are referencing sub-systems like crypto API, the Registry for some transparent reason and it is adding a tremendous amount of overhead to straight and pure compiles. While a faster machine may hide some of hide slow down, one could only wonder if Microsoft can optimize the compiler by offering options that disables unnecessary overhead references. I understand the better compiler comes with some overhead, but what I see is a 300-500% compile time degradation - thats awful. Hector Santos, CTO Santronics Software A: This is a purely subjective thing I am afraid. * *May it is because of your low end system configuration. *May be VS trying to get updates from the net? *May be you are running too many application in the background. *May be you are trying to open a huge solution. A: Recently I've had both Visual Studio 2008 and Visual Studio 2005 on my machine, and I agree that VS2005 is really heavy. They improved upon it in VS2008, although I'm not sure if you'll consider the performance improvements enough. A: Could you maybe time some operations and post them so we get an idea what you mean by "slow"? On my machine, I wouldn't call VS 2005 slow, but if you compare it to notepad or my web browser it seems slow. Here's some things that might help people figure out what's going on: * *Turn off any features that could affect load time. This includes uninstalling all add-ons and making sure that VS isn't configured to automatically open a project. *Reboot your machine. *Time how long it starts VS 2005 to start, from the time you click the icon until the program starts. *Create a program that you're willing to post here that seems to compile slowly (this might not be possible depending on what it takes to make a slow compile); post the program and how long it takes your computer to build it. *Do you know anyone else with the same kind of machine that has VS 2005 installed? Does it seem slower or faster than yours? I believe Lord Kelvin said the best thing that can be said about situations like this: When you can measure what you are speaking about, and express it in numbers, you know something about it; but when you cannot measure it, when you cannot express it in numbers, your knowledge of it is of a meager and unsatisfactory kind; it may be the beginning of knowledge, but you have scarcely, in your thoughts, advanced it to the stage of science. Until you give us some measurements to look at, we can't tell you if your machine is genuinely slow or if you are expecting more out of your machine than it can give. Your HT CPU might be the problem; I have roughly equivalent machines at work and at home, but my dual-core work machine runs circles around my single-core home machine when it comes to running VS. A: VS 2005 is slower than VS 6 because it is less well optimized for speed. The developers of VS 6 had slower machines than the developers of VS 2005. They made it fast "enough" back then. On a modern machine VS is now "pleasantly fast", where VS 2005 is only just fast enough. What annoys me is that they decided to scrap VS 6 and start again for VS 2005, when VS 6 was an awesome piece of software that just needed updating. A: I noticed above you mentioned you are using perforcet too. Do projects load faster when not in perforce, I am willing to bet that some of the delay you are seeing is related to perforce during load. The latest version of perforce seems a lot slower too. A: Change your Solution Platform on "Any CPU" option which is given on the top of Visual Studio then your program build speed will be definitely increased. A: here's ya problem: 3.2GHz P4 Hyperthreaded, 2GB RAM Hypertheaded means "doesn't actually have two CPU's, but it fakes it". If you have a process with just one thread running, then you get bad performance. It was a good short-term measure, but compared to having two REAL CPU's, it's a slow hack. 2GB of RAM would be an issue too, based on what you said you run. If you have a basic 5400RPM disk, then it's going to make it all worse. I'd recommend, based on what you posted: * *A good core2 machine, maybe a quad if you have the budget. *3GB of ram if you are running a 32bit OS, 4+GB if you are running x64. 4GB means you waste 1GB under 32bit. *Get 7200RPM disks, or better. If you can, RAID0 them (stripe) or RAID0+1 (stripe+mirror) if you can get 4 drives (stripe == split content over the two disks, so you can read from both at the same time. stripe+mirror == the safe version of striping, so your code is on TWO disks at all times) I have a 2.0ghz Core2 (so roughly 3-4x the performance of your P4, if you count 2 CPU's(cores) to be 2x) with 2GB, and the most I can run well is 2 instances of VS.NET 2008. This is normal - nothing wrong with VS.NET, it's just a huge app. More RAM. More CPU. More Screen. More. More. More :)
{ "language": "en", "url": "https://stackoverflow.com/questions/43524", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Images not displaying in WebKit based browsers For some strange, bizarre reason, my images in my website just will not display on webkit based languages (such as safari and chrome). This is the image tag <img src="images/dukkah.jpg" class="imgleft"/> Not only does it not display in the website, it wont display when accessed directly at http://kilkin.massiveatom.com/kilkin/images/dukkah.jpg ...Why? A: I have come across this problem a couple of times. I think it is because of some problem in the file format. Try importing the file in some image editor and saving it again. This should get rid of the problem. A: Imagemagick reports that this particular image is saved in CMYK colorspace instead of the more standard RGB. Try converting it, it should be more compatible with the webkit rendering engine. Imagemagick is available for download from http://www.imagemagick.org/script/index.php - it's available for windows and *NIX systems. A: I tried the url you gave in FireFox 3 and IE 6, IE 6 won't show it either, firefox works. My guess is that there is something wrong with the jpg file. A: Are you JPEG's compressed in Jpeg 2000 Format? If so, there is a known bug: * *https://bugs.webkit.org/show_bug.cgi?id=8754 A: "The image “http://kilkin.massiveatom.com/kilkin/images/dukkah.jpg” cannot be displayed, because it contains errors." and the image itself has some XML-fragment in it. So as others proposed: try to open with an editor and resave it. A: It's as stated elsewere a bug in the image. Irfanview is a very good viewer that will display any image (and other formats as well), is small and free and will also let you adjust, crop or rescale images very easily without heavy programs like photoshop. I suggest download irfanview and the image, open the image in irfanview and hit CTRL+S and save it over itself. Then upload the image again. Any problem should be solved. A: Your image file does not contain image data, it contains html text: $ curl -s http://kilkin.massiveatom.com/kilkin/images/dukkah.jpg <html><head></head><body><!-- vbe --></body></html>
{ "language": "en", "url": "https://stackoverflow.com/questions/43525", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Embedding flv (flash) player in windows forms I'm trying to the the flv Flash player from here in a windows forms application. I currently have it playing 1 .flv file with no problems but I really need to be able to play multiple files. Has anyone had experienace of using the playlists that this control offers or is there a better way to do this? A: I would be very hesitant to place the WebBrowser control between your software and the flv, because you will lose all control of the flv and will not get any meaningful notifications about its status. The lack of tight integration will lead to a very poor user experience. The blog post here has instructions on embedding flash via COM. A: Can you get the control to run the way you want it in a webpage/browser? If yes (and the problem is with winforms, I'd just embed it in a browser control. If no, I'd as the creators directly. A: Hmm I ran into this same problem as well. The prob is that loadmovie method doesnt seem to clear the last movie. And so far I haven't found any technique to load a new movie into the same flash player. A: Well I found myself needing to do the same thing and since there was no clear solution yet I figured I would provide mine. Here's what I ended up doing: //Load JWPlayer swf axShockwaveFlash1.FlashVars = "autostart=true"; axShockwaveFlash1.ScaleMode = 0; axShockwaveFlash1.LoadMovie(0, Directory.GetCurrentDirectory() + @"\JWPlayer\player.swf"); axShockwaveFlash1.Play(); //Play new flv axShockwaveFlash1.CallFunction("<invoke name=\"sendEvent\" returntype=\"xml\">" + "<arguments><string>load</string><string>" + @"C:\FLVFiles\Example.flv" + "</string></arguments></invoke>"); My primary reference for figuring this out was: (Look at last post) http://www.longtailvideo.com/support/forums/jw-player/bug-reports/8687/how-to-call-sendevent-from-c I mention this primarily because there are links to other events that can be called which people might be interested in.
{ "language": "en", "url": "https://stackoverflow.com/questions/43533", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Dynamic Form Controls Using C# 2.0 what is the best way to implement dynamic form controls? I need to provide a set of controls per data object, so should i just do it manually and lay them out while increment the top value or is there a better way? A: You can use panels with automatic layout such as FlowLayoutPanel and TableLayoutPanel. Unfortunately there are only 2 panels with automatic layout out of box but you can create custom layout panel. I would recommend you to read following articles: How to: Create a Resizable Windows Form for Data Entry Walkthrough: Creating a Resizable Windows Form for Data Entry Another option would be using of WPF (Windows Presentation Presentation). WPF is a perfect match for your task. WPF controls can be hosted in WinForms apps so you don't have to switch to it completely. A: @Sam I know this question was about Windows Forms, but you should definitely start looking at WPF. This sort of scenario is really easy in WPF with DataTemplates and TemplateSelectors. A: What do you mean by “dynamic”? A new, fixed set of controls for each data row in the data set? Then use a UserControl that contains your controls. Or do you mean that, depending on your data layout, you want to provide the user with a customized set of controls, say, one TextBox for each column? A: Yeah, I've found manually layout out controls (incrementing their Top property by the height of the control plus a margin as I go) to be reasonably effective. Another approach is to place your controls in Panels with Dock set to Top, so that each successive panel docks up against the one above. Then you can toggle the visibility of individual panels and the controls underneath will snap up to fill the available space. Be aware that this can be a bit unpredictable: showing a hidden panel that's docked can sometimes change its position relative to other docked controls. A: Well that's the way we are doing it right now on a project. but that's only useful for simple cases. I suggest you use some sort of template for more complex cases. For instance I used Reflection to map a certain type of control to a certain property on my domain objects on an older project. You could try generating the code from templates using t4 see T4 Templates in Visual Studio for Code Generation Screencast for a simple example. You can apply this to WinForms. Also DevExperience has a nice ( expensive ) framework, see DevExpress eXpressApp Framework™ .
{ "language": "en", "url": "https://stackoverflow.com/questions/43536", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Max length for HTML How to restrict the maximum number of characters that can be entered into an HTML <textarea>? I'm looking for a cross-browser solution. A: HTML5 now allows maxlength attribute on <textarea>. It is supported by all browsers except IE <= 9 and iOS Safari 8.4. See support table on caniuse.com. A: The TEXTAREA tag does not have a MAXLENGTH attribute the way that an INPUT tag does, at least not in most standard browsers. A very simple and effective way to limit the number of characters that can be typed into a TEXTAREA tag is: <textarea onKeyPress="return ( this.value.length < 50 );"></textarea> Note: onKeyPress, is going to prevent any button press, any button including the backspace key. This works because the Boolean expression compares the field's length before the new character is added to the maximum length you want (50 in this example, use your own here), and returns true if there is room for one more, false if not. Returning false from most events cancels the default action. So if the current length is already 50 (or more), the handler returns false, the KeyPress action is cancelled, and the character is not added. One fly in the ointment is the possibility of pasting into a TEXTAREA, which does not cause the KeyPress event to fire, circumventing this check. Internet Explorer 5+ contains an onPaste event whose handler can contain the check. However, note that you must also take into account how many characters are waiting in the clipboard to know if the total is going to take you over the limit or not. Fortunately, IE also contains a clipboard object from the window object.1 Thus: <textarea onKeyPress="return ( this.value.length < 50 );" onPaste="return (( this.value.length + window.clipboardData.getData('Text').length) < 50 );"></textarea> Again, the onPaste event and clipboardData object are IE 5+ only. For a cross-browser solution, you will just have to use an OnChange or OnBlur handler to check the length, and handle it however you want (truncate the value silently, notify the user, etc.). Unfortunately, this doesn't catch the error as it's happening, only when the user attempts to leave the field, which is not quite as friendly. Source Also, there is another way here, including a finished script you could include in your page: http://cf-bill.blogspot.com/2005/05/textarea-maxlength-revisited.html A: $(function(){ $("#id").keypress(function() { var maxlen = 100; if ($(this).val().length > maxlen) { return false; } }) }); Reference Set maxlength in Html Textarea
{ "language": "en", "url": "https://stackoverflow.com/questions/43569", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "17" }
Q: How to find the mime type of a file in python? Let's say you want to save a bunch of files somewhere, for instance in BLOBs. Let's say you want to dish these files out via a web page and have the client automatically open the correct application/viewer. Assumption: The browser figures out which application/viewer to use by the mime-type (content-type?) header in the HTTP response. Based on that assumption, in addition to the bytes of the file, you also want to save the MIME type. How would you find the MIME type of a file? I'm currently on a Mac, but this should also work on Windows. Does the browser add this information when posting the file to the web page? Is there a neat python library for finding this information? A WebService or (even better) a downloadable database? A: You didn't state what web server you were using, but Apache has a nice little module called Mime Magic which it uses to determine the type of a file when told to do so. It reads some of the file's content and tries to figure out what type it is based on the characters found. And as Dave Webb Mentioned the MimeTypes Module under python will work, provided an extension is handy. Alternatively, if you are sitting on a UNIX box you can use sys.popen('file -i ' + fileName, mode='r') to grab the MIME type. Windows should have an equivalent command, but I'm unsure as to what it is. A: @toivotuo 's method worked best and most reliably for me under python3. My goal was to identify gzipped files which do not have a reliable .gz extension. I installed python3-magic. import magic filename = "./datasets/test" def file_mime_type(filename): m = magic.open(magic.MAGIC_MIME) m.load() return(m.file(filename)) print(file_mime_type(filename)) for a gzipped file it returns: application/gzip; charset=binary for an unzipped txt file (iostat data): text/plain; charset=us-ascii for a tar file: application/x-tar; charset=binary for a bz2 file: application/x-bzip2; charset=binary and last but not least for me a .zip file: application/zip; charset=binary A: python 3 ref: https://docs.python.org/3.2/library/mimetypes.html mimetypes.guess_type(url, strict=True) Guess the type of a file based on its filename or URL, given by url. The return value is a tuple (type, encoding) where type is None if the type can’t be guessed (missing or unknown suffix) or a string of the form 'type/subtype', usable for a MIME content-type header. encoding is None for no encoding or the name of the program used to encode (e.g. compress or gzip). The encoding is suitable for use as a Content-Encoding header, not as a Content-Transfer-Encoding header. The mappings are table driven. Encoding suffixes are case sensitive; type suffixes are first tried case sensitively, then case insensitively. The optional strict argument is a flag specifying whether the list of known MIME types is limited to only the official types registered with IANA. When strict is True (the default), only the IANA types are supported; when strict is False, some additional non-standard but commonly used MIME types are also recognized. import mimetypes print(mimetypes.guess_type("sample.html")) A: In Python 3.x and webapp with url to the file which couldn't have an extension or a fake extension. You should install python-magic, using pip3 install python-magic For Mac OS X, you should also install libmagic using brew install libmagic Code snippet import urllib import magic from urllib.request import urlopen url = "http://...url to the file ..." request = urllib.request.Request(url) response = urlopen(request) mime_type = magic.from_buffer(response.readline()) print(mime_type) alternatively you could put a size into the read import urllib import magic from urllib.request import urlopen url = "http://...url to the file ..." request = urllib.request.Request(url) response = urlopen(request) mime_type = magic.from_buffer(response.read(128)) print(mime_type) A: More reliable way than to use the mimetypes library would be to use the python-magic package. import magic m = magic.open(magic.MAGIC_MIME) m.load() m.file("/tmp/document.pdf") This would be equivalent to using file(1). On Django one could also make sure that the MIME type matches that of UploadedFile.content_type. A: This seems to be very easy >>> from mimetypes import MimeTypes >>> import urllib >>> mime = MimeTypes() >>> url = urllib.pathname2url('Upload.xml') >>> mime_type = mime.guess_type(url) >>> print mime_type ('application/xml', None) Please refer Old Post Update - In python 3+ version, it's more convenient now: import mimetypes print(mimetypes.guess_type("sample.html")) A: I try mimetypes library first. If it's not working, I use python-magic libary instead. import mimetypes def guess_type(filename, buffer=None): mimetype, encoding = mimetypes.guess_type(filename) if mimetype is None: try: import magic if buffer: mimetype = magic.from_buffer(buffer, mime=True) else: mimetype = magic.from_file(filename, mime=True) except ImportError: pass return mimetype A: 13 year later... Most of the answers on this page for python 3 were either outdated or incomplete. To get the mime type of a file I use: import mimetypes mt = mimetypes.guess_type("https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf") if mt: print("Mime Type:", mt[0]) else: print("Cannot determine Mime Type") # Mime Type: application/pdf Live Demo From Python docs: mimetypes.guess_type(url, strict=True) Guess the type of a file based on its filename, path or URL, given by url. URL can be a string or a path-like object. The return value is a tuple (type, encoding) where type is None if the type can’t be guessed (missing or unknown suffix) or a string of the form 'type/subtype', usable for a MIME content-type header. encoding is None for no encoding or the name of the program used to encode (e.g. compress or gzip). The encoding is suitable for use as a Content-Encoding header, not as a Content-Transfer-Encoding header. The mappings are table driven. Encoding suffixes are case sensitive; type suffixes are first tried case sensitively, then case insensitively. The optional strict argument is a flag specifying whether the list of known MIME types is limited to only the official types registered with IANA. When strict is True (the default), only the IANA types are supported; when strict is False, some additional non-standard but commonly used MIME types are also recognized. Changed in version 3.8: Added support for url being a path-like object. A: The python-magic method suggested by toivotuo is outdated. Python-magic's current trunk is at Github and based on the readme there, finding the MIME-type, is done like this. # For MIME types import magic mime = magic.Magic(mime=True) mime.from_file("testdata/test.pdf") # 'application/pdf' A: The mimetypes module just recognise an file type based on file extension. If you will try to recover a file type of a file without extension, the mimetypes will not works. A: I'm surprised that nobody has mentioned it but Pygments is able to make an educated guess about the mime-type of, particularly, text documents. Pygments is actually a Python syntax highlighting library but is has a method that will make an educated guess about which of 500 supported document types your document is. i.e. c++ vs C# vs Python vs etc import inspect def _test(text: str): from pygments.lexers import guess_lexer lexer = guess_lexer(text) mimetype = lexer.mimetypes[0] if lexer.mimetypes else None print(mimetype) if __name__ == "__main__": # Set the text to the actual defintion of _test(...) above text = inspect.getsource(_test) print('Text:') print(text) print() print('Result:') _test(text) Output: Text: def _test(text: str): from pygments.lexers import guess_lexer lexer = guess_lexer(text) mimetype = lexer.mimetypes[0] if lexer.mimetypes else None print(mimetype) Result: text/x-python Now, it's not perfect, but if you need to be able to tell which of 500 document formats are being used, this is pretty darn useful. A: Python bindings to libmagic All the different answers on this topic are very confusing, so I’m hoping to give a bit more clarity with this overview of the different bindings of libmagic. Previously mammadori gave a short answer listing the available option. libmagic * *module name: magic *pypi: file-magic *source: https://github.com/file/file/tree/master/python When determining a files mime-type, the tool of choice is simply called file and its back-end is called libmagic. (See the Project home page.) The project is developed in a private cvs-repository, but there is a read-only git mirror on github. Now this tool, which you will need if you want to use any of the libmagic bindings with python, already comes with its own python bindings called file-magic. There is not much dedicated documentation for them, but you can always have a look at the man page of the c-library: man libmagic. The basic usage is described in the readme file: import magic detected = magic.detect_from_filename('magic.py') print 'Detected MIME type: {}'.format(detected.mime_type) print 'Detected encoding: {}'.format(detected.encoding) print 'Detected file type name: {}'.format(detected.name) Apart from this, you can also use the library by creating a Magic object using magic.open(flags) as shown in the example file. Both toivotuo and ewr2san use these file-magic bindings included in the file tool. They mistakenly assume, they are using the python-magic package. This seems to indicate, that if both file and python-magic are installed, the python module magic refers to the former one. python-magic * *module name: magic *pypi: python-magic *source: https://github.com/ahupp/python-magic This is the library that Simon Zimmermann talks about in his answer and which is also employed by Claude COULOMBE as well as Gringo Suave. filemagic * *module name: magic *pypi: filemagic *source: https://github.com/aliles/filemagic Note: This project was last updated in 2013! Due to being based on the same c-api, this library has some similarity with file-magic included in libmagic. It is only mentioned by mammadori and no other answer employs it. A: 2017 Update No need to go to github, it is on PyPi under a different name: pip3 install --user python-magic # or: sudo apt install python3-magic # Ubuntu distro package The code can be simplified as well: >>> import magic >>> magic.from_file('/tmp/img_3304.jpg', mime=True) 'image/jpeg' A: The mimetypes module in the standard library will determine/guess the MIME type from a file extension. If users are uploading files the HTTP post will contain the MIME type of the file alongside the data. For example, Django makes this data available as an attribute of the UploadedFile object. A: There are 3 different libraries that wraps libmagic. 2 of them are available on pypi (so pip install will work): * *filemagic *python-magic And another, similar to python-magic is available directly in the latest libmagic sources, and it is the one you probably have in your linux distribution. In Debian the package python-magic is about this one and it is used as toivotuo said and it is not obsoleted as Simon Zimmermann said (IMHO). It seems to me another take (by the original author of libmagic). Too bad is not available directly on pypi. A: in python 2.6: import shlex import subprocess mime = subprocess.Popen("/usr/bin/file --mime " + shlex.quote(PATH), shell=True, \ stdout=subprocess.PIPE).communicate()[0] A: For byte Array type data you can use magic.from_buffer(_byte_array,mime=True) A: I 've tried a lot of examples but with Django mutagen plays nicely. Example checking if files is mp3 from mutagen.mp3 import MP3, HeaderNotFoundError try: audio = MP3(file) except HeaderNotFoundError: raise ValidationError('This file should be mp3') The downside is that your ability to check file types is limited, but it's a great way if you want not only check for file type but also to access additional information.
{ "language": "en", "url": "https://stackoverflow.com/questions/43580", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "256" }
Q: "undefined handler" from prototype.js line 3877 A very niche problem: I sometimes (30% of the time) get an 'undefined handler' javascript error on line 3877 of the prototype.js library (version 1.6.0.2 from google: http://ajax.googleapis.com/ajax/libs/prototype/1.6.0.2/prototype.js). Now on this page I have a Google Map and I use the Prototype Window library. The problem occurs in IE7 and FF3. This is the info FireBug gives: handler is undefined ? in prototype.js@3871()prototype.js (line 3877) handler.call(element, event); I switched to a local version of prototypejs and added some debugging in the offending method (createWraper) but the debugging never appears before the error... I googled around and found 1 other mention of the error on the same line, but no answer so I'm posting it here where maybe, some day someone will have an answer :). A: I just found out this error also occurs if you accidentally leave on the parenthesis on your observer call: Event.observe(document, 'myapp:application_ready', myapp.MyClass.initApp()); instead of Event.observe(document, 'myapp:application_ready', myapp.MyClass.initApp); A: I switched to a local version of prototypejs and added some debugging in the offending method (createWraper) but the debugging never appears before the error... Actually the offending function being called when the error occurs is "wrapper" which is created inside createWrapper (but not called there). Basically what is happening is that you've attached a function as the event handler for an element, and the function doesn't actually exist. If you're trying to put any debug information in to try and pinpoint which function "doesn't exist" then add your alert messages or firebug console output inside the wrapper function between lines 3871 and 3878. A: This will probably cause an error: Event.observe(myElement, 'click', myFunction(myParameters)); You should do it like this instead: Event.observe(myElement, 'click', function() { myFunction(myParameters) }); A: Really simple solution for “undefined handler” from prototype.js error in Prototype is just... fix prototype. I found advice here: https://prototype.lighthouseapp.com/projects/8886/tickets/407-ie7-i8-report-handler-is-null-or-not-an-object and it's actually working. Just find line with: handler.call(element, event); and replace with if (handler) handler.call(element, event) problem solved with prototype 1.6.0.3 and latest :)
{ "language": "en", "url": "https://stackoverflow.com/questions/43584", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: In PHP, is there an easy way to get the first and last date of a month? I need to get the first and last day of a month in the format YYYY-MM-DD given only the month and year. Is there a good, easy way to do this? A: First day is always YYYY-MM-01, isn't it? Example: date("Y-M-d", mktime(0, 0, 0, 8, 1, 2008)) Last day is the previous day of the next month's first day: $date = new DateTime("2008-09-01"); $date->modify("-1 day"); echo $date->format("Y-m-d"); A: $first = date('Y-m-d', mktime(0, 0, 0, $month, 1, $year)); $last = date('Y-m-t', mktime(0, 0, 0, $month, 1, $year)); See date() in PHP documentation. A: The first day of the month is always 1. So it will become YYYY-MM-01 the last day can be calculated as: <?php $num = cal_days_in_month(CAL_GREGORIAN, 8, 2003); // 31 echo "There was $num days in August 2003"; ?> A: OK, first is dead easy. date ('Y-m-d', mktime(0,0,0,MM,01,YYYY)); Last is a little trickier, but not much. date ('Y-m-d', mktime(0,0,0,MM + 1,-1,YYYY)); If I remember my PHP date stuff correctly... **edit - Gah! Beaten to it about a million times... Edit by Pat: Last day should have been date ('Y-m-d', mktime(0,0,0,$MM + 1,0,$YYYY)); // Day zero instead of -1 A: <?php echo "Month Start - " . $monthStart = date("Y-m-1") . "<br/>"; $num = cal_days_in_month(CAL_GREGORIAN, date("m"), date("Y")); echo "Monthe End - " . $monthEnd = date("Y-m-".$num); ?> A: The easiest way to do this with PHP is $dateBegin = strtotime("first day of last month"); $dateEnd = strtotime("last day of last month"); echo date("MYDATEFORMAT", $dateBegin); echo "<br>"; echo date("MYDATEFORMAT", $dateEnd); Or the last week if (date('N', time()) == 7) { $dateBegin = strtotime("-2 weeks Monday"); $dateEnd = strtotime("last Sunday"); } else { $dateBegin = strtotime("Monday last week"); $dateEnd = strtotime("Sunday last week"); } Or the last year $dateBegin = strtotime("1/1 last year"); $dateEnd = strtotime("12/31 this year"); A: By the way @ZombieSheep solution date ('Y-m-d', mktime(0,0,0,$MM + 1,-1,$YYYY)); does not work it should be date ('Y-m-d', mktime(0,0,0,$MM + 1,0,$YYYY)); // Day zero instead of -1 Of course @Michał Słaby's accepted solution is the simplest. A: Just to verify that I didn't miss any loose ends: $startDay = 1; if (date("m") == 1) { $startMonth = 12; $startYear = date("Y") - 1; $endMonth = 12; $endYear = date("Y") - 1; } else { $startMonth = date("m") - 1; $startYear = date("Y"); $endMonth = date("m") - 1; $endYear = date("Y"); } $endDay = date("d") - 1; $startDate = date('Y-m-d', mktime(0, 0, 0, $startMonth , $startDay, $startYear)); $endDate = date('Y-m-d', mktime(0, 0, 0, $endMonth, $endDay, $endYear)); A: try this to get the number of days in the month: $numdays = date('t', mktime(0, 0, 0, $m, 1, $Y)); A: Example; I want to get first day and last day of current month. $month = (int) date('F'); $year = (int) date('Y'); date('Y-m-d', mktime(0, 0, 0, $month + 1, 1, $year)); //first date('Y-m-d', mktime(0, 0, 0, $month + 2, 0, $year)); //last When you run this for instance at date 2015-01-09, the first and last values will be sequentially; 2015-01-01 2015-01-31 Tested. A: From here(get next month last day) that is marked as duplicated, so i can't add comment there, but people can got bad answers from there. Correct one for last day of next month: echo ((new DateTime(date('Y-m').'-01'))->modify('+1 month')->format('Y-m-t')); Correct one for first day of next month: echo ((new DateTime(date('Y-m').'-01'))->modify('+1 month')->format('Y-m-01')); Code like this will be providing March from January, so that's not what could be expected. echo ((new DateTime())->modify('+1 month')->format('Y-m-t')); A: proper way to build a relative date from now is: //bad example - will be broken when generated at 30 of December (broken February) echo date("Y-m-d", strtotime("now"))."\n"; echo date("Y-m-d", strtotime("now + 1 month"))."\n"; echo date("Y-m-d", strtotime("now + 2 month"))."\n"; echo date("Y-m-d", strtotime("now + 3 month"))."\n"; //good example, you can change first day to last day or any day echo date("Y-m-d", strtotime("first day of this month"))."\n"; echo date("Y-m-d", strtotime("first day of next month"))."\n"; echo date("Y-m-d", strtotime("first day of +2 month"))."\n"; echo date("Y-m-d", strtotime("first day of +3 month"))."\n"; and the result will be: 2021-12-30 2022-01-30 2022-03-02 2022-03-30 2021-12-01 2022-01-01 2022-02-01 2022-03-01
{ "language": "en", "url": "https://stackoverflow.com/questions/43589", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "35" }
Q: Override WebClientProtocol.Timeout via web.config Is it possible to override default value of WebClientProtocol.Timeout property via web.config? <httpRuntime executionTimeout="500" /> <!-- this doesn't help --> A: I cant think of a way to have just the Timeout property changed automatically via the webconfig. Manually configure the value or use DI to read the value in for you. It maybe possible also to change the value globally on the machine config.
{ "language": "en", "url": "https://stackoverflow.com/questions/43591", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How well does WPF blend with XNA in real life? I understand that there are several ways to blend XNA and WPF within the same application. I find it enticing to use WPF for all GUI and HUD stuff in my XNA games. Does anyone have any practical experience on how well this approach works in real life using .NET 3.5 SP1 ? Any pitfalls (such as the "airspace problem")? Any hint on what appoach works best? A: There is an addition in 3.5 SP1 that allows better interaction between DirectX and WPF (D3DImage), and one way to get to that is through XNA. Here are some details: http://jmorrill.hjtcentral.com/Default.aspx?tabid=428&EntryID=259 A: XNA integration is high on our list of things to add to WPF so we're looking in to this for future versions. Stay tuned (to GregSc's blog) for the details as they become available. Ian Ellison-Taylor Read more about this here A: Thamir Khason presented a excellent session about WPF/XNA/Silverlight at Tech-ed... Here is his slides: http://blogs.microsoft.co.il/blogs/tamir/archive/2008/04/14/my-teched-08-presentation-slides-download.aspx PS. This was quite impressive to see... he had a game that ran on the xbox. On his desktop using WPF to host XNA and ons his mobile phone using silverlight all playing against each other!!! A: You want to use a D3DImage, but D3DImage works different on windows XP vs windows Vista or 7. On Vista or 7, you create a NON-lockable renderTarget to use with the D3DImage & you use a Direct3D9EX Device. On XP, you create a lockable renderTarget to use with the D3DImage & use a normal Direct3D9 Device. Also insted of using XNA it might be better to use SlimDX if your just making this for the PC. SlimDX is not lacking any Direct3D features & supports Direct3D 9, 10 & 11. http://slimdx.org/ A: I personally would advise against trying to do this integration. I know what you're going for ... the ease of defining GUI/HUD elements in WPF greatly outweighs trying to do the same in just plain old XNA. However, think realistically of the time you'll spend trying to enable this scenario vs. how much you'd save if you just did everything "natively" in XNA. Also (and this may not be an issue for you), WPF isn't supported on the xbox or zune ... so you'd be limiting yourself :-) A: Hey I know this is a while after you posted but if you are still looking for a WPF solution for XNA you may want to keep an eye on http://red-badger.com/product. The XPF soloution puts wpf into XNA. SO have a look, at the moment it is free as it is in beta but that will be changing as they add more components
{ "language": "en", "url": "https://stackoverflow.com/questions/43596", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: Can you make just part of a regex case-insensitive? I've seen lots of examples of making an entire regular expression case-insensitive. What I'm wondering about is having just part of the expression be case-insensitive. For example, let's say I have a string like this: fooFOOfOoFoOBARBARbarbarbAr What if I want to match all occurrences of "foo" regardless of case but I only want to match the upper-case "BAR"s? The ideal solution would be something that works across regex flavors but I'm interested in hearing language-specific ones as well (Thanks Espo) Edit The link Espo provided was very helpful. There's a good example in there about turning modifiers on and off within the expression. For my contrived example, I can do something like this: (?i)foo*(?-i)|BAR which makes the match case-insensitive for just the foo portion of the match. That seemed to work in most regex implementations except Javascript, Python, and a few others (as Espo mentioned). The big ones that I was wondering about (Perl, PHP, .NET) all support inline mode changes. A: Perl lets you make part of your regular expression case-insensitive by using the (?i:) pattern modifier. Modern regex flavors allow you to apply modifiers to only part of the regular expression. If you insert the modifier (?ism) in the middle of the regex, the modifier only applies to the part of the regex to the right of the modifier. You can turn off modes by preceding them with a minus sign. All modes after the minus sign will be turned off. E.g. (?i-sm) turns on case insensitivity, and turns off both single-line mode and multi-line mode. Not all regex flavors support this. JavaScript and Python apply all mode modifiers to the entire regular expression. They don't support the (?-ismx) syntax, since turning off an option is pointless when mode modifiers apply to the whole regular expressions. All options are off by default. You can quickly test how the regex flavor you're using handles mode modifiers. The regex (?i)te(?-i)st should match test and TEst, but not teST or TEST. Source A: What language are you using? A standard way to do this would be something like /([Ff][Oo]{2}|BAR)/ with case sensitivity on, but in Java, for example, there is a case sensitivity modifier (?i) which makes all characters to the right of it case insensitive and (?-i) which forces sensitivity. An example of that Java regex modifier can be found here. A: Unfortunately syntax for case-insensitive matching is not common. In .NET you can use RegexOptions.IgnoreCase flag or ?i modifier A: You could use (?:F|f)(?:O|o)(?:O|o) The ?: in the brackets in .Net means it's non-capturing, and just used to group the terms of the | (or) statement. A: It is true one can rely on inline modifiers as described in Turning Modes On and Off for Only Part of The Regular Expression: The regex (?i)te(?-i)st should match test and TEst, but not teST or TEST. However, a bit more supported feature is an (?i:...) inline modifier group (see Modifier Spans). The syntax is (?i:, then the pattern that you want to make cas-insensitive, and then a ). (?i:foo)|BAR The reverse: If your pattern is compiled with a case insensitive option and you need to make a part of a regex case sensitive, you add - after ?: (?-i:...). Example uses in various languages (wrapping the matches with angle brackets): * *php - preg_replace("~(?i:foo)|BAR~", '<$0>', "fooFOOfOoFoOBARBARbarbarbAr") (demo) *python - re.sub(r'(?i:foo)|BAR', r'<\g<0>>', 'fooFOOfOoFoOBARBARbarbarbAr') (demo) (note Python re supports inline modifier groups since Python 3.6) *c# / vb.net / .net - Regex.Replace("fooFOOfOoFoOBARBARbarbarbAr", "(?i:foo)|BAR", "<$&>") (demo) *java - "fooFOOfOoFoOBARBARbarbarbAr".replaceAll("(?i:foo)|BAR", "<$0>") (demo) *perl - $s =~ s/(?i:foo)|BAR/<$&>/g (demo) *ruby - "fooFOOfOoFoOBARBARbarbarbAr".gsub(/(?i:foo)|BAR/, '<\0>') (demo) *r - gsub("((?i:foo)|BAR)", "<\\1>", "fooFOOfOoFoOBARBARbarbarbAr", perl=TRUE) (demo) *swift - "fooFOOfOoFoOBARBARbarbarbAr".replacingOccurrences(of: "(?i:foo)|BAR", with: "<$0>", options: [.regularExpression]) *go - (uses RE2) - regexp.MustCompile(`(?i:foo)|BAR`).ReplaceAllString( "fooFOOfOoFoOBARBARbarbarbAr", `<${0}>`) (demo) Not supported in javascript, bash, sed, c++ std::regex, lua, tcl. In these case, you can put both letter variants into a character class (not a group, see Why is a character class faster than alternation?). Examples: * *sed posix-ere - sed -E 's/[Ff][Oo][Oo]|BAR/<&>/g' file > outfile (demo) *grep posix-ere - grep -Eo '[Ff][Oo][Oo]|BAR' file (or if you are using GNU grep, you can still use the PCRE regex, grep -Po '(?i:foo)|BAR' file (demo))
{ "language": "en", "url": "https://stackoverflow.com/questions/43632", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "118" }
Q: Is there a good WPF diagrammer / toolkit / provider? Basically we need a custom diagram component in our new WPF based application. Needs to show text/lines, linked 2D Nodes and custom images apart from the other diagramming features like Undo/Redo, Align, Group, etc.. ala Visio. The initial team did a bit of investigation and settled on the WinForms Northwoods GoDiagrams suite... a solution to embed it in our WPF application. Are there any equivalent WPF diagramming packages out there yet? Preferably tried ones. Thanks.. A: My colleague has been using WpfDiagram from MindFusion for the last two weeks and says that it's an excellent product. A: Mindscape provide a WPF Flow Diagram component which includes a base library that exposes nodes, connections, etc. Includes grouping, undo/redo and the features you mention. Not free, but there is a trial to see if it meets your needs. Mindscape WPF Flow Diagrams A: What about WPF Diagram Designer - this one is free. Is there someone with any experience with this? A: Just remember DO NOT choose Syncfusion. I've been suffering from it when developing WPF Application. There are so many bugs in it.
{ "language": "en", "url": "https://stackoverflow.com/questions/43638", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: How do I style (css) radio buttons and labels? Given the code bellow, how do I style the radio buttons to be next to the labels and style the label of the selected radio button differently than the other labels? <link href="http://yui.yahooapis.com/2.5.2/build/reset-fonts-grids/reset-fonts-grids.css" rel="stylesheet"> <link href="http://yui.yahooapis.com/2.5.2/build/base/base-min.css" rel="stylesheet"> <div class="input radio"> <fieldset> <legend>What color is the sky?</legend> <input type="hidden" name="color" value="" id="SubmitQuestion" /> <input type="radio" name="color" id="SubmitQuestion1" value="1" /> <label for="SubmitQuestion1">A strange radient green.</label> <input type="radio" name="color" id="SubmitQuestion2" value="2" /> <label for="SubmitQuestion2">A dark gloomy orange</label> <input type="radio" name="color" id="SubmitQuestion3" value="3" /> <label for="SubmitQuestion3">A perfect glittering blue</label> </fieldset> </div> Also let me state that I use the yui css styles as base. If you are not familir with them, they can be found here: * *reset-fonts-grids.css *base-min.css Documentation for them both here : Yahoo! UI Library @pkaeding: Thanks. I tried some floating both thing that just looked messed up. The styling active radio button seemed to be doable with some input[type=radio]:active nomination on a google search, but I didnt get it to work properly. So the question I guess is more: Is this possible on all of todays modern browsers, and if not, what is the minimal JS needed? A: This will get your buttons and labels next to each other, at least. I believe the second part can't be done in css alone, and will need javascript. I found a page that might help you with that part as well, but I don't have time right now to try it out: http://www.webmasterworld.com/forum83/6942.htm <style type="text/css"> .input input { float: left; } .input label { margin: 5px; } </style> <div class="input radio"> <fieldset> <legend>What color is the sky?</legend> <input type="hidden" name="data[Submit][question]" value="" id="SubmitQuestion" /> <input type="radio" name="data[Submit][question]" id="SubmitQuestion1" value="1" /> <label for="SubmitQuestion1">A strange radient green.</label> <input type="radio" name="data[Submit][question]" id="SubmitQuestion2" value="2" /> <label for="SubmitQuestion2">A dark gloomy orange</label> <input type="radio" name="data[Submit][question]" id="SubmitQuestion3" value="3" /> <label for="SubmitQuestion3">A perfect glittering blue</label> </fieldset> </div> A: The first part of your question can be solved with just HTML & CSS; you'll need to use Javascript for the second part. Getting the Label Near the Radio Button I'm not sure what you mean by "next to": on the same line and near, or on separate lines? If you want all of the radio buttons on the same line, just use margins to push them apart. If you want each of them on their own line, you have two options (unless you want to venture into float: territory): * *Use <br />s to split the options apart and some CSS to vertically align them: <style type='text/css'> .input input { width: 20px; } </style> <div class="input radio"> <fieldset> <legend>What color is the sky?</legend> <input type="hidden" name="data[Submit][question]" value="" id="SubmitQuestion" /> <input type="radio" name="data[Submit][question]" id="SubmitQuestion1" value="1" /> <label for="SubmitQuestion1">A strange radient green.</label> <br /> <input type="radio" name="data[Submit][question]" id="SubmitQuestion2" value="2" /> <label for="SubmitQuestion2">A dark gloomy orange</label> <br /> <input type="radio" name="data[Submit][question]" id="SubmitQuestion3" value="3" /> <label for="SubmitQuestion3">A perfect glittering blue</label> </fieldset> </div> * *Follow A List Apart's article: Prettier Accessible Forms Applying a Style to the Currently Selected Label + Radio Button Styling the <label> is why you'll need to resort to Javascript. A library like jQuery is perfect for this: <style type='text/css'> .input label.focused { background-color: #EEEEEE; font-style: italic; } </style> <script type='text/javascript' src='jquery.js'></script> <script type='text/javascript'> $(document).ready(function() { $('.input :radio').focus(updateSelectedStyle); $('.input :radio').blur(updateSelectedStyle); $('.input :radio').change(updateSelectedStyle); }) function updateSelectedStyle() { $('.input :radio').removeClass('focused').next().removeClass('focused'); $('.input :radio:checked').addClass('focused').next().addClass('focused'); } </script> The focus and blur hooks are needed to make this work in IE. A: For any CSS3-enabled browser you can use an adjacent sibling selector for styling your labels input:checked + label { color: white; } MDN's browser compatibility table says essentially all of the current, popular browsers (Chrome, IE, Firefox, Safari), on both desktop and mobile, are compatible.
{ "language": "en", "url": "https://stackoverflow.com/questions/43643", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "31" }
Q: Can I update/select from a table in one query? I need to select data when a page is viewed and update the 'views' column is there a way to do this in one query, or do I have to use to distinct queries? A: You would have to do this in two statements in one transaction Begin Tran Update Pages Set Views = Views + 1 Where ID = @ID Select Columns From Pages Where ID = @ID Commit Tran A: If you do not want/need to use a transaction, you could create a stored procedure that first updates the view count and then selects the values and return them to the user. A: It would help if you listed the RDBMS you are using SQL Server has the OUTPUT statement Example USE AdventureWorks; GO DECLARE @MyTestVar table ( OldScrapReasonID int NOT NULL, NewScrapReasonID int NOT NULL, WorkOrderID int NOT NULL, ProductID int NOT NULL, ProductName nvarchar(50)NOT NULL); UPDATE Production.WorkOrder SET ScrapReasonID = 4 OUTPUT DELETED.ScrapReasonID, INSERTED.ScrapReasonID, INSERTED.WorkOrderID, INSERTED.ProductID, p.Name INTO @MyTestVar FROM Production.WorkOrder AS wo INNER JOIN Production.Product AS p ON wo.ProductID = p.ProductID AND wo.ScrapReasonID= 16 AND p.ProductID = 733; SELECT OldScrapReasonID, NewScrapReasonID, WorkOrderID, ProductID, ProductName FROM @MyTestVar; GO A: PostgreSQL's UPDATE statement has the RETURNING clause that will return a result set like a SELECT statement: UPDATE mytable SET views = 5 WHERE id = 16 RETURNING id, views, othercolumn; I'm pretty sure this is not standard though. I don't know if any other databases implement it. Edit: I just noticed that your question has the "MySQL" tag. Maybe you should mention it in the question itself. It's a good generic database question though - I would like to see how to do it in other databases. A: I used this trick with Java and SQL Server will also let you send two commands in a single PreparedStatement. update tablex set y=z where a=b \r\n select a,b,y,z from tablex This will need to be in a read committed transaction to work like you think it should though.
{ "language": "en", "url": "https://stackoverflow.com/questions/43644", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: What types of executables can be decompiled? I think that java executables (jar files) are trivial to decompile and get the source code. What about other languages? .net and all? Which all languages can compile only to a decompile-able code? A: Managed languages can be easily decompiled because executable must contain a lot of metadata to support reflection. Languages like C++ can be compiled to native code. Program structure can be totally changed during compilation\translation processes. Compiler can easily replace\merge\delete parts of your code. There is no 1 to 1 relationship between original and compiled (native) code. A: .NET is very easy to decompile. The best tool to do that would be the .NET reflector recently acquired by RedGate. A: In general, languages like Java, C#, and VB.NET are relatively easy to decompile because they are compiled to an intermediary language, not pure machine language. In their IL form, they retain more metadata than C code does when compiled to machine language. Technically you aren't getting the original source code out, but a variation on the source code that, when compiled, will give you the compiled code back. It isn't identical to the source code, as things like comments, annotations, and compiler directives usually aren't carried forward into the compiled code. A: Most languages can be decompiled but some are easier to decompile than others. .Net and Java put more information about the original program in the executables (method names, variable names etc.) so you get more of your original information back. C++ for example will translate variables and functions etc. to memory adresses (yeah I know this is a gross simplification) so the decompiler won't know what stuff was called. But you can still get some of the structure of the program back though. A: VB6 if compiled to pcode is also possible to decompile to almost full source using P32Dasm, Flash (or actionscript) is also possible to decompile to full source using something like Flare
{ "language": "en", "url": "https://stackoverflow.com/questions/43672", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Pros and Cons of different approaches to web programming in Python I'd like to do some server-side scripting using Python. But I'm kind of lost with the number of ways to do that. It starts with the do-it-yourself CGI approach and it seems to end with some pretty robust frameworks that would basically do all the job themselves. And a huge lot of stuff in between, like web.py, Pyroxide and Django. * *What are the pros and cons of the frameworks or approaches that you've worked on? *What trade-offs are there? *For what kind of projects they do well and for what they don't? Edit: I haven't got much experience with web programing yet. I would like to avoid the basic and tedious things like parsing the URL for parameters, etc. On the other hand, while the video of blog created in 15 minutes with Ruby on Rails left me impressed, I realized that there were hundreds of things hidden from me - which is cool if you need to write a working webapp in no time, but not that great for really understanding the magic - and that's what I seek now. A: If you decide to go with a framework that is WSGI-based (for instance TurboGears), I would recommend you go through the excellent article Another Do-It-Yourself Framework by Ian Bicking. In the article, he builds a simple web application framework from scratch. Also, check out the video Creating a web framework with WSGI by Kevin Dangoor. Dangoor is the founder of the TurboGears project. A: If you want to go big, choose Django and you are set. But if you want just to learn, roll your own framework using already mentioned WebOb - this can be really fun and I am sure you'll learn much more (plus you can use components you like: template system, url dispatcher, database layer, sessions, et caetera). In last 2 years I built few large sites using Django and all I can say, Django will fill 80% of your needs in 20% of time. Remaining 20% of work will take 80% of the time, no matter which framework you'd use. A: It's always worth doing something the hard way - once - as a learning exercise. Once you understand how it works, pick a framework that suits your application, and use that. You don't need to reinvent the wheel once you understand angular velocity. :-) It's also worth making sure that you have a fairly robust understanding of the programming language behind the framework before you jump in -- trying to learn both Django and Python at the same time (or Ruby and Rails, or X and Y), can lead to even more confusion. Write some code in the language first, then add the framework. We learn to develop, not by using tools, but by solving problems. Run into a few walls, climb over, and find some higher walls! A: If you've never done any CGI programming before I think it would be worth doing one project - perhaps just a sample play site just for yourself - using the DIY approach. You'll learn a lot more about how all the various parts work than you would by using a framework. This will help in you design and debug and so on all your future web applications however you write them. Personally I now use Django. The real benefit is very fast application deployment. The object relational mapping gets things moving fast and the template library is a joy to use. Also the admin interface gives you basic CRUD screens for all your objects so you don't need to write any of the "boring" stuff. The downside of using an ORM based solution is that if you do want to handcraft some SQL, say for performance reasons, it much harder than it would have been otherwise, although still very possible. A: If you are using Python you should not start with CGI, instead start with WSGI (and you can use wsgiref.handlers.CGIHandler to run your WSGI script as a CGI script. The result is something that is basically as low-level as CGI (which might be useful in an educational sense, but will also be somewhat annoying), but without having to write to an entirely outdated interface (and binding your application to a single process model). If you want a less annoying, but similarly low-level interface, using WebOb would provide that. You would be implementing all the logic, and there will be few dark corners that you won't understand, but you won't have to spend time figuring out how to parse HTTP dates (they are weird!) or parse POST bodies. I write applications this way (without any other framework) and it is entirely workable. As a beginner, I'd advise this if you were interested in understanding what frameworks do, because it is inevitable you will be writing your own mini framework. OTOH, a real framework will probably teach you good practices of application design and structure. To be a really good web programmer, I believe you need to try both seriously; you should understand everything a framework does and not be afraid of its internals, but you should also spend time in a thoughtful environment someone else designed (i.e., an existing framework) and understand how that structure helps you. A: CGI is great for low-traffic websites, but it has some performance problems for anything else. This is because every time a request comes in, the server starts the CGI application in its own process. This is bad for two reasons: 1) Starting and stopping a process can take time and 2) you can't cache anything in memory. You can go with FastCGI, but I would argue that you'd be better off just writing a straight WSGI app if you're going to go that route (the way WSGI works really isn't a whole heck of a lot different from CGI). Other than that, your choices are for the most part how much you want the framework to do. You can go with an all singing, all dancing framework like Django or Pylons. Or you can go with a mix-and-match approach (use something like CherryPy for the HTTP stuff, SQLAlchemy for the database stuff, paste for deployment, etc). I should also point out that most frameworks will also let you switch different components out for others, so these two approaches aren't necessarily mutually exclusive. Personally, I dislike frameworks that do too much magic for me and prefer the mix-and-match technique, but I've been told that I'm also completely insane. :) How much web programming experience do you have? If you're a beginner, I say go with Django. If you're more experienced, I say to play around with the different approaches and techniques until you find the right one. A: The simplest web program is a CGI script, which is basically just a program whose standard output is redirected to the web browser making the request. In this approach, every page has its own executable file, which must be loaded and parsed on every request. This makes it really simple to get something up and running, but scales badly both in terms of performance and organization. So when I need a very dynamic page very quickly that won't grow into a larger system, I use a CGI script. One step up from this is embedding your Python code in your HTML code, such as with PSP. I don't think many people use this nowadays, since modern template systems have made this pretty obsolete. I worked with PSP for awhile and found that it had basically the same organizational limits as CGI scripts (every page has its own file) plus some whitespace-related annoyances from trying to mix whitespace-ignorant HTML with whitespace-sensitive Python. The next step up is very simple web frameworks such as web.py, which I've also used. Like CGI scripts, it's very simple to get something up and running, and you don't need any complex configuration or automatically generated code. Your own code will be pretty simple to understand, so you can see what's happening. However, it's not as feature-rich as other web frameworks; last time I used it, there was no session tracking, so I had to roll my own. It also has "too much magic behavior" to quote Guido ("upvars(), bah"). Finally, you have feature-rich web frameworks such as Django. These will require a bit of work to get simple Hello World programs working, but every major one has a great, well-written tutorial (especially Django) to walk you through it. I highly recommend using one of these web frameworks for any real project because of the convenience and features and documentation, etc. Ultimately you'll have to decide what you prefer. For example, frameworks all use template languages (special code/tags) to generate HTML files. Some of them such as Cheetah templates let you write arbitrary Python code so that you can do anything in a template. Others such as Django templates are more restrictive and force you to separate your presentation code from your program logic. It's all about what you personally prefer. Another example is URL handling; some frameworks such as Django have you define the URLs in your application through regular expressions. Others such as CherryPy automatically map your functions to urls by your function names. Again, this is a personal preference. I personally use a mix of web frameworks by using CherryPy for my web server stuff (form parameters, session handling, url mapping, etc) and Django for my object-relational mapping and templates. My recommendation is to start with a high level web framework, work your way through its tutorial, then start on a small personal project. I've done this with all of the technologies I've mentioned and it's been really beneficial. Eventually you'll get a feel for what you prefer and become a better web programmer (and a better programmer in general) in the process. A: OK, rails is actually pretty good, but there is just a little bit too much magic going on in there (from the Ruby world I would much prefer merb to rails). I personally use Pylons, and am pretty darn happy. I'd say (compared to django), that pylons allows you to interchange ints internal parts easier than django does. The downside is that you will have to write more stuff all by youself (like the basic CRUD). Pros of using a framework: * *get stuff done quickly (and I mean lighning fast once you know the framework) *everything is compying to standards (which is probably not that easy to achieve when rolling your own) *easier to get something working (lots of tutorials) without reading gazillion articles and docs Cons: * *you learn less *harder to replace parts (not that much of an issue in pylons, more so with django) *harder to tweak some low-level stuff (like the above mentioned SQLs) From that you can probably devise what they are good for :-) Since you get all the code it is possible to tweak it to fit even the most bizzare situations (pylons supposedly work on the Google app engine now...). A: For smaller projects, rolling your own is fairly easy. Especially as you can simply import a templating engine like Genshi and get alot happening quite quickly and easily. Sometimes it's just quicker to use a screwdriver than to go looking for the power drill. Full blown frameworks provide alot more power, but do have to be installed and setup first before you can leverage that power. For larger projects, this is a negligible concern, but for smaller projects this might wind up taking most of your time - especially if the framework is unfamiliar.
{ "language": "en", "url": "https://stackoverflow.com/questions/43709", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "25" }
Q: What's a good way to overwrite DateTime.Now during testing? I've got some (C#) code that relies on today's date to correctly calculate things in the future. If I use today's date in the testing, I have to repeat the calculation in the test, which doesn't feel right. What's the best way to set the date to a known value within the test so that I can test that the result is a known value? A: Ayende Rahien uses a static method that is rather simple... public static class SystemTime { public static Func<DateTime> Now = () => DateTime.Now; } A: I'd suggest using IDisposable pattern: [Test] public void CreateName_AddsCurrentTimeAtEnd() { using (Clock.NowIs(new DateTime(2010, 12, 31, 23, 59, 00))) { string name = new ReportNameService().CreateName(...); Assert.AreEqual("name 2010-12-31 23:59:00", name); } } In detail described here: http://www.lesnikowski.com/blog/index.php/testing-datetime-now/ A: Simple answer: ditch System.DateTime :) Instead, use NodaTime and it's testing library: NodaTime.Testing. Further reading: * *Unit testing with Noda Time *Dependency Injection: Inject Your Dependencies, Period! A: You could inject the class (better: method/delegate) you use for DateTime.Now in the class being tested. Have DateTime.Now be a default value and only set it in testing to a dummy method that returns a constant value. EDIT: What Blair Conrad said (he has some code to look at). Except, I tend to prefer delegates for this, as they don't clutter up your class hierarchy with stuff like IClock... A: Using Microsoft Fakes to create a shim is a really easy way to do this. Suppose I had the following class: public class MyClass { public string WhatsTheTime() { return DateTime.Now.ToString(); } } In Visual Studio 2012 you can add a Fakes assembly to your test project by right clicking on the assembly you want to create Fakes/Shims for and selecting "Add Fakes Assembly" Finally, Here is what the test class would look like: using System; using ConsoleApplication11; using Microsoft.QualityTools.Testing.Fakes; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace DateTimeTest { [TestClass] public class UnitTest1 { [TestMethod] public void TestWhatsTheTime() { using(ShimsContext.Create()){ //Arrange System.Fakes.ShimDateTime.NowGet = () => { return new DateTime(2010, 1, 1); }; var myClass = new MyClass(); //Act var timeString = myClass.WhatsTheTime(); //Assert Assert.AreEqual("1/1/2010 12:00:00 AM",timeString); } } } } A: I think creating a separate clock class for something simple like getting the current date is a bit overkill. You can pass today's date as a parameter so you can input a different date in the test. This has the added benefit of making your code more flexible. A: My preference is to have classes that use time actually rely on an interface, such as interface IClock { DateTime Now { get; } } With a concrete implementation class SystemClock: IClock { DateTime Now { get { return DateTime.Now; } } } Then if you want, you can provide any other kind of clock you want for testing, such as class StaticClock: IClock { DateTime Now { get { return new DateTime(2008, 09, 3, 9, 6, 13); } } } There may be some overhead in providing the clock to the class that relies on it, but that could be handled by any number of dependency injection solutions (using an Inversion of Control container, plain old constructor/setter injection, or even a Static Gateway Pattern). Other mechanisms of delivering an object or method that provides desired times also work, but I think the key thing is to avoid resetting the system clock, as that's just going to introduce pain on other levels. Also, using DateTime.Now and including it in your calculations doesn't just not feel right - it robs you of the ability to test particular times, for example if you discover a bug that only happens near a midnight boundary, or on Tuesdays. Using the current time won't allow you to test those scenarios. Or at least not whenever you want. A: The key to successful unit testing is decoupling. You have to separate your interesting code from its external dependencies, so it can be tested in isolation. (Luckily, Test-Driven Development produces decoupled code.) In this case, your external is the current DateTime. My advice here is to extract the logic that deals with the DateTime to a new method or class or whatever makes sense in your case, and pass the DateTime in. Now, your unit test can pass an arbitrary DateTime in, to produce predictable results. A: Another one using Microsoft Moles (Isolation framework for .NET). MDateTime.NowGet = () => new DateTime(2000, 1, 1); Moles allows to replace any .NET method with a delegate. Moles supports static or non-virtual methods. Moles relies on the profiler from Pex. A: I faced this situation so often, that I created simple nuget which exposes Now property through interface. public interface IDateTimeTools { DateTime Now { get; } } Implementation is of course very straightforward public class DateTimeTools : IDateTimeTools { public DateTime Now => DateTime.Now; } So after adding nuget to my project I can use it in the unit tests You can install module right from the GUI Nuget Package Manager or by using the command: Install-Package -Id DateTimePT -ProjectName Project And the code for the Nuget is here. The example of usage with the Autofac can be found here. A: Just pass DateTime.Now as a parameter to the method that needs it. Can't be more simple than that. https://blog.thecodewhisperer.com/permalink/beyond-mock-objects A: Have you considered using conditional compilation to control what happens during debug/deployment? e.g. DateTime date; #if DEBUG date = new DateTime(2008, 09, 04); #else date = DateTime.Now; #endif Failing that, you want to expose the property so you can manipulate it, this is all part of the challenge of writing testable code, which is something I am currently wrestling myself :D Edit A big part of me would preference Blair's approach. This allows you to "hot plug" parts of the code to aid in testing. It all follows the design principle encapsulate what varies test code is no different to production code, its just no one ever sees it externally. Creating and interface may seem like a lot of work for this example though (which is why I opted for conditional compilation).
{ "language": "en", "url": "https://stackoverflow.com/questions/43711", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "126" }
Q: DefaultValue for System.Drawing.SystemColors I have a line color property in my custom grid control. I want it to default to Drawing.SystemColors.InactiveBorder. I tried: [DefaultValue(typeof(System.Drawing.SystemColors), "InactiveBorder")] public Color LineColor { get; set; } But it doesn't seem to work. How do I do that with the default value attribute? A: According to the link Matt posted, the DefaultValue attribute doesn't set the default value of the property, it just lets the form designer know that the property has a default value. If you change a property from the default value it is shown as bold in the properties window. You can't set a default value using automatic properties - you'll have to do it the old-fashioned way: class MyClass { Color lineColor = SystemColors.InactiveBorder; [DefaultValue(true)] public Color LineColor { get { return lineColor; } set { lineColor = value; } } } A: You need to change first argument from SystemColors to Color. It seems that there is no type converter for the SystemColors type, only for the Color type. [DefaultValue(typeof(Color),"InactiveBorder")]
{ "language": "en", "url": "https://stackoverflow.com/questions/43738", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: SQL Profiler on SQL Server 2005 Professional Edition I want to use SQL Profiler to trace the queries executed agains my database, track performance, etc. However it seems that the SQL Profiler is only available in the Enterprise edition of SQL Server 2005. Is this the case indeed, and can I do something about it? A: You don't need any SQL license to run the client tools (Management Studio, Profiler, etc). If your organization has a copy of the installation media for Developer, Standard, or Enterprise, you can install the client tools on your local machine under the same license. If you're working solo, I would recommend purchasing SQL Developer edition, it's only $50. A: If you are open to using third party profilers, I have used xSQL Profiler and it performed well enough. A: The SQL Profiler tool is only available with the Standard and Enterprise version of SQL Server, however, all version can be profiled using the tool. Source: http://www.microsoft.com/sql/prodinfo/features/compare-features.mspx A: Client tools are not licensed separately. So you can download the evaluation edition of SQL 2008 R2 and use the client tools from it (the client tools will still work even once the eval expires and the engine is no longer usable). You must be licensed in some way for each sql server you connect to but that is not the same as requiring a license to use the tools. You can use SQL Profiler on both Standard and Enterprise editions, but you will need certain rights to run it (you need to have sa rights or be granted ALTER TRACE permissions)
{ "language": "en", "url": "https://stackoverflow.com/questions/43742", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: ASP.NET MVC Performance I found some wild remarks that ASP.NET MVC is 30x faster than ASP.NET WebForms. What real performance difference is there, has this been measured and what are the performance benefits. This is to help me consider moving from ASP.NET WebForms to ASP.NET MVC. A: I think the problem here is that no matter how much faster ASP.Net MVC is than the old webforms, it won't make a difference, because most of the time taken is in the database. Most of the time, you web servers will be sitting at 0-10% CPU usage just waiting on your database server. Unless you get an extremely large number of hits on your website, and your database is extremely fast, you probably won't notice a big difference. A: We haven't performed the type of scalability and perf tests necessary to come up with any conclusions. I think ScottGu may have been discussing potential perf targets. As we move towards Beta and RTM, we will internally be doing more perf testing. However, I'm not sure what our policy is on publishing results of perf tests. In any case, any such tests really need to consider real world applications... A: The only concrete numbers I can find which are from early ASP.NET MVC-development is on this forum-thread: http://forums.asp.net/p/1231621/2224136.aspx Rob Connery himself somewhat confirms statement that ScottGu has claimed that ASP.NET MVC can serve 8000 requests per second. Maybe Jeff and his crew can give some kind of hint from their development of this site. A: I think this will be a hard question to definitively answer as so much will depend on A) how you implement the WebForms application, and B) how you implement the MVC application. In their "raw" forms, MVC is likely faster than WebForms, but years and years of tools and experience have produced a number of techniques for building fast WebForms applications. I'd be willing to bet that a senior ASP.NET developer could produce a WebForms application that rivals the speed of any MVC application- or at least achieve a negligible difference. The real difference- as @tvanfosson suggested- is in testability and clean SoC. If improving performance is your chief concern, I don't think it's a great reason to jump ship on WebForms and start re-building in MVC. Not at least until you've tried the available techniques for optimizing WebForms. A: It decreased one of my pages from 2MB payload, to 200k, just by eliminating the viewstate and making it bearable programatically to work with the submitted output. The size alone, even though the processing was the same will create vast improvements in connections per second and speed of the requests. A: Contrary to the accepted opinion, optimized webforms usage completely kills MVC in terms of raw performance. Webforms has been hyper-optimized for the task of serving html far longer than MVC has. Metrics are available on http://www.techempower.com/benchmarks/#section=data-r7&hw=i7&test=db Every single comparison mvc is on the lower-middle/lower-upper rankings of the list, while optimized webforms usage places in the upper-middle/upper-lower rankings. Anecdotal but very serious validation to these metrics, www.microsoft.com is served by webforms not MVC. Does anyone here believe that they wouldn't have chosen MVC if it was empirically faster? A: I think that many of the people who think that WebForms are inherently slow or resource intensive are placing the blame in the wrong place. 9 times out of 10 when I am brought in to optimize a webforms app there are way too many places where the apps authors misunderstand the purpose of the viewstate. I'm not saying that the viewstate is perfect or anything, but it is WAY too easy to abuse it, and it is this abuse that is causing the bloated viewstate field. This article was invalueable in helping me understand many of these abuses. https://weblogs.asp.net/infinitiesloop/truly-understanding-viewstate In order to make a valid comparison between MVC and WebForms we need to be sure that both apps are using the architectures correctly. A: There's really no way to answer this. MVC uses the Web Forms view engine by default itself, and can be configured to use any number of custom view engines, so if you want a performance comparison you'll have to be more specific. A: I started out work in MVC about a year ago, I was inspired but not impressed. I loath the view state and see it as the root of all evil in terms of ASP.NET. This is why I just don't use it and to be perfectly honest why would you? I took basically the ASP.NET MVC Framework concept and built that in my own way. I changed a couple of things though. I built my controller wrapping code, or URL routing code around dynamic recompilation. Now, I would go as far as to say that ASP.NET MVC applications will be faster based on how you use it. If you completely abandon WebForms you'll be faster becuase the ASP.NET life-cycle and object model is humongous. When you're writing you're instantiating an army... no wait, a legion of objects that will participate in the rendering of your view. This is gonna be slower than if you where to express the minimal amount of behavior in the ASPX page itself. (I don't care about view engine abstraction because the support for ASPX pages in Visual Studio is decent, but I've completely dropped WebForms as a concept and basically any ASP.NET framework due to code bloat or not being able to change the things that wire my application). I've found ways of relying on dynamic recompilation (System.Reflection.Emit) for emitting special purpose objects and code whenever needed. The executing of this code is faster than reflection but initially built through the reflection service. This has given my MVC flavored framework great performance but also very statically typed. I don't use strings and name/value pair collections. Instead my custom compiler services goes in a rewrites a form post to a controller action being passed an reference type. Behind the scene there is a lot of things going on but this code is fast, a lot faster than WebForms or the MVC Framework. Also, I don't write URLs, I write lambda expressions that get translated into URLs that later tell which controller action to invoke. This isn't particularly fast but it beats having broken URLs. It's like if you had statically typed resources as well as statically typed objects. A statically typed web application? That is what I want! I would encourage more people to try this out. A: The projects created with visual studio. One is mvc4 template, another is WebForm (tranditional). And when make load test with WCAT, this is the result, MVC4 is quite slow than WebForms, any ideas? MVC4 * *could get about 11 rps *rps is quite low both 2-cpu or 4-cpu server WebForms (aspx) * *could get above 2500 rps *the performance killer has been found that it's a bug of MVC Bata or RC. And The performance would be improved once i remove Bundles things. Now the latest version fixed this. A: My testing shows something between 2x and 7x more req/sec on MVC, but it depends how you build your webforms app. With just "hello world" text on it, without any server side control, mvc is around 30-50% faster. A: For me the real "performance" improvement in MVC is the increase the testable surface of the application. With WebForms there was a lot of the application that was hard to test. With MVC the amount of code that becomes testable basically doubles. Basically all that isn't easily testable is the code that generates the layout. All of your business logic and data access logic -- including the logic that populates the actual data used in the view -- is now amenable to testing. While I expect it to be more performant as well -- the page life cycle is greatly simplified and more more amenable to web programming -- even if it were the same or a little slower it would be worth switching to from a quality perspective. A: Performance depends on what you are doing... Usually MVC is faster than asp.net mostly because Viewstate is absent and because MVC works more with Callback than Postback by default. If you optimize your webform page you can have the same performance as MVC but it will be a lot of work. Also, their is a lot of nugets for MVC (and also for Webform) to help you to improve website performance like combine and minify your css and javascripts, group your images and use them as a sprite, and so on. Website's performance depend greatly of your architecture. A clean one with good separation of concern will bring you a more clean code and a better idea of how improve performance. You can take a look at this template "Neos-SDI MVC Template" which will create for you a clean architecture with lots of performance improvements by default (check MvcTemplate website). A: I did a small VSTS load test experiment with some basic code and found ASP.NET MVC response time to be twice faster as compared to ASP.NET Webforms. Above is the attached graph with the plot. You can read this load test experiment in details from this CP article https://www.codeproject.com/Articles/864950/ASP-NET-MVC-vs-ASP-NET-WebForm-performance-compari Test was conducted with the below specifications using VSTS and telerik load test software:- User load 25 users. Run duration of test was 10 minutes. Machine config DELL 8 GB Ram, Core i3 Project was hosted in IIS 8. Project was created using MVC 5. Network LAN connection was assumed. So this test does not account for network lag for now. Browser in the test selected Chrome and Internet explorer. Multiple reading where taken during the test to average unknown events. 7 readings where taken and all readings are published in this article as reading 1 , 2 and so on.
{ "language": "en", "url": "https://stackoverflow.com/questions/43743", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "102" }
Q: MS Access Reporting - can it be pretty? I am working on a project converting a "spreadsheet application" to a database solution. A macro was written that takes screen shots of each page and pastes them into a PowerPoint presentation. Because of the nice formatting options in Excel, the presentation looks very pretty. The problem I'm having is that I haven't ever seen an Access report that would be pretty enough to display to upper management. I think the output still has to be a PowerPoint presentation. It needs to look as close as possible to the original output. I am currently trying to write some code to use a .pot (presentation template) and fill in the data programmatically. Putting the data into a PowerPoint table has been tricky because the tables are not easy to manipulate. For example, if a particular description is too long, I need to break into the next cell down (word-wrap isn't allowed because I can only have n lines per page). Is there a way to make an Access report pretty, am I headed down the right path, or should I just try to programmatically fill in the Excel spreadsheet and use the code that already exists there to produce the presentation? (I'd still need to figure out how to know when to break a line when using a non-monospaced font, as the users are currently doing that manually when they enter the data in the spreadsheet) Jason Z: If I set it to wrap, and I already have n lines, it would make n+1 or 2 lines on the slide, which is unacceptable. Dennis: That article looks very good, I should be able to glean something from it. Thanks! A: Joel, (your co-host here) did a thing about using access reports for shipping labels a few years back... maybe this could be a inspriation for you? http://www.joelonsoftware.com/articles/HowToShipAnything.html A: Access has the capability to create downright beautiful reports. The problem is that it can't make a spreadsheet look better than Excel. You have to know when to use each tool. Use Excel when you have spreadsheet-like formatting, need a lot of boxes and lines, or want to draw charts. Use Access when you will output a report as a PDF. It's very useful for one-record-per-page detail reports, formatting where you need to position things very precisely, and where you need to embed subreports with related or unrelated data. Think about the reports that would be nasty in Excel because you'd have to merge cells all over the place and do funny things with the placement and the layout would never work. That's where Access shines. A: I have implemented Access reports which were 'pretty' enough. The downside is that it takes a lot of time and effort, and trial and error to produce the desired output. You can definitely get there, but it requires the patience of a saint. A: I guess it depends on what you mean by pretty. For example, I do not find it particularly difficult to produce say, reasonable graphs and tables with alternate line shading in Access. It is also possible to use MS Word and fill in bookmarks, or mail merge. If the present system uses VBA to create the PowerPoint presentation, perhaps much of it could be transferred to Access? Microsoft have an article on Access to Powerpoint: http://msdn.microsoft.com/en-us/library/aa159920(office.11).aspx Finally, it is not impossible to build HTML output from Access. A: I would suggest that the problem you're having is because the requirement to replicate the old method identically is an incredibly bad idea. You're not using Excel any more. You're using a different tool with different capabilities. Thus, you will use different methods to get results. Re-evaluate the original requirements to see if they still make sense (e.g., exactly why is PowerPoint involved at all? Can PowerPoint import from the Access report snapshot viewer? Can PowerPoint import from a PDF produced from an Access report?), or if they are too connected to the old tools, and then determine what is important and what isn't, and only then should you start designing your solution. A: We create multi-colored, conditionally formated, reports that are printed for the partner meeting each month of a publically traded corporation. They're real pretty. A: I personally would not try to re-invent the wheel here. If you already have an Excel sheet that has the formatting you want, just export the data from Access into Excel for the report. Now, if you didn't have the original Excel sheet to begin with, that would be a completely different story. As for breaking lines with non-monospaced fonts, have you tried setting the cell format to wrap? A: It sounds like the path of least resistance is to fill in the Excel spreadsheet. We have a contractor who does our Access stuff, and for the more complicated reports he uses Excel. I guess complicated == hard to make look good. A: Rather than filling in the excel spreadsheet programmatically, you may want to use the external data features of Excel and Access. Generally I put a query on each tab, which of course may be hidden. An "update all" causes all the queries to be updated. Then summary tabs show the pretty results from all the individual queries. For one particularly complex system, a bit of excel vba programmatically changed a query and then walked through the tabs updating each one. Finally, rather than doing screen shots, Excel has a "copy cells as a image" copy that populates the copy buffer with a resizeable image. This could give you better looking results than a pure screenshot since a screenshot can have various deficiencies depending on pixel density. A: Just an update: After a few hours of work, I was able to get a nice report out of Access (almost an exact copy of the excel version). It wasn't as difficult as I thought, I just had to figure the correct mixture of out subreports and pagebreaks. Working with the wordwrap features of Excel/Powerpoint were a dead end because there could only be a set number of lines per page, period; plus I was too lazy to nail down all the pagination with VBA code issues myself. Like Shelley says, Access shines at report generation. The output ended up being a PDF (Using Adobe Acrobat Professional). The problem I have left is getting select pages of said PDF into Powerpoint without Powerpoint antialiasing the results for me and making the resulting slide's text fuzzy. I found a couple of articles on converting .snp output to .wmf, which sounds like the way to go on that front.
{ "language": "en", "url": "https://stackoverflow.com/questions/43764", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Pin Emacs buffers to windows (for cscope) For my day job, I live in Emacs. Utterly. I also have become pretty dependent on CScope to help me find things in the code. Normally, I have 2 windows in a split (C-x 3): alt text http://bitthicket.com/files/emacs-2split.JPG And I use the right window for code buffers and the left window for the CScope search buffer. When you do a CScope search and select a result, it automatically updates the right-side window to show the buffer referred to by the result. This is all well and good, except that it causes me to lose my place in some other buffer that I was studying. Sometimes this is no biggie, because [C-s u] gets me back to where I was. What would be better, though, is to have 3 split windows like this ([C-x 2] in the left window): alt text http://bitthicket.com/files/emacs-3split.jpg And have the bottom left window contain the CScope search buffer, and the top left window be the only buffer that CScope ever updates. That way, I can see my CScope searches and navigate around the code without losing the buffer I'm focused on. Anyone know how I can do that? A: Put this in your .emacs file: ;; Toggle window dedication (defun toggle-window-dedicated () "Toggle whether the current active window is dedicated or not" (interactive) (message (if (let (window (get-buffer-window (current-buffer))) (set-window-dedicated-p window (not (window-dedicated-p window)))) "Window '%s' is dedicated" "Window '%s' is normal") (current-buffer))) Then bind it to some key - I use the Pause key: (global-set-key [pause] 'toggle-window-dedicated) And then use it to "dedicate" the window you want locked. then cscope can only open files from its result window in some OTHER window. Works a charm. I specifically use it for exactly this purpose - keeping one source file always on screen, while using cscope in a second buffer/window, and looking at cscope results in a third. A: Well, I decided to not be a reputation-whore and find the answer myself. I looked in cscope.el as shown on the Emacs wiki, as well as the xcscope.el that comes with the cscope RPM package on RHEL. Neither appear to give a way to do what I'm wanting. The way is probably to edit the ELisp by adding a package variable like *browse-buffer* or something and just initialize that variable if not already initialized the first time the user does [C-c C-s g] or whatever, and always have the resulting code shown in *browse-buffer*. Then the user can put the *browse-buffer* wherever he wants it.
{ "language": "en", "url": "https://stackoverflow.com/questions/43765", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "24" }
Q: VS.Net 2005 required on Build box with .Net 2.0 C++ Projects? We have a build box that uses CruiseControl.Net and has been building VB.Net and C# projects using msbuild. All I have installed on the box as far as .Net is concerned is .Net 2.0 SDK (I'm trying to keep the box as clean as possible). We are now trying to get a C++ app building on this box. The problem we are running into is that the header files (e.g. windows.h) are not installed with the SDK. Do I have to install VS 2005 to get this to work? Edit: As a couple people have answered, I had actually downloaded the 3.5 Platform SDK, but the applications built on this box MUST run on boxes that do not have 3.5 installed. By installing the 3.5 SDK on my 2.0 build box, am I compromising my build box? Edit: I'm going to leave this as unanswered, but thought I would add that I went ahead and installed Visual Studio on the box and all is well. I hate having to do that, but didn't want to run the risk of having a 3.5 SDK on my 2.0 build box. I would still love to hear a better solution. A: Visual Studio is not needed, but for C++ you need the Platform SDK as well: http://www.microsoft.com/downloads/details.aspx?familyid=484269E2-3B89-47E3-8EB7-1F2BE6D7123A&displaylang=en Edit: There is also one for Windows 2008/Vista, not sure which is the correct one: http://www.microsoft.com/downloads/details.aspx?familyid=E6E1C3DF-A74F-4207-8586-711EBE331CDC&displaylang=en A: No, you have to install the windows platform SDK. You'll need to download this: http://www.microsoft.com/downloads/details.aspx?FamilyId=E6E1C3DF-A74F-4207-8586-711EBE331CDC&displaylang=en Edit: @Michael Stum You need the Server 2008 / Vista / .NET 3.5 SDK version. A: Depending on what you are using in C++ (MFC, ATL, etc) you are probably going to have to install Visual Studio Professional (not express) as a lot of the libraries and headers are part of Visual Studio and not included in the SDK or Visual Studio Express (if you are doing managed C++ using .Net as the main framework then installing the SDK will be enough). We run our build boxes on VM's and so like to have as little installed as possible, so I spent a fair bit of time trying to get things working by installing as little as possible and for our C++ I ended up having to install Visual Studio. A: I don't see why having .NET 3.5 would comprimise the build box - 2.0 and 3.5 co-exist without a problem. The only concern I could see would be a developer upgrading a solution to VS2008 without your "permission" and the build not failing... A: In general, you need some set of SDKs (Software Development Kits) to be able to build, and some set of redistributable packages to run. In case it's not obvious, you should be testing your product on an otherwise clean machine before you ship, so you know you got the dependencies right.
{ "language": "en", "url": "https://stackoverflow.com/questions/43766", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: WPF control performance What is a good (and preferably simple) way to test the rendering performance of WPF custom controls? I have several complex controls in which rendering performance is highly crucial. I want to be able to make sure that I can have lots of them drawwing out in a designer with a minimal impact on performance. A: Tool called Perforator will help you. See following article for details: Performance Profiling Tools for WPF
{ "language": "en", "url": "https://stackoverflow.com/questions/43768", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Modulus operation with negatives values - weird thing? Can you please tell me how much is (-2) % 5? According to my Python interpreter is 3, but do you have a wise explanation for this? I've read that in some languages the result can be machine-dependent, but I'm not sure though. A: Like the documentation says in Binary arithmetic operations, Python assures that: The integer division and modulo operators are connected by the following identity: x == (x/y)*y + (x%y). Integer division and modulo are also connected with the built-in function divmod(): divmod(x, y) == (x/y, x%y). And truly, >>> divmod(-2, 5) (-1, 3). Another way to visualize the uniformity of this method is to calculate divmod for a small sequence of numbers: >>> for number in xrange(-10, 10): ... print divmod(number, 5) ... (-2, 0) (-2, 1) (-2, 2) (-2, 3) (-2, 4) (-1, 0) (-1, 1) (-1, 2) (-1, 3) (-1, 4) (0, 0) (0, 1) (0, 2) (0, 3) (0, 4) (1, 0) (1, 1) (1, 2) (1, 3) (1, 4) A: Well, 0 % 5 should be 0, right? -1 % 5 should be 4 because that's the next allowed digit going in the reverse direction (i.e., it can't be 5, since that's out of range). And following along by that logic, -2 must be 3. The easiest way to think of how it will work is that you keep adding or subtracting 5 until the number falls between 0 (inclusive) and 5 (exclusive). I'm not sure about machine dependence - I've never seen an implementation that was, but I can't say it's never done. A: As explained in other answers, there are many choices for a modulo operation with negative values. In general different languages (and different machine architectures) will give a different result. According to the Python reference manual, The modulo operator always yields a result with the same sign as its second operand (or zero); the absolute value of the result is strictly smaller than the absolute value of the second operand. is the choice taken by Python. Basically modulo is defined so that this always holds: x == (x/y)*y + (x%y) so it makes sense that (-2)%5 = -2 - (-2/5)*5 = 3 A: By the way: most programming languages would disagree with Python and give the result -2. Depending on the interpretation of modulus this is correct. However, the most agreed-upon mathematical definition states that the modulus of a and b is the (strictly positive) rest r of the division of a / b. More precisely, 0 <= r < b by definition. A: Your Python interpreter is correct. One (stupid) way of calculating a modulus is to subtract or add the modulus until the resulting value is between 0 and (modulus − 1). e.g.: 13 mod 5 = (13 − 5) mod 5 = (13 − 10) mod 5 = 3 or in your case: −2 mod 5 = (−2 + 5) mod 5 = 3 A: The result of the modulus operation on negatives seems to be programming language dependent and here is a listing http://en.wikipedia.org/wiki/Modulo_operation A: Well, -2 divided by 5 would be 0 with a remainder of 3. I don't believe that should be very platform dependent, but I've seen stranger things. A: It is indeed 3. In modular arithmetic, a modulus is simply the remainder of a division, and the remainder of -2 divided by 5 is 3. A: The result depends on the language. Python returns the sign of the divisor, where for example c# returns the sign of the dividend (ie. -2 % 5 returns -2 in c#). A: One explanation might be that negative numbers are stored using 2's complement. When the python interpreter tries to do the modulo operation it converts to unsigned value. As such instead of doing (-2) % 5 it actually computes 0xFFFF_FFFF_FFFF_FFFD % 5 which is 3. A: Be careful not to rely on this mod behavior in C/C++ on all OSes and architectures. If I recall correctly, I tried to rely on C/C++ code like float x2 = x % n; to keep x2 in the range from 0 to n-1 but negative numbers crept in when I would compile on one OS, but things would work fine on another OS. This made for an evil time debugging since it only happened half the time! A: There seems to be a common confusion between the terms "modulo" and "remainder". In math, a remainder should always be defined consistent with the quotient, so that if a / b == c rem d then (c * b) + d == a. Depending on how you round your quotient, you get different remainders. However, modulo should always give a result 0 <= r < divisor, which is only consistent with round-to-minus-infinity division if you allow negative integers. If division rounds towards zero (which is common), modulo and remainder are only equivalent for non-negative values. Some languages (notably C and C++) don't define the required rounding/remainder behaviours and % is ambiguous. Many define rounding as towards zero, yet use the term modulo where remainder would be more correct. Python is relatively unusual in that it rounds to negative infinity, so modulo and remainder are equivalent. Ada rounds towards zero IIRC, but has both mod and rem operators. The C policy is intended to allow compilers to choose the most efficient implementation for the machine, but IMO is a false optimisation, at least these days. A good compiler will probably be able to use the equivalence for optimisation wherever a negative number cannot occur (and almost certainly if you use unsigned types). On the other hand, where negative numbers can occur, you almost certainly care about the details - for portability reasons you have to use very carefully designed overcomplex algorithms and/or checks to ensure that you get the results you want irrespective of the rounding and remainder behaviour. In other words, the gain for this "optimisation" is mostly (if not always) an illusion, whereas there are very real costs in some cases - so it's a false optimisation.
{ "language": "en", "url": "https://stackoverflow.com/questions/43775", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "18" }
Q: 'method' vs. 'message' vs. 'function' vs. '???' I recently asked a question about what I called "method calls". The answer referred to "messages". As a self-taught hobby programmer trying to phrase questions that don't make me look like an idiot, I'm realizing that the terminology that I use reveals a lot about how I learned to program. Is there a distinction between the various terms for methods/messages/etc. in OO programming? Is this a difference that comes from different programming languages using different terminology to describe similar concepts? I seem to remember that in pre-OO languages, a distinction would sometimes be made between "subroutines" and "functions" based on whether a return value was expected, but even then, was this a language-by-language distinction? A: In Object Oriented implementations like C#, the concept of a "message" does not really exist as an explicit language construct. You can't look at a particular bit of code and say "there's the message." Instead, a method of an object's class implies the idea that other objects can send a type of message which trigger the behaviour within that method. So you end up just specifying the method directly, rather than sending a message. With other implementations like Smalltalk, you can see the message being passed, and the receiving object has the ability to do with that message what it will. There are libraries which sit on top of languages such as C# which attempt to restore the explicit message passing feel to the language. I've been cooking up one of my own for fun here: http://collaborateframework.codeplex.com/ A: I believe message is used in smalltalk. Java, C# etc. tend to use method or instance method. A: I am pretty sure (but a quick Wikipedia check seems to confirm this) that the `message passing' terminology comes from the Smalltalk community. I think it is more or less equivalent to a method call. A: The "Message" term can refer to sending a message to an object, which is supported in some programming languages and not others. If the object supports the message, then it will execute some code. Otherwise it will just ignore it. This is a more dynamic approach than an explicit function/method call where the object must support that function. Objective-c, I believe, uses this messaging approach. A: I've found this to be a language and programming-paradigm thing. One paradigm — OOP — refers to objects with member methods, which conceptually are how you send messages to those objects (this view is reflected in UML, for example). Another paradigm — functional — may or may not involve classes of objects, but functions are the atomic unit of work. In structured programming, you had sub-routines (notice that the prefix "sub" implies structure). In imperative programming (which overlaps with structured quite a lot, but a slightly different way of looking at things), you have a more formulaic view of the world, and so 'functions' represent some operation (often mathematical). All you have to do to not sound like a rube is to use the terminology used by the language reference for the language you're using. A: Message!=Method!=function in OOP different objects may have different methods bound to the same message. for example: the message "rotate left n degrees" would be implemented diffrently by diffrent objects such as shape, circle, rectangle and square. Messages: Objects communicate through messages. -Objects send and recieve messages. -the response to a message is executing a method. -the method to use is determine be the reciever at run-time. In C++ Methods and Messages are called function members. A: I'm not sure about origin of message terminology. Most ofter I encounter messages in UML design. Objects (Actors in UML terminology) can communicate with each other by means of messages. In real-world code message is just a function call usually. I think of message as of attempt to communicate with some object. It can be a real message (like messages in OS) or function calls. A: Usually, "Method" seems to be the proper name for Functions. However, each language has it's own keywords. Delphi for example even makes a difference between Methods that return something ("Functions") and Methods that return Nothing ("Procedures") whereas in C-Type languages, there is no difference. A: Here's some simplified definitions: methods/subroutines/voids: perform an action functions: perform an action and return a value events: are called when an object is acted upon handlers: are the functions/methods that handle the events PS: this is a perfect example of why SO should support DL/DT/DD tags. A: I believe that it is a matter of preference at this point. The words that you mention are basically synonyms in today's languages and for the most part people will understand what you mean if you say either "method" or "function". If you use "message", which is only used really in OOP, then you may confuse what you are attempting to convey.For example: "I need to create a message to send an email message." Other terms that could be synonymous, and this isn't a complete list, are subroutine, action, procedure, operation (although usually mathematical in nature), subprogram, command... A: method : similar to function in traditional languages message : similar to parameter passing in traditional language
{ "language": "en", "url": "https://stackoverflow.com/questions/43777", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "34" }
Q: sqlite3-ruby gem: Failed to build gem native extension Update: Check out this follow-up question: Gem Update on Windows - is it broken? On Windows, when I do this: gem install sqlite3-ruby I get the following error: Building native extensions. This could take a while... ERROR: Error installing sqlite3-ruby: ERROR: Failed to build gem native extension. c:/ruby/bin/ruby.exe extconf.rb install sqlite3-ruby --platform Win32 checking for fdatasync() in rt.lib... no checking for sqlite3.h... no nmake 'nmake' is not recognized as an internal or external command, operable program or batch file. Gem files will remain installed in c:/ruby/lib/ruby/gems/1.8/gems/sqlite3-ruby-1.2.4 for inspection. Results logged to c:/ruby/lib/ruby/gems/1.8/gems/sqlite3-ruby-1.2.4/ext/sqlite3_api/gem_make.out Same thing happens with the hpricot gem. I seem to remember these gems installed just fine on < 1.0 gems, but now I'm on 1.2.0, things have gone screwy. I have also tried this: gem install sqlite3-ruby --platform Win32 Needless to say, this doesn't work either (same error) Does anyone know what is going on here and how to fix this? Update: Check out this follow-up question: Gem Update on Windows - is it broken? A: I had the same problem on Ubuntu, this solved the problem for me: http://newsgroups.derkeiler.com/Archive/Comp/comp.lang.ruby/2008-08/msg00339.html A: first from sqlite.org(http://www.sqlite.org/download.html) download -> Precompiled Binaries: sqlite-dll-win32-x86-3071700.zip and Source Code: sqlite-autoconf-3071700.tar.gz then extract as: -include --sqlite3.h --sqlite3ext.h -lib --shell.c --sqlite3.c --sqlite3.def --sqlite3.dll last install gem like: gem install sqlite3 --platform=ruby -- --with-sqlite3-include=path\to\include --with-sqlite3-lib=path\to\lib --no-ri --no-rdoc Good luck! A: As Nathan suggests, this does appear to be related to the fact that the latest versions of the sqlite3-ruby and hpricot gems don't appear to have Windows versions. Here's what to do when faced with this situation (note, the name of the gem is automatically wildcarded, so you can type just sql and get a list of all gems beginning with sql): $ gem list --remote --all sqlite *** REMOTE GEMS *** sqlite (2.0.1, 2.0.0, 1.3.1, 1.3.0, 1.2.9.1, 1.2.0, 1.1.3, 1.1.2, 1.1.1, 1.1) sqlite-ruby (2.2.3, 2.2.2, 2.2.1, 2.2.0, 2.1.0, 2.0.3, 2.0.2) sqlite3-ruby (1.2.4, 1.2.3, 1.2.2, 1.2.1, 1.2.0, 1.1.0, 1.0.1, 1.0.0, 0.9.0, 0.6.0, 0.5.0) Then you can choose the version you would like to install: gem install sqlite3-ruby -v 1.2.3 To successfully install hpricot, I did this: gem install hpricot -v 0.6 Annoyingly, doing a gem update tries to update the gems to their latest, broken-on-Windows, versions. When the update routine encounters an error, it ditches you out of the whole process. There's a (hacky) solution to this problem here. So, is this issue a bug in gems? Should gems not automatically detect the platform and install the latest compatible version? A: Is it possible that the newest version has not yet been ported to Win32 yet? Since this particular gem does have bindings to compiled code, it would require a platform-specific gem. If I force installation of version 1.2.3 rather than the current 1.2.4, the platform-specific version does install, but when I allow gem to try to install the current version, I get the generic 1.2.4 version (in the gems library folder, it lacks the -x86-mswin32 suffix that the other sqlite3-ruby folders have in their names. Maybe someone else can answer how gem handles platform specific gems. Are separate gems uploaded for each platform and the gem software selects which one to pull down? A: I also ran into this problem. It's worth knowing that the difference between 1.2.3 and 1.2.4 is not significant. Here are the 1.2.4. release notes: Release Name: 1.2.4 Notes: This release only updates the generated C file to reflect the compatibility changes that were made to the SWIG file. Binary builds (e.g., Windows) are not affected, and need no update. In general, you will not need this update unless you are using a version of Ruby prior to 1.8.6. (source: 1.2.4. release notes) Hope that helps others! A: I had the same problem on Windows and I have installe MinGW http://sourceforge.net/projects/mingw/files/Automated%20MinGW%20Installer/MinGW%205.1.6/MinGW-5.1.6.exe/download and the problem has gone :-) C:>gem install hpricot Successfully installed hpricot-0.8.2-x86-mswin32 1 gem installed Installing ri documentation for hpricot-0.8.2-x86-mswin32... Installing RDoc documentation for hpricot-0.8.2-x86-mswin32... C:>gem install ruby-postgres Successfully installed ruby-postgres-0.7.1.2006.04.06-x86-mswin32 1 gem installed Installing ri documentation for ruby-postgres-0.7.1.2006.04.06-x86-mswin32... Installing RDoc documentation for ruby-postgres-0.7.1.2006.04.06-x86-mswin32...
{ "language": "en", "url": "https://stackoverflow.com/questions/43778", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "22" }
Q: How to convert a date String to a Date or Calendar object? I have a String representation of a date that I need to create a Date or Calendar object from. I've looked through Date and Calendar APIs but haven't found anything that can do this other than creating my own ugly parse method. I know there must be a way, does anyone know of a solution? A: The highly regarded Joda Time library is also worth a look. This is basis for the new date and time api that is pencilled in for Java 7. The design is neat, intuitive, well documented and avoids a lot of the clumsiness of the original java.util.Date / java.util.Calendar classes. Joda's DateFormatter can parse a String to a Joda DateTime. A: tl;dr LocalDate.parse( "2015-01-02" ) java.time Java 8 and later has a new java.time framework that makes these other answers outmoded. This framework is inspired by Joda-Time, defined by JSR 310, and extended by the ThreeTen-Extra project. See the Tutorial. The old bundled classes, java.util.Date/.Calendar, are notoriously troublesome and confusing. Avoid them. LocalDate Like Joda-Time, java.time has a class LocalDate to represent a date-only value without time-of-day and without time zone. ISO 8601 If your input string is in the standard ISO 8601 format of yyyy-MM-dd, you can ask that class to directly parse the string with no need to specify a formatter. The ISO 8601 formats are used by default in java.time, for both parsing and generating string representations of date-time values. LocalDate localDate = LocalDate.parse( "2015-01-02" ); Formatter If you have a different format, specify a formatter from the java.time.format package. You can either specify your own formatting pattern or let java.time automatically localize as appropriate to a Locale specifying a human language for translation and cultural norms for deciding issues such as period versus comma. Formatting pattern Read the DateTimeFormatter class doc for details on the codes used in the format pattern. They vary a bit from the old outmoded java.text.SimpleDateFormat class patterns. Note how the second argument to the parse method is a method reference, syntax added to Java 8 and later. String input = "January 2, 2015"; DateTimeFormatter formatter = DateTimeFormatter.ofPattern ( "MMMM d, yyyy" , Locale.US ); LocalDate localDate = LocalDate.parse ( input , formatter ); Dump to console. System.out.println ( "localDate: " + localDate ); localDate: 2015-01-02 Localize automatically Or rather than specify a formatting pattern, let java.time localize for you. Call DateTimeFormatter.ofLocalizedDate, and be sure to specify the desired/expected Locale rather than rely on the JVM’s current default which can change at any moment during runtime(!). String input = "January 2, 2015"; DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDate ( FormatStyle.LONG ); formatter = formatter.withLocale ( Locale.US ); LocalDate localDate = LocalDate.parse ( input , formatter ); Dump to console. System.out.println ( "input: " + input + " | localDate: " + localDate ); input: January 2, 2015 | localDate: 2015-01-02 A: In brief: DateFormat formatter = new SimpleDateFormat("MM/dd/yy"); try { Date date = formatter.parse("01/29/02"); } catch (ParseException e) { e.printStackTrace(); } See SimpleDateFormat javadoc for more. And to turn it into a Calendar, do: Calendar calendar = Calendar.getInstance(); calendar.setTime(date); A: Try this: DateFormat.parse(String) A: The DateFormat class has a parse method. See DateFormat for more information.
{ "language": "en", "url": "https://stackoverflow.com/questions/43802", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "63" }
Q: How do I best populate an HTML table in ASP.NET? This is what I've got. It works. But, is there a simpler or better way? ASPX Page… <asp:Repeater ID="RepeaterBooks" runat="server"> <HeaderTemplate> <table class="report"> <tr> <th>Published</th> <th>Title</th> <th>Author</th> <th>Price</th> </tr> </HeaderTemplate> <ItemTemplate> <tr> <td><asp:Literal ID="LiteralPublished" runat="server" /></td> <td><asp:Literal ID="LiteralTitle" runat="server" /></td> <td><asp:Literal ID="LiteralAuthor" runat="server" /></td> <td><asp:Literal ID="LiteralPrice" runat="server" /></td> </tr> </ItemTemplate> <FooterTemplate> </table> </FooterTemplate> </asp:Repeater> ASPX.VB Code Behind… Protected Sub Page_Load( ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Dim db As New BookstoreDataContext RepeaterBooks.DataSource = From b In db.Books _ Order By b.Published _ Select b RepeaterBooks.DataBind() End Sub Sub RepeaterBooks_ItemDataBound( ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles RepeaterBooks.ItemDataBound If e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem Then Dim b As Book = DirectCast(e.Item.DataItem, Book) DirectCast(e.Item.FindControl("LiteralPublished"), Literal).Text = "<nobr>" + b.Published.ToShortDateString + "</nobr>" DirectCast(e.Item.FindControl("LiteralTitle"), Literal).Text = "<nobr>" + TryNbsp(HttpContext.Current.Server.HtmlEncode(b.Title)) + "</nobr>" DirectCast(e.Item.FindControl("LiteralAuthor"), Literal).Text = "<nobr>" + TryNbsp(HttpContext.Current.Server.HtmlEncode(b.Author)) + "</nobr>" DirectCast(e.Item.FindControl("LiteralPrice"), Literal).Text = "<nobr>" + Format(b.Price, "c") + "</nobr>" End If End Sub Function TryNbsp(ByVal s As String) As String If s = "" Then Return "&nbsp;" Else Return s End If End Function A: @Geoff That sort of Eval statement was actually added in 2.0, but if performance is important Eval should be avoided since it uses Reflection. The repeater is a pretty good way of doing it, although it might be faster to generate the table in code: ASPX Page: <table class="report" id="bookTable" runat="server"> <tr> <th>Published</th> <th>Title</th> <th>Author</th> <th>Price</th> </tr> </table> Code Behind: Protected Sub Page_Load( ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load If Not Page.IsPostback Then BuildTable() End If End Sub Private Sub BuildTable() Dim db As New BookstoreDataContext Dim bookCollection = from b in db.Books _ Order By b.Published _ Select b Dim row As HtmlTableRow Dim cell As HtmlTableCell For Each book As Books In bookCollection row = New HtmlTableRow() cell = New HtmlTableCell With { .InnerText = b.Published.ToShortDateString } row.Controls.Add(cell) cell = New HtmlTableCell With { .InnerText = TryNbsp(HttpContext.Current.Server.HtmlEncode(b.Title)) } row.Controls.Add(cell) cell = New HtmlTableCell With { .InnerText = TryNbsp(HttpContext.Current.Server.HtmlEncode(b.Author)) row.Controls.Add(cell) cell = New HtmlTableCell With { .InnerText = Format(b.Price, "c") } row.Controls.Add(cell) bookTable.Controls.Add(row) Next I guess it depends on how important speed is to you. For simplicity's sake I think I would go with the Repeater. A: The ListView control introduced with framework 3.5 might be a little bit better solution. Your markup would look like this: <asp:ListView runat="server" ID="ListView1" DataSourceID="SqlDataSource1"> <LayoutTemplate> <table runat="server" id="table1" runat="server" > <tr runat="server" id="itemPlaceholder" ></tr> </table> </LayoutTemplate> <ItemTemplate> <tr runat="server"> <td runat="server"> <asp:Label ID="NameLabel" runat="server" Text='<%#Eval("Name") %>' /> </td> </tr> </ItemTemplate> </asp:ListView> You'll want to set your data source ID from a public or private property in the code-behind class. A: In .Net 3.0+ you can replace your ItemDataBound to the asp:Literal by doing something like this: <ItemTemplate> <tr> <td><%# Eval("published") %></td> ... where "published" is the name of a field in the data you have bound to the repeater Edit: @Alassek: I think the performance hit of reflection is often over-emphasized. Obviously you need to benchmark performance of your app, but the hit of the Eval is likely measured in milliseconds. Unless your app is serving many concurrent hits, this probably isn't an issue, and the simplicity of the code using Eval, along with it being a good separation of the presentation, make it a good solution. A: I agree with Geoff, the only time we use Literals is if we want to do something different with the data. For example, we might want a DueDate field to say "Today" or "Yesterday" instead of the actual date. A: This is what the GridView is for. <asp:GridView runat="server" DataSourceID="SqlDataSource1"> <Columns> <asp:BoundField HeaderText="Published" DataField="Published" /> <asp:BoundField HeaderText="Author" DataField="Author" /> </Columns> </asp:GridView> A: I would use a GridView (or DataGrid, if you are using an older version of ASP.NET). <asp:GridView ID="gvBooks" runat="server" AutoGenerateColumns="False"> <Columns> <asp:BoundField HeaderText="Published" DataField="Published" /> <asp:BoundField HeaderText="Title" DataField="Title" /> <asp:BoundField HeaderText="Author" DataField="Author" /> <asp:BoundField HeaderText="Price" DataField="Price" /> </Columns> </asp:GridView> With some code-behind: Private Sub gvBooksRowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gvBooks.RowDataBound Select Case e.Row.RowType Case DataControlRowType.DataRow ''' Your code here ''' End Select End Sub You can bind it in a similar way. The RowDataBound event is what you need. A: ALassek wrote: …generate the table in code… I like the look of that! It seems MUCH less likely to produce a run-time exception due to a typo or field name change. A: If you don't need ASP.NET handled edit cabilities I would stay away from the DataGrid and the GridView ... they provide unnecessary bloat.
{ "language": "en", "url": "https://stackoverflow.com/questions/43803", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Example of c# based rule language? Can you provide a good example of rule definition language written in C#. Java guys have JESS, is there anything good for C#? A: This page shows some examples of open-source rules engines in C#: http://csharp-source.net/open-source/rule-engines A: You can use the forward chaining inference engine that is part of Windows Workflow Foundation (.NET 3.5 and higher) The best part is that this has a free runtime licensing. You can use the Rule Manager from Acumen Business and install the Windows Workflow Foundation adapter. Once installed, export the rules as WFRules (*.rules). A visual studio .NET solution will be generated that shows how the rule engine can be invoked standalone (no workflow is necessary) See also http://bizknowledge.blogspot.com/search/label/Windows%20Workflow%20Foundation A: Try http://rulesengine.codeplex.com It has a fluent-interface wrapper for creating rules. It's lightweight and simple to use. A: You could use Windows Workflow Foundation's (WF) workflow engine with C#. I'd started a small and simple project using WF as the workflow engine, it's actually quite straightforward to use. Check out the first part entry I've been developing on this here. What is interesting about WF is that you don't have to use the whole thing if you want to - if you only want to write some custom rules against some entities or objects, you can - quite ingenious! Also, it's a lot less to take on board than BizTalk's BRE (and no licensing cost). You need to add a reference to the following .Net assemblies, available in the .Net Framework v3.0 and onwards: * *System.Workflow.Activities *System.Workflow.ComponentModel *System.Workflow.Runtime Check out the article for more info. A: There is the Microsoft Business Rules Engine: http://msdn.microsoft.com/en-us/library/aa561216.aspx. Not sure if it can only be used inside Biztalk - it does says it is a .Net Class Library. A: Microsoft Business Rule Engine(BRE) is quite nice. But(and that's a big BUT) you'll need a BizTalk Server license to use it. A: Take a look at Jetfire on codeplex. It supports forward chaining 'rules'.
{ "language": "en", "url": "https://stackoverflow.com/questions/43805", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: How to prefetch Oracle sequence ID-s in a distributed environment I have a distributed Java application running on 5 application servers. The servers all use the same Oracle 9i database running on a 6th machine. The application need to prefetch a batch of 100 IDs from a sequence. It's relatively easy to do in a single-threaded, non-distributed environment, you can just issue these queries: SELECT seq.nextval FROM dual; ALTER SEQUENCE seq INCREMENT BY 100; SELECT seq.nextval FROM dual; The first select fetches the first sequence ID that the application can use, the second select returns the last one that can be used. Things get way more interesting in a multithreaded environment. You can't be sure that before the second select another thread doesn't increase the sequence by 100 again. This issue can be solved by synchronizing the access on the Java side - you only let one thread begin fetching the IDs at one time. The situation becomes really hard when you can't synchronize because parts of the application doesn't run on the same JVM, not even on the same physical machine. I found some references on forums that others have problems with solving this problem too, but none of the answers are really working not to mention being reasonable. Can the community provide a solution for this problem? Some more information: * *I can't really play with the transaction isolation levels. I use JPA and the change would affect the entire application, not only the prefetching queries and that's not acceptable for me. *On PostgreSQL I could do the following: SELECT setval('seq', NEXTVAL('seq') + n - 1) *The solution by Matthew works when you can use a fixed increment value (which is perfectly acceptable in my case). However is there a solution when you don't want to fix the size of the increment, but want to adjust it dynamically? A: Why do you need to fetch the sequence IDs in the first place? In most cases you would insert into a table and return the ID. insert into t (my_pk, my_data) values (mysequence.nextval, :the_data) returning my_pk into :the_pk; It sounds like you are trying to pre-optimize the processing. If you REALLY need to pre-fetch the IDs then just call the sequence 100 times. The entire point of a sequence is that it manages the numbering. You're not supposed to assume that you can get 100 consecutive numbers. A: Why not just have the sequence as increment by 100 all the time? each "nextval" gives you 100 sequence numbers to work with SQL> create sequence so_test start with 100 increment by 100 nocache; Sequence created. SQL> select so_test.nextval - 99 as first_seq, so_test.currval as last_seq from dual; FIRST_SEQ LAST_SEQ ---------- ---------- 1 100 SQL> / FIRST_SEQ LAST_SEQ ---------- ---------- 101 200 SQL> / FIRST_SEQ LAST_SEQ ---------- ---------- 201 300 SQL> A note on your example.. Watch out for DDL.. It will produce an implicit commit Example of commit produced by DDL SQL> select * from xx; no rows selected SQL> insert into xx values ('x'); 1 row created. SQL> alter sequence so_test increment by 100; Sequence altered. SQL> rollback; Rollback complete. SQL> select * from xx; Y ----- x SQL> A: Matthew has the correct approach here. In my opinion, it is very unusual for an application to reset a sequence's current value after every use. Much more conventional to set the increment size to whatever you need upfront. Also, this way is much more performant. Selecting nextval from a sequence is a highly optimised operation in Oracle, whereas running ddl to alter the sequence is much more expensive. I guess that doesn't really answer the last point in your edited question... A: For when you don't want a fixed size increment, sequences aren't really what you are after, all they really guarantee is that you will be getting a unique number always bigger than the last one you got. There is always the possibility that you'll end up with gaps, and you can't really adjust the increment amount on the fly safely or effectively. I can't really think of any case where I've had to do this kind of thing, but likely the easiest way is just to store the "current" number somewhere and update it as you need it. Something like this. drop table t_so_test; create table t_so_test (curr_num number(10)); insert into t_so_test values (1); create or replace procedure p_get_next_seq (inc IN NUMBER, v_next_seq OUT NUMBER) As BEGIN update t_so_test set curr_num = curr_num + inc RETURNING curr_num into v_next_seq; END; / SQL> var p number; SQL> execute p_get_next_seq(100,:p); PL/SQL procedure successfully completed. SQL> print p; P ---------- 101 SQL> execute p_get_next_seq(10,:p); PL/SQL procedure successfully completed. SQL> print p; P ---------- 111 SQL> execute p_get_next_seq(1000,:p); PL/SQL procedure successfully completed. SQL> print p; P ---------- 1111 SQL>
{ "language": "en", "url": "https://stackoverflow.com/questions/43808", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Which JSTL URL should I reference in my JSPs? I'm getting the following error when trying to run a JSP. I'm using Tomcat 6.0.18, and I'd like to use the latest version of JSTL. What version of JSTL should I use, and which URL goes with which version of JSTL? I'm getting this error "According to TLD or attribute directive in tag file, attribute key does not accept any expressions" <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %> I'll just say I had this working, but I want to switch the JSTL jar file that has the TLD files in the jar file. (instead of having to deploy them somewhere in the web application and define the references in web.xml). A: Go with <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> More on this topic here
{ "language": "en", "url": "https://stackoverflow.com/questions/43809", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: jQuery slicing and click events This is probably a really simple jQuery question, but I couldn't answer it after 10 minutes in the documentation so... I have a list of checkboxes, and I can get them with the selector 'input[type=checkbox]'. I want the user to be able to shift-click and select a range of checkboxes. To accomplish this, I need to get the index of a checkbox in the list, so I can pass that index to .slice(start, end). How do I get the index when the user clicks a box? A: The following selector should also work in jQuery: input:checkbox. You can then string the :gt(index) and :lt(index) filters together, so if you want the 5th to 7th checkboxes, you'd use input:checkbox:gt(4):lt(2). To get the index of the currently clicked checkbox, just use $("input:checkbox").index($(this)). A: This is a quick solution, but I would give each checkbox a unique ID, perhaps with an index hint, like so: <input id="checkbox-0" type="checkbox" /> <input id="checkbox-1" type="checkbox" /> <input id="checkbox-2" type="checkbox" /> <input id="checkbox-3" type="checkbox" /> <input id="checkbox-4" type="checkbox" /> You can then easily obtain the index: $(document).ready(function() { $("input:checkbox").click(function() { index = /checkbox-(\d+)/.exec(this.id)[1]; alert(index); }); }); A: Thanks for the answer, samjudson. After further experimentation, I found that you can even use just $(':checkbox') to select them. It's interesting that you can use the .slice() function to get the range, but you also have the option of doing it in the selector with :gt and :lt. I do find the syntax of .slice() to be cleaner than using the selector filters, though. I'm going to have to say that I don't like Ryan Duffield's solution as much, because it requires changes to the markup, and involves repeating code. A: @Gorgapor: I guess I need to take questions a little less literally sometimes. :-) I figured you were locked down to requiring some sort of index. I think you'll find though that as you use jQuery more, you usually don't need to do that sort of thing.
{ "language": "en", "url": "https://stackoverflow.com/questions/43811", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Why won't my 2008 Team Build trigger on developer check-ins despite CI being enabled I have a Team Foundation Server 2008 Installation and a separate machine with the Team Build service. I can create team builds and trigger them manually in Visual Studio or via the command line (where they complete successfully). However check ins to the source tree do not cause a build to trigger despite the option to build every check in being ticked on the build definition. Update: To be clear I had a fully working build definition with the CI option enabled. The source tree is configured is a pretty straight forward manner with code either under a Main folder or under a Branch\branchName folder. Each branch of code (including main) has a standard Team Build definition relating to the solution file contained within. The only thing that is slightly changed from default settings is that the build server working folder; i.e. for main this is Server:"$\main" Local:"c:\build\main" due to path length. The only thing I've been able to guess at (possible red herring) is that there might be some oddity with the developer workspaces. Currently each developer maps Server:"$\" to local:"c:\tfs\" so that there is only one workspace for all branches. This is mainly to avoid re-mapping problems that some of the developers had previously gotten themselves into. But I can't see how this would affect CI. UPDATE: Ifound the answer indirectly; please read below A: Ok I have found the answer myself after several dead ends. In the end I fixed this unintentionally while fixing another issue. Basically we had just turned on the automatic execution of unit tests for our builds. The test would run sucessfully but then immediately the build would bomb out with a message saying it was unable to report to the build drop folder. What was happening was that while the Build service runs under one account and has a set of rights; some of the functionality is actually driven through the TFSService account. fter wading a heap of permissions I had my tests being reported. Then I noticed that builds had started to trigger on check-ins; I can't tell you exactly which permission fixed this but hopefully this answer will at least set people down the right path. One other note a few of the builds started failing due to conflicting workspace mappings - this was a separate issue that I resolved by deleting some obsolete workspaces using the Attrice Sidekicks for Team Foundation tool. Hope this helps somebody else. A: Select your team project from team explorer, then right click on the Builds folder. Select a new build definition and then select the trigger tab. Move the radio button to "Build each check-in (more builds)" More info can be found here MSDN How to: Create a Build Definition A: Are there any errors in the log on the TFS application server? Anything that indicates that it tried to fire but failed?
{ "language": "en", "url": "https://stackoverflow.com/questions/43815", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Oracle equivalent to SQL Server/Sybase DateDiff We are now using NHibernate to connect to different database base on where our software is installed. So I am porting many SQL Procedures to Oracle. SQL Server has a nice function called DateDiff which takes a date part, startdate and enddate. Date parts examples are day, week, month, year, etc. . . What is the Oracle equivalent? I have not found one do I have to create my own version of it? (update by Mark Harrison) there are several nice answers that explain Oracle date arithmetic. If you need an Oracle datediff() see Einstein's answer. (I need this to keep spme SQL scripts compatible between Sybase and Oracle.) Note that this question applies equally to Sybase. A: I stole most of this from an old tom article a few years ago, fixed some bugs from the article and cleaned it up. The demarcation lines for datediff are calculated differently between oracle and MSSQL so you have to be careful with some examples floating around out there that don't properly account for MSSQL/Sybase style boundaries which do not provide fractional results. With the following you should be able to use MSSQL syntax and get the same results as MSSQL such as SELECT DATEDIFF(dd,getdate(),DATEADD(dd,5,getdate())) FROM DUAL; I claim only that it works - not that its effecient or the best way to do it. I'm not an Oracle person :) And you might want to think twice about using my function macros to workaround needing quotes around dd,mm,hh,mi..etc. (update by Mark Harrison) added dy function as alias for dd. CREATE OR REPLACE FUNCTION GetDate RETURN date IS today date; BEGIN RETURN(sysdate); END; / CREATE OR REPLACE FUNCTION mm RETURN VARCHAR2 IS BEGIN RETURN('mm'); END; / CREATE OR REPLACE FUNCTION yy RETURN VARCHAR2 IS BEGIN RETURN('yyyy'); END; / CREATE OR REPLACE FUNCTION dd RETURN VARCHAR2 IS BEGIN RETURN('dd'); END; / CREATE OR REPLACE FUNCTION dy RETURN VARCHAR2 IS BEGIN RETURN('dd'); END; / CREATE OR REPLACE FUNCTION hh RETURN VARCHAR2 IS BEGIN RETURN('hh'); END; / CREATE OR REPLACE FUNCTION mi RETURN VARCHAR2 IS BEGIN RETURN('mi'); END; / CREATE OR REPLACE FUNCTION ss RETURN VARCHAR2 IS BEGIN RETURN('ss'); END; / CREATE OR REPLACE Function DateAdd(date_type IN varchar2, offset IN integer, date_in IN date ) RETURN date IS date_returned date; BEGIN date_returned := CASE date_type WHEN 'mm' THEN add_months(date_in,TRUNC(offset)) WHEN 'yyyy' THEN add_months(date_in,TRUNC(offset) * 12) WHEN 'dd' THEN date_in + TRUNC(offset) WHEN 'hh' THEN date_in + (TRUNC(offset) / 24) WHEN 'mi' THEN date_in + (TRUNC(offset) /24/60) WHEN 'ss' THEN date_in + (TRUNC(offset) /24/60/60) END; RETURN(date_returned); END; / CREATE OR REPLACE Function DateDiff( return_type IN varchar2, date_1 IN date, date_2 IN date) RETURN integer IS number_return integer; BEGIN number_return := CASE return_type WHEN 'mm' THEN ROUND(MONTHS_BETWEEN(TRUNC(date_2,'MM'),TRUNC(date_1, 'MM'))) WHEN 'yyyy' THEN ROUND(MONTHS_BETWEEN(TRUNC(date_2,'YYYY'), TRUNC(date_1, 'YYYY')))/12 WHEN 'dd' THEN ROUND((TRUNC(date_2,'DD') - TRUNC(date_1, 'DD'))) WHEN 'hh' THEN (TRUNC(date_2,'HH') - TRUNC(date_1,'HH')) * 24 WHEN 'mi' THEN (TRUNC(date_2,'MI') - TRUNC(date_1,'MI')) * 24 * 60 WHEN 'ss' THEN (date_2 - date_1) * 24 * 60 * 60 END; RETURN(number_return); END; / A: JohnLavoie - you don't need that. DATE in Oracle is actually a date and time data type. The only difference between DATE and TIMESTAMP is that DATE resolves down to the second but TIMESTAMP resolves down to the micro second. Therefore the Ask Tom article is perfectly valid for TIMESTAMP columns as well. A: Tom's article is very old. It only discusses the DATE type. If you use TIMESTAMP types then date arithmetic is built into PL/SQL. http://www.akadia.com/services/ora_date_time.html DECLARE ts_a timestamp; ts_b timestamp; diff interval day to second; BEGIN ts_a := systimestamp; ts_b := systimestamp-1/24; diff := ts_a - ts_b; dbms_output.put_line(diff); END; +00 01:00:00.462000 or DECLARE ts_b timestamp; ts_a timestamp; date_part interval day to second; BEGIN ts_a := systimestamp; date_part := to_dsinterval('0 01:23:45.678'); ts_b := ts_a + date_part; dbms_output.put_line(ts_b); END; 04-SEP-08 05.00.38.108000 PM A: YOU Could write a function in oracle for this function datediff( p_what in varchar2, p_d1 in date, p_d2 in date) return number as l_result number; BEGIN select (p_d2-p_d1) * decode( upper(p_what), 'SS', 24*60*60, 'MI', 24*60, 'HH', 24, NULL ) into l_result from dual; return l_result; END; and use it like : DATEDIFF('YYYY-MM-DD', SYSTIMESTAMP, SYSTIMESTAMP)
{ "language": "en", "url": "https://stackoverflow.com/questions/43819", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How well will WCF scale to a large number of client users? Does anyone have any experience with how well web services build with Microsoft's WCF will scale to a large number of users? The level I'm thinking of is in the region of 1000+ client users connecting to a collection of WCF services providing the business logic for our application, and these talking to a database - similar to a traditional 3-tier architecture. Are there any particular gotchas that have slowed down performance, or any design lessons learnt that have enabled this level of scalability? A: WCF configuration default limits, concurrency and scalability A: Probably the 4 biggest things you can start looking at first (besides just having good service code) are items related to: * *Bindings - some binding and they protocols they run on are just faster than others, tcp is going to be faster than any of the http bindings *Instance Mode - this determines how your classes are allocated against the session callers *One & Two Way Operations - if a response isn't needed back to the client, then do one-way *Throttling - Max Sessions / Concurant Calls and Instances They did design WCF to be secure by default so the defaults are very limiting. A: To ensure your WCF application can scale to the desired level I think you might need to tweak your thinking about the stats your services have to meet. You mention servicing "1000+ client users" but to gauge if your services can perform at that level you'll also need to have some estimated usage figures, which will help you calculate some simpler stats such as the number of requests per second your app needs to handle. Having just finished working on a WCF project we managed to get 400 requests per second on our test hardware, which combined with our expected usage pattern of each user making 300 requests a day indicated we could handle an average of 100,000 users a day (assuming a flat usage graph across the day). In addition, since it's fairly common to make the WCF service code stateless, it's pretty easy to scale out the actual WCF code by adding additional boxes, which means the overall performance of your system is much more likely to be limited by your business logic and persistence layer than it is by WCF.
{ "language": "en", "url": "https://stackoverflow.com/questions/43823", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "19" }
Q: How Would You Programmatically Create a Pattern from a Date that is Stored in a String? I have a string that contains the representation of a date. It looks like: Thu Nov 30 19:00:00 EST 2006 I'm trying to create a Date object using SimpleDateFormat and have 2 problems. 1.) I can't figure out the pattern to hard-code the solution into the SimpleDateFormat constructor 2.) I can't find a way I could parse the string using API to determine the pattern so I could reuse this for different patterns of date output If anyone knows a solution using API or a custom solution I would greatly appreciate it. A: The format to pass to SimpleDateFormat could be looked up at http://java.sun.com/javase/6/docs/api/java/text/SimpleDateFormat.html new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy") As for your second question, I don't know of any Java library to figure out a date format and parse it without knowing in advance what the format is. A: The POJava date parser org.pojava.datetime.DateTime is an immutable, and robust parser that supports multiple languages, time zones, and formats. Best of all, the parser is heuristic and does not require a pre-existing “format” to work. You just pass it a date/date-time text string and get out a java.util.Date! A: I'm not sure there's any easy way to parse a date and work out its pattern, but I would have thought that the pattern for the one you posted would be: EEE MMM dd HH:mm:ss zzz yyyy A: If you want to do anything other than parse or format a date there is not much out there for handling the patterns themselves. Sometime ago I was writing a Swing component for entering dates into a formatted text field. You supplied a pattern and it moved the text entry cursor through the elements of that pattern, only allowing valid values. As part of that I wrote a DateFormatParser available here as part of the OpenHarmonise open source project. Parsing a date into a pattern would be an extremely interesting problem to tackle. You would have to make certain assumptions (e.g. use of : in time not date) but you would face the eternal problems of 2 digit years and day/month or month/day arrangements. A: It's worth knowing that the date format you have given is not an arbitrary one. It is the output of the built-in Date.toString() method (at least in the UK and US locales). Not coincidentally, it is also the format of the unix 'date' command (at least on linux, and I believe in other implementations too) - though to be pedantic, Date.toString() pads one-digit day numbers with a zero while unix date does not. What this means is that you are likely to receive this input format when you output an unformatted date into a user-modifiable field (e.g. an HTML INPUT field) and receive it back unmodified. So just because input is coming in this format, doesn't mean the users will type in a thousand other arbitrary formats. Of course, they still might. The way I handle date inputs in general is with a bunch of try/catch blocks, where I try it against one format, then another, then another. Our standard framework is now up to about 20 different formats by default. Of course it is still not perfect; I found someone the other day entering "03 Sept" as the date (a non-standard month abbreviation, and with no year) and we hadn't handled that scenario. A: See Apache Commons' DateUtils. There's a parseDate method that takes your String and multiple patterns to try and spits out a Date instance. A: As others have said, the pattern looks like it should be new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy" As for parsing an arbitrary format date, I'm not aware of any library which does this in Java. If you were keen to develop such a thing, I would start by looking at the perl str2time function. A: I must say i find the other question very interesting. There is one serious problem though - parse this: 08/07/06! If you limit yourself on a subset of expected formats, you could probably solve problem by playing around with regexps, you could build up bunch of expected patterns, and then break Strings on spaces or whatever, and match part by part. A: Are you just asking for the pattern for that given date? If so, I think this should do it: "EEE MMM d HH:mm:ss z yyyy" Or are you trying to take any formatted date, and infer the format, and parse it? A: How about: EEE MMM dd HH:mm:ss zzz yyyy Just pass the string into the constructor of SimpleDateFormat. To use the object, just call the parse method passing in the string you want converted to a Date. You could take a look at: http://java.sun.com/j2se/1.4.2/docs/api/java/text/SimpleDateFormat.html A: This isn't really the same, but you might want to look at something like JChronic, which can do natural language processing on dates. So, the input date could be something like "tomorrow", or "two weeks from next tuesday". This may not help at all for your application, but then again, it might.
{ "language": "en", "url": "https://stackoverflow.com/questions/43842", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: What web control library to use for easy form creation with many different types of input fields? I'm about to create a web application that requires a lot of different web forms where the user needs to be able to input a lot of different types of information. What I mean is that one of those forms may require some text input fields, some integer input fields, some decimal input fields, some date input fields, some datetime input fields, etc. I would like to have a, maybe JavaScript-based, control library that I can simple provide with some text labels, input types and default values. The control library would then somehow render the form in HTML without me having to create an HTML table, select the appropriate standard web controls and all that. I have used dhtmlxGrid to create quite a lot of tables and that works well for me. What I need now is something that can help me in a similar way when creating something like card forms. I have also found ActiveWidgets, but it looks like it will require a lot of work on my behalf. I'm not only looking for individual web controls, but rather something like a library that can help me with the overall card. I'm guessing many of you have had this problem before. Looking forward to hearing what solutions you have found to be the best. BTW: I'm working in VisualStudio with ASP.NET. A: I would be tempted to look at Ext JS for this. Ext JS A: have you had a look at InputEx A: I know it doesn't answer the question, but I have always written my own, or rather written it once and tweaked it for other apps. When I store the questions in the DB I store what input type it is, then on the form I dynamically create the appropriate control depending on which input type the question needs and add that control to a dynamically created table cell as I go. If you choose to do that just remember when processing the form that the controls don't exist on postback, you need to recreate them. It is not too bad to write it, if you have the time. My current form module is running a few dozen forms from the one module.
{ "language": "en", "url": "https://stackoverflow.com/questions/43856", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How SID is different from Service name in Oracle tnsnames.ora Why do I need two of them? When I have to use one or another? A: what is a SID and Service name please look into oracle's documentation at https://docs.oracle.com/cd/B19306_01/network.102/b14212/concepts.htm In case if the above link is not accessable in future, At the time time of writing this answer, the above link will direct you to, "Database Service and Database Instance Identification" topic in Connectivity Concepts chapter of "Database Net Services Administrator's Guide". This guide is published by oracle as part of "Oracle Database Online Documentation, 10g Release 2 (10.2)" When I have to use one or another? Why do I need two of them? Consider below mapping in a RAC Environment, SID      SERVICE_NAME bob1    bob bob2    bob bob3    bob bob4    bob if load balancing is configured, the listener will 'balance' the workload across all four SIDs. Even if load balancing is configured, you can connect to bob1 all the time if you want to by using the SID instead of SERVICE_NAME. Please refer, https://community.oracle.com/thread/4049517 A: Please see: http://www.sap-img.com/oracle-database/finding-oracle-sid-of-a-database.htm What is the difference between Oracle SIDs and Oracle SERVICE NAMES. One config tool looks for SERVICE NAME and then the next looks for SIDs! What's going on?! Oracle SID is the unique name that uniquely identifies your instance/database where as Service name is the TNS alias that you give when you remotely connect to your database and this Service name is recorded in Tnsnames.ora file on your clients and it can be the same as SID and you can also give it any other name you want. SERVICE_NAME is the new feature from oracle 8i onwards in which database can register itself with listener. If database is registered with listener in this way then you can use SERVICE_NAME parameter in tnsnames.ora otherwise - use SID in tnsnames.ora. Also if you have OPS (RAC) you will have different SERVICE_NAME for each instance. SERVICE_NAMES specifies one or more names for the database service to which this instance connects. You can specify multiple services names in order to distinguish among different uses of the same database. For example: SERVICE_NAMES = sales.acme.com, widgetsales.acme.com You can also use service names to identify a single service that is available from two different databases through the use of replication. In an Oracle Parallel Server environment, you must set this parameter for every instance. In short: SID = the unique name of your DB instance, ServiceName = the alias used when connecting A: I know this is ancient however when dealing with finicky tools, uses, users or symptoms re: sid & service naming one can add a little flex to your tnsnames entries as like: mySID, mySID.whereever.com = (DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)(HOST = myHostname)(PORT = 1521)) ) (CONNECT_DATA = (SERVICE_NAME = mySID.whereever.com) (SID = mySID) (SERVER = DEDICATED) ) ) I just thought I'd leave this here as it's mildly relevant to the question and can be helpful when attempting to weave around some less than clear idiosyncrasies of oracle networking. A: Quote by @DAC In short: SID = the unique name of your DB, ServiceName = the alias used when connecting Not strictly true. SID = unique name of the INSTANCE (eg the oracle process running on the machine). Oracle considers the "Database" to be the files. Service Name = alias to an INSTANCE (or many instances). The main purpose of this is if you are running a cluster, the client can say "connect me to SALES.acme.com", the DBA can on the fly change the number of instances which are available to SALES.acme.com requests, or even move SALES.acme.com to a completely different database without the client needing to change any settings. A: As per Oracle Glossary : SID is a unique name for an Oracle database instance. ---> To switch between Oracle databases, users must specify the desired SID <---. The SID is included in the CONNECT DATA parts of the connect descriptors in a TNSNAMES.ORA file, and in the definition of the network listener in the LISTENER.ORA file. Also known as System ID. Oracle Service Name may be anything descriptive like "MyOracleServiceORCL". In Windows, You can your Service Name running as a service under Windows Services. You should use SID in TNSNAMES.ORA as a better approach.
{ "language": "en", "url": "https://stackoverflow.com/questions/43866", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "195" }
Q: How to concatenate strings of a string field in a PostgreSQL 'group by' query? I am looking for a way to concatenate the strings of a field within a group by query. So for example, I have a table: ID COMPANY_ID EMPLOYEE 1 1 Anna 2 1 Bill 3 2 Carol 4 2 Dave and I wanted to group by company_id to get something like: COMPANY_ID EMPLOYEE 1 Anna, Bill 2 Carol, Dave There is a built-in function in mySQL to do this group_concat A: As already mentioned, creating your own aggregate function is the right thing to do. Here is my concatenation aggregate function (you can find details in French): CREATE OR REPLACE FUNCTION concat2(text, text) RETURNS text AS ' SELECT CASE WHEN $1 IS NULL OR $1 = \'\' THEN $2 WHEN $2 IS NULL OR $2 = \'\' THEN $1 ELSE $1 || \' / \' || $2 END; ' LANGUAGE SQL; CREATE AGGREGATE concatenate ( sfunc = concat2, basetype = text, stype = text, initcond = '' ); And then use it as: SELECT company_id, concatenate(employee) AS employees FROM ... A: PostgreSQL 9.0 or later: Modern Postgres (since 2010) has the string_agg(expression, delimiter) function which will do exactly what the asker was looking for: SELECT company_id, string_agg(employee, ', ') FROM mytable GROUP BY company_id; Postgres 9 also added the ability to specify an ORDER BY clause in any aggregate expression; otherwise you have to order all your results or deal with an undefined order. So you can now write: SELECT company_id, string_agg(employee, ', ' ORDER BY employee) FROM mytable GROUP BY company_id; PostgreSQL 8.4.x: Please note that support for Postgres 8.4 ended in 2014, so you should probably upgrade for more important reasons than string aggregation. PostgreSQL 8.4 (in 2009) introduced the aggregate function array_agg(expression) which collects the values in an array. Then array_to_string() can be used to give the desired result: SELECT company_id, array_to_string(array_agg(employee), ', ') FROM mytable GROUP BY company_id; PostgreSQL 8.3.x and older: When this question was originally posed, there was no built-in aggregate function to concatenate strings. The simplest custom implementation (suggested by Vajda Gabo in this mailing list post, among many others) is to use the built-in textcat function: CREATE AGGREGATE textcat_all( basetype = text, sfunc = textcat, stype = text, initcond = '' ); Here is the CREATE AGGREGATE documentation. This simply glues all the strings together, with no separator. In order to get a ", " inserted in between them without having it at the end, you might want to make your own concatenation function and substitute it for the "textcat" above. Here is one I put together and tested on 8.3.12: CREATE FUNCTION commacat(acc text, instr text) RETURNS text AS $$ BEGIN IF acc IS NULL OR acc = '' THEN RETURN instr; ELSE RETURN acc || ', ' || instr; END IF; END; $$ LANGUAGE plpgsql; This version will output a comma even if the value in the row is null or empty, so you get output like this: a, b, c, , e, , g If you would prefer to remove extra commas to output this: a, b, c, e, g Then add an ELSIF check to the function like this: CREATE FUNCTION commacat_ignore_nulls(acc text, instr text) RETURNS text AS $$ BEGIN IF acc IS NULL OR acc = '' THEN RETURN instr; ELSIF instr IS NULL OR instr = '' THEN RETURN acc; ELSE RETURN acc || ', ' || instr; END IF; END; $$ LANGUAGE plpgsql; A: This latest announcement list snippet might be of interest if you'll be upgrading to 8.4: Until 8.4 comes out with a super-effient native one, you can add the array_accum() function in the PostgreSQL documentation for rolling up any column into an array, which can then be used by application code, or combined with array_to_string() to format it as a list: http://www.postgresql.org/docs/current/static/xaggr.html I'd link to the 8.4 development docs but they don't seem to list this feature yet. A: Following up on Kev's answer, using the Postgres docs: First, create an array of the elements, then use the built-in array_to_string function. CREATE AGGREGATE array_accum (anyelement) ( sfunc = array_append, stype = anyarray, initcond = '{}' ); select array_to_string(array_accum(name),'|') from table group by id; A: Following yet again on the use of a custom aggregate function of string concatenation: you need to remember that the select statement will place rows in any order, so you will need to do a sub select in the from statement with an order by clause, and then an outer select with a group by clause to aggregate the strings, thus: SELECT custom_aggregate(MY.special_strings) FROM (SELECT special_strings, grouping_column FROM a_table ORDER BY ordering_column) MY GROUP BY MY.grouping_column A: Use STRING_AGG function for PostgreSQL and Google BigQuery SQL: SELECT company_id, STRING_AGG(employee, ', ') FROM employees GROUP BY company_id; A: I found this PostgreSQL documentation helpful: http://www.postgresql.org/docs/8.0/interactive/functions-conditional.html. In my case, I sought plain SQL to concatenate a field with brackets around it, if the field is not empty. select itemid, CASE itemdescription WHEN '' THEN itemname ELSE itemname || ' (' || itemdescription || ')' END from items; A: As from PostgreSQL 9.0 you can use the aggregate function called string_agg. Your new SQL should look something like this: SELECT company_id, string_agg(employee, ', ') FROM mytable GROUP BY company_id; A: If you are on Amazon Redshift, where string_agg is not supported, try using listagg. SELECT company_id, listagg(EMPLOYEE, ', ') as employees FROM EMPLOYEE_table GROUP BY company_id; A: I claim no credit for the answer because I found it after some searching: What I didn't know is that PostgreSQL allows you to define your own aggregate functions with CREATE AGGREGATE This post on the PostgreSQL list shows how trivial it is to create a function to do what's required: CREATE AGGREGATE textcat_all( basetype = text, sfunc = textcat, stype = text, initcond = '' ); SELECT company_id, textcat_all(employee || ', ') FROM mytable GROUP BY company_id; A: How about using Postgres built-in array functions? At least on 8.4 this works out of the box: SELECT company_id, array_to_string(array_agg(employee), ',') FROM mytable GROUP BY company_id; A: According to version PostgreSQL 9.0 and above you can use the aggregate function called string_agg. Your new SQL should look something like this: SELECT company_id, string_agg(employee, ', ') FROM mytable GROUP BY company_id; A: You can also use format function. Which can also implicitly take care of type conversion of text, int, etc by itself. create or replace function concat_return_row_count(tbl_name text, column_name text, value int) returns integer as $row_count$ declare total integer; begin EXECUTE format('select count(*) from %s WHERE %s = %s', tbl_name, column_name, value) INTO total; return total; end; $row_count$ language plpgsql; postgres=# select concat_return_row_count('tbl_name','column_name',2); --2 is the value A: I'm using Jetbrains Rider and it was a hassle copying the results from above examples to re-execute because it seemed to wrap it all in JSON. This joins them into a single statement that was easier to run select string_agg('drop table if exists "' || tablename || '" cascade', ';') from pg_tables where schemaname != $$pg_catalog$$ and tableName like $$rm_%$$
{ "language": "en", "url": "https://stackoverflow.com/questions/43870", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "458" }
Q: Restrict selection of SELECT option without disabling the field I have a multiple selection SELECT field which I don't want the end user to be able to change the value of. For UI reasons, I would like to be able to do this without using the disabled="true" attribute. I've tried using onmousedown, onfocus, onclick and setting each to blur or return false but with no success. Can this be done or am I trying to do the impossible? A: I know you mentioned that you don't want to, but I actually think that using the disabled attribute is a better solution: <select multiple="multiple"> <option value="volvo" selected="true" disabled="disabled">Volvo</option> <option value="saab" disabled="disabled">Saab</option> <option value="opel" disabled="disabled">Opel</option> <option value="audi" disabled="disabled">Audi</option> </select> If necessary, you can always give the select a class and style it with CSS. This solution will work in all browsers regardless of scripting capabilities. A: Could you do it with an onchange event? <select onfocus="this.oldIndex=this.selectedIndex" onchange="this.selectedIndex=this.oldIndex"> A: Your best bet would be to swap out the options within the select box. If you only have one answer in that box, it doesn't matter if it is clickable. I would, however, try to find another way of doing this as it seems like it would cause frustration for a user. Imagine this user scenario: * *"Look, a select box of options." *click *"Hrm, why didn't that work?" *click *click! *"This stupid thing is broken, I'm never coming back here." If you swap out the select for HTML text, it accomplishes the same goal. This is a fairly simple task for most of the major Javascript frameworks. A: @Jack & @17 of 26, good point but the end user will be expecting the select box to be disabled so that confusion shouldn't be an issue. I should have been clearer about why I couldn't just disable the control. The application that will be using this will need to disable the selection of the options and there is a requirement that the "locked" control still maintain the look and feel of normal form controls. A: Try this trigger. <select multiple onchange="this.selectedIndex=this.selectedIndex"> <option>1</option> <option>2</option> </select> A: There is a recent new addition to CSS3 that is 95% compatible with all current browsers except Opera Mini, called pointer-events. Put simply, you can "disable" the default action on a SELECT or any other element, and still be able to perform specific events on it... You can view Chris Coyier's article on them at enter link description here. Is this closer to what you're looking for... Sorry that I couldn't provide any of my own coding examples...
{ "language": "en", "url": "https://stackoverflow.com/questions/43874", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }