source_id
int64 1
74.7M
| question
stringlengths 0
40.2k
| response
stringlengths 0
111k
| metadata
dict |
---|---|---|---|
78,592 | In perl one would simply do the following to store and iterate over a list of names my @fruit = (apple, orange, kiwi);foreach (@fruit) { print $_;} What would the equivalent be in bash? | bash (unlike POSIX sh) supports arrays: fruits=(apple orange kiwi "dried mango")for fruit in "${fruits[@]}"; do echo "${fruit}"done This has the advantage that array elements may contain spaces or other members of $IFS; as long as they were correctly inserted as separate elements, they are read out the same way. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/78592",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10747/"
]
} |
78,619 | What is the fastest way you know to convert a floating-point number to an int on an x86 CPU. Preferrably in C or assembly (that can be in-lined in C) for any combination of the following: 32/64/80-bit float -> 32/64-bit integer I'm looking for some technique that is faster than to just let the compiler do it. | It depends on if you want a truncating conversion or a rounding one and at what precision. By default, C will perform a truncating conversion when you go from float to int. There are FPU instructions that do it but it's not an ANSI C conversion and there are significant caveats to using it (such as knowing the FPU rounding state). Since the answer to your problem is quite complex and depends on some variables you haven't expressed, I recommend this article on the issue: http://www.stereopsis.com/FPU.html | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/78619",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10184/"
]
} |
78,703 | Does any know of a good calendar (not datepicker, but a BIG browsable calendar) plugin for one of the major javascript frameworks. I'd prefer jQuery. | just published a new open source project (jQuery plugin). sounds exactly like what you want: FullCalendar Hope it works well for you! | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/78703",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14521/"
]
} |
78,716 | A while ago, I started on a project where I designed a html-esque XML schema so that authors could write their content (educational course material) in a simplified format which would then be transformed into HTML via XSLT. I played around (struggled) with it for a while and got it to a very basic level but then was too annoyed by the limitations I was encountering (which may well have been limitations of my knowledge) and when I read a blog suggesting to ditch XSLT and just write your own XML-to-whatever parser in your language of choice, I eagerly jumped onto that and it's worked out brilliantly. I'm still working on it to this day ( I'm actually supposed to be working on it right now, instead of playing on SO ), and I am seeing more and more things which make me think that the decision to ditch XSLT was a good one. I know that XSLT has its place, in that it is an accepted standard, and that if everyone is writing their own interpreters, 90% of them will end up on TheDailyWTF . But given that it is a functional style language instead of the procedural style which most programmers are familiar with, for someone embarking on a project such as my own, would you recommend they go down the path that I did, or stick it out with XSLT ? | Advantages of XSLT: Domain-specific to XML, so for example no need to quote literal XML in the output. Supports XPath/XQuery, which can be a nice way to query DOMs, in the same way that regular expressions can be a nice way to query strings. Functional language. Disadvantages of XSLT: Can be obscenely verbose - you don't have to quote literal XML, which effectively means you do have to quote code. And not in a pretty way. But then again, it's not much worse than your typical SSI. Doesn't do certain things which most programmers take for granted. For instance string manipulation can be a chore. This can lead to "unfortunate moments" when novices design code, then frantically search the web for hints how to implement functions they assumed would just be there and didn't give themselves time to write. Functional language. One way to get procedural behaviour, by the way, is to chain multiple transforms together. After each step you have a brand new DOM to work on which reflects the changes in that step. Some XSL processors have extensions to effectively do this in one transform, but I forget the details. So, if your code is mostly output and not much logic, XSLT can be a very neat way to express it. If there is a lot of logic, but mostly of forms which are built in to XSLT (select all elements which look like blah, and for each one output blah), it's likely to be quite a friendly environment. If you fancy thinking XML-ishly at all times, then give XSLT 2 a go. Otherwise, I'd say that if your favourite programming language has a good DOM implementation supporting XPath and allowing you to build documents in a useful way, then there are few benefits to using XSLT. Bindings to libxml2 and gdome2 should do nicely, and there's no shame in sticking to general-purpose languages you know well. Home-grown XML parsers are usually either incomplete (in which case you'll come unstuck some day) or else not much smaller than something you could have got off the shelf (in which case you're probably wasting your time), and give you any number of opportunities to introduce severe security issues around malicious input. Don't write one unless you know exactly what you gain by doing it. Which is not to say you can't write a parser for something simpler than XML as your input format, if you don't need everything that XML offers. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/78716",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9021/"
]
} |
78,799 | What I'm talking about here are nested classes. Essentially, I have two classes that I'm modeling. A DownloadManager class and a DownloadThread class. The obvious OOP concept here is composition. However, composition doesn't necessarily mean nesting, right? I have code that looks something like this: class DownloadThread: def foo(self): passclass DownloadManager(): def __init__(self): dwld_threads = [] def create_new_thread(): dwld_threads.append(DownloadThread()) But now I'm wondering if there's a situation where nesting would be better. Something like: class DownloadManager(): class DownloadThread: def foo(self): pass def __init__(self): dwld_threads = [] def create_new_thread(): dwld_threads.append(DownloadManager.DownloadThread()) | You might want to do this when the "inner" class is a one-off, which will never be used outside the definition of the outer class. For example to use a metaclass, it's sometimes handy to do class Foo(object): class __metaclass__(type): .... instead of defining a metaclass separately, if you're only using it once. The only other time I've used nested classes like that, I used the outer class only as a namespace to group a bunch of closely related classes together: class Group(object): class cls1(object): ... class cls2(object): ... Then from another module, you can import Group and refer to these as Group.cls1, Group.cls2 etc. However one might argue that you can accomplish exactly the same (perhaps in a less confusing way) by using a module. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/78799",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10708/"
]
} |
78,801 | Running a rails site right now using SQLite3. About once every 500 requests or so, I get a ActiveRecord::StatementInvalid (SQLite3::BusyException: database is locked:... What's the way to fix this that would be minimally invasive to my code? I'm using SQLLite at the moment because you can store the DB in source control which makes backing up natural and you can push changes out very quickly. However, it's obviously not really set up for concurrent access. I'll migrate over to MySQL tomorrow morning. | You mentioned that this is a Rails site. Rails allows you to set the SQLite retry timeout in your database.yml config file: production: adapter: sqlite3 database: db/mysite_prod.sqlite3 timeout: 10000 The timeout value is specified in miliseconds. Increasing it to 10 or 15 seconds should decrease the number of BusyExceptions you see in your log. This is just a temporary solution, though. If your site needs true concurrency then you will have to migrate to another db engine. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/78801",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14559/"
]
} |
78,806 | Where a new system concept or new technology is used, one has to build a system to throw away, for even the best planning is not so omniscient as to get it right the first time. Hence plan to throw one away; you will, anyhow. -- Fred Brooks, The Mythical Man-Month [Emphasis mine] Build one to throw away. That's what they told me. Then they told me that we're all agile now, so we should Refactor Mercilessly . What gives? Is it always better to refactor my way out of trouble? If not, can anyone suggest a rule-of-thumb to help me decide when to stick with it, and when to give up and start over? | If you're doing test-driven development, you can refactor your way out of almost any trouble. I've changed major design decisions without much trouble, and rescued decade-old codebases. The only exception is when you've discovered that your architecture is completely wrong from beginning to end. For example, if you wrote your app using threads, but you discovered that you wanted a bunch of asynchronous state machines. At that point, go ahead and throw away the first draft. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/78806",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1260685/"
]
} |
78,811 | Is there an effective tool to convert C# code to Java code? | I have never encountered a C#->Java conversion tool. The syntax would be easy enough, but the frameworks are dramatically different. Even if there were a tool, I would strongly advise against it. I have worked on several "migration" projects, and can't say emphatically enough that while conversion seems like a good choice, conversion projects always always always turn in to money pits. It's not a shortcut, what you end up with is code that is not readable, and doesn't take advantage of the target language. speaking from personal experience, assume that a rewrite is the cheaper option. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/78811",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
78,816 | I have recently written an application(vb.net) that stores and allows searching for old council plans. Now while the application works well, the other day I was having a look at the routine that I use to generate the SQL string to pass the database and frankly, it was bad. I was just posting a question here to see if anyone else has a better way of doing this. What I have is a form with a bunch of controls ranging from text boxes to radio buttons, each of these controls are like database filters and when the user hits search button, a SQL string(I would really like it to be a LINQ query because I have changed to LINQ to SQL) gets generated from the completed controls and run. The problem that I am having is matching each one of these controls to a field in the database and generating a LINQ query efficiently without doing a bunch of "if ...then...else." statements. In the past I have just used the tag property on the control to link to control to a field name in the database. I'm sorry if this is a bit confusing, its a bit hard to describe. Just throwing it out there to see if anyone has any ideas. ThanksNathan | I have never encountered a C#->Java conversion tool. The syntax would be easy enough, but the frameworks are dramatically different. Even if there were a tool, I would strongly advise against it. I have worked on several "migration" projects, and can't say emphatically enough that while conversion seems like a good choice, conversion projects always always always turn in to money pits. It's not a shortcut, what you end up with is code that is not readable, and doesn't take advantage of the target language. speaking from personal experience, assume that a rewrite is the cheaper option. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/78816",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6335/"
]
} |
78,826 | How do you use gen_udp in Erlang to do multicasting ? I know its in the code, there is just no documentation behind it. Sending out data is obvious and simple. I was wondering on how to add memberships. Not only adding memberships at start-up, but adding memberships while running would be useful too. | Here is example code on how to listen in on Bonjour / Zeroconf traffic. -module(zcclient).-export([open/2,start/0]).-export([stop/1,receiver/0]).open(Addr,Port) -> {ok,S} = gen_udp:open(Port,[{reuseaddr,true}, {ip,Addr}, {multicast_ttl,4}, {multicast_loop,false}, binary]), inet:setopts(S,[{add_membership,{Addr,{0,0,0,0}}}]), S.close(S) -> gen_udp:close(S).start() -> S=open({224,0,0,251},5353), Pid=spawn(?MODULE,receiver,[]), gen_udp:controlling_process(S,Pid), {S,Pid}.stop({S,Pid}) -> close(S), Pid ! stop.receiver() -> receive {udp, _Socket, IP, InPortNo, Packet} -> io:format("~n~nFrom: ~p~nPort: ~p~nData: ~p~n",[IP,InPortNo,inet_dns:decode(Packet)]), receiver(); stop -> true; AnythingElse -> io:format("RECEIVED: ~p~n",[AnythingElse]), receiver() end. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/78826",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10432/"
]
} |
78,869 | I'm looking around for a Java code signing certificate so my Java applets don't throw up such scary security warnings. However, all the places I've found offering them charge (in my opinion) way too much, like over USD200 per year. While doing research, a code signing certificate seems almost exactly the same as an SSL certificate. The main question I have: is it possible to buy an SSL certificate, but use it to sign Java applets? | Short answer: No, they're different. Long answer: It's the same sort of certificate and it uses the same crypto software, but the certificate has flags indicating what it is allowed to be used for. Code signing and web server are different uses. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/78869",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14569/"
]
} |
78,932 | I have the following HTML <select> element: <select id="leaveCode" name="leaveCode"> <option value="10">Annual Leave</option> <option value="11">Medical Leave</option> <option value="14">Long Service</option> <option value="17">Leave Without Pay</option></select> Using a JavaScript function with the leaveCode number as a parameter, how do I select the appropriate option in the list? | You can use this function: function selectElement(id, valueToSelect) { let element = document.getElementById(id); element.value = valueToSelect;}selectElement('leaveCode', '11'); <select id="leaveCode" name="leaveCode"> <option value="10">Annual Leave</option> <option value="11">Medical Leave</option> <option value="14">Long Service</option> <option value="17">Leave Without Pay</option></select> Optionally if you want to trigger onchange event also, you can use : element.dispatchEvent(new Event('change')) | {
"score": 11,
"source": [
"https://Stackoverflow.com/questions/78932",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6340/"
]
} |
79,023 | Briefly: Does anyone know of a GUI for gdb that brings it on par or close to the feature set you get in the more recent version of Visual C++? In detail: As someone who has spent a lot of time programming in Windows, one of the larger stumbling blocks I've found whenever I have to code C++ in Linux is that debugging anything using commandline gdb takes me several times longer than it does in Visual Studio, and it does not seem to be getting better with practice. Some things are just easier or faster to express graphically. Specifically, I'm looking for a GUI that: Handles all the basics like stepping over & into code, watch variables and breakpoints Understands and can display the contents of complex & nested C++ data types Doesn't get confused by and preferably can intelligently step through templated code and data structures while displaying relevant information such as the parameter types Can handle threaded applications and switch between different threads to step through or view the state of Can handle attaching to an already-started process or reading a core dump, in addition to starting the program up in gdb If such a program does not exist, then I'd like to hear about experiences people have had with programs that meet at least some of the bullet points.Does anyone have any recommendations? Edit: Listing out the possibilities is great, and I'll take what I can get, but it would be even more helpful if you could include in your responses: (a) Whether or not you've actually used this GUI and if so, what positive/negative feedback you have about it. (b) If you know, which of the above-mentioned features are/aren't supported Lists are easy to come by, sites like this are great because you can get an idea of people's personal experiences with applications. | You won't find anything overlaying GDB which can compete with the raw power of the Visual Studio debugger. It's just too powerful, and it's just too well integrated inside the IDE. For a Linux alternative, try DDD if free software is your thing. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/79023",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14266/"
]
} |
79,126 | I'm building a function to extend the Enum.Parse concept that Allows a default value to be parsed in case that an Enum value is not found Is case insensitive So I wrote the following: public static T GetEnumFromString<T>(string value, T defaultValue) where T : Enum{ if (string.IsNullOrEmpty(value)) return defaultValue; foreach (T item in Enum.GetValues(typeof(T))) { if (item.ToString().ToLower().Equals(value.Trim().ToLower())) return item; } return defaultValue;} I am getting a Error Constraint cannot be special class System.Enum . Fair enough, but is there a workaround to allow a Generic Enum, or am I going to have to mimic the Parse function and pass a type as an attribute, which forces the ugly boxing requirement to your code. EDIT All suggestions below have been greatly appreciated, thanks. Have settled on (I've left the loop to maintain case insensitivity - I am using this when parsing XML) public static class EnumUtils{ public static T ParseEnum<T>(string value, T defaultValue) where T : struct, IConvertible { if (!typeof(T).IsEnum) throw new ArgumentException("T must be an enumerated type"); if (string.IsNullOrEmpty(value)) return defaultValue; foreach (T item in Enum.GetValues(typeof(T))) { if (item.ToString().ToLower().Equals(value.Trim().ToLower())) return item; } return defaultValue; }} EDIT: (16th Feb 2015) Christopher Currens has posted a compiler enforced type-safe generic solution in MSIL or F# below, which is well worth a look, and an upvote. I will remove this edit if the solution bubbles further up the page. EDIT 2: (13th Apr 2021) As this has now been addressed, and supported, since C# 7.3, I have changed the accepted answer, though full perusal of the top answers is worth it for academic, and historical, interest :) | This feature is finally supported in C# 7.3! The following snippet (from the dotnet samples ) demonstrates how: public static Dictionary<int, string> EnumNamedValues<T>() where T : System.Enum{ var result = new Dictionary<int, string>(); var values = Enum.GetValues(typeof(T)); foreach (int item in values) result.Add(item, Enum.GetName(typeof(T), item)); return result;} Be sure to set your language version in your C# project to version 7.3. Original Answer below: I'm late to the game, but I took it as a challenge to see how it could be done. It's not possible in C# (or VB.NET, but scroll down for F#), but is possible in MSIL. I wrote this little....thing // license: http://www.apache.org/licenses/LICENSE-2.0.html.assembly MyThing{}.class public abstract sealed MyThing.Thing extends [mscorlib]System.Object{ .method public static !!T GetEnumFromString<valuetype .ctor ([mscorlib]System.Enum) T>(string strValue, !!T defaultValue) cil managed { .maxstack 2 .locals init ([0] !!T temp, [1] !!T return_value, [2] class [mscorlib]System.Collections.IEnumerator enumerator, [3] class [mscorlib]System.IDisposable disposer) // if(string.IsNullOrEmpty(strValue)) return defaultValue; ldarg strValue call bool [mscorlib]System.String::IsNullOrEmpty(string) brfalse.s HASVALUE br RETURNDEF // return default it empty // foreach (T item in Enum.GetValues(typeof(T))) HASVALUE: // Enum.GetValues.GetEnumerator() ldtoken !!T call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) call class [mscorlib]System.Array [mscorlib]System.Enum::GetValues(class [mscorlib]System.Type) callvirt instance class [mscorlib]System.Collections.IEnumerator [mscorlib]System.Array::GetEnumerator() stloc enumerator .try { CONDITION: ldloc enumerator callvirt instance bool [mscorlib]System.Collections.IEnumerator::MoveNext() brfalse.s LEAVE STATEMENTS: // T item = (T)Enumerator.Current ldloc enumerator callvirt instance object [mscorlib]System.Collections.IEnumerator::get_Current() unbox.any !!T stloc temp ldloca.s temp constrained. !!T // if (item.ToString().ToLower().Equals(value.Trim().ToLower())) return item; callvirt instance string [mscorlib]System.Object::ToString() callvirt instance string [mscorlib]System.String::ToLower() ldarg strValue callvirt instance string [mscorlib]System.String::Trim() callvirt instance string [mscorlib]System.String::ToLower() callvirt instance bool [mscorlib]System.String::Equals(string) brfalse.s CONDITION ldloc temp stloc return_value leave.s RETURNVAL LEAVE: leave.s RETURNDEF } finally { // ArrayList's Enumerator may or may not inherit from IDisposable ldloc enumerator isinst [mscorlib]System.IDisposable stloc.s disposer ldloc.s disposer ldnull ceq brtrue.s LEAVEFINALLY ldloc.s disposer callvirt instance void [mscorlib]System.IDisposable::Dispose() LEAVEFINALLY: endfinally } RETURNDEF: ldarg defaultValue stloc return_value RETURNVAL: ldloc return_value ret }} Which generates a function that would look like this, if it were valid C#: T GetEnumFromString<T>(string valueString, T defaultValue) where T : Enum Then with the following C# code: using MyThing;// stuff...private enum MyEnum { Yes, No, Okay }static void Main(string[] args){ Thing.GetEnumFromString("No", MyEnum.Yes); // returns MyEnum.No Thing.GetEnumFromString("Invalid", MyEnum.Okay); // returns MyEnum.Okay Thing.GetEnumFromString("AnotherInvalid", 0); // compiler error, not an Enum} Unfortunately, this means having this part of your code written in MSIL instead of C#, with the only added benefit being that you're able to constrain this method by System.Enum . It's also kind of a bummer, because it gets compiled into a separate assembly. However, it doesn't mean you have to deploy it that way. By removing the line .assembly MyThing{} and invoking ilasm as follows: ilasm.exe /DLL /OUTPUT=MyThing.netmodule you get a netmodule instead of an assembly. Unfortunately, VS2010 (and earlier, obviously) does not support adding netmodule references, which means you'd have to leave it in 2 separate assemblies when you're debugging. The only way you can add them as part of your assembly would be to run csc.exe yourself using the /addmodule:{files} command line argument. It wouldn't be too painful in an MSBuild script. Of course, if you're brave or stupid, you can run csc yourself manually each time. And it certainly gets more complicated as multiple assemblies need access to it. So, it CAN be done in .Net. Is it worth the extra effort? Um, well, I guess I'll let you decide on that one. F# Solution as alternative Extra Credit: It turns out that a generic restriction on enum is possible in at least one other .NET language besides MSIL: F#. type MyThing = static member GetEnumFromString<'T when 'T :> Enum> str defaultValue: 'T = /// protect for null (only required in interop with C#) let str = if isNull str then String.Empty else str Enum.GetValues(typedefof<'T>) |> Seq.cast<_> |> Seq.tryFind(fun v -> String.Compare(v.ToString(), str.Trim(), true) = 0) |> function Some x -> x | None -> defaultValue This one is easier to maintain since it's a well-known language with full Visual Studio IDE support, but you still need a separate project in your solution for it. However, it naturally produces considerably different IL (the code is very different) and it relies on the FSharp.Core library, which, just like any other external library, needs to become part of your distribution. Here's how you can use it (basically the same as the MSIL solution), and to show that it correctly fails on otherwise synonymous structs: // works, result is inferred to have type StringComparisonvar result = MyThing.GetEnumFromString("OrdinalIgnoreCase", StringComparison.Ordinal);// type restriction is recognized by C#, this fails at compile timevar result = MyThing.GetEnumFromString("OrdinalIgnoreCase", 42); | {
"score": 11,
"source": [
"https://Stackoverflow.com/questions/79126",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5302/"
]
} |
79,129 | For the life of me, I cannot get the SqlProfileProvider to work in an MVC project that I'm working on. The first interesting thing that I realized is that Visual Studio does not automatically generate the ProfileCommon proxy class for you. That's not a big deal since it's simpy a matter of extending the ProfileBase class. After creating a ProfileCommon class, I wrote the following Action method for creating the user profile. [AcceptVerbs("POST")]public ActionResult CreateProfile(string company, string phone, string fax, string city, string state, string zip){ MembershipUser user = Membership.GetUser(); ProfileCommon profile = ProfileCommon.Create(user.UserName, user.IsApproved) as ProfileCommon; profile.Company = company; profile.Phone = phone; profile.Fax = fax; profile.City = city; profile.State = state; profile.Zip = zip; profile.Save(); return RedirectToAction("Index", "Account"); } The problem that I'm having is that the call to ProfileCommon.Create() cannot cast to type ProfileCommon, so I'm not able to get back my profile object, which obviously causes the next line to fail since profile is null. Following is a snippet of my web.config: <profile defaultProvider="AspNetSqlProfileProvider" automaticSaveEnabled="false" enabled="true"> <providers> <clear/> <add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" connectionStringName="ApplicationServices" applicationName="/" /> </providers> <properties> <add name="FirstName" type="string" /> <add name="LastName" type="string" /> <add name="Company" type="string" /> <add name="Phone" type="string" /> <add name="Fax" type="string" /> <add name="City" type="string" /> <add name="State" type="string" /> <add name="Zip" type="string" /> <add name="Email" type="string" > </properties></profile> The MembershipProvider is working without a hitch, so I know that the connection string is good. Just in case it's helpful, here is my ProfileCommon class: public class ProfileCommon : ProfileBase { public virtual string Company { get { return ((string)(this.GetPropertyValue("Company"))); } set { this.SetPropertyValue("Company", value); } } public virtual string Phone { get { return ((string)(this.GetPropertyValue("Phone"))); } set { this.SetPropertyValue("Phone", value); } } public virtual string Fax { get { return ((string)(this.GetPropertyValue("Fax"))); } set { this.SetPropertyValue("Fax", value); } } public virtual string City { get { return ((string)(this.GetPropertyValue("City"))); } set { this.SetPropertyValue("City", value); } } public virtual string State { get { return ((string)(this.GetPropertyValue("State"))); } set { this.SetPropertyValue("State", value); } } public virtual string Zip { get { return ((string)(this.GetPropertyValue("Zip"))); } set { this.SetPropertyValue("Zip", value); } } public virtual ProfileCommon GetProfile(string username) { return ((ProfileCommon)(ProfileBase.Create(username))); } } Any thoughts on what I might be doing wrong? Have any of the rest of you successfully integrated a ProfileProvider with your ASP.NET MVC projects? Thank you in advance... | Here's what you need to do: 1) In Web.config's section, add "inherits" attribute in addition to your other attribute settings: <profile inherits="MySite.Models.ProfileCommon" defaultProvider=".... 2) Remove entire <properties> section from Web.config, since you have already defined them in your custom ProfileCommon class and also instructed to inherit from your custom class in previous step 3) Change the code of your ProfileCommon.GetProfile() method to public virtual ProfileCommon GetProfile(string username) { return Create(username) as ProfileCommon; } Hope this helps. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/79129",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10792/"
]
} |
79,165 | I read the Git manual, FAQ, Git - SVN crash course, etc. and they all explain this and that, but nowhere can you find a simple instruction like: SVN repository in: svn://myserver/path/to/svn/repos Git repository in: git://myserver/path/to/git/repos git-do-the-magic-svn-import-with-history \svn://myserver/path/to/svn/repos \git://myserver/path/to/git/repos I don't expect it to be that simple, and I don't expect it to be a single command. But I do expect it not to try to explain anything - just to say what steps to take given this example. | Create a users file (i.e. users.txt ) for mapping SVN users to Git: user1 = First Last Name <[email protected]>user2 = First Last Name <[email protected]>... You can use this one-liner to build a template from your existing SVN repository: svn log -q | awk -F '|' '/^r/ {gsub(/ /, "", $2); sub(" $", "", $2); print $2" = "$2" <"$2">"}' | sort -u > users.txt SVN will stop if it finds a missing SVN user, not in the file. But after that, you can update the file and pick up where you left off. Now pull the SVN data from the repository: git svn clone --stdlayout --no-metadata --authors-file=users.txt svn://hostname/path dest_dir-tmp This command will create a new Git repository in dest_dir-tmp and start pulling the SVN repository. Note that the "--stdlayout" flag implies you have the common "trunk/, branches/, tags/" SVN layout. If your layout differs, become familiar with --tags , --branches , --trunk options (in general git svn help ). All common protocols are allowed: svn:// , http:// , https:// . The URL should target the base repository, something like http://svn.mycompany.com/myrepo/repository . The URL string must not include /trunk , /tag or /branches . Note that after executing this command it very often looks like the operation is "hanging/frozen", and it's quite normal that it can be stuck for a long time after initializing the new repository. Eventually, you will then see log messages which indicate that it's migrating. Also note that if you omit the --no-metadata flag, Git will append information about the corresponding SVN revision to the commit message (i.e. git-svn-id: svn://svn.mycompany.com/myrepo/<branchname/trunk>@<RevisionNumber> <Repository UUID> ) If a user name is not found, update your users.txt file then: cd dest_dir-tmpgit svn fetch You might have to repeat that last command several times, if you have a large project until all of the Subversion commits have been fetched: git svn fetch When completed, Git will checkout the SVN trunk into a new branch. Any other branches are set up as remotes. You can view the other SVN branches with: git branch -r If you want to keep other remote branches in your repository, you want to create a local branch for each one manually. (Skip trunk/master.) If you don't do this, the branches won't get cloned in the final step. git checkout -b local_branch remote_branch# It's OK if local_branch and remote_branch are the same names Tags are imported as branches. You have to create a local branch, make a tag and delete the branch to have them as tags in Git. To do it with tag "v1": git checkout -b tag_v1 remotes/tags/v1git checkout mastergit tag v1 tag_v1git branch -D tag_v1 Clone your GIT-SVN repository into a clean Git repository: git clone dest_dir-tmp dest_dirrm -rf dest_dir-tmpcd dest_dir The local branches that you created earlier from remote branches will only have been copied as remote branches into the newly cloned repository. (Skip trunk/master.) For each branch you want to keep: git checkout -b local_branch origin/remote_branch Finally, remove the remote from your clean Git repository that points to the now-deleted temporary repository: git remote rm origin | {
"score": 11,
"source": [
"https://Stackoverflow.com/questions/79165",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14690/"
]
} |
79,197 | What's a simple way to combine feed and feed2 ? I want the items from feed2 to be added to feed . Also I want to avoid duplicates as feed might already have items when a question is tagged with both WPF and Silverlight. Uri feedUri = new Uri("http://stackoverflow.com/feeds/tag/silverlight");XmlReader reader = XmlReader.Create(feedUri.AbsoluteUri);SyndicationFeed feed = SyndicationFeed.Load(reader); Uri feed2Uri = new Uri("http://stackoverflow.com/feeds/tag/wpf");XmlReader reader2 = XmlReader.Create(feed2Uri.AbsoluteUri);SyndicationFeed feed2 = SyndicationFeed.Load(reader2); | You can use LINQ to simplify the code to join two lists (don't forget to put System.Linq in your usings and if necessary reference System.Core in your project) Here's a Main that does the union and prints them to console (with proper cleanup of the Reader). using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Xml;using System.ServiceModel.Syndication;namespace FeedUnion{ class Program { static void Main(string[] args) { Uri feedUri = new Uri("http://stackoverflow.com/feeds/tag/silverlight"); SyndicationFeed feed; SyndicationFeed feed2; using(XmlReader reader = XmlReader.Create(feedUri.AbsoluteUri)) { feed= SyndicationFeed.Load(reader); } Uri feed2Uri = new Uri("http://stackoverflow.com/feeds/tag/wpf"); using (XmlReader reader2 = XmlReader.Create(feed2Uri.AbsoluteUri)) { feed2 = SyndicationFeed.Load(reader2); } SyndicationFeed feed3 = new SyndicationFeed(feed.Items.Union(feed2.Items)); StringBuilder builder = new StringBuilder(); using (XmlWriter writer = XmlWriter.Create(builder)) { feed3.SaveAsRss20(writer); System.Console.Write(builder.ToString()); System.Console.Read(); } } }} | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/79197",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1133/"
]
} |
79,210 | What is the best C++ IDE for a *nix envirnoment? I have heard the C/C++ module of Eclipse is decent as well as Notepad++ but beyond these two I have no real idea. Any thoughts or comments? | On Ubuntu, some the IDEs that are available in the repositories are: Kdevelop Geany Anjuta There is also: Eclipse (Recommended you don't install from repositories, due to issues with file/folder permissions) Code::blocks And of course, everyone's favourite text-based editors: vi/vim emacs Its true that vim and emacs are very powerful tools, but the learning curve is very steep.. I really don't like Eclipse that much, I find it buggy and a bit too clunky. I've started using Geany as a bare-bones but functional and usable IDE. It has a basic code-completion feature, and is a nice, clean [Gnome] interface. Anjuta I tried for a day, didn't like it at all. I didn't find it as useful as Geany. Kdevelop and code::blocks get a bunch of good reviews, but I haven't tried them. I use gnome, and I'm yet to see a KDE app that looks good in gnome (sorry, I'm sure its a great program). If only bloodshed dev-c++ was released under linux. That is a fantastic (but windows-only) program. You could always run it under Wine ;) To a degree, it comes down to personal preference. My advice is to investigate Kdevelop, Geany and code::blocks as a starting point. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/79210",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14717/"
]
} |
79,229 | In your experience, how often should Oracle database statistics be run? Our team of developers recently discovered that statistics hadn't been run our production box in over 2 1/2 months. That sounds like a long time to me, but I'm not a DBA. | At my last job we ran statistics once a week. If I remember correctly, we scheduled them on a Thursday night, and on Friday the DBAs were very careful to monitor the longest running queries for anything unexpected. (Friday was picked because it was often just after a code release, and tended to be a fairly low traffic day.) When they saw a bad query they would find a better query plan and save that one so it wouldn't change again unexpectedly. (Oracle has tools to do this for you automatically, you tell it the query to optimize and it does.) Many organizations avoid running statistics out of fear of bad query plans popping up unexpectedly. But this usually means that their query plans get worse and worse over time. And when they do run statistics then they encounter a number of problems. The resulting scramble to fix those issues confirms their fears about the dangers of running statistics. But if they ran statistics regularly, used the monitoring tools as they are supposed to, and fixed issues as they came up then they would have fewer headaches, and they wouldn't encounter them all at once. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/79229",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
79,241 | When working with tables in Oracle, how do you know when you are setting up a good index versus a bad index? | This depends on what you mean by 'good' and 'bad'. Basically you need to realise that every index you add will increase performance on any search by that column (so adding an index to the 'lastname' column of a person table will increase performance on queries that have "where lastname = " in them) but decrease write performance across the whole table. The reason for this is when you add or update a row, it must add-to or update both the table itself and every index that row is a member of. So if you have five indexes on a table, each addition must write to six places - five indexes and the table - and an update may be touching up to six places in the worst case. Index creation is a balancing act then between query speed and write speed. In some cases, such as a datamart that is only loaded with data once a week in an overnight job but queried thousands of times daily, it makes a great deal of sense to overload with indexes and speed the queries up as much as possible. In the case of online transaction processing systems however, you want to try and find a balance between them. So in short, add indexes to columns that are used a lot in select queries, but try to avoid adding too many and so add the most-used columns first. After that its a matter of load testing to see how the performance reacts under production conditions, and a lot of tweaking to find an aceeptable balance. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/79241",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
79,248 | What are the characteristics of a multitasking operating system? What makes it multitasking? Are there non-multitasking operating systems? | What are the characteristics of a multitasking operating system? What makes it multitasking? Multitasking operating systems allow more than one program to run at a time. They can support either preemptive multitasking, where the OS doles out time to applications (virtually all modern OSes) or cooperative multitasking, where the OS waits for the program to give back control (Windows 3.x, Mac OS 9 and earlier). Are there non-multitasking operating systems? Any OS that only allows one thing to be done at a time (DOS for instance). | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/79248",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10703/"
]
} |
79,266 | When attempting to understand how a SQL statement is executing, it is sometimes recommended to look at the explain plan. What is the process one should go through in interpreting (making sense) of an explain plan? What should stand out as, "Oh, this is working splendidly?" versus "Oh no, that's not right." | I shudder whenever I see comments that full tablescans are bad and index access is good. Full table scans, index range scans, fast full index scans, nested loops, merge join, hash joins etc. are simply access mechanisms that must be understood by the analyst and combined with a knowledge of the database structure and the purpose of a query in order to reach any meaningful conclusion. A full scan is simply the most efficient way of reading a large proportion of the blocks of a data segment (a table or a table (sub)partition), and, while it often can indicate a performance problem, that is only in the context of whether it is an efficient mechanism for achieving the goals of the query. Speaking as a data warehouse and BI guy, my number one warning flag for performance is an index based access method and a nested loop. So, for the mechanism of how to read an explain plan the Oracle documentation is a good guide: http://download.oracle.com/docs/cd/B28359_01/server.111/b28274/ex_plan.htm#PFGRF009 Have a good read through the Performance Tuning Guide also. Also have a google for "cardinality feedback", a technique in which an explain plan can be used to compare the estimations of cardinality at various stages in a query with the actual cardinalities experienced during the execution. Wolfgang Breitling is the author of the method, I believe. So, bottom line: understand the access mechanisms. Understand the database. Understand the intention of the query. Avoid rules of thumb. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/79266",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
79,322 | The documentation with the module itself is pretty thin, and just tends to point to MOP. | First you should read through the Manual if you haven't already. Then you can go on to read the Cookbook . I think the docs are actually pretty good these days, as long as you read the right ones. You really shouldn't bother looking at most of the docs for any class name starting with " Moose::Meta " unless you're interested in Moose's introspection features. I've tried to make this more obvious in the Moose.pm docs, which as of 0.57 tell you to read the Manual and Cookbook first. If you're coming from a background of doing Perl 5 OO "the old school way", I'd also suggest taking a look at the Moose::Manual::Unsweetened document, which compares Moose to equivalent Perl 5 "by hand" code. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/79322",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11289/"
]
} |
79,381 | I am wanting to access a website from a different port than 80 or 8080. Is this possible? I just want to view the website but through a different port. I do not have a router. I know this can be done because I have a browser that accessing websites through different ports, Called XB Browser by Xero Bank. Thanks for the answers. So, if I setup a proxy on one computer, I could have it go from my computer, to another computer that then returns the website to me. Would this bypass logging software? | If your question is about IIS(or other server) configuration - yes, it's possible. All you need is to create ports mapping under your Default Site or Virtual Directory and assign specific ports to the site you need. For example it is sometimes very useful for web services, when default port is assigned to some UI front-end and you want to assign service to the same address but with different port. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/79381",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14769/"
]
} |
79,389 | In a multitasking operating system context, sometimes you hear the term round-robin scheduling. What does it refer to? What other kind of scheduling is there? | Round Robin Scheduling If you are a host in a party of 100 guests, round-robin scheduling would mean that you spend 1 minute (a fixed amount) per guest. You go through each guest one-by-one, and after 100 minutes, you would have spent 1 minute with each guest. More on Wikipedia . There are many other types of scheduling, such as priority-based (i.e. most important people first), first-come-first-serve, earliest-deadline-first (i.e. person leaving earliest first), etc. You can start off by googling for scheduling algorithms or check out scheduling at Wikipedia | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/79389",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10703/"
]
} |
79,415 | What, at a minimum, should an application health-monitoring system do for you (the developer) and/or your boss (the IT Manager) and/or the operations (on-call) staff? What else should it do above the minimum requirements? Is monitoring the 'infrastructure' applications (ms-exchange, apache, etc.) sufficient or do individual user applications, web sites, and databases also need to be monitored? if the latter, what do you need to know about them? ADDENDUM: thanks for the input, i was really looking for application-level monitoring not infrastructure monitoring, but it is good to know about both | Whether the application is running. Unusual cpu/memory/network usage. Report any unhandled exceptions. Status of various modules (if applicable). Status of external components (databases, webservices, fileservers, etc.) Number of pending background tasks (if applicable). Maybe track usage of the application and report statistics on most/less used functionalities so you know where optimizations are most beneficial. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/79415",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9345/"
]
} |
79,434 | I think it's associating my Web Service's CS files with the related ASMX files. But whatever's happening, I can't double-click to open the CS files - I have to "view Code" or it opens in the designer. Anyone know how to turn off this automatic behavior? I just want to edit the code! | Try right-clicking, select "Open with...", mark "CSharp Editor" and select "Set as Default". That works for avoiding the WinForms Designer. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/79434",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7104/"
]
} |
79,445 | I'd like to write a simple C# application to monitor the line-in audio and give me the current (well, the rolling average) beats per minute. I've seen this gamedev article , and that was absolutely no help. I went through and tried to implement what he was doing but it just wasn't working. I know there have to be tons of solutions for this, because lots of DJ software does it, but I'm not having any luck in finding any open-source library or instructions on doing it myself. | Calculate a powerspectrum with a sliding window FFT:Take 1024 samples: double[] signal = stream.Take(1024); Feed it to an FFT algorithm: double[] real = new double[signal.Length];double[] imag = new double[signal.Length);FFT(signal, out real, out imag); You will get a real part and an imaginary part. Do NOT throw away the imaginary part. Do the same to the real part as the imaginary. While it is true that the imaginary part is pi / 2 out of phase with the real, it still contains 50% of the spectrum information. EDIT: Calculate the power as opposed to the amplitude so that you have a high number when it is loud and close to zero when it is quiet: for (i=0; i < real.Length; i++) real[i] = real[i] * real[i]; Similarly for the imaginary part. for (i=0; i < imag.Length; i++) imag[i] = imag[i] * imag[i]; Now you have a power spectrum for the last 1024 samples. Where the first part of the spectrum is the low frequencies and the last part of the spectrum is the high frequencies. If you want to find BPM in popular music you should probably focus on the bass. You can pick up the bass intensity by summing the lower part of the power spectrum. Which numbers to use depends on the sampling frequency: double bassIntensity = 0;for (i=8; i < 96; i++) bassIntensity += real[i]; Now do the same again but move the window 256 samples before you calculate a new spectrum. Now you end up with calculating the bassIntensity for every 256 samples. This is a good input for your BPM analysis. When the bass is quiet you do not have a beat and when it is loud you have a beat. Good luck! | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/79445",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14758/"
]
} |
79,461 | I have a div with two images and an h1 . All of them need to be vertically aligned within the div, next to each other. One of the images needs to be absolute positioned within the div . What is the CSS needed for this to work on all common browsers? <div id="header"> <img src=".." ></img> <h1>testing...</h1> <img src="..."></img></div> | Wow, this problem is popular. It's based on a misunderstanding in the vertical-align property. This excellent article explains it: Understanding vertical-align , or "How (Not) To Vertically Center Content" by Gavin Kistner. “How to center in CSS” is a great web tool which helps to find the necessary CSS centering attributes for different situations. In a nutshell (and to prevent link rot) : Inline elements (and only inline elements) can be vertically aligned in their context via vertical-align: middle . However, the “context” isn’t the whole parent container height, it’s the height of the text line they’re in. jsfiddle example For block elements, vertical alignment is harder and strongly depends on the specific situation: If the inner element can have a fixed height , you can make its position absolute and specify its height , margin-top and top position. jsfiddle example If the centered element consists of a single line and its parent height is fixed you can simply set the container’s line-height to fill its height. This method is quite versatile in my experience. jsfiddle example … there are more such special cases. | {
"score": 11,
"source": [
"https://Stackoverflow.com/questions/79461",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5232/"
]
} |
79,474 | I've set up Passenger in development (Mac OS X) and it works flawlessly. The only problem came later: now I have a custom GEM_HOME path and ImageMagick binaries installed in "/usr/local" . I can put them in one of the shell rc files that get sourced and this solves the environment variables for processes spawned from the console; but what about Passenger? The same application cannot find my gems when run this way. | I know of two solutions. The first (documented here ) is essentially the same as manveru's—set the ENV variable directly in your code. The second is to create a wrapper around the Ruby interpreter that Passenger uses, and is documented here (look for passenger_with_ruby). The gist is that you create (and point PassengerRuby in your Apache config to) /usr/bin/ruby_with_env, an executable file consisting of: #!/bin/bashexport ENV_VAR=value/usr/bin/ruby $* Both work; the former approach is a little less hackish, I think. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/79474",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11687/"
]
} |
79,490 | How can I get a history of uptimes for my debian box? After a reboot, I dont see an option for the uptime command to print a history of uptimes. If it matters, I would like to use these uptimes for graphing a page in php to show my webservers uptime lengths between boots. Update: Not sure if it is based on a length of time or if last gets reset on reboot but I only get the most recent boot timestamp with the last command. last -x also does not return any further info. Sounds like a script is my best bet. Update:Uptimed is the information I am looking for, not sure how to grep that info in code. Managing my own script for a db sounds like the best fit for an application. | You could create a simple script which runs uptime and dumps it to a file. uptime >> uptime.log Then set up a cron job for it. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/79490",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/777/"
]
} |
79,498 | I have determined that my JSON, coming from the server, is valid (making the ajax call manually), but I would really like to use JQuery. I have also determined that the "post" URL, being sent to the server, is correct, using firebug. However, the error callback is still being triggered (parse error). I also tried datatype: text. Are there other options that I should include? $(function() { $("#submit").bind("click", function() { $.ajax({ type: "post", url: "http://myServer/cgi-bin/broker" , datatype: "json", data: {'start' : start,'end' : end}, error: function(request,error){ alert(error); }, success: function(request) { alert(request.length); } }); // End ajax }); // End bind}); // End eventlistener | Here are a few suggestions I would try: 1) the 'datatype' option you have specified should be 'dataType' (case-sensitive I believe) 2) try using the 'contentType' option as so: contentType: "application/json; charset=utf-8" I'm not sure how much that will help as it's used in the request to your post url, not in the response.See this article for more info: http://encosia.com/2008/06/05/3-mistakes-to-avoid-when-using-jquery-with-aspnet-ajax (It's written for asp.net, but may be applicable) 3) Triple check the output of your post url and run the output through a JSON validator just to be absolutely sure it's valid and can be parsed into a JSON object. http://www.jsonlint.com Hope some of this helps! | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/79498",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2755/"
]
} |
79,537 | I teach a sort of "lite" C++ programming course to novices ("lite" meaning no pointers, no classes, just plain old C, plus references and STL string and vectors). Students have no previous experience in programming, so I believe that using an interactive debugger would help them understand program flow, variables, and recursion. The course is taught in Linux. Teaching them to use gdb is just overkill (they will not use nor understand most features). I just need something simple but easy to use: to see at which line the program is now, what is in the stack (local variables, previous calls, etc.). I look something similar to old Turbo Pascal or Turbo C++ Borland's debugger, or Visual Studio debugger. Thank you, | ddd is a graphical front-end to gdb that is pretty nice. One of the down sides is a classic X interface, but I seem to recall it being pretty intuitive. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/79537",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
79,658 | A Java6 application sits in the system tray. It needs to be activated using a hotkey (e.g. Super-G or Ctrl-Shift-L etc) and do something (e.g. showing an input box). How do I do that on: Windows (XP or Vista) OS/X Linux (Gnome or KDE) | I've compiled a library for global hotkeys in java using JNA. It currently supports Windows, Linux and Mac OSX. It also supports media keys on windows and linux. if anyone is interested, try https://github.com/tulskiy/jkeymaster I would appreciate any feedback. Thank you. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/79658",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
79,669 | I need to copy about 40 databases from one server to another. The new databases should have new names, but all the same tables, data and indexes as the original databases. So far I've been: 1) creating each destination database 2) using the " Tasks->Export Data " command to create and populate tables for each database individually 3) rebuilding all of the indexes for each database with a SQL script Only three steps per database, but I'll bet there's an easier way. Do any MS SQL Server experts out there have any advice? | Given that you're performing this on multiple databases -- you want a simple scripted solution, not a point and click solution. This is a backup script that i keep around. Get it working for one file and then modify it for many. (on source server...)BACKUP DATABASE Northwind TO DISK = 'c:\Northwind.bak'(target server...)RESTORE FILELISTONLY FROM DISK = 'c:\Northwind.bak'(look at the device names... and determine where you want the mdf andldf files to go on this target server)RESTORE DATABASE TestDB FROM DISK = 'c:\Northwind.bak' WITH MOVE 'Northwind' TO 'c:\test\testdb.mdf', MOVE 'Northwind_log' TO 'c:\test\testdb.ldf'GO | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/79669",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13728/"
]
} |
79,677 | I need to speed up a program for the Nintendo DS which doesn't have an FPU, so I need to change floating-point math (which is emulated and slow) to fixed-point. How I started was I changed floats to ints and whenever I needed to convert them, I used x>>8 to convert the fixed-point variable x to the actual number and x<<8 to convert to fixed-point. Soon I found out it was impossible to keep track of what needed to be converted and I also realized it would be difficult to change the precision of the numbers (8 in this case.) My question is, how should I make this easier and still fast? Should I make a FixedPoint class, or just a FixedPoint8 typedef or struct with some functions/macros to convert them, or something else? Should I put something in the variable name to show it's fixed-point? | You can try my fixed point class (Latest available @ https://github.com/eteran/cpp-utilities ) // From: https://github.com/eteran/cpp-utilities/edit/master/Fixed.h// See also: http://stackoverflow.com/questions/79677/whats-the-best-way-to-do-fixed-point-math/* * The MIT License (MIT) * * Copyright (c) 2015 Evan Teran * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */#ifndef FIXED_H_#define FIXED_H_#include <ostream>#include <exception>#include <cstddef> // for size_t#include <cstdint>#include <type_traits>#include <boost/operators.hpp>namespace numeric {template <size_t I, size_t F>class Fixed;namespace detail {// helper templates to make magic with types :)// these allow us to determine resonable types from// a desired size, they also let us infer the next largest type// from a type which is nice for the division optemplate <size_t T>struct type_from_size { static const bool is_specialized = false; typedef void value_type;};#if defined(__GNUC__) && defined(__x86_64__)template <>struct type_from_size<128> { static const bool is_specialized = true; static const size_t size = 128; typedef __int128 value_type; typedef unsigned __int128 unsigned_type; typedef __int128 signed_type; typedef type_from_size<256> next_size;};#endiftemplate <>struct type_from_size<64> { static const bool is_specialized = true; static const size_t size = 64; typedef int64_t value_type; typedef uint64_t unsigned_type; typedef int64_t signed_type; typedef type_from_size<128> next_size;};template <>struct type_from_size<32> { static const bool is_specialized = true; static const size_t size = 32; typedef int32_t value_type; typedef uint32_t unsigned_type; typedef int32_t signed_type; typedef type_from_size<64> next_size;};template <>struct type_from_size<16> { static const bool is_specialized = true; static const size_t size = 16; typedef int16_t value_type; typedef uint16_t unsigned_type; typedef int16_t signed_type; typedef type_from_size<32> next_size;};template <>struct type_from_size<8> { static const bool is_specialized = true; static const size_t size = 8; typedef int8_t value_type; typedef uint8_t unsigned_type; typedef int8_t signed_type; typedef type_from_size<16> next_size;};// this is to assist in adding support for non-native base// types (for adding big-int support), this should be fine// unless your bit-int class doesn't nicely support castingtemplate <class B, class N>B next_to_base(const N& rhs) { return static_cast<B>(rhs);}struct divide_by_zero : std::exception {};template <size_t I, size_t F>Fixed<I,F> divide(const Fixed<I,F> &numerator, const Fixed<I,F> &denominator, Fixed<I,F> &remainder, typename std::enable_if<type_from_size<I+F>::next_size::is_specialized>::type* = 0) { typedef typename Fixed<I,F>::next_type next_type; typedef typename Fixed<I,F>::base_type base_type; static const size_t fractional_bits = Fixed<I,F>::fractional_bits; next_type t(numerator.to_raw()); t <<= fractional_bits; Fixed<I,F> quotient; quotient = Fixed<I,F>::from_base(next_to_base<base_type>(t / denominator.to_raw())); remainder = Fixed<I,F>::from_base(next_to_base<base_type>(t % denominator.to_raw())); return quotient;}template <size_t I, size_t F>Fixed<I,F> divide(Fixed<I,F> numerator, Fixed<I,F> denominator, Fixed<I,F> &remainder, typename std::enable_if<!type_from_size<I+F>::next_size::is_specialized>::type* = 0) { // NOTE(eteran): division is broken for large types :-( // especially when dealing with negative quantities typedef typename Fixed<I,F>::base_type base_type; typedef typename Fixed<I,F>::unsigned_type unsigned_type; static const int bits = Fixed<I,F>::total_bits; if(denominator == 0) { throw divide_by_zero(); } else { int sign = 0; Fixed<I,F> quotient; if(numerator < 0) { sign ^= 1; numerator = -numerator; } if(denominator < 0) { sign ^= 1; denominator = -denominator; } base_type n = numerator.to_raw(); base_type d = denominator.to_raw(); base_type x = 1; base_type answer = 0; // egyptian division algorithm while((n >= d) && (((d >> (bits - 1)) & 1) == 0)) { x <<= 1; d <<= 1; } while(x != 0) { if(n >= d) { n -= d; answer += x; } x >>= 1; d >>= 1; } unsigned_type l1 = n; unsigned_type l2 = denominator.to_raw(); // calculate the lower bits (needs to be unsigned) // unfortunately for many fractions this overflows the type still :-/ const unsigned_type lo = (static_cast<unsigned_type>(n) << F) / denominator.to_raw(); quotient = Fixed<I,F>::from_base((answer << F) | lo); remainder = n; if(sign) { quotient = -quotient; } return quotient; }}// this is the usual implementation of multiplicationtemplate <size_t I, size_t F>void multiply(const Fixed<I,F> &lhs, const Fixed<I,F> &rhs, Fixed<I,F> &result, typename std::enable_if<type_from_size<I+F>::next_size::is_specialized>::type* = 0) { typedef typename Fixed<I,F>::next_type next_type; typedef typename Fixed<I,F>::base_type base_type; static const size_t fractional_bits = Fixed<I,F>::fractional_bits; next_type t(static_cast<next_type>(lhs.to_raw()) * static_cast<next_type>(rhs.to_raw())); t >>= fractional_bits; result = Fixed<I,F>::from_base(next_to_base<base_type>(t));}// this is the fall back version we use when we don't have a next size// it is slightly slower, but is more robust since it doesn't// require and upgraded typetemplate <size_t I, size_t F>void multiply(const Fixed<I,F> &lhs, const Fixed<I,F> &rhs, Fixed<I,F> &result, typename std::enable_if<!type_from_size<I+F>::next_size::is_specialized>::type* = 0) { typedef typename Fixed<I,F>::base_type base_type; static const size_t fractional_bits = Fixed<I,F>::fractional_bits; static const size_t integer_mask = Fixed<I,F>::integer_mask; static const size_t fractional_mask = Fixed<I,F>::fractional_mask; // more costly but doesn't need a larger type const base_type a_hi = (lhs.to_raw() & integer_mask) >> fractional_bits; const base_type b_hi = (rhs.to_raw() & integer_mask) >> fractional_bits; const base_type a_lo = (lhs.to_raw() & fractional_mask); const base_type b_lo = (rhs.to_raw() & fractional_mask); const base_type x1 = a_hi * b_hi; const base_type x2 = a_hi * b_lo; const base_type x3 = a_lo * b_hi; const base_type x4 = a_lo * b_lo; result = Fixed<I,F>::from_base((x1 << fractional_bits) + (x3 + x2) + (x4 >> fractional_bits));}}/* * inheriting from boost::operators enables us to be a drop in replacement for base types * without having to specify all the different versions of operators manually */template <size_t I, size_t F>class Fixed : boost::operators<Fixed<I,F>> { static_assert(detail::type_from_size<I + F>::is_specialized, "invalid combination of sizes");public: static const size_t fractional_bits = F; static const size_t integer_bits = I; static const size_t total_bits = I + F; typedef detail::type_from_size<total_bits> base_type_info; typedef typename base_type_info::value_type base_type; typedef typename base_type_info::next_size::value_type next_type; typedef typename base_type_info::unsigned_type unsigned_type;public: static const size_t base_size = base_type_info::size; static const base_type fractional_mask = ~((~base_type(0)) << fractional_bits); static const base_type integer_mask = ~fractional_mask;public: static const base_type one = base_type(1) << fractional_bits;public: // constructors Fixed() : data_(0) { } Fixed(long n) : data_(base_type(n) << fractional_bits) { // TODO(eteran): assert in range! } Fixed(unsigned long n) : data_(base_type(n) << fractional_bits) { // TODO(eteran): assert in range! } Fixed(int n) : data_(base_type(n) << fractional_bits) { // TODO(eteran): assert in range! } Fixed(unsigned int n) : data_(base_type(n) << fractional_bits) { // TODO(eteran): assert in range! } Fixed(float n) : data_(static_cast<base_type>(n * one)) { // TODO(eteran): assert in range! } Fixed(double n) : data_(static_cast<base_type>(n * one)) { // TODO(eteran): assert in range! } Fixed(const Fixed &o) : data_(o.data_) { } Fixed& operator=(const Fixed &o) { data_ = o.data_; return *this; }private: // this makes it simpler to create a fixed point object from // a native type without scaling // use "Fixed::from_base" in order to perform this. struct NoScale {}; Fixed(base_type n, const NoScale &) : data_(n) { }public: static Fixed from_base(base_type n) { return Fixed(n, NoScale()); }public: // comparison operators bool operator==(const Fixed &o) const { return data_ == o.data_; } bool operator<(const Fixed &o) const { return data_ < o.data_; }public: // unary operators bool operator!() const { return !data_; } Fixed operator~() const { Fixed t(*this); t.data_ = ~t.data_; return t; } Fixed operator-() const { Fixed t(*this); t.data_ = -t.data_; return t; } Fixed operator+() const { return *this; } Fixed& operator++() { data_ += one; return *this; } Fixed& operator--() { data_ -= one; return *this; }public: // basic math operators Fixed& operator+=(const Fixed &n) { data_ += n.data_; return *this; } Fixed& operator-=(const Fixed &n) { data_ -= n.data_; return *this; } Fixed& operator&=(const Fixed &n) { data_ &= n.data_; return *this; } Fixed& operator|=(const Fixed &n) { data_ |= n.data_; return *this; } Fixed& operator^=(const Fixed &n) { data_ ^= n.data_; return *this; } Fixed& operator*=(const Fixed &n) { detail::multiply(*this, n, *this); return *this; } Fixed& operator/=(const Fixed &n) { Fixed temp; *this = detail::divide(*this, n, temp); return *this; } Fixed& operator>>=(const Fixed &n) { data_ >>= n.to_int(); return *this; } Fixed& operator<<=(const Fixed &n) { data_ <<= n.to_int(); return *this; }public: // conversion to basic types int to_int() const { return (data_ & integer_mask) >> fractional_bits; } unsigned int to_uint() const { return (data_ & integer_mask) >> fractional_bits; } float to_float() const { return static_cast<float>(data_) / Fixed::one; } double to_double() const { return static_cast<double>(data_) / Fixed::one; } base_type to_raw() const { return data_; }public: void swap(Fixed &rhs) { using std::swap; swap(data_, rhs.data_); }public: base_type data_;};// if we have the same fractional portion, but differing integer portions, we trivially upgrade the smaller typetemplate <size_t I1, size_t I2, size_t F>typename std::conditional<I1 >= I2, Fixed<I1,F>, Fixed<I2,F>>::type operator+(const Fixed<I1,F> &lhs, const Fixed<I2,F> &rhs) { typedef typename std::conditional< I1 >= I2, Fixed<I1,F>, Fixed<I2,F> >::type T; const T l = T::from_base(lhs.to_raw()); const T r = T::from_base(rhs.to_raw()); return l + r;}template <size_t I1, size_t I2, size_t F>typename std::conditional<I1 >= I2, Fixed<I1,F>, Fixed<I2,F>>::type operator-(const Fixed<I1,F> &lhs, const Fixed<I2,F> &rhs) { typedef typename std::conditional< I1 >= I2, Fixed<I1,F>, Fixed<I2,F> >::type T; const T l = T::from_base(lhs.to_raw()); const T r = T::from_base(rhs.to_raw()); return l - r;}template <size_t I1, size_t I2, size_t F>typename std::conditional<I1 >= I2, Fixed<I1,F>, Fixed<I2,F>>::type operator*(const Fixed<I1,F> &lhs, const Fixed<I2,F> &rhs) { typedef typename std::conditional< I1 >= I2, Fixed<I1,F>, Fixed<I2,F> >::type T; const T l = T::from_base(lhs.to_raw()); const T r = T::from_base(rhs.to_raw()); return l * r;}template <size_t I1, size_t I2, size_t F>typename std::conditional<I1 >= I2, Fixed<I1,F>, Fixed<I2,F>>::type operator/(const Fixed<I1,F> &lhs, const Fixed<I2,F> &rhs) { typedef typename std::conditional< I1 >= I2, Fixed<I1,F>, Fixed<I2,F> >::type T; const T l = T::from_base(lhs.to_raw()); const T r = T::from_base(rhs.to_raw()); return l / r;}template <size_t I, size_t F>std::ostream &operator<<(std::ostream &os, const Fixed<I,F> &f) { os << f.to_double(); return os;}template <size_t I, size_t F>const size_t Fixed<I,F>::fractional_bits;template <size_t I, size_t F>const size_t Fixed<I,F>::integer_bits;template <size_t I, size_t F>const size_t Fixed<I,F>::total_bits;}#endif It is designed to be a near drop in replacement for floats/doubles and has a choose-able precision. It does make use of boost to add all the necessary math operator overloads, so you will need that as well (I believe for this it is just a header dependency, not a library dependency). BTW, common usage could be something like this: using namespace numeric;typedef Fixed<16, 16> fixed;fixed f; The only real rule is that the number have to add up to a native size of your system such as 8, 16, 32, 64. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/79677",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/813/"
]
} |
79,693 | How do you get all the classes in a namespace through reflection in C#? | Following code prints names of classes in specified namespace defined in current assembly. As other guys pointed out, a namespace can be scattered between different modules, so you need to get a list of assemblies first. string nspace = "...";var q = from t in Assembly.GetExecutingAssembly().GetTypes() where t.IsClass && t.Namespace == nspace select t;q.ToList().ForEach(t => Console.WriteLine(t.Name)); | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/79693",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
79,754 | No matter what I do sys.exit() is called by unittest, even the most trivial examples. I can't tell if my install is messed up or what is going on. IDLE 1.2.2 ==== No Subprocess ====>>> import unittest>>> >>> class Test(unittest.TestCase): def testA(self): a = 1 self.assertEqual(a,1)>>> unittest.main()option -n not recognizedUsage: idle.pyw [options] [test] [...]Options: -h, --help Show this message -v, --verbose Verbose output -q, --quiet Minimal output Examples: idle.pyw - run default set of tests idle.pyw MyTestSuite - run suite 'MyTestSuite' idle.pyw MyTestCase.testSomething - run MyTestCase.testSomething idle.pyw MyTestCase - run all 'test*' test methods in MyTestCaseTraceback (most recent call last): File "<pyshell#7>", line 1, in <module> unittest.main() File "E:\Python25\lib\unittest.py", line 767, in __init__ self.parseArgs(argv) File "E:\Python25\lib\unittest.py", line 796, in parseArgs self.usageExit(msg) File "E:\Python25\lib\unittest.py", line 773, in usageExit sys.exit(2)SystemExit: 2>>> | Your example is exiting on my install too. I can make it execute the tests and stay within Python by changing unittest.main() to unittest.TextTestRunner().run(unittest.TestLoader().loadTestsFromTestCase(Test)) More information is available here in the Python Library Reference. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/79754",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3176/"
]
} |
79,764 | I know there have been a few threads on this before, but I have tried absolutely everything suggested (that I could find) and nothing has worked for me thus far... With that in mind, here is what I'm trying to do: First, I want to allow users to publish pages and give them each a subdomain of their choice (ex: user.example.com ). From what I can gather, the best way to do this is to map user.example.com to example.com/user with mod_rewrite and .htaccess - is that correct? If that is correct, can somebody give me explicit instructions on how to do this? Also, I am doing all of my development locally, using MAMP, so if somebody could tell me how to set up my local environment to work in the same manner (I've read this is more difficult), I would greatly appreciate it. Honestly, I have been trying a everything to no avail, and since this is my first time doing something like this, I am completely lost. Some of these answers have been REALLY helpful, but for the system I have in mind, manually adding a subdomain for each user is not an option. What I'm really asking is how to do this on the fly, and redirect wildcard.example.com to example.com/wildcard -- the way Tumblr is set up is a perfect example of what I'd like to do. | As far as how to set up the DNS subdomain wildcard, that would be a function of your DNS hosting provider. This would be different steps depending on which hosting provider you have and would be a better question for them. Once you've set that up with the DNS host, from your web app you really are just URL rewriting, which can be done with some sort of module for the web server itself, such as isapi rewrite if you're on IIS (this would be the preferred route if possible). You could also handle rewriting at the application level as well (like using routing if on ASP.NET). You'd rewrite the URL so http://myname.example.com would become http://example.com/something.aspx?name=myname or something. From there on out, you just handle it as if the myname value was in the query string as normal. Does that make sense? Hope I didn't misunderstand what you're after. I am not suggesting that you create a subdomain for each user, but instead create a wildcard subdomain for the domain itself, so anything .example.com (basically *.example.com ) goes to your site. I have several domains setup with MyDomain. Their instructions for setting this up is like this: Yes, you can configure a wild card butit will only work if you set it up asan A Record. Wildcards do not workwith a C Name. To use a wildcard, youuse the asterisks character ' '. Forexample, if you create and A Recordusing a wild card, *.example.com ,anything that is entered in the placewhere the ' ' is located, will resolveto the specified IP address. So if youenter 'www', 'ftp', 'site', oranything else before the domain name,it will always resolve to the IPaddress I have some that are setup in just this way, having *.example.com go to my site. I then can read the base URL in my web app to see that ryan.example.com is what was currently accessed, or that bill.example.com is what was used. I can then either: Use URL rewriting so that the subdomain becomes a part of the query string OR Simply read the host value from the accessed URL and perform some logic based on that value. Does that make sense? I have several sites set up in just this exact way: create the wildcard for the domain with the DNS host and then simply read the host, or base domain from the URL to decide what to display based on the subdomain (which was actually a username) Edit 2: There is no way to do this without a DNS entry. The "online world" needs to know that name1.example.com , name2.example.com ,..., nameN.example.com all go to the IP address for your server. The only way to do this is with the appropriate DNS entry. You have to add the wildcard DNS entry for your domain with your DNS host. Then it's just a matter of you reading the subdomain from the URL and taking the appropriate action in your code. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/79764",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14891/"
]
} |
79,780 | I've had a new found interest in building a small, efficient web server in C and have had some trouble parsing POST methods from the HTTP Header. Would anyone have any advice as to how to handle retrieving the name/value pairs from the "posted" data? POST /test HTTP/1.1Host: test-domain.com:7017User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.1) Gecko/2008070208 Firefox/3.0.1Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8Accept-Language: en-us,en;q=0.5Accept-Encoding: gzip,deflateAccept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7Keep-Alive: 300Connection: keep-aliveReferer: http://test-domain.com:7017/index.htmlCookie: __utma=43166241.217413299.1220726314.1221171690.1221200181.16; __utmz=43166241.1220726314.1.1.utmccn=(direct)|utmcsr=(direct)|utmcmd=(none)Cache-Control: max-age=0Content-Type: application/x-www-form-urlencodedContent-Length: 25field1=asfd&field2=a3f3f3// ^-this I see no tangible way to retrieve the bottom line as a whole and ensure that it works every time. I'm not a fan of hard-coding in anything. | You can retrieve the name/value pairs by searching for newline newline or more specifically \r\n\r\n (after this, the body of the message will start). Then you can simply split the list by the &, and then split each of those returned strings between the = for name/value pairs. See the HTTP 1.1 RFC . | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/79780",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14877/"
]
} |
79,797 | How do I convert a datetime string in local time to a string in UTC time ? I'm sure I've done this before, but can't find it and SO will hopefully help me (and others) do that in future. Clarification : For example, if I have 2008-09-17 14:02:00 in my local timezone ( +10 ), I'd like to generate a string with the equivalent UTC time: 2008-09-17 04:02:00 . Also, from http://lucumr.pocoo.org/2011/7/15/eppur-si-muove/ , note that in general this isn't possible as with DST and other issues there is no unique conversion from local time to UTC time. | First, parse the string into a naive datetime object. This is an instance of datetime.datetime with no attached timezone information. See its documentation . Use the pytz module, which comes with a full list of time zones + UTC. Figure out what the local timezone is, construct a timezone object from it, and manipulate and attach it to the naive datetime. Finally, use datetime.astimezone() method to convert the datetime to UTC. Source code, using local timezone "America/Los_Angeles", for the string "2001-2-3 10:11:12": from datetime import datetime import pytzlocal = pytz.timezone("America/Los_Angeles")naive = datetime.strptime("2001-2-3 10:11:12", "%Y-%m-%d %H:%M:%S")local_dt = local.localize(naive, is_dst=None)utc_dt = local_dt.astimezone(pytz.utc) From there, you can use the strftime() method to format the UTC datetime as needed: utc_dt.strftime("%Y-%m-%d %H:%M:%S") | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/79797",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3715/"
]
} |
79,816 | I'd like a short smallest possible javascript routine that when a mousedown occurs on a button it first responds just like a mouseclick and then if the user keeps the button pressed it responds as if the user was continously sending mouseclicks and after a while with the button held down acts as if the user was accelerating their mouseclicks...basically think of it like a keypress repeat with acceleration in time. i.e. user holds down mouse button (x=call function) - x___x___x___x__x__x_x_x_x_xxxxxxx | function holdit(btn, action, start, speedup) { var t; var repeat = function () { action(); t = setTimeout(repeat, start); start = start / speedup; } btn.mousedown = function() { repeat(); } btn.mouseup = function () { clearTimeout(t); }};/* to use */holdit(btn, function () { }, 1000, 2); /* x..1000ms..x..500ms..x..250ms..x */ | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/79816",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14907/"
]
} |
79,850 | Since the Google App Engine Datastore is based on Bigtable and we know that's not a relational database, how do you design a database schema / data model for applications that use this type of database system? | Designing a bigtable schema is an open process, and basically requires you to think about: The access patterns you will be using and how often each will be used The relationships between your types What indices you are going to need The write patterns you will be using (in order to effectively spread load) GAE's datastore automatically denormalizes your data. That is, each index contains a (mostly) complete copy of the data, and thus every index adds significantly to time taken to perform a write, and the storage space used. If this were not the case, designing a Datastore schema would be a lot more work: You would have to think carefully about the primary key for each type, and consider the effect of your decision on the locality of data. For example, when rendering a blog post you would probably need to display the comments to go along with it, so each comment's key would probably begin with the associated post's key. With Datastore, this is not such a big deal: The query you use will look something like "Select * FROM Comment WHERE post_id = N." (If you want to page the comments, you would also have a limit clause, and a possible suffix of " AND comment_id > last_comment_id".) Once you add such a query, Datastore will build the index for you, and your reads will be magically fast. Something to keep in mind is that each additional index creates some additional cost: it is best if you can use as few access patterns as possible, since it will reduce the number of indices GAE will construct, and thus the total storage required by your data. Reading over this answer, I find it a little vague. Maybe a hands-on design question would help to scope this down? :-) | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/79850",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10708/"
]
} |
79,891 | While we try to set up as many unit tests as time allows for our applications, I always find the amount of UI-level tests lacking. There are many options out there, but I'm not sure what would be a good place to start. What is your preferred unit testing tool for testing Swing applications? Why do you like it? | On our side, we use to test SWING GUI with FEST . This is an adapter on the classical swing robot, but it ease dramatically its use. Combined with TestNG, We found it an easy way to simulate "human" actions trough the GUI. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/79891",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13812/"
]
} |
79,923 | What are the stack and heap? Where are they located physically in a computer's memory? To what extent are they controlled by the OS or language run-time? What is their scope? What determines their sizes? What makes one faster? | The stack is the memory set aside as scratch space for a thread of execution. When a function is called, a block is reserved on the top of the stack for local variables and some bookkeeping data. When that function returns, the block becomes unused and can be used the next time a function is called. The stack is always reserved in a LIFO (last in first out) order; the most recently reserved block is always the next block to be freed. This makes it really simple to keep track of the stack; freeing a block from the stack is nothing more than adjusting one pointer. The heap is memory set aside for dynamic allocation. Unlike the stack, there's no enforced pattern to the allocation and deallocation of blocks from the heap; you can allocate a block at any time and free it at any time. This makes it much more complex to keep track of which parts of the heap are allocated or free at any given time; there are many custom heap allocators available to tune heap performance for different usage patterns. Each thread gets a stack, while there's typically only one heap for the application (although it isn't uncommon to have multiple heaps for different types of allocation). To answer your questions directly: To what extent are they controlled by the OS or language runtime? The OS allocates the stack for each system-level thread when the thread is created. Typically the OS is called by the language runtime to allocate the heap for the application. What is their scope? The stack is attached to a thread, so when the thread exits the stack is reclaimed. The heap is typically allocated at application startup by the runtime, and is reclaimed when the application (technically process) exits. What determines the size of each of them? The size of the stack is set when a thread is created. The size of the heap is set on application startup, but can grow as space is needed (the allocator requests more memory from the operating system). What makes one faster? The stack is faster because the access pattern makes it trivial to allocate and deallocate memory from it (a pointer/integer is simply incremented or decremented), while the heap has much more complex bookkeeping involved in an allocation or deallocation. Also, each byte in the stack tends to be reused very frequently which means it tends to be mapped to the processor's cache, making it very fast. Another performance hit for the heap is that the heap, being mostly a global resource, typically has to be multi-threading safe, i.e. each allocation and deallocation needs to be - typically - synchronized with "all" other heap accesses in the program. A clear demonstration: Image source: vikashazrati.wordpress.com | {
"score": 14,
"source": [
"https://Stackoverflow.com/questions/79923",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13161/"
]
} |
79,954 | When I debug in Visual Studio, Firefox opens and that is annoying because of the hookups that Internet Explorer and Visual Studio have, such as when you close the Internet Explorer browser that starting debug opened, Visual Studio stops debugging. How can I get Visual Studio to open Internet Explorer instead without having to set Internet Explorer as my default browser? | Scott Guthrie has made a post on how to change Visual Studio's default browser : 1) Right click on a .aspx page in your solution explorer 2) Select the "browse with" context menu option 3) In the dialog you can select or add a browser. If you want Firefox in the list, click "add" and point to the firefox.exe filename 4) Click the "Set as Default" button to make this the default browser when you run any page on the site. I however dislike the fact that this isn't as straightforward as it should be. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/79954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/590/"
]
} |
79,960 | I have a code snippet written in PHP that pulls a block of text from a database and sends it out to a widget on a webpage. The original block of text can be a lengthy article or a short sentence or two; but for this widget I can't display more than, say, 200 characters. I could use substr() to chop off the text at 200 chars, but the result would be cutting off in the middle of words-- what I really want is to chop the text at the end of the last word before 200 chars. | By using the wordwrap function. It splits the texts in multiple lines such that the maximum width is the one you specified, breaking at word boundaries. After splitting, you simply take the first line: substr($string, 0, strpos(wordwrap($string, $your_desired_width), "\n")); One thing this oneliner doesn't handle is the case when the text itself is shorter than the desired width. To handle this edge-case, one should do something like: if (strlen($string) > $your_desired_width) { $string = wordwrap($string, $your_desired_width); $string = substr($string, 0, strpos($string, "\n"));} The above solution has the problem of prematurely cutting the text if it contains a newline before the actual cutpoint. Here a version which solves this problem: function tokenTruncate($string, $your_desired_width) { $parts = preg_split('/([\s\n\r]+)/', $string, null, PREG_SPLIT_DELIM_CAPTURE); $parts_count = count($parts); $length = 0; $last_part = 0; for (; $last_part < $parts_count; ++$last_part) { $length += strlen($parts[$last_part]); if ($length > $your_desired_width) { break; } } return implode(array_slice($parts, 0, $last_part));} Also, here is the PHPUnit testclass used to test the implementation: class TokenTruncateTest extends PHPUnit_Framework_TestCase { public function testBasic() { $this->assertEquals("1 3 5 7 9 ", tokenTruncate("1 3 5 7 9 11 14", 10)); } public function testEmptyString() { $this->assertEquals("", tokenTruncate("", 10)); } public function testShortString() { $this->assertEquals("1 3", tokenTruncate("1 3", 10)); } public function testStringTooLong() { $this->assertEquals("", tokenTruncate("toooooooooooolooooong", 10)); } public function testContainingNewline() { $this->assertEquals("1 3\n5 7 9 ", tokenTruncate("1 3\n5 7 9 11 14", 10)); }} EDIT : Special UTF8 characters like 'à' are not handled. Add 'u' at the end of the REGEX to handle it: $parts = preg_split('/([\s\n\r]+)/u', $string, null, PREG_SPLIT_DELIM_CAPTURE); | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/79960",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14956/"
]
} |
79,968 | I have a string which is like this: this is "a test" I'm trying to write something in Python to split it up by space while ignoring spaces within quotes. The result I'm looking for is: ['this', 'is', 'a test'] PS. I know you are going to ask "what happens if there are quotes within the quotes, well, in my application, that will never happen. | You want split , from the built-in shlex module. >>> import shlex>>> shlex.split('this is "a test"')['this', 'is', 'a test'] This should do exactly what you want. If you want to preserve the quotation marks, then you can pass the posix=False kwarg. >>> shlex.split('this is "a test"', posix=False)['this', 'is', '"a test"'] | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/79968",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5324/"
]
} |
79,992 | Ideally the reader has upgraded a native C++ program to Visual Studio 2008, which contains an OpenClipboard() block. Why not try setting a breakpoint just after getting a successful return-code from OpenClipboard() and step through your code. According to the Internet it may work on your system, but of course, not on mine, thanks for trying. Googling on e.g. (( OpenClipboard 1418 vc6 )) finds articles like "GetClipboardData fails in debugger" and "No Error in VC++6 but Error in VC++ 2005". Pragmatically for-the-moment, problem solved - I simply cannot set breakpoints within such code, I need to squirrel information and set the breakpoint after the clipboard operations are done. Error 1418 is "Thread does not have a clipboard open" but it works fine as long as you don't step with VS.NET, or like I say if you keep breakpoints outside of the clipboard-open-close-block. I would feel better knowing what the exact issue is with the VS.NET debugger. Being a C++ person I am only dimly aware that you are not supposed to think in terms of threads when doing dot-Net. Anyway I did not find a guru-quality explanation of what's really going on, whether in-fact the problem is that the dot-Net debugger is subtly interfering with the thread-information somehow, when you single-step thru native C++ code. System-wise: about a year old, two dual-core Xeon's, 4 CPU's according to XP-pro. I had just finished debugging the code by single-stepping thru it in vc6 under XP-SP2-32-bit. So I know the code was pretty-much-fine under vc6. However when I tested with a 10-megabyte CF_TEXT I got exceptions. I thought to try debugging under the nicer exception model of XP-x64. Recompiled with visual-studio-2008, I could not get the code to single-step at all. OpenClipboard worked, but EnumClipboardFormats() did not work, nothing worked when single-stepped. However, when I set the breakpoint below the complete block of code, everything worked fine. And YES vc2008 made a pinpoint diagnostic 'stack frame corruption around szBuf. There is a lot to like about vc2008. It would be nice if this were somehow merely a clipboard problem - without knowing that I would feel compelled to worry about stepping thru ANYTHING, whether thread-context-issues might be due to the dot-Net-debugger. | You want split , from the built-in shlex module. >>> import shlex>>> shlex.split('this is "a test"')['this', 'is', 'a test'] This should do exactly what you want. If you want to preserve the quotation marks, then you can pass the posix=False kwarg. >>> shlex.split('this is "a test"', posix=False)['this', 'is', '"a test"'] | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/79992",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10972/"
]
} |
79,999 | If you were writing a new application from scratch today, and wanted it to scale to all the cores you could throw at it tomorrow, what parallel programming model/system/language/library would you choose? Why? I am particularly interested in answers along these axes: Programmer productivity / ease of use (can mortals successfully use it?) Target application domain (what problems is it (not) good at?) Concurrency style (does it support tasks, pipelines, data parallelism, messages...?) Maintainability / future-proofing (will anybody still be using it in 20 years?) Performance (how does it scale on what kinds of hardware?) I am being deliberately vague on the nature of the application in anticipation of getting good general answers useful for a variety of applications. | Multi-core programming may actually require more than one paradigm. Some current contenders are: MapReduce . This works well where a problem can be easily decomposed into parallel chunks. Nested Data Parallelism . This is similar to MapReduce, but actually supports recursive decomposition of a problem, even when the recursive chunks are of irregular size. Look for NDP to be a big win in purely functional languages running on massively parallel but limited hardware (like GPUs). Software Transactional Memory . If you need traditional threads, STM makes them bearable. You pay a 50% performance hit in critical sections, but you can scale complex locking schemes to 100s of processors without pain. This will not, however, work for distributed systems. Parallel object threads with messaging . This really clever model is used by Erlang. Each "object" becomes a lightweight thread, and objects communicate by asynchronous messages and pattern matching. It's basically true parallel OO. This has succeeded nicely in several real-world applications, and it works great for unreliable distributed systems. Some of these paradigms give you maximum performance, but only work if the problem decomposes cleanly. Others sacrifice some performance, but allow a wider variety of algorithms. I suspect that some combination of the above will ultimately become a standard toolkit. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/79999",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/171236/"
]
} |
80,084 | In JavaScript, the "this" operator can refer to different things under different scenarios. Typically in a method within a JavaScript "object", it refers to the current object. But when used as a callback, it becomes a reference to the calling object. I have found that this causes problems in code, because if you use a method within a JavaScript "object" as a callback function you can't tell whether "this" refers to the current "object" or whether "this" refers to the calling object. Can someone clarify usage and best practices regarding how to get around this problem? function TestObject() { TestObject.prototype.firstMethod = function(){ this.callback(); YAHOO.util.Connect.asyncRequest(method, uri, callBack); } TestObject.prototype.callBack = function(o){ // do something with "this" //when method is called directly, "this" resolves to the current object //when invoked by the asyncRequest callback, "this" is not the current object //what design patterns can make this consistent? this.secondMethod(); } TestObject.prototype.secondMethod = function() { alert('test'); } } | Quick advice on best practices before I babble on about the magic this variable. If you want Object-oriented programming (OOP) in Javascript that closely mirrors more traditional/classical inheritance patterns, pick a framework, learn its quirks, and don't try to get clever. If you want to get clever, learn javascript as a functional language, and avoid thinking about things like classes. Which brings up one of the most important things to keep in mind about Javascript, and to repeat to yourself when it doesn't make sense. Javascript does not have classes. If something looks like a class, it's a clever trick. Javascript has objects (no derisive quotes needed) and functions . (that's not 100% accurate, functions are just objects, but it can sometimes be helpful to think of them as separate things) The this variable is attached to functions. Whenever you invoke a function, this is given a certain value, depending on how you invoke the function. This is often called the invocation pattern. There are four ways to invoke functions in javascript. You can invoke the function as a method , as a function , as a constructor , and with apply . As a Method A method is a function that's attached to an object var foo = {};foo.someMethod = function(){ alert(this);} When invoked as a method, this will be bound to the object the function/method is a part of. In this example, this will be bound to foo. As A Function If you have a stand alone function, the this variable will be bound to the "global" object, almost always the window object in the context of a browser. var foo = function(){ alert(this); } foo(); This may be what's tripping you up , but don't feel bad. Many people consider this a bad design decision. Since a callback is invoked as a function and not as a method, that's why you're seeing what appears to be inconsistent behaviour. Many people get around the problem by doing something like, um, this var foo = {};foo.someMethod = function (){ var that=this; function bar(){ alert(that); }} You define a variable that which points to this . Closure (a topic all it's own) keeps that around, so if you call bar as a callback, it still has a reference. As a Constructor You can also invoke a function as a constructor. Based on the naming convention you're using ( TestObject ) this also may be what you're doing and is what's tripping you up . You invoke a function as a Constructor with the new keyword. function Foo(){ this.confusing = 'hell yeah';}var myObject = new Foo(); When invoked as a constructor, a new Object will be created, and this will be bound to that object. Again, if you have inner functions and they're used as callbacks, you'll be invoking them as functions, and this will be bound to the global object. Use that var that = this; trick/pattern. Some people think the constructor/new keyword was a bone thrown to Java/traditional OOP programmers as a way to create something similar to classes. With the Apply Method. Finally, every function has a method (yes, functions are objects in Javascript) named apply . Apply lets you determine what the value of this will be, and also lets you pass in an array of arguments. Here's a useless example. function foo(a,b){ alert(a); alert(b); alert(this);}var args = ['ah','be'];foo.apply('omg',args); | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/80084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
80,091 | How do I do a diff of two strings or arrays in Ruby? | diff.rb is what you want, which is available at http://users.cybercity.dk/~dsl8950/ruby/diff.html via internet archive: http://web.archive.org/web/20140421214841/http://users.cybercity.dk:80/~dsl8950/ruby/diff.html | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/80091",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5004/"
]
} |
80,105 | Java is one of my programming languages of choice. I always run into the problem though of distributing my application to end-users. Giving a user a JAR is not always as user friendly as I would like and using Java WebStart requires that I maintain a web server. What's the best way to distribute a Java application? What if the Java application needs to install artifacts to the user's computer? Are there any good Java installation/packaging systems out there? | There are a variety of solutions, depending on your distribution requirements. Just use a jar. This assumes that the user has the the correct java version installed, otherwise the user will get "class-file format version" exceptions. This is fine for internal distribution inside a company. Use launch4j and an installer like NSIS. This gives you a lot more control, although the user can still do stupid stuff like un-installing the java runtime. This is probably the most popular approach, and what I currently use. Use Webstart. This also assumes that the user has the correct java version installed, but it's a lot easier to get going. My experience is that this is fine for tightly controlled intranet environments, but becomes a pain with larger deployments because it has some many weird failures. It may get better with the new plug-in technology in Java 1.7. Use a native-code compiler like Excelsior JET and distribute as a executable, or wrap it up in an installer. Expensive, and it generally ties you to a slightly older version of java, and there is some pain with dynamic class-loading, but its very effective for large-scale deployment where you need to minimise your support hassles. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/80105",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14204/"
]
} |
80,112 | I've never really understand why a web service implementer would choose one over the other. Is XML-RPC generally found in older systems? Any help in understanding this would be greatly appreciated. | Differences? SOAP is more powerful, and is much preferred by software tool vendors (MSFT .NET, Java Enterprise edition, that sort of things). SOAP was for a long time (2001-2007ish) seen as the protocol of choice for SOA. xml-rpc not so much. REST is the new SOA darling, although it's not a protocol. SOAP is more verbose, but more capable. SOAP is not supported in some of the older stuff. For example, no SOAP libs for classic ASP (that I could find). SOAP is not well supported in python. XML-RPC has great support in python, in the standard library. SOAP supports document-level transfer, whereas xml-rpc is more about values transfer, although it can transfer structures such as structs, lists, etc. xm-rpc is really about program to program language agnostic transfer. It primarily goes over http/https. SOAP messages can go over email as well. xml-rpc is more unixy. It lets you do things simply, and when you know what you're doing, it's very fast to deploy quality web services, even when using terminal text editors. Doing SOAP that way is a zoo; you really need a good IDE to make it feasible. Knowing SOAP, though, will look much better on your resume/CV if you're vying for a Fortune 500 IT job. xml-rpc has some issues with non-ascii character sets. XML-RPC does not support named parameters. They must be in correct order. Not sure about SOAP, but think so. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/80112",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4916/"
]
} |
80,120 | Our team is setting up nightly and continuous integration builds. We own Team Foundation Server and could use Team Foundation Build. I'm more familiar with CC.Net and lean that way but management sees all the money spent on TFS and wants to use it. Some things I like better about CC.Net is the flexibility of notifications as well as the ease of implementing custom scripts. If you have experience with both products, which do you prefer and why? | I've used both. I guess it depends on what your organization values. Since you are familiar with CC Net, I won't speak much to that. You already know what makes it cool. Here's what I like about Team Foundation Build: Build Agents. It's very simple to turn any box into a build machine and run a build on it. MSFT got this one right. Reporting. All relevant build results (test included) are stored in a SQL database and reported on via SQL Server Reporting Services. This is an immensely powerful tool for charting build and test results over time. CC Net doesn't have this built in. You can do similar customizations via MSBUILD. It's basically the same as using NAnt with CC Net Here's what drives me up the wall about Team Foundation Build: To build C++/CLI projects (or run unit tests...?) the build agent must have VSTS Dev or Team Suite installed. This, friends, is just batsh*t crazy. It must be connected to the TFS Mothership If you're in a big org with lots of bosses who have huge budgets and love reports (and don't get me wrong, this has huge value) OR you need to scale up to a multi-machine build farm, I'd prefer Team Foundation Build. If you're a leaner shop, stick with CC Net and grow your own reporting solutions. That's what we did. Until we got acquired. And got TFS :P | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/80120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1321/"
]
} |
80,186 | I can't seem to find much documentation on X-Sendfile or example code for PHP (there is some rails code). Anyone used it before and would mind giving a quick snippet of code and a brief description? | X-Sendfile is an HTTP header, so you want something like this: header("X-Sendfile: $filename"); Your web server picks it up if correctly configured. Here's some more details: http://www.jasny.net/articles/how-i-php-x-sendfile/ | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/80186",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
80,243 | I have mixed feelings about TDD. While I believe in testing I have a issues with the idea of the test driving my development effort. When you code to satisfy some tests written for an interface for requirements you have right now, you might shift your focus from building maintainable code, from clean design and from sound architecture. I have a problem with driven not with testing. Any thoughts? | No. If done right, Test Driven Development IS your design tool. I hope you forgive me for linking to my own blog entry, wherein I discuss the pitfalls of Test Driven Development that went wrong simply because developers treated their tests as, merely, tests. In a previous project, devs used a highly damaging singleton pattern that enforced dependencies throughout the project, which just broke the whole thing when requirements were changed: TDD was treated as a task, when it should have been treated as an an approach. [...] There was a failure to recognize that TDD is not about tests, it’s about design. The rampant case of singleton abuse in the unit tests made this obvious: instead of the test writers thinking “WTF are these singleton = value; statements doing in my tests?”, the test writers just propagated the singleton into the tests. 330 times. The unfortunate consequence is that the build server-enforced testing was made to pass, whatever it took. Test Driven Development, done right, should make developers highly aware of design pitfalls like tight coupling, violations of DRY (don't repeat yourself), violations of SRP (Single Responsibility Principle), etc. If you write passing code for your tests for the sake of passing your tests, you have already failed: you should treat hard to write tests as signposts that make you ask: why is this done this way? Why can't I test this code without depending on some other code? Why can't I reuse this code? Why is this code breaking when used by itself? Besides if your design is truly clean, and your code truly maintainable why is it not trivial to write a test for it? | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/80243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13615/"
]
} |
80,247 | How can I get all implementations of an interface through reflection in C#? | The answer is this; it searches through the entire application domain -- that is, every assembly currently loaded by your application. /// <summary>/// Returns all types in the current AppDomain implementing the interface or inheriting the type. /// </summary>public static IEnumerable<Type> TypesImplementingInterface(Type desiredType){ return AppDomain .CurrentDomain .GetAssemblies() .SelectMany(assembly => assembly.GetTypes()) .Where(type => desiredType.IsAssignableFrom(type));} It is used like this; var disposableTypes = TypesImplementingInterface(typeof(IDisposable)); You may also want this function to find actual concrete types -- i.e., filtering out abstracts, interfaces, and generic type definitions. public static bool IsRealClass(Type testType){ return testType.IsAbstract == false && testType.IsGenericTypeDefinition == false && testType.IsInterface == false;} | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/80247",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
80,351 | I have tried: Xdebug and Eclipse. Eclipse launches a web browser, but the browser tries to access a non-existent file in Eclipse's .app bundle. Xdebug and NetBeans. It does a little bit better; a browser opens a page in /tmp which says "Launching. Please wait…" but nothing happens beyond that. Xdebug and debugclient, the CLI tool which comes with Xdebug. MacPorts (which I used to install PHP and Xdebug) doesn't seem to install this by itself, and when I try compiling it by hand, I get told "you have strange libedit". Installing libedit via MacPorts doesn't solve that. Zend's debugger (the precise name escapes me right now) and Eclipse. I can't recall what the problem was, as this was some time ago, but it didn't work. With regards to Xdebug, at least, I'm fairly confident I've installed it correctly. It shows up with both a phpinfo() in a PHP file and a php -i in the CLI. If anyone has managed to get PHP debugging working in some way or other on the Mac, I'd appreciate it if you could share with me how. Littering code with var_dump($foo);die(); gets old quick. Bonus points if it can be done without using some bloatware editor like Eclipse, or that expensive proprietary thing Zend wants to sell me. My server is connecting to PHP via FastCGI, if that makes a diff. | You may want to look into MacGDBp . It's new, free, and the UI looks great. It utilizes the Xdebug PHP extension as well. You can find instructions in the help section, which includes Xdebug configurations, and there's also a nice overview of the app from the guys at Particletree here: Silence The Echo with MacGDBp . | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/80351",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11023/"
]
} |
80,357 | Is there a quick way to find every match of a regular expression in Ruby? I've looked through the Regex object in the Ruby STL and searched on Google to no avail. | Using scan should do the trick: string.scan(/regex/) | {
"score": 11,
"source": [
"https://Stackoverflow.com/questions/80357",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/422/"
]
} |
80,388 | I'm trying to trigger a progress animation when ever the ViewModel/Presentation Model is Busy. I have an IsBusy Property, and the ViewModel is set as the DataContext of the UserControl. What is the best way to trigger a "progressAnimation" storyboard when the IsBusy property is true? Blend only lets me add event triggers at the UserControl level, and I can only create property triggers in my data templates. The "progressAnimation" is defined as a resource in the user control. I tried adding the DataTriggers as a Style on the UserControl, but when I try to start the StoryBoard I get the following error: 'System.Windows.Style' value cannot be assigned to property 'Style'of object'Colorful.Control.SearchPanel'. A Storyboard tree in a Stylecannot specify a TargetName. Remove TargetName 'progressWheel'. ProgressWheel is the name of the object I'm trying to animate, so removing the target name is obviously NOT what I want. I was hoping to solve this in XAML using data binding techniques, instead of having to expose events and start/stop the animation through code. | What you want is possible by declaring the animation on the progressWheel itself:The XAML: <UserControl x:Class="TriggerSpike.UserControl1"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"Height="300" Width="300"><UserControl.Resources> <DoubleAnimation x:Key="SearchAnimation" Storyboard.TargetProperty="Opacity" To="1" Duration="0:0:4"/> <DoubleAnimation x:Key="StopSearchAnimation" Storyboard.TargetProperty="Opacity" To="0" Duration="0:0:4"/></UserControl.Resources><StackPanel> <TextBlock Name="progressWheel" TextAlignment="Center" Opacity="0"> <TextBlock.Style> <Style> <Style.Triggers> <DataTrigger Binding="{Binding IsBusy}" Value="True"> <DataTrigger.EnterActions> <BeginStoryboard> <Storyboard> <StaticResource ResourceKey="SearchAnimation"/> </Storyboard> </BeginStoryboard> </DataTrigger.EnterActions> <DataTrigger.ExitActions> <BeginStoryboard> <Storyboard> <StaticResource ResourceKey="StopSearchAnimation"/> </Storyboard> </BeginStoryboard> </DataTrigger.ExitActions> </DataTrigger> </Style.Triggers> </Style> </TextBlock.Style> Searching </TextBlock> <Label Content="Here your search query"/> <TextBox Text="{Binding SearchClause}"/> <Button Click="Button_Click">Search!</Button> <TextBlock Text="{Binding Result}"/></StackPanel> Code behind: using System.Windows;using System.Windows.Controls;namespace TriggerSpike{ public partial class UserControl1 : UserControl { private MyViewModel myModel; public UserControl1() { myModel=new MyViewModel(); DataContext = myModel; InitializeComponent(); } private void Button_Click(object sender, RoutedEventArgs e) { myModel.Search(myModel.SearchClause); } }} The viewmodel: using System.ComponentModel;using System.Threading;using System.Windows;namespace TriggerSpike{ class MyViewModel:DependencyObject { public string SearchClause{ get;set;} public bool IsBusy { get { return (bool)GetValue(IsBusyProperty); } set { SetValue(IsBusyProperty, value); } } public static readonly DependencyProperty IsBusyProperty = DependencyProperty.Register("IsBusy", typeof(bool), typeof(MyViewModel), new UIPropertyMetadata(false)); public string Result { get { return (string)GetValue(ResultProperty); } set { SetValue(ResultProperty, value); } } public static readonly DependencyProperty ResultProperty = DependencyProperty.Register("Result", typeof(string), typeof(MyViewModel), new UIPropertyMetadata(string.Empty)); public void Search(string search_clause) { Result = string.Empty; SearchClause = search_clause; var worker = new BackgroundWorker(); worker.DoWork += worker_DoWork; worker.RunWorkerCompleted += worker_RunWorkerCompleted; IsBusy = true; worker.RunWorkerAsync(); } void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { IsBusy=false; Result = "Sorry, no results found for: " + SearchClause; } void worker_DoWork(object sender, DoWorkEventArgs e) { Thread.Sleep(5000); } }} Hope this helps! | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/80388",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1199387/"
]
} |
80,415 | I have a string which starts with //#... goes upto the newline characater. I have figured out the regex for the which is this ..#([^\n]*) . My question is how do you remove this line from a file if the following condition matches | Your regex is badly chosen on several points: Instead of matching two slashes specifically, you use .. to match two characters that can be anything at all, presumably because you don’t know how to match slashes when you’re also using them as delimiters. (Actually, dots match almost anything, as we’ll see in #3.) Within a slash-delimited regex literal, // , you can match slashes simply by protecting them with backslashes, eg. /\/\// . The nicer variant, however, is to use the longer form of regex literal, m// , where you can choose the delimiter, eg. m!! . Since you use something other than slashes for delimitation, you can then write them without escaping them: m!//! . See perldoc perlop . It’s not anchored to the start of the string so it will match anywhere. Use the ^ start-of-string assertion in front. You wrote [^\n] to match “any character except newline” when there is a much simpler way to write that, which is just the . wildcard. It does exactly that – match any character except newline. You are using parentheses to group a part of the match, but the group is neither quantified (you are not specifying that it can match any other number of times than exactly once) nor are you interested in keeping it. So the parentheses are superfluous. Altogether, that makes it m!^//#.*! . But putting an uncaptured .* (or anything with a * quantifier) at the end of a regex is meaningless, since it never changes whether a string will match or not: the * is happy to match nothing at all. So that leaves you with m!^//#! . As for removing the line from the file, as everyone else explained, read it in line by line and print all the lines you want to keep back to another file. If you are not doing this within a larger program, use perl’s command line switches to do it easily: perl -ni.bak -e'print unless m!^//#!' somefile.txt Here, the -n switch makes perl put a loop around the code you provide which will read all the files you pass on the command line in sequence. The -i switch (for “in-place”) says to collect the output from your script and overwrite the original contents of each file with it. The .bak parameter to the -i option tells perl to keep a backup of the original file in a file named after the original file name with .bak appended. For all of these bits, see perldoc perlrun . If you want to do this within the context of a larger program, the easiest way to do it safely is to open the file twice, once for reading, and separately, with IO::AtomicFile , another time for writing. IO::AtomicFile will replace the original file only if it’s successfully closed. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/80415",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13046/"
]
} |
80,427 | Code I have: cell_val = CStr(Nz(fld.value, ""))Dim iter As LongFor iter = 0 To Len(cell_val) - 1 Step 1 If Asc(Mid(cell_val, iter, 1)) > 127 Then addlog "Export contains ascii character > 127" End IfNext iter This code doesn't work. Anyone know how to do this? I've simply got no idea with VB or VBA. | I believe your problem is that in VBA string indexes start at 1 and not at 0. Try the following: For iter = 1 To Len(cell_val) If Asc(Mid(cell_val, iter, 1)) > 127 Then addlog "Export contains ascii character > 127" End IfNext | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/80427",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/924607/"
]
} |
80,476 | I need to concatenate two String arrays in Java. void f(String[] first, String[] second) { String[] both = ???} Which is the easiest way to do this? | Here's a simple method that will concatenate two arrays and return the result: public <T> T[] concatenate(T[] a, T[] b) { int aLen = a.length; int bLen = b.length; @SuppressWarnings("unchecked") T[] c = (T[]) Array.newInstance(a.getClass().getComponentType(), aLen + bLen); System.arraycopy(a, 0, c, 0, aLen); System.arraycopy(b, 0, c, aLen, bLen); return c;} Note that it will not work with primitive data types, only with object types. The following slightly more complicated version works with both object and primitive arrays. It does this by using T instead of T[] as the argument type. It also makes it possible to concatenate arrays of two different types by picking the most general type as the component type of the result. public static <T> T concatenate(T a, T b) { if (!a.getClass().isArray() || !b.getClass().isArray()) { throw new IllegalArgumentException(); } Class<?> resCompType; Class<?> aCompType = a.getClass().getComponentType(); Class<?> bCompType = b.getClass().getComponentType(); if (aCompType.isAssignableFrom(bCompType)) { resCompType = aCompType; } else if (bCompType.isAssignableFrom(aCompType)) { resCompType = bCompType; } else { throw new IllegalArgumentException(); } int aLen = Array.getLength(a); int bLen = Array.getLength(b); @SuppressWarnings("unchecked") T result = (T) Array.newInstance(resCompType, aLen + bLen); System.arraycopy(a, 0, result, 0, aLen); System.arraycopy(b, 0, result, aLen, bLen); return result;} Here is an example: Assert.assertArrayEquals(new int[] { 1, 2, 3 }, concatenate(new int[] { 1, 2 }, new int[] { 3 }));Assert.assertArrayEquals(new Number[] { 1, 2, 3f }, concatenate(new Integer[] { 1, 2 }, new Number[] { 3f })); | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/80476",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2948/"
]
} |
80,486 | I need to know how to turn on Code Coverage when running TFS builds on a solution with a .testrunconfig file. There is an option in the testrunconfig file that is for code coverage, but when running a TFS build there is no code coverage results. I am running my tests using the *Tests.dll mask and NOT using Test Lists (.vsmdi). | How are you running the tests? Are you using a .vsmdi file or just specifying that you run all tests in *Tests.dll assemblies? If it is the latter and you are using TFS 2008, then you need to add the following to the and of the first PropertyGroup in your TFSBuild.proj file for the build. <RunConfigFile>$(SolutionRoot)\TestRunConfig.testrunconfig</RunConfigFile> This points the build at your .testrunconfig so it can pick up the instructions to run code coverage. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/80486",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5132/"
]
} |
80,564 | Is there a way to trigger a beep/alarm/sound when my breakpoint is hit? I'm using Visual Studio 2005/2008. | Windows XP Control Panel -> Sounds and Audio... -> Program Events - Microsoft Developer -> Breakpoint Hit Windows 7 Control Panel -> All Control Panel Items -> Sounds -> Sounds (tab) - Microsoft Visual Studio -> Breakpoint Hit | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/80564",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1630/"
]
} |
80,619 | While refactoring some old code I have stripped out a number of public methods that should actually of been statics as they a) don't operate on any member data or call any other member functions and b) because they might prove useful elsewhere. This led me to think about the best way to group 'helper' functions together. The Java/C# way would be to use a class of static functions with a private constructor, e.g.: class Helper { private: Helper() { }public: static int HelperFunc1(); static int HelperFunc2(); }; However, being C++ you could also use a namespace: namespace Helper { int HelperFunc1(); int HelperFunc2(); } In most cases I think I would prefer the namespace approach but I wanted to know what the pros and cons of each approach are. If used the class approach for example, would there be any overheads? | Overhead is not an issue, namespaces have some advantages though You can reopen a namespace in another header, grouping things more logically whilekeeping compile dependencies low You can use namespace aliasing to your advantage (debug/release, platform specific helpers, ....) e.g. I've done stuff like namespace LittleEndianHelper { void Function();}namespace BigEndianHelper { void Function();}#if powerpc namespace Helper = BigEndianHelper;#elif intel namespace Helper = LittleEndianHelper;#endif | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/80619",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9236/"
]
} |
80,646 | What is the difference between == and === ? How exactly does the loosely == comparison work? How exactly does the strict === comparison work? What would be some useful examples? | Difference between == and === The difference between the loosely == equal operator and the strict === identical operator is exactly explained in the manual : Comparison Operators Example Name Result $a == $b Equal TRUE if $a is equal to $b after type juggling. $a === $b Identical TRUE if $a is equal to $b, and they are of the same type. Loosely == equal comparison If you are using the == operator, or any other comparison operator which uses loosely comparison such as != , <> or == , you always have to look at the context to see what, where and why something gets converted to understand what is going on. Converting rules Converting to boolean Converting to integer Converting to float Converting to string Converting to array Converting to object Converting to resource Converting to NULL Type comparison table As reference and example you can see the comparison table in the manual : TRUE FALSE 1 0 -1 "1" "0" "-1" NULL array() "php" "" TRUE TRUE FALSE TRUE FALSE TRUE TRUE FALSE TRUE FALSE FALSE TRUE FALSE FALSE FALSE TRUE FALSE TRUE FALSE FALSE TRUE FALSE TRUE TRUE FALSE TRUE 1 TRUE FALSE TRUE FALSE FALSE TRUE FALSE FALSE FALSE FALSE FALSE FALSE 0 FALSE TRUE FALSE TRUE FALSE FALSE TRUE FALSE TRUE FALSE TRUE TRUE -1 TRUE FALSE FALSE FALSE TRUE FALSE FALSE TRUE FALSE FALSE FALSE FALSE "1" TRUE FALSE TRUE FALSE FALSE TRUE FALSE FALSE FALSE FALSE FALSE FALSE "0" FALSE TRUE FALSE TRUE FALSE FALSE TRUE FALSE FALSE FALSE FALSE FALSE "-1" TRUE FALSE FALSE FALSE TRUE FALSE FALSE TRUE FALSE FALSE FALSE FALSE NULL FALSE TRUE FALSE TRUE FALSE FALSE FALSE FALSE TRUE TRUE FALSE TRUE array() FALSE TRUE FALSE FALSE FALSE FALSE FALSE FALSE TRUE TRUE FALSE FALSE "php" TRUE FALSE FALSE TRUE FALSE FALSE FALSE FALSE FALSE FALSE TRUE FALSE "" FALSE TRUE FALSE TRUE FALSE FALSE FALSE FALSE TRUE FALSE FALSE TRUE Strict === identical comparison If you are using the === operator, or any other comparison operator which uses strict comparison such as !== or === , then you can always be sure that the types won't magically change, because there will be no converting going on. So with strict comparison the type and value have to be the same, not only the value. Type comparison table As reference and example you can see the comparison table in the manual : Strict comparisons with === TRUE FALSE 1 0 -1 "1" "0" "-1" NULL array() "php" "" TRUE TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE 1 FALSE FALSE TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE 0 FALSE FALSE FALSE TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE -1 FALSE FALSE FALSE FALSE TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE "1" FALSE FALSE FALSE FALSE FALSE TRUE FALSE FALSE FALSE FALSE FALSE FALSE "0" FALSE FALSE FALSE FALSE FALSE FALSE TRUE FALSE FALSE FALSE FALSE FALSE "-1" FALSE FALSE FALSE FALSE FALSE FALSE FALSE TRUE FALSE FALSE FALSE FALSE NULL FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE TRUE FALSE FALSE FALSE array() FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE TRUE FALSE FALSE "php" FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE TRUE FALSE "" FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE TRUE Editor's note - This was properly quoted previously, but is more readable as a markdown table. This is not plagiarism | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/80646",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9021/"
]
} |
80,650 | How do I register a custom protocol with Windows so that when clicking a link in an email or on a web page my application is opened and the parameters from the URL are passed to it? | Go to Start then in Find type regedit -> it should open Registry editor Click Right Mouse on HKEY_CLASSES_ROOT then New -> Key In the Key give the lowercase name by which you want urls to be called (in my case it will be testus://sdfsdfsdf ) then Click Right Mouse on testus -> then New -> String Value and add URL Protocol without value. Then add more entries like you did with protocol ( Right Mouse New -> Key ) and create hierarchy like testus -> shell -> open -> command and inside command change (Default) to the path where .exe you want to launch is, if you want to pass parameters to your exe then wrap path to exe in "" and add "%1" to look like: "c:\testing\test.exe" "%1" To test if it works go to Internet Explorer (not Chrome or Firefox) and enter testus:have_you_seen_this_man this should fire your .exe (give you some prompts that you want to do this - say Yes) and pass into args testus://have_you_seen_this_man . Here's sample console app to test: using System;namespace Testing{ class Program { static void Main(string[] args) { if (args!= null && args.Length > 0) Console.WriteLine(args[0]); Console.ReadKey(); } }} Hope this saves you some time. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/80650",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2189521/"
]
} |
80,657 | In the process of learning TinyOS I have discovered that I am totally clueless about makefiles. There are many optional compile time features that can be used by way of declaring preprocessor variables. To use them you have to do things like: CFLAGS="-DPACKET_LINK" this enables a certain feature. and CFLAGS="-DPACKET_LINK" "-DLOW_POWER" enables two features. Can someone dissect these lines for me and tell me whats going on? Not in terms of TinyOS, but in terms of makefiles! | CFLAGS is a variable that is most commonly used to add arguments to the compiler. In this case, it define macros. So the -DPACKET_LINK is the equivalent of putting #define PACKET_LINK 1 at the top of all .c and .h files in your project. Most likely, you have code inside your project that looks if these macros are defined and does something depending on that: #ifdef PACKET_LINK// This code will be ignored if PACKET_LINK is not defineddo_packet_link_stuff();#endif#ifdef LOW_POWER// This code will be ignored if LOW_POWER is not defined handle_powersaving_functions();#endif If you look further down in your makefile, you should see that $(CFLAGS) is probably used like: $(CC) $(CFLAGS) ...some-more-arguments... | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/80657",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
80,692 | public static Logger getLogger() { final Throwable t = new Throwable(); final StackTraceElement methodCaller = t.getStackTrace()[1]; final Logger logger = Logger.getLogger(methodCaller.getClassName()); logger.setLevel(ResourceManager.LOGLEVEL); return logger;} This method would return a logger that knows the class it's logging for.Any ideas against it? Many years later: https://github.com/yanchenko/droidparts/blob/master/droidparts/src/org/droidparts/util/L.java | I guess it adds a lot of overhead for every class. Every class has to be 'looked up'. You create new Throwable objects to do that... These throwables don't come for free. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/80692",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15187/"
]
} |
80,706 | I want to find 2 nd , 3 rd , ... n th maximum value of a column. | You could sort the column into descending format and then just obtain the value from the nth row. EDIT:: Updated as per comment request. WARNING completely untested! SELECT DOB FROM (SELECT DOB FROM USERS ORDER BY DOB DESC) WHERE ROWID = 6 Something like the above should work for Oracle ... you might have to get the syntax right first! | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/80706",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15181/"
]
} |
80,787 | Any ideas how to determine the number of active threads currently running in an ExecutorService ? | Use a ThreadPoolExecutor implementation and call getActiveCount() on it: int getActiveCount() // Returns the approximate number of threads that are actively executing tasks. The ExecutorService interface does not provide a method for that, it depends on the implementation. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/80787",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8441/"
]
} |
80,799 | I've been doing some work with the JAX-RS reference implementation (Jersey).I know of at least two other frameworks (Restlet & Apache CXF). My question is: Has anyone done some comparison between those frameworks and if so, which framework would you recommend and why? | FWIW we're using Jersey as its packed full of features (e.g. WADL, implicit views, XML/JSON/Atom support) has a large and vibrant developer community behind it and has great spring integration . If you use JBoss/SEAM you might find RESTeasy integrates a little better - but if you use Spring for Dependency Injection then Jersey seems the easiest, most popular, active and functional implementation. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/80799",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15100/"
]
} |
80,801 | If I have a large number of SQLite databases, all with the same schema, what is the best way to merge them together in order to perform a query on all databases? I know it is possible to use ATTACH to do this but it has a limit of 32 and 64 databases depending on the memory system on the machine. | To summarize from the Nabble post in DavidM's answer: attach 'c:\test\b.db3' as toMerge; BEGIN; insert into AuditRecords select * from toMerge.AuditRecords; COMMIT; detach toMerge; Repeat as needed. Note: added detach toMerge; as per mike's comment. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/80801",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2183/"
]
} |
80,802 | I've been wondering, is there a performance difference between using named functions and anonymous functions in Javascript? for (var i = 0; i < 1000; ++i) { myObjects[i].onMyEvent = function() { // do something };} vs function myEventHandler() { // do something}for (var i = 0; i < 1000; ++i) { myObjects[i].onMyEvent = myEventHandler;} The first is tidier since it doesn't clutter up your code with rarely-used functions, but does it matter that you're re-declaring that function multiple times? | The performance problem here is the cost of creating a new function object at each iteration of the loop and not the fact that you use an anonymous function: for (var i = 0; i < 1000; ++i) { myObjects[i].onMyEvent = function() { // do something };} You are creating a thousand distinct function objects even though they have the same body of code and no binding to the lexical scope ( closure ). The following seems faster, on the other hand, because it simply assigns the same function reference to the array elements throughout the loop: function myEventHandler() { // do something}for (var i = 0; i < 1000; ++i) { myObjects[i].onMyEvent = myEventHandler;} If you were to create the anonymous function before entering the loop, then only assign references to it to the array elements while inside the loop, you will find that there is no performance or semantic difference whatsoever when compared to the named function version: var handler = function() { // do something };for (var i = 0; i < 1000; ++i) { myObjects[i].onMyEvent = handler;} In short, there is no observable performance cost to using anonymous over named functions. As an aside, it may appear from above that there is no difference between: function myEventHandler() { /* ... */ } and: var myEventHandler = function() { /* ... */ } The former is a function declaration whereas the latter is a variable assignment to an anonymous function. Although they may appear to have the same effect, JavaScript does treat them slightly differently. To understand the difference, I recommend reading, “ JavaScript function declaration ambiguity ”. The actual execution time for any approach is largely going to be dictated by the browser's implementation of the compiler and runtime. For a complete comparison of modern browser performance, visit the JS Perf site | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/80802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9021/"
]
} |
80,833 | As the local subversion czar i explain to everyone to keep only source code and non-huge text files in the repository, not huge binary data files. Smaller binary files that are parts of tests, maybe. Unfortunately i work with humans ! Someone is likely to someday accidentally commit a 800MB binary hulk. This slows down repository operations. Last time i checked, you can't delete a file from the repository; only make it not part of the latest revision. The repository keeps the monster for all eternity, in case anyone ever wants to recall the state of the repository for that date or revision number. Is there a way to really delete that monster file and end up with a decent sized repository? I've tried the svnadmin dump/load thing but it was a pain. | Some extra info about this can be found at the blog post: Subversion Obliterate, the missing feature Be sure to read through the comments too, where Karl Fogel puts the article into perspective :-) | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/80833",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10468/"
]
} |
80,875 | How do you create a hardlink (as opposed to a symlink or a Mac OS alias) in OS X that points to a directory? I already know the command "ln target destination" but that only works when the target is a file. I know that Mac OS, unlike other Unix environments, does allow hardlinking to folders (this is used for Time Machine, for example) but I don't know how to do it myself. | You can't do it directly in BASH then. However... I found an article here that discusses how to do it indirectly: http://www.mactech.com/articles/mactech/Vol.23/23.11/ExploringLeopardwithDTrace/index.html by compiling a simple little C program: #include <unistd.h>#include <stdio.h>int main(int argc, char *argv[]){ if (argc != 3) return 1; int ret = link(argv[1], argv[2]); if (ret != 0) perror("link"); return ret;} ...and build in Terminal.app with: $ gcc -o hlink hlink.c -Wall | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/80875",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4939/"
]
} |
81,022 | In the KornShell (ksh) on AIX UNIX Version 5.3 with the editor mode set to vi using: set -o vi What are the key-strokes at the shell command line to autocomplete a file or directory name? | ESC\ works fine on AIX4.2 at least. One thing I noticed is that it only autocompletes to the unique part of the file name. So if you have the files x.txt, x171go and x171stop, the following will happen: Press keys: Command line is:x x<ESC>\ x1 x1<ESC>\ x171g<ESC>\ x171go | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/81022",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/381/"
]
} |
81,062 | What free and commercial garbage collection libraries are available for C++, and what are the pros and cons of each? I am interested in hard-won lessons from actual use in the field, not marketing or promotional blurb. There is no need to elaborate on the usual trade offs associated with automatic garbage collection, but please do mention the algorithms used (reference counting, mark and sweep, incremental, etc.) and briefly summarise the consequences. | I have used the Boehm collector in the past with good success. It's open source and can be used in commercial software. It's a conservative collector, and has a long history of development by one of the foremost researchers in garbage collection technology. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/81062",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15315/"
]
} |
81,099 | As the title states, I'd be interested to find a safe feature-based (that is, without using navigator.appName or navigator.appVersion) way to detect Google Chrome. By feature-based I mean, for example: if(window.ActiveXObject) { // internet explorer!} Edit: As it's been pointed out, the question doesn't make much sense (obviously if you want to implement a feature, you test for it, if you want to detect for a specific browser, you check the user agent), sorry, it's 5am ;) Let me me phrase it like this: Are there any javascript objects and/or features that are unique to Chrome... | isChrome = function() { return Boolean(window.chrome);} | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/81099",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14981/"
]
} |
81,150 | Possible Duplicate: How can I register a global hot key to say CTRL+SHIFT+(LETTER) using WPF and .NET 3.5? I'd like to have multiple global hotkeys in my new app (to control the app from anywhere in windows), and all of the given sources/solutions I found on the web seem to provide with a sort of a limping solution (either solutions only for one g.hotkey, or solutions that while running create annoying mouse delays on the screen). Does anyone here know of a resource that can help me achive this, that I can learn from?Anything? Thanks ! :) | The nicest solution I've found is http://bloggablea.wordpress.com/2007/05/01/global-hotkeys-with-net/ Hotkey hk = new Hotkey();hk.KeyCode = Keys.1;hk.Windows = true;hk.Pressed += delegate { Console.WriteLine("Windows+1 pressed!"); };hk.Register(myForm); Note how you can set different lambdas to different hotkeys | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/81150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
81,202 | Why does the linux kernel generate a segfault on stack overflow? This can make debugging very awkward when alloca in c or fortran creation of temporary arrays overflows. Surely it mjust be possible for the runtime to produce a more helpful error. | You can actually catch the condition for a stack overflow using signal handlers. To do this, you must do two things: Setup a signal handler for SIGSEGV (the segfault) using sigaction, to do this set the SO_ONSTACK flag. This instructs the kernel to use an alternative stack when delivering the signal. Call sigaltstack() to setup the alternate stack that the handler for SIGSEGV will use. Then when you overflow the stack, the kernel will switch to your alternate stack before delivering the signal. Once in your signal handler, you can examine the address that caused the fault and determine if it was a stack overflow, or a regular fault. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/81202",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
81,214 | I just want an ASP.NET DropDownList with no selected item. Setting SelectedIndex to -1 is of no avail, so far. I am using Framework 3.5 with AJAX, i.e. this DropDownList is within an UpdatePanel.Here is what I am doing: protected void Page_Load (object sender, EventArgs e) { this.myDropDownList.SelectedIndex = -1; this.myDropDownList.ClearSelection(); this.myDropDownList.Items.Add("Item1"); this.myDropDownList.Items.Add("Item2"); } The moment I add an element in the DropDown, its SelectedIndex changes to 0 and can be no more set to -1 (I tried calling SelectedIndex after adding items as well)... What I am doing wrong? Ant help would be appreciated! | Bare in mind myDropDownList.Items.Add will add a new Listitem element at the bottom if you call it after performing a DataSource/DataBind call so use myDropDownList.Items.Insert method instead eg... myDropDownList.DataSource = DataAccess.GetDropDownItems(); // Psuedo CodemyDropDownList.DataTextField = "Value";myDropDownList.DataValueField = "Id";myDropDownList.DataBind();myDropDownList.Items.Insert(0, new ListItem("Please select", "")); Will add the 'Please select' drop down item to the top. And as mentioned there will always be exactly one Item selected in a drop down (ListBoxes are different I believe), and this defaults to the top one if none are explicitly selected. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/81214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
81,236 | Which built in (if any) tool can I use to determine the allocation unit size of a certain NTFS partition ? | Open an administrator command prompt, and do this command: fsutil fsinfo ntfsinfo [your drive] The Bytes Per Cluster is the equivalent of the allocation unit. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/81236",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
81,260 | Is there a tool or script which easily merges a bunch of JAR files into one JAR file? A bonus would be to easily set the main-file manifest and make it executable. The concrete case is a Java restructured text tool . I would like to run it with something like: java -jar rst.jar As far as I can tell, it has no dependencies which indicates that it shouldn't be an easy single-file tool, but the downloaded ZIP file contains a lot of libraries. 0 11-30-07 10:01 jrst-0.8.1/ 922 11-30-07 09:53 jrst-0.8.1/jrst.bat 898 11-30-07 09:53 jrst-0.8.1/jrst.sh 2675 11-30-07 09:42 jrst-0.8.1/readmeEN.txt 108821 11-30-07 09:59 jrst-0.8.1/jrst-0.8.1.jar 2675 11-30-07 09:42 jrst-0.8.1/readme.txt 0 11-30-07 10:01 jrst-0.8.1/lib/ 81508 11-30-07 09:49 jrst-0.8.1/lib/batik-util-1.6-1.jar2450757 11-30-07 09:49 jrst-0.8.1/lib/icu4j-2.6.1.jar 559366 11-30-07 09:49 jrst-0.8.1/lib/commons-collections-3.1.jar 83613 11-30-07 09:49 jrst-0.8.1/lib/commons-io-1.3.1.jar 207723 11-30-07 09:49 jrst-0.8.1/lib/commons-lang-2.1.jar 52915 11-30-07 09:49 jrst-0.8.1/lib/commons-logging-1.1.jar 260172 11-30-07 09:49 jrst-0.8.1/lib/commons-primitives-1.0.jar 313898 11-30-07 09:49 jrst-0.8.1/lib/dom4j-1.6.1.jar1994150 11-30-07 09:49 jrst-0.8.1/lib/fop-0.93-jdk15.jar 55147 11-30-07 09:49 jrst-0.8.1/lib/activation-1.0.2.jar 355030 11-30-07 09:49 jrst-0.8.1/lib/mail-1.3.3.jar 77977 11-30-07 09:49 jrst-0.8.1/lib/servlet-api-2.3.jar 226915 11-30-07 09:49 jrst-0.8.1/lib/jaxen-1.1.1.jar 153253 11-30-07 09:49 jrst-0.8.1/lib/jdom-1.0.jar 50789 11-30-07 09:49 jrst-0.8.1/lib/jewelcli-0.41.jar 324952 11-30-07 09:49 jrst-0.8.1/lib/looks-1.2.2.jar 121070 11-30-07 09:49 jrst-0.8.1/lib/junit-3.8.1.jar 358085 11-30-07 09:49 jrst-0.8.1/lib/log4j-1.2.12.jar 72150 11-30-07 09:49 jrst-0.8.1/lib/logkit-1.0.1.jar 342897 11-30-07 09:49 jrst-0.8.1/lib/lutinwidget-0.9.jar2160934 11-30-07 09:49 jrst-0.8.1/lib/docbook-xsl-nwalsh-1.71.1.jar 301249 11-30-07 09:49 jrst-0.8.1/lib/xmlgraphics-commons-1.1.jar 68610 11-30-07 09:49 jrst-0.8.1/lib/sdoc-0.5.0-beta.jar3149655 11-30-07 09:49 jrst-0.8.1/lib/xalan-2.6.0.jar1010675 11-30-07 09:49 jrst-0.8.1/lib/xercesImpl-2.6.2.jar 194205 11-30-07 09:49 jrst-0.8.1/lib/xml-apis-1.3.02.jar 78440 11-30-07 09:49 jrst-0.8.1/lib/xmlParserAPIs-2.0.2.jar 86249 11-30-07 09:49 jrst-0.8.1/lib/xmlunit-1.1.jar 108874 11-30-07 09:49 jrst-0.8.1/lib/xom-1.0.jar 63966 11-30-07 09:49 jrst-0.8.1/lib/avalon-framework-4.1.3.jar 138228 11-30-07 09:49 jrst-0.8.1/lib/batik-gui-util-1.6-1.jar 216394 11-30-07 09:49 jrst-0.8.1/lib/l2fprod-common-0.1.jar 121689 11-30-07 09:49 jrst-0.8.1/lib/lutinutil-0.26.jar 76687 11-30-07 09:49 jrst-0.8.1/lib/batik-ext-1.6-1.jar 124724 11-30-07 09:49 jrst-0.8.1/lib/xmlParserAPIs-2.6.2.jar As you can see, it is somewhat desirable to not need to do this manually. So far I've only tried AutoJar and ProGuard, both of which were fairly easy to get running. It appears that there's some issue with the constant pool in the JAR files. Apparently jrst is slightly broken, so I'll make a go of fixing it. The Maven pom.xml file was apparently broken too, so I'll have to fix that before fixing jrst ... I feel like a bug-magnet :-) Update: I never got around to fixing this application, but I checked out Eclipse 's "Runnable JAR export wizard" which is based on a fat JAR. I found this very easy to use for deploying my own code. Some of the other excellent suggestions might be better for builds in a non-Eclipse environment, oss probably should make a nice build using Ant . (Maven, so far has just given me pain, but others love it.) | Eclipse 3.4 JDT's Runnable JAR export wizard. In Eclipse 3.5, this has been extended. Now you can chose how you want to treat your referenced JAR files. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/81260",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12677/"
]
} |
81,272 | I know the combination Ctrl + A to jump to the beginning of the current command, and Ctrl + E to jump to the end. But is there any way to jump word by word, like Alt + ← / → in Cocoa applications does? | Out of the box you can use the quite bizarre Esc + F to move to the beginning of the next word and Esc + B to move to the beginning of the current word. | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/81272",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
81,283 | How do people usually detect the MIME type of an uploaded file using ASP.NET? | in the aspx page: <asp:FileUpload ID="FileUpload1" runat="server" /> in the codebehind (c#): string contentType = FileUpload1.PostedFile.ContentType | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/81283",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15396/"
]
} |
81,285 | I re-image one of my machines regularly; and have a script that I run after the OS install completes to configure my machine; such that it works how I like. I happen to have my data on another drive...and I'd like to add code to my script to change the location of the Documents directory from "C:\Users\bryansh\Documents" to "D:\Users\bryansh\Documents". Does anybody have any insight, before I fire up regmon and really roll up my sleeves? | in the aspx page: <asp:FileUpload ID="FileUpload1" runat="server" /> in the codebehind (c#): string contentType = FileUpload1.PostedFile.ContentType | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/81285",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/211367/"
]
} |
81,306 | We're currently having a debate whether it's better to throw faults over a WCF channel, versus passing a message indicating the status or the response from a service. Faults come with built-in support from WCF where by you can use the built-in error handlers and react accordingly. This, however, carries overhead as throwing exceptions in .NET can be quite costly. Messages can contain the necessary information to determine what happened with your service call without the overhead of throwing an exception. It does however need several lines of repetitive code to analyze the message and determine actions following its contents. We took a stab at creating a generic message object we could utilize in our services, and this is what we came up with: public class ReturnItemDTO<T>{ [DataMember] public bool Success { get; set; } [DataMember] public string ErrorMessage { get; set; } [DataMember] public T Item { get; set; }} If all my service calls return this item, I can consistently check the "Success" property to determine if all went well. I then have an error message string in the event indicating something went wrong, and a generic item containing a Dto if needed. The exception information will have to be logged away to a central logging service and not passed back from the service. Thoughts? Comments? Ideas? Suggestions? Some further clarification on my question An issue I'm having with fault contracts is communicating business rules. Like, if someone logs in, and their account is locked, how do I communicate that? Their login obviously fails, but it fails due to the reason "Account Locked". So do I: A) use a boolean, throw Fault with message account locked B) return AuthenticatedDTO with relevant information | This however carries overhead as throwing exceptions in .NET can be quite costly. You're serializing and de-serializing objects to XML and sending them over a slow network.. the overhead from throwing an exception is negligable compared to that. I usually stick to throwing exceptions, since they clearly communicate something went wrong and all webservice toolkits have a good way of handling them. In your sample I would throw an UnauthorizedAccessException with the message "Account Locked". Clarification: The .NET wcf services translate exceptions to FaultContracts by default, but you can change this behaviour. MSDN:Specifying and Handling Faults in Contracts and Services | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/81306",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15360/"
]
} |
81,338 | got a new blog at wordpress few days ago ( http://ghads.wordpress.com ) and I want to post some code snippets now or then. Is there anyway to make it look like code without paying for extra plugins? | See here: http://en.support.wordpress.com/code/posting-source-code/ Wrap your code in these tags: [sourcecode language='css'] .. [/sourcecode] (or shorter [code lang='css'] .. [/code] ) Note that Visual Editor doesn't interpret the tags, you need to click Preview to see how it works. Available language codes: actionscript3 bash clojure coldfusion cpp csharp css delphi erlang fsharp diff groovy html javascript java javafx matlab (keywords only) objc perl php text powershell python r ruby scala sql vb xml Hope that helps. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/81338",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11705/"
]
} |
81,346 | I hope this question is not considered too basic for this forum, but we'll see. I'm wondering how to refactor some code for better performance that is getting run a bunch of times. Say I'm creating a word frequency list, using a Map (probably a HashMap), where each key is a String with the word that's being counted and the value is an Integer that's incremented each time a token of the word is found. In Perl, incrementing such a value would be trivially easy: $map{$word}++; But in Java, it's much more complicated. Here the way I'm currently doing it: int count = map.containsKey(word) ? map.get(word) : 0;map.put(word, count + 1); Which of course relies on the autoboxing feature in the newer Java versions. I wonder if you can suggest a more efficient way of incrementing such a value. Are there even good performance reasons for eschewing the Collections framework and using a something else instead? Update: I've done a test of several of the answers. See below. | Some test results I've gotten a lot of good answers to this question--thanks folks--so I decided to run some tests and figure out which method is actually fastest. The five methods I tested are these: the "ContainsKey" method that I presented in the question the "TestForNull" method suggested by Aleksandar Dimitrov the "AtomicLong" method suggested by Hank Gay the "Trove" method suggested by jrudolph the "MutableInt" method suggested by phax.myopenid.com Method Here's what I did... created five classes that were identical except for the differences shown below. Each class had to perform an operation typical of the scenario I presented: opening a 10MB file and reading it in, then performing a frequency count of all the word tokens in the file. Since this took an average of only 3 seconds, I had it perform the frequency count (not the I/O) 10 times. timed the loop of 10 iterations but not the I/O operation and recorded the total time taken (in clock seconds) essentially using Ian Darwin's method in the Java Cookbook . performed all five tests in series, and then did this another three times. averaged the four results for each method. Results I'll present the results first and the code below for those who are interested. The ContainsKey method was, as expected, the slowest, so I'll give the speed of each method in comparison to the speed of that method. ContainsKey: 30.654 seconds (baseline) AtomicLong: 29.780 seconds (1.03 times as fast) TestForNull: 28.804 seconds (1.06 times as fast) Trove: 26.313 seconds (1.16 times as fast) MutableInt: 25.747 seconds (1.19 times as fast) Conclusions It would appear that only the MutableInt method and the Trove method are significantly faster, in that only they give a performance boost of more than 10%. However, if threading is an issue, AtomicLong might be more attractive than the others (I'm not really sure). I also ran TestForNull with final variables, but the difference was negligible. Note that I haven't profiled memory usage in the different scenarios. I'd be happy to hear from anybody who has good insights into how the MutableInt and Trove methods would be likely to affect memory usage. Personally, I find the MutableInt method the most attractive, since it doesn't require loading any third-party classes. So unless I discover problems with it, that's the way I'm most likely to go. The code Here is the crucial code from each method. ContainsKey import java.util.HashMap;import java.util.Map;...Map<String, Integer> freq = new HashMap<String, Integer>();...int count = freq.containsKey(word) ? freq.get(word) : 0;freq.put(word, count + 1); TestForNull import java.util.HashMap;import java.util.Map;...Map<String, Integer> freq = new HashMap<String, Integer>();...Integer count = freq.get(word);if (count == null) { freq.put(word, 1);}else { freq.put(word, count + 1);} AtomicLong import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.ConcurrentMap;import java.util.concurrent.atomic.AtomicLong;...final ConcurrentMap<String, AtomicLong> map = new ConcurrentHashMap<String, AtomicLong>();...map.putIfAbsent(word, new AtomicLong(0));map.get(word).incrementAndGet(); Trove import gnu.trove.TObjectIntHashMap;...TObjectIntHashMap<String> freq = new TObjectIntHashMap<String>();...freq.adjustOrPutValue(word, 1, 1); MutableInt import java.util.HashMap;import java.util.Map;...class MutableInt { int value = 1; // note that we start at 1 since we're counting public void increment () { ++value; } public int get () { return value; }}...Map<String, MutableInt> freq = new HashMap<String, MutableInt>();...MutableInt count = freq.get(word);if (count == null) { freq.put(word, new MutableInt());}else { count.increment();} | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/81346",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10204/"
]
} |
81,350 | What are the private IP address ranges? | You will find the answers to this in RFC 1918 . Though, I have listed them below for you. 10.0.0.0 - 10.255.255.255 (10/8 prefix) 172.16.0.0 - 172.31.255.255 (172.16/12 prefix) 192.168.0.0 - 192.168.255.255 (192.168/16 prefix) It is a common misconception that 169.254.0.0/16 is a private IP address block. This is not true. It is link local, basically it is meant to be only used within networks, but it isn't official RFC1918. Additional information about IPv4 addresses can be found in RFC 3300 . On the other hand IPv6 doesn't have an equivalent to RFC1918, but any sort of site-local work should be done in fc00::/7. This is further touched on in RFC 4193 . | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/81350",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11034/"
]
} |
81,361 | I have set up a repository using SVN and uploaded projects. There are multiple users working on these projects. But, not everyone requires access to all projects. I want to set up user permissions for each project. How can I achieve this? | In your svn\repos\YourRepo\conf folder you will find two files, authz and passwd . These are the two you need to adjust. In the passwd file you need to add some usernames and passwords. I assume you have already done this since you have people using it: [users]User1=password1User2=password2 Then you want to assign permissions accordingly with the authz file: Create the conceptual groups you want, and add people to it: [groups]allaccess = user1someaccess = user2 Then choose what access they have from both the permissions and project level. So let's give our "all access" guys all access from the root: [/]@allaccess = rw But only give our "some access" guys read-only access to some lower level project: [/someproject]@someaccess = r You will also find some simple documentation in the authz and passwd files. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/81361",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15425/"
]
} |
81,392 | If you declare variables of type byte or short and attempt to perform arithmetic operations on these, you receive the error "Type mismatch: cannot convert int to short" (or correspondingly "Type mismatch: cannot convert int to byte"). byte a = 23;byte b = 34;byte c = a + b; In this example, the compile error is on the third line. | Although the arithmetic operators are defined to operate on any numeric type, according the Java language specification (5.6.2 Binary Numeric Promotion), operands of type byte and short are automatically promoted to int before being handed to the operators. To perform arithmetic operations on variables of type byte or short, you must enclose the expression in parentheses (inside of which operations will be carried out as type int), and then cast the result back to the desired type. byte a = 23;byte b = 34;byte c = (byte) (a + b); Here's a follow-on question to the real Java gurus: why? The types byte and short are perfectly fine numeric types. Why does Java not allow direct arithmetic operations on these types? (The answer is not "loss of precision", as there is no apparent reason to convert to int in the first place.) Update: jrudolph suggests that this behavior is based on the operations available in the JVM, specifically, that only full- and double-word operators are implemented. Hence, to operator on bytes and shorts, they must be converted to int. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/81392",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7732/"
]
} |
81,406 | Which parsers are available for parsing C# code? I'm looking for a C# parser that can be used in C# and give me access to line and file informations about each artefact of the analysed code. | Works on source code: CSParser :From C# 1.0 to 2.0, open-source Metaspec C# Parser :From C# 1.0 to 3.0, commercial product (about 5000$) #recognize! :From C# 1.0 to 3.0, commercial product (about 900€) (answer by SharpRecognize ) SharpDevelop Parser (answer by Akselsson ) NRefactory :From C# 1.0 to 4.0 (+async), open-source, parser used in SharpDevelop. Includes semantic analysis. C# Parser and CodeDOM :A complete C# 4.0 Parser, already support the C# 5.0 async feature. Commercial product (49$ to 299$) (answer by Ken Beckett ) Microsoft Roslyn CTP :Compiler as a service. Works on assembly: System.Reflection Microsoft Common Compiler Infrastructure :From C# 1.0 to 3.0, Microsoft Public License. Used by Fxcop and Spec# Mono.Cecil :From C# 1.0 to 3.0, open-source The problem with assembly "parsing" is that we have less informations about line and file (the informations is based on .pdb file, and Pdb contains lines informations only for methods) I personnaly recommend Mono.Cecil and NRefactory . | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/81406",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12248/"
]
} |
81,448 | In Oracle, what is the difference between : CREATE TABLE CLIENT( NAME VARCHAR2(11 BYTE), ID_CLIENT NUMBER) and CREATE TABLE CLIENT( NAME VARCHAR2(11 CHAR), -- or even VARCHAR2(11) ID_CLIENT NUMBER) | Let us assume the database character set is UTF-8, which is the recommended setting in recent versions of Oracle. In this case, some characters take more than 1 byte to store in the database. If you define the field as VARCHAR2(11 BYTE) , Oracle can use up to 11 bytes for storage, but you may not actually be able to store 11 characters in the field, because some of them take more than one byte to store, e.g. non-English characters. By defining the field as VARCHAR2(11 CHAR) you tell Oracle it can use enough space to store 11 characters, no matter how many bytes it takes to store each one. A single character may require up to 4 bytes. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/81448",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12388/"
]
} |
81,449 | In a server-side application running on Tomcat, I am generating full HTML pages (with header) based on random user-requested sites pulled down from the Internet. The client-side application uses asynchronous callbacks for requesting processing of a particular web page. Since processing can take a while, I want to inform the user about progress via polling, hence the callbacks. On server-side, after the web page is retrieved, it is processed and an "enhanced" version is created. Then this version has to go back to the user.Displaying the page as part of the page of the client-side application is not an option. Currently, the server generates a temporary file and sends back a link to it. This is clearly suboptimal. The next best solution I can come up with inolves creating a caching-DB that stores the HTML content together with its md5-sums or sha1-ids and then sends back a link to a servlet, with the hash-ID as an argument. The servlet then requests the site from the caching-DB. Is there any better solution? If not, which DB-backend would you propose? I'm thinking of SQLite. Part of the problem to be solved is: how do I push a page <html> to </html> back to client side? | Let us assume the database character set is UTF-8, which is the recommended setting in recent versions of Oracle. In this case, some characters take more than 1 byte to store in the database. If you define the field as VARCHAR2(11 BYTE) , Oracle can use up to 11 bytes for storage, but you may not actually be able to store 11 characters in the field, because some of them take more than one byte to store, e.g. non-English characters. By defining the field as VARCHAR2(11 CHAR) you tell Oracle it can use enough space to store 11 characters, no matter how many bytes it takes to store each one. A single character may require up to 4 bytes. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/81449",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11797/"
]
} |
81,451 | I am planning to create a web app that allows users to downgrade their visual studio project files. However, It seems Google App Engine accepts files uploading and flat file storing on the Google Server through db.TextProperty and db.BlobProperty . I'll be glad anyone can provide code sample (both the client and the server side) on how this can be done. | Here is a complete, working file. I pulled the original from the Google site and modified it to make it slightly more real world. A few things to notice: This code uses the BlobStore API The purpose of this line in theServeHandler class is to "fix" thekey so that it gets rid of any namemangling that may have occurred inthe browser (I didn't observe any inChrome) blob_key = str(urllib.unquote(blob_key)) The "save_as" clause at the end of this is important. It will make sure that the file name does not get mangled when it is sent to your browser. Get rid of it to observe what happens. self.send_blob(blobstore.BlobInfo.get(blob_key), save_as=True) Good Luck! import osimport urllibfrom google.appengine.ext import blobstorefrom google.appengine.ext import webappfrom google.appengine.ext.webapp import blobstore_handlersfrom google.appengine.ext.webapp import templatefrom google.appengine.ext.webapp.util import run_wsgi_appclass MainHandler(webapp.RequestHandler): def get(self): upload_url = blobstore.create_upload_url('/upload') self.response.out.write('<html><body>') self.response.out.write('<form action="%s" method="POST" enctype="multipart/form-data">' % upload_url) self.response.out.write("""Upload File: <input type="file" name="file"><br> <input type="submit" name="submit" value="Submit"> </form></body></html>""") for b in blobstore.BlobInfo.all(): self.response.out.write('<li><a href="/serve/%s' % str(b.key()) + '">' + str(b.filename) + '</a>')class UploadHandler(blobstore_handlers.BlobstoreUploadHandler): def post(self): upload_files = self.get_uploads('file') blob_info = upload_files[0] self.redirect('/')class ServeHandler(blobstore_handlers.BlobstoreDownloadHandler): def get(self, blob_key): blob_key = str(urllib.unquote(blob_key)) if not blobstore.get(blob_key): self.error(404) else: self.send_blob(blobstore.BlobInfo.get(blob_key), save_as=True)def main(): application = webapp.WSGIApplication( [('/', MainHandler), ('/upload', UploadHandler), ('/serve/([^/]+)?', ServeHandler), ], debug=True) run_wsgi_app(application)if __name__ == '__main__': main() | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/81451",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3834/"
]
} |
81,459 | If I understand correctly, ClickOnce only checks for prerequisites with the first install of an application through the setup.exe file that contains the prerequisite information. If the user opens the app in the future it will check for new versions, but it does not launch the setup.exe again, thus not checking for any NEW prerequisites that might have been added. Is there any way to force ClickOnce to check the prerequisites again or does anyone have a good solution without asking the user to run the setup.exe again? | Unfortunately, your users will have to re-run the setup.exe to check and install all the new prerequisites that you have added. Applications deployed using ClickOnce only check for application updates (if enabled), not prerequisites as it's the bootstrapper's job to make sure all dependencies are installed before the application is installed. I found this at Microsoft's site : The Setup.exe (bootstrapper) is responsible for installing all dependencies before your application runs. This bootstrapper runs as a separate process that is independent of the ClickOnce run-time engine. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/81459",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15415/"
]
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.