Search Results

Search found 11639 results on 466 pages for 'numerical methods'.

Page 7/466 | < Previous Page | 3 4 5 6 7 8 9 10 11 12 13 14  | Next Page >

  • Why you shouldn't add methods to interfaces in APIs

    - by Simon Cooper
    It is an oft-repeated maxim that you shouldn't add methods to a publically-released interface in an API. Recently, I was hit hard when this wasn't followed. As part of the work on ApplicationMetrics, I've been implementing auto-reporting of MVC action methods; whenever an action was called on a controller, ApplicationMetrics would automatically report it without the developer needing to add manual ReportEvent calls. Fortunately, MVC provides easy hook when a controller is created, letting me log when it happens - the IControllerFactory interface. Now, the dll we provide to instrument an MVC webapp has to be compiled against .NET 3.5 and MVC 1, as the lowest common denominator. This MVC 1 dll will still work when used in an MVC 2, 3 or 4 webapp because all MVC 2+ webapps have a binding redirect redirecting all references to previous versions of System.Web.Mvc to the correct version, and type forwards taking care of any moved types in the new assemblies. Or at least, it should. IControllerFactory In MVC 1 and 2, IControllerFactory was defined as follows: public interface IControllerFactory { IController CreateController(RequestContext requestContext, string controllerName); void ReleaseController(IController controller); } So, to implement the logging controller factory, we simply wrap the existing controller factory: internal sealed class LoggingControllerFactory : IControllerFactory { private readonly IControllerFactory m_CurrentController; public LoggingControllerFactory(IControllerFactory currentController) { m_CurrentController = currentController; } public IController CreateController( RequestContext requestContext, string controllerName) { // log the controller being used FeatureSessionData.ReportEvent("Controller used:", controllerName); return m_CurrentController.CreateController(requestContext, controllerName); } public void ReleaseController(IController controller) { m_CurrentController.ReleaseController(controller); } } Easy. This works as expected in MVC 1 and 2. However, in MVC 3 this type was throwing a TypeLoadException, saying a method wasn't implemented. It turns out that, in MVC 3, the definition of IControllerFactory was changed to this: public interface IControllerFactory { IController CreateController(RequestContext requestContext, string controllerName); SessionStateBehavior GetControllerSessionBehavior( RequestContext requestContext, string controllerName); void ReleaseController(IController controller); } There's a new method in the interface. So when our MVC 1 dll was redirected to reference System.Web.Mvc v3, LoggingControllerFactory tried to implement version 3 of IControllerFactory, was missing the GetControllerSessionBehaviour method, and so couldn't be loaded by the CLR. Implementing the new method Fortunately, there was a workaround. Because interface methods are normally implemented implicitly in the CLR, if we simply declare a virtual method matching the signature of the new method in MVC 3, then it will be ignored in MVC 1 and 2 and implement the extra method in MVC 3: internal sealed class LoggingControllerFactory : IControllerFactory { ... public virtual SessionStateBehaviour GetControllerSessionBehaviour( RequestContext requestContext, string controllerName) {} ... } However, this also has problems - the SessionStateBehaviour type only exists in .NET 4, and we're limited to .NET 3.5 by support for MVC 1 and 2. This means that the only solutions to support all MVC versions are: Construct the LoggingControllerFactory type at runtime using reflection Produce entirely separate dlls for MVC 1&2 and MVC 3. Ugh. And all because of that blasted extra method! Another solution? Fortunately, in this case, there is a third option - System.Web.Mvc also provides a DefaultControllerFactory type that can provide the implementation of GetControllerSessionBehaviour for us in MVC 3, while still allowing us to override CreateController and ReleaseController. However, this does mean that LoggingControllerFactory won't be able to wrap any calls to GetControllerSessionBehaviour. This is an acceptable bug, given the other options, as very few developers will be overriding GetControllerSessionBehaviour in their own custom controller factory. So, if you're providing an interface as part of an API, then please please please don't add methods to it. Especially if you don't provide a 'default' implementing type. Any code compiled against the previous version that can't be updated will have some very tough decisions to make to support both versions.

    Read the article

  • array_splice() - Numerical Offsets of Associative Arrays

    - by Alix Axel
    I'm trying to do something but I can't find any solution, I'm also having some trouble putting it into works so here is a sample code, maybe it'll be enough to demonstrate what I'm aiming for: $input = array ( 'who' => 'me', 'what' => 'car', 'more' => 'car', 'when' => 'today', ); Now, I want to use array_splice() to remove (and return) one element from the array: $spliced = key(array_splice($input, 2, 1)); // I'm only interested in the key... The above will remove and return 1 element (third argument) from $input (first argument), at offset 2 (second argument), so $spliced will hold the value more. I'll be iterating over $input with a foreach loop, I know the key to be spliced but the problem is I don't know its numerical offset and since array_splice only accepts integers I don't know what to do. A very dull example: $result = array(); foreach ($input as $key => $value) { if ($key == 'more') { // Remove the index "more" from $input and add it to $result. $result[] = key(array_splice($input, 2 /* How do I know its 2? */, 1)); } } I first though of using array_search() but it's pointless since it'll return the associative index.... How do I determine the numerical offset of a associative index?

    Read the article

  • Numerical calculations in Prolog

    - by user8472
    While reading SICP I came across logic programming chapter 4.4. Then I started looking into the Prolog programming language and tried to understand some simple assignments in Prolog. I found that Prolog seems to have troubles with numerical calculations. Here is the computation of a factorial in standard Prolog: f(0, 1). f(A, B) :- A > 0, C is A-1, f(C, D), B is A*D. The issues I find is that I need to introduce two auxiliary variables (C and D), a new syntax (is) and that the problem is non-reversible (i.e., f(5,X) works as expected, but f(X,120) does not). Naively, I expect that at the very least C is A-1, f(C, D) above may be replaced by f(A-1,D), but even that does not work. My question is: Why do I need to do this extra "stuff" in numerical calculations but not in other queries? I do understand (and SICP is quite clear about it) that in general information on "what to do" is insufficient to answer the question of "how to do it". So the declarative knowledge in (at least some) math problems is insufficient to actually solve these problems. But that begs the next question: How does this extra "stuff" in Prolog help me to restrict the formulation to just those problems where "what to do" is sufficient to answer "how to do it"?

    Read the article

  • Reversible numerical calculations in Prolog

    - by user8472
    While reading SICP I came across logic programming chapter 4.4. Then I started looking into the Prolog programming language and tried to understand some simple assignments in Prolog. I found that Prolog seems to have troubles with numerical calculations. Here is the computation of a factorial in standard Prolog: f(0, 1). f(A, B) :- A > 0, C is A-1, f(C, D), B is A*D. The issues I find is that I need to introduce two auxiliary variables (C and D), a new syntax (is) and that the problem is non-reversible (i.e., f(5,X) works as expected, but f(X,120) does not). Naively, I expect that at the very least C is A-1, f(C, D) above may be replaced by f(A-1,D), but even that does not work. My question is: Why do I need to do this extra "stuff" in numerical calculations but not in other queries? I do understand (and SICP is quite clear about it) that in general information on "what to do" is insufficient to answer the question of "how to do it". So the declarative knowledge in (at least some) math problems is insufficient to actually solve these problems. But that begs the next question: How does this extra "stuff" in Prolog help me to restrict the formulation to just those problems where "what to do" is sufficient to answer "how to do it"?

    Read the article

  • Why do some programmers think there is a contrast between theory and practice?

    - by Giorgio
    Comparing software engineering with civil engineering, I was surprised to observe a different way of thinking: any civil engineer knows that if you want to build a small hut in the garden you can just get the materials and go build it whereas if you want to build a 10-storey house you need to do quite some maths to be sure that it won't fall apart. In contrast, speaking with some programmers or reading blogs or forums I often find a wide-spread opinion that can be formulated more or less as follows: theory and formal methods are for mathematicians / scientists while programming is more about getting things done. What is normally implied here is that programming is something very practical and that even though formal methods, mathematics, algorithm theory, clean / coherent programming languages, etc, may be interesting topics, they are often not needed if all one wants is to get things done. According to my experience, I would say that while you do not need much theory to put together a 100-line script (the hut), in order to develop a complex application (the 10-storey building) you need a structured design, well-defined methods, a good programming language, good text books where you can look up algorithms, etc. So IMO (the right amount of) theory is one of the tools for getting things done. So my question is why do some programmers think that there is a contrast between theory (formal methods) and practice (getting things done)? Is software engineering (building software) perceived by many as easy compared to, say, civil engineering (building houses)? Or are these two disciplines really different (apart from mission-critical software, software failure is much more acceptable than building failure)?

    Read the article

  • Should I use formal methods on my software project?

    - by Michael
    Our client wants us to build a web-based, rich internet application for gathering software requirements. Basically it's a web-based case tool that follows a specific process for getting requirements from stakeholders. I'm the project manager and we're still in the early phases of the project. I've been thinking about using formal methods to help clarify the requirements for the tool for both my client and the developers. By formal methods I mean some form of modeling, possibly something mathematically-based. Some of the things I've read about and are considering include Z (http://en.wikipedia.org/wiki/Z_notation), state machines, UML 2.0 (possibly with extensions such as OCL), Petri nets, and some coding-level stuff like contracts and pre and post conditions. Is there anything else I should consider? The developers are experienced but depending on the formalism used they may have to learn some math. I'm trying to determine whether it's worth while for me to use formal methods on this project and if so, to what extent. I know "it depends" so the most helpful answers for me is a yes/no and supporting arguments. Would you use formal methods if you were on this project?

    Read the article

  • Can static methods be called using object/instance in .NET

    Ans is Yes and No   Yes in C++, Java and VB.NET No in C#   This is only compiler restriction in c#. You might see in some websites that we can break this restriction using reflection and delegates, but we can’t, according to my little research J I shall try to explain you…   Following is code sample to break this rule using reflection, it seems that it is possible to call a static method using an object, p1 using System; namespace T {     class Program     {         static void Main()         {             var p1 = new Person() { Name = "Smith" };             typeof(Person).GetMethod("TestStatMethod").Invoke(p1, new object[] { });                     }         class Person         {             public string Name { get; set; }             public static void TestStatMethod()             {                 Console.WriteLine("Hello");             }         }     } } but I do not think so this method is being called using p1 rather Type Name “Person”. I shall try to prove this… look at another example…  Test2 has been inherited from Test1. Let’s see various scenarios… Scenario1 using System; namespace T {     class Program     {         static void Main()         {             Test1 t = new Test1();            typeof(Test2).GetMethod("Method1").Invoke(t,                                  new object[] { });         }     }     class Test1     {         public static void Method1()         {             Console.WriteLine("At test1::Method1");         }     }       class Test2 : Test1     {         public static void Method1()         {             Console.WriteLine("At test1::Method2");         }     } } Output:   At test1::Method2 Scenario2         static void Main()         {             Test2 t = new Test2();            typeof(Test2).GetMethod("Method1").Invoke(t,                                          new object[] { });         }   Output:   At test1::Method2   Scenario3         static void Main()         {             Test1 t = new Test2();            typeof(Test2).GetMethod("Method1").Invoke(t,                             new object[] { });         }   Output: At test1::Method2 In all above scenarios output is same, that means, Reflection also not considering the object what you pass to Invoke method in case of static methods. It is always considering the type which you specify in typeof(). So, what is the use passing instance to “Invoke”. Let see below sample using System; namespace T {     class Program     {         static void Main()         {            typeof(Test2).GetMethod("Method1").                Invoke(null, new object[] { });         }     }       class Test1     {         public static void Method1()         {             Console.WriteLine("At test1::Method1");         }     }     class Test2 : Test1     {         public static void Method1()         {             Console.WriteLine("At test1::Method2");         }     } }   Output is   At test1::Method2   I was able to call Invoke “Method1” of Test2 without any object.  Yes, there no wonder here as Method1 is static. So we may conclude that static methods cannot be called using instances (only in c#) Why Microsoft has restricted it in C#? Ans: Really there Is no use calling static methods using objects because static methods are stateless. but still Java and C++ latest compilers allow calling static methods using instances. Java sample class Test {      public static void main(String str[])      {            Person p = new Person();            System.out.println(p.GetCount());      } }   class Person {   public static int GetCount()   {      return 100;   } }   Output          100 span.fullpost {display:none;}

    Read the article

  • System.Reflection - Global methods aren't available for reflection

    - by mrjoltcola
    I have an issue with a semantic gap between the CLR and System.Reflection. System.Reflection does not (AFAIK) support reflecting on global methods in an assembly. At the assembly level, I must start with the root types. My compiler can produce assemblies with global methods, and my standard bootstrap lib is a dll that includes some global methods. My compiler uses System.Reflection to import assembly metadata at compile time. It seems if I depend on System.Reflection, global methods are not a possibility. The cleanest solution is to convert all of my standard methods to class static methods, but the point is, my language allows global methods, and the CLR supports it, but System.Reflection leaves a gap. ildasm shows the global methods just fine, but I assume it does not use System.Reflection itself and goes right to the metadata and bytecode. Besides System.Reflection, is anyone aware of any other 3rd party reflection or disassembly libs that I could make use of (assuming I will eventually release my compiler as free, BSD licensed open source).

    Read the article

  • When should a method of a class return the same instance after modifying itself?

    - by modiX
    I have a class that has three methods A(), B() and C(). Those methods modify the own instance. While the methods have to return an instance when the instance is a separate copy (just as Clone()), I got a free choice to return void or the same instance (return this;) when modifying the same instance in the method and not returning any other value. When deciding for returning the same modified instance, I can do neat method chains like obj.A().B().C();. Would this be the only reason for doing so? Is it even okay to modify the own instance and return it, too? Or should it only return a copy and leave the original object as before? Because when returning the same modified instance the user would maybe admit the returned value is a copy, otherwise it would not be returned? If it's okay, what's the best way to clarify such things on the method?

    Read the article

  • Why is it impossible to declare extension methods in a generic static class?

    - by Hun1Ahpu
    I'd like to create a lot of extension methods for some generic class, e.g. for public class SimpleLinkedList<T> where T:IComparable And I've started creating methods like this: public static class LinkedListExtensions { public static T[] ToArray<T>(this SimpleLinkedList<T> simpleLinkedList) where T:IComparable { //// code } } But when I tried to make LinkedListExtensions class generic like this: public static class LinkedListExtensions<T> where T:IComparable { public static T[] ToArray(this SimpleLinkedList<T> simpleLinkedList) { ////code } } I get "Extension methods can only be declared in non-generic, non-nested static class". And I'm trying to guess where this restriction came from and have no ideas.

    Read the article

  • Simple way to reorder methods of a Java class in IntelliJ?

    - by Péter Török
    Is there a simpler way of reordering methods within a class source file in IntelliJ than cutting and pasting the code manually? Nowadays I often need this while refactoring legacy code, e.g. to move related methods close to each other in the source code. In Eclipse AFAIK there is a view similar to the Structure view of IntelliJ, where I can drag and drop methods around. However, this does not work in IntelliJ and I couldn't find any hints from its help either. I am using IntelliJ 9.0.2 to be specific.

    Read the article

  • Background & Research Methods section (Writing an Article)

    - by sterz
    It is my first time writing an article on a software project. I am supposed to use ACM UbiComp paper format. I already have a structure that I should follow and there is a Background & Research Methods section after Abstract, Introduction, Related Work sections. I have browser through several articles, but some of them either dont have it, have only background section or have only research methods section. I am having hard time to find an article that has this section and moreover what I must write on here. My project is about Bluetooth location tracking and I do have the implementation and evaluation, so it is not something theoretical.

    Read the article

  • Use Extension Methods to find first and last day of the month

    - by Tim Hibbard
    A lot of reports work on data from last month.  It is a nice touch to have these dates pre-populated for your users.  Using extension methods, the code can look cleaner too. Extension Methods: public static class DateHelper { public static DateTime FirstOfTheMonth(this DateTime dt) { return new DateTime(dt.Year, dt.Month, 1); }   public static DateTime LastOfTheMonth(this DateTime dt) { return dt.FirstOfTheMonth().AddMonths(1).AddDays(-1); } } Consuming Code: void Prepopulate() { startDateBox.CurrentlySelectedDate = DateTime.Now.AddMonths(-1).FirstOfTheMonth(); endDateBox.CurrentlySelectedDate = DateTime.Now.AddMonths(-1).LastOfTheMonth(); }

    Read the article

  • Advantages to Multiple Methods over Switch

    - by tandu
    I received a code review from a senior developer today asking "By the way, what is your objection to dispatching functions by way of a switch statement?" I have read in many places about how pumping an argument through switch to call methods is bad OOP, not as extensible, etc. However, I can't really come up with a definitive answer for him. I would like to settle this for myself once and for all. Here are our competing code suggestions (php used as an example, but can apply more universally): class Switch { public function go($arg) { switch ($arg) { case "one": echo "one\n"; break; case "two": echo "two\n"; break; case "three": echo "three\n"; break; default: throw new Exception("Unknown call: $arg"); break; } } } class Oop { public function go_one() { echo "one\n"; } public function go_two() { echo "two\n"; } public function go_three() { echo "three\n"; } public function __call($_, $__) { throw new Exception("Unknown call $_ with arguments: " . print_r($__, true)); } } Part of his argument was "It (switch method) has a much cleaner way of handling default cases than what you have in the generic __call() magic method." I disagree about the cleanliness and in fact prefer call, but I would like to hear what others have to say. Arguments I can come up with in support of Oop scheme: A bit cleaner in terms of the code you have to write (less, easier to read, less keywords to consider) Not all actions delegated to a single method. Not much difference in execution here, but at least the text is more compartmentalized. In the same vein, another method can be added anywhere in the class instead of a specific spot. Methods are namespaced, which is nice. Does not apply here, but consider a case where Switch::go() operated on a member rather than a parameter. You would have to change the member first, then call the method. For Oop you can call the methods independently at any time. Arguments I can come up with in support of Switch scheme: For the sake of argument, cleaner method of dealing with a default (unknown) request Seems less magical, which might make unfamiliar developers feel more comfortable Anyone have anything to add for either side? I'd like to have a good answer for him.

    Read the article

  • How to design 2D collision callback methods?

    - by Ahmed Fakhry
    In a 2D game where you have a lot of possible combination of collision between objects, such as: object A vs object B = object B vs A; object A vs object C = object C vs A; object A vs object D = object D vs A; and so on ... Do we need to create callback methods for all single type of collision? and do we need to create the same method twice? Like, say a bullet hits a wall, now I need a method to penetrate the wall for the wall, and a method to destroy the bullet for the bullet!! At the same time, a bullet can hit many objects in the game, and hence, more different callback methods!!! Is there a design pattern for that?

    Read the article

  • Using extension methods to decrease the surface area of a C# interface

    - by brian_ritchie
    An interface defines a contract to be implemented by one or more classes.  One of the keys to a well-designed interface is defining a very specific range of functionality. The profile of the interface should be limited to a single purpose & should have the minimum methods required to implement this functionality.  Keeping the interface tight will keep those implementing the interface from getting lazy & not implementing it properly.  I've seen too many overly broad interfaces that aren't fully implemented by developers.  Instead, they just throw a NotImplementedException for the method they didn't implement. One way to help with this issue, is by using extension methods to move overloaded method definitions outside of the interface. Consider the following example: .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: Consolas, "Courier New", Courier, Monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } 1: public interface IFileTransfer 2: { 3: void SendFile(Stream stream, Uri destination); 4: } 5:   6: public static class IFileTransferExtension 7: { 8: public static void SendFile(this IFileTransfer transfer, 9: string Filename, Uri destination) 10: { 11: using (var fs = File.OpenRead(Filename)) 12: { 13: transfer.SendFile(fs, destination); 14: } 15: } 16: } 17:   18: public static class TestIFileTransfer 19: { 20: static void Main() 21: { 22: IFileTransfer transfer = new FTPFileTransfer("user", "pass"); 23: transfer.SendFile(filename, new Uri("ftp://ftp.test.com")); 24: } 25: } In this example, you may have a number of overloads that uses different mechanisms for specifying the source file. The great part is, you don't need to implement these methods on each of your derived classes.  This gives you a better interface and better code reuse.

    Read the article

  • Identifying methods with a specified Id in D [migrated]

    - by Ekyo777
    I want to have specific methods with a specific pattern recognized at compile time and registered along with a specified id trough mixins in a parent class. ex.: take a method 'X' from a class with a predetermined id:5, what I want is that, in a mixin in a parent class, method X will be registered as a delegate with its id to be called later on by its id. What would be the best way to specify the Id considering I want the id to be of type int and only the specified methods to be registered? should I (if it is even possible) do it with a custom annotation pretty much like the @property but with an argument, like: @autoregister(id) void method(...) if it is possible to do it this way, an example or a link to the documentation on how to do it would be nice since I didn't find it in the documentation.

    Read the article

  • using static methods and classes

    - by vedant1811
    I know that static methods/variables are associated with the class and not the objects of the class and are useful in situations when we need to keep count of, say the number of objects of the class that were created. Non-static members on the other hand may need to work on the specific object (i.e. to use the variables initialized by the constructor) My question what should we do when we need neither of the functionalities? Say I just need a utility function that accepts value(s) and returns a value besed solely on the values passed. I want to know whether such methods should be static or not. How is programming efficiency affected and which is a better coding practice/convention and why. PS: I don't want to spark off a debate, I just want a subjective answer and/or references.

    Read the article

  • How do I assign a number value to a non-numerical value in Excel

    - by Keyslinger
    Greetings I have an some survey responses with values like "VU" for "Very Unlikely" and "S" for Sometimes. Each survey response occupies a cell. For each cell containing a survey response, I want to fill another cell with a corresponding number. For example, for every cell containing "VU" I want to fill a corresponding cell with the number 1. How is this done?

    Read the article

  • Excel Pivot Tables -- Divide Numerical Column Data into Ranges

    - by ktm5124
    Hi, I have an Excel spreadsheet with a column called "Time Elapsed" that stores the number of days it took to complete a task. I would like to make a pivot table out of this spreadsheet where I divide the "Time Elapsed" column into ranges, e.g., how many tasks took 0 to 4 days to complete how many tasks took 5 to 9 days how many took 10 to 14 days how many took 15+ days Do I have to create new columns in my spreadsheet dedicated to each interval (0 to 4, 5 to 9, etc.) or can I use some feature of pivot tables to separate my one "Time Elapsed" column into intervals? Thanks in advance.

    Read the article

  • Access element in json having numerical index

    - by hunt
    i have following format of json in which i want to asscess 0.4 , kem , 2 , 2000 values but it seems it doesn't have name index so how one can access it in jquery. when i paste following code in json viewer then i am getting numerical index for 0.4 , kem , 2 "td": [ { "@attributes": { "class": "odd" }, "span": [ "3", "7" ] }, "0.4", "Kem", "24\/04\/2010", "2000", "2", "14000", "Good", "Buckley", "56.0", "2:05.32", "36.65", "54.5" ] }

    Read the article

< Previous Page | 3 4 5 6 7 8 9 10 11 12 13 14  | Next Page >