Search Results

Search found 5279 results on 212 pages for 'optional arguments'.

Page 5/212 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Which is the better way to simulate optional parameters in Java?

    - by froadie
    I have a Java method that takes 3 parameters, and I'd like it to also have a 4th "optional" parameter. I know that Java doesn't support optional parameters directly, so I coded in a 4th parameter and when I don't want to pass it I pass null. (And then the method checks for null before using it.) I know this is kind of clunky... but the other way is to overload the method which will result in quite a bit of duplication. Which is the better way to implement optional method parameters in Java: using a nullable parameter, or overloading? And why?

    Read the article

  • NSClient++: external script with optional arguments

    - by syneticon-dj
    I am trying to define an external script which would take optional arguments in NSClient++ 0.4.1 on Windows. Following the nsclient-full.ini example code I have defined mycheck=cmd /C echo C:\mydir\myscript.ps1 %ARGS% | powershell.exe -command - which simply yields the string %ARGS% passed as the only argument to myscript.ps1, no matter what I specify in my call through NRPE (using Nagios' check_nrpe if that matters). I then tried to rewrite the definition to mycheck=cmd /C echo C:\mydir\myscript.ps1 $ARG1$ $ARG2$ | powershell.exe -command - (myscript.ps1 would take up to two arguments), which does help a bit. At least, if two arguments are provided, I can fetch them via the args[] array. The trouble starts when the call has less than two arguments - in this case the literal strings $ARG2 and $ARG1$ are passed through as arguments. Handling this case in the code of myscript.ps1 makes the whole argument processing routine ugly at best. Is there a sane way of defining optional parameters to an external script which would not pass NSClient's variable names if no parameter has been specified?

    Read the article

  • Should you declare methods using overloads or optional parameters in C# 4.0?

    - by Greg Beech
    I was watching Anders' talk about C# 4.0 and sneak preview of C# 5.0, and it got me thinking about when optional parameters are available in C# what is going to be the recommended way to declare methods that do not need all parameters specified? For example something like the FileStream class has about fifteen different constructors which can be divided into logical 'families' e.g. the ones below from a string, the ones from an IntPtr and the ones from a SafeFileHandle. FileStream(string,FileMode); FileStream(string,FileMode,FileAccess); FileStream(string,FileMode,FileAccess,FileShare); FileStream(string,FileMode,FileAccess,FileShare,int); FileStream(string,FileMode,FileAccess,FileShare,int,bool); It seems to me that this type of pattern could be simplified by having three constructors instead, and using optional parameters for the ones that can be defaulted, which would make the different families of constructors more distinct [note: I know this change will not be made in the BCL, I'm talking hypothetically for this type of situation]. What do you think? From C# 4.0 will it make more sense to make closely related groups of constructors and methods a single method with optional parameters, or is there a good reason to stick with the traditional many-overload mechanism?

    Read the article

  • How can I process command line arguments in Python?

    - by photographer
    What would be an easy expression to process command line arguments if I'm expecting anything like 001 or 999 (let's limit expectations to 001...999 range for this time), and few other arguments passed, and would like to ignore any unexpected? I understand if for example I need to find out if "debug" was passed among parameters it'll be something like that: if 'debug' in argv[1:]: print 'Will be running in debug mode.' How to find out if 009 or 575 was passed? All those are expected calls: python script.py python script.py 011 python script.py 256 debug python script.py 391 xls python script.py 999 debug pdf At this point I don't care about calls like that: python script.py 001 002 245 568 python script.py some unexpected argument python script.py 0001 python script.py 02 ...first one - because of more than one "numeric" argument; second - because of... well, unexpected arguments; third and fourth - because of non-3-digits arguments.

    Read the article

  • Memento with optional state?

    - by Korey Hinton
    EDIT: As pointed out by Steve Evers and pdr, I am not correctly implementing the Memento pattern, my design is actually State pattern. Menu Program I built a console-based menu program with multiple levels that selects a particular test to run. Each level more precisely describes the operation. At any level you can type back to go back one level (memento). Level 1: Server Type? [1] Server A [2] Server B Level 2: Server environment? [1] test [2] production Level 3: Test type? [1] load [2] unit Level 4: Data Collection? [1] Legal docs [2] Corporate docs Level 4.5 (optional): Load Test Type [2] Multi TIF [2] Single PDF Level 5: Command Type? [1] Move [2] Copy [3] Remove [4] Custom Level 6: Enter a keyword [setup, cleanup, run] Design States PROBLEM: Right now the STATES enum is the determining factor as to what state is BACK and what state is NEXT yet it knows nothing about what the current memento state is. Has anyone experienced a similar issue and found an effective way to handle mementos with optional state? static enum STATES { SERVER, ENVIRONMENT, TEST_TYPE, COLLECTION, COMMAND_TYPE, KEYWORD, FINISHED } Possible Solution (Not-flexible) In reference to my code below, every case statement in the Menu class could check the state of currentMemo and then set the STATE (enum) accordingly to pass to the Builder. However, this doesn't seem flexible very flexible to change and I'm struggling to see an effective way refactor the design. class Menu extends StateConscious { private State state; private Scanner reader; private ServerUtils utility; Menu() { state = new State(); reader = new Scanner(System.in); utility = new ServerUtils(); } // Recurring menu logic public void startPromptingLoop() { List<State> states = new ArrayList<>(); states.add(new State()); boolean redoInput = false; boolean userIsDone = false; while (true) { // get Memento from last loop Memento currentMemento = states.get(states.size() - 1) .saveMemento(); if (currentMemento == null) currentMemento = new Memento.Builder(0).build(); if (!redoInput) System.out.println(currentMemento.prompt); redoInput = false; // prepare Memento for next loop Memento nextMemento = null; STATES state = STATES.values()[states.size() - 1]; // get user input String selection = reader.nextLine(); switch (selection) { case "exit": reader.close(); return; // only escape case "quit": nextMemento = new Memento.Builder(first(), currentMemento, selection).build(); states.clear(); break; case "back": nextMemento = new Memento.Builder(previous(state), currentMemento, selection).build(); if (states.size() <= 1) { states.remove(0); } else { states.remove(states.size() - 1); states.remove(states.size() - 1); } break; case "1": nextMemento = new Memento.Builder(next(state), currentMemento, selection).build(); break; case "2": nextMemento = new Memento.Builder(next(state), currentMemento, selection).build(); break; case "3": nextMemento = new Memento.Builder(next(state), currentMemento, selection).build(); break; case "4": nextMemento = new Memento.Builder(next(state), currentMemento, selection).build(); break; default: if (state.equals(STATES.CATEGORY)) { String command = selection; System.out.println("Executing " + command + " command on: " + currentMemento.type + " " + currentMemento.environment); utility.executeCommand(currentMemento.nickname, command); userIsDone = true; states.clear(); nextMemento = new Memento.Builder(first(), currentMemento, selection).build(); } else if (state.equals(STATES.KEYWORD)) { nextMemento = new Memento.Builder(next(state), currentMemento, selection).build(); states.clear(); nextMemento = new Memento.Builder(first(), currentMemento, selection).build(); } else { redoInput = true; System.out.println("give it another try"); continue; } break; } if (userIsDone) { // start the recurring menu over from the beginning for (int i = 0; i < states.size(); i++) { if (i != 0) { states.remove(i); // remove all except first } } reader = new Scanner(System.in); this.state = new State(); userIsDone = false; } if (!redoInput) { this.state.restoreMemento(nextMemento); states.add(this.state); } } } }

    Read the article

  • Named arguments (parameters) as a readability aid

    - by Damian Mehers
    A long time ago I programmed a lot in ADA, and it was normal to name arguments when invoking a function - SomeObject.DoSomething(SomeParameterName = someValue); Now that C# supports named arguments, I'm thinking about reverting to this habit in situations where it might not be obvious what an argument means. You might argue that it should always be obvious what an argument means, but if you have a boolean argument, and callers are passing in "true" or "false" then qualifying the value with the name makes the call site more readable. contentFetcher.DownloadNote(note, manual : true); I guess I could create Enums instead of using true or false (Manual, Automatic in this case). What do you think about occasionally using named arguments to make code easier to read?

    Read the article

  • Input to program without command-line arguments

    - by Core Xii
    Let's assume that there are no command-line arguments. How do you pass input data to a program? I'm thinking you'd write the input to a file with a specific name, such that the program knows to open and read it as input. However, how would one discover the name of that file? Usually, running a command-line program without arguments or with some standard help argument (e.g. \?) produces some instruction on how to use it. But given an environment with no command-line arguments, how does one discover how to operate a program?

    Read the article

  • C#: Optional Parameters - Pros and Pitfalls

    - by James Michael Hare
    When Microsoft rolled out Visual Studio 2010 with C# 4, I was very excited to learn how I could apply all the new features and enhancements to help make me and my team more productive developers. Default parameters have been around forever in C++, and were intentionally omitted in Java in favor of using overloading to satisfy that need as it was though that having too many default parameters could introduce code safety issues.  To some extent I can understand that move, as I’ve been bitten by default parameter pitfalls before, but at the same time I feel like Java threw out the baby with the bathwater in that move and I’m glad to see C# now has them. This post briefly discusses the pros and pitfalls of using default parameters.  I’m avoiding saying cons, because I really don’t believe using default parameters is a negative thing, I just think there are things you must watch for and guard against to avoid abuses that can cause code safety issues. Pro: Default Parameters Can Simplify Code Let’s start out with positives.  Consider how much cleaner it is to reduce all the overloads in methods or constructors that simply exist to give the semblance of optional parameters.  For example, we could have a Message class defined which allows for all possible initializations of a Message: 1: public class Message 2: { 3: // can either cascade these like this or duplicate the defaults (which can introduce risk) 4: public Message() 5: : this(string.Empty) 6: { 7: } 8:  9: public Message(string text) 10: : this(text, null) 11: { 12: } 13:  14: public Message(string text, IDictionary<string, string> properties) 15: : this(text, properties, -1) 16: { 17: } 18:  19: public Message(string text, IDictionary<string, string> properties, long timeToLive) 20: { 21: // ... 22: } 23: }   Now consider the same code with default parameters: 1: public class Message 2: { 3: // can either cascade these like this or duplicate the defaults (which can introduce risk) 4: public Message(string text = "", IDictionary<string, string> properties = null, long timeToLive = -1) 5: { 6: // ... 7: } 8: }   Much more clean and concise and no repetitive coding!  In addition, in the past if you wanted to be able to cleanly supply timeToLive and accept the default on text and properties above, you would need to either create another overload, or pass in the defaults explicitly.  With named parameters, though, we can do this easily: 1: var msg = new Message(timeToLive: 100);   Pro: Named Parameters can Improve Readability I must say one of my favorite things with the default parameters addition in C# is the named parameters.  It lets code be a lot easier to understand visually with no comments.  Think how many times you’ve run across a TimeSpan declaration with 4 arguments and wondered if they were passing in days/hours/minutes/seconds or hours/minutes/seconds/milliseconds.  A novice running through your code may wonder what it is.  Named arguments can help resolve the visual ambiguity: 1: // is this days/hours/minutes/seconds (no) or hours/minutes/seconds/milliseconds (yes) 2: var ts = new TimeSpan(1, 2, 3, 4); 3:  4: // this however is visually very explicit 5: var ts = new TimeSpan(days: 1, hours: 2, minutes: 3, seconds: 4);   Or think of the times you’ve run across something passing a Boolean literal and wondered what it was: 1: // what is false here? 2: var sub = CreateSubscriber(hostname, port, false); 3:  4: // aha! Much more visibly clear 5: var sub = CreateSubscriber(hostname, port, isBuffered: false);   Pitfall: Don't Insert new Default Parameters In Between Existing Defaults Now let’s consider a two potential pitfalls.  The first is really an abuse.  It’s not really a fault of the default parameters themselves, but a fault in the use of them.  Let’s consider that Message constructor again with defaults.  Let’s say you want to add a messagePriority to the message and you think this is more important than a timeToLive value, so you decide to put messagePriority before it in the default, this gives you: 1: public class Message 2: { 3: public Message(string text = "", IDictionary<string, string> properties = null, int priority = 5, long timeToLive = -1) 4: { 5: // ... 6: } 7: }   Oh boy have we set ourselves up for failure!  Why?  Think of all the code out there that could already be using the library that already specified the timeToLive, such as this possible call: 1: var msg = new Message(“An error occurred”, myProperties, 1000);   Before this specified a message with a TTL of 1000, now it specifies a message with a priority of 1000 and a time to live of -1 (infinite).  All of this with NO compiler errors or warnings. So the rule to take away is if you are adding new default parameters to a method that’s currently in use, make sure you add them to the end of the list or create a brand new method or overload. Pitfall: Beware of Default Parameters in Inheritance and Interface Implementation Now, the second potential pitfalls has to do with inheritance and interface implementation.  I’ll illustrate with a puzzle: 1: public interface ITag 2: { 3: void WriteTag(string tagName = "ITag"); 4: } 5:  6: public class BaseTag : ITag 7: { 8: public virtual void WriteTag(string tagName = "BaseTag") { Console.WriteLine(tagName); } 9: } 10:  11: public class SubTag : BaseTag 12: { 13: public override void WriteTag(string tagName = "SubTag") { Console.WriteLine(tagName); } 14: } 15:  16: public static class Program 17: { 18: public static void Main() 19: { 20: SubTag subTag = new SubTag(); 21: BaseTag subByBaseTag = subTag; 22: ITag subByInterfaceTag = subTag; 23:  24: // what happens here? 25: subTag.WriteTag(); 26: subByBaseTag.WriteTag(); 27: subByInterfaceTag.WriteTag(); 28: } 29: }   What happens?  Well, even though the object in each case is SubTag whose tag is “SubTag”, you will get: 1: SubTag 2: BaseTag 3: ITag   Why?  Because default parameter are resolved at compile time, not runtime!  This means that the default does not belong to the object being called, but by the reference type it’s being called through.  Since the SubTag instance is being called through an ITag reference, it will use the default specified in ITag. So the moral of the story here is to be very careful how you specify defaults in interfaces or inheritance hierarchies.  I would suggest avoiding repeating them, and instead concentrating on the layer of classes or interfaces you must likely expect your caller to be calling from. For example, if you have a messaging factory that returns an IMessage which can be either an MsmqMessage or JmsMessage, it only makes since to put the defaults at the IMessage level since chances are your user will be using the interface only. So let’s sum up.  In general, I really love default and named parameters in C# 4.0.  I think they’re a great tool to help make your code easier to read and maintain when used correctly. On the plus side, default parameters: Reduce redundant overloading for the sake of providing optional calling structures. Improve readability by being able to name an ambiguous argument. But remember to make sure you: Do not insert new default parameters in the middle of an existing set of default parameters, this may cause unpredictable behavior that may not necessarily throw a syntax error – add to end of list or create new method. Be extremely careful how you use default parameters in inheritance hierarchies and interfaces – choose the most appropriate level to add the defaults based on expected usage. Technorati Tags: C#,.NET,Software,Default Parameters

    Read the article

  • C++0x, How do I expand a tuple into variadic template function arguments?

    - by Gustaf
    Consider the case of a templated function with variadic template arguments: template<typename Tret, typename... T> Tret func(const T&... t); Now, I have a tuple t of values. How do I call func() using the tuple values as arguments? I've read about the bind() function object, with call() function, and also the apply() function in different some now-obsolete documents. The GNU GCC 4.4 implementation seems to have a call() function in the bind() class, but there is very little documentation on the subject. Some people suggest hand-written recursive hacks, but the true value of variadic template arguments is to be able to use them in cases like above. Does anyone have a solution to is, or hint on where to read about it?

    Read the article

  • How to handle optional variables of an object in Java?

    - by Arvanem
    Hi folks, For my trading program, I have a Merchant class. A given Merchant object may or may not have a particular special quality or bundle of special qualities. For example, one Merchant object may have the Stockbroker quality, another Merchant may have the Financial Services and Stockbroker qualities, and another Merchant may have no special qualities at all. My initial thought was to create a HashMap and a Qualities class as follows: Map<Qualities, Boolean> merchantQualities = new HashMap<Qualities, Boolean>(); The only problem is, there are at least 50 possible special qualities for Merchants, such that it would be extremely tiresome to subclass all the qualities from the Quality class. Is there a better way of coding for these optional special qualities and representing them in the Merchants class than a HashMap and subclassing a Qualities class?

    Read the article

  • grep - what arguments do you usually specify?

    - by meder
    My most common grep line is just.. grep -IRl "text" * However I'm kinda getting tired of retyping this over and over - is there some way I can make an alias command so that those arguments are always enabled? And, I was wondering what arguments you usually specify for text searching - my two arguments 'R' for recursion, 'I' for not including binary types like jpg/gif, and 'l' for line number seem a bit too minimal. Which arguments do you use?

    Read the article

  • C# 4.0: Can I use a Color as an optional parameter with a default value?

    - by DTown
    public void log(String msg, Color c = Color.black) { loggerText.ForeColor = c; loggerText.AppendText("\n" + msg); } This results in an error that c must be a compile-time constant. I've read up on this a little and most examples are dealing with strings and ints. I've figured out I can use the colorconverter class but I'm not sure it will be very efficient. Is there a way to just pass a basic color as an optional parameter? public void log(String msg, String c = "Black") { ColorConverter conv = new ColorConverter(); Color color = (Color)conv.ConvertFromString(c); loggerText.ForeColor = color; loggerText.AppendText("\n" + msg); }

    Read the article

  • Cannot use String.Empty as a default value for an optional parameter in C# - then what's the point?

    - by Mikeyg36
    I am reading Effective C# by Bill Wagner. In Item 14 - Minimize Duplicate Initialization Logic, he shows the following example of using the new optional parameters feature in a constructor: public MyClass(int initialCount = 0, string name = "") Notice that he used "" instead of string.Empty. He comments: You'll note [in an example above] that the second constructor specified "" for the default value on the name parameter, rather than the more customary string.Empty. That's because string.Empty is not a compile-time constant. It is a static property defined in the string class. Because it is not a compile constant, you cannot use it for the default value for a parameter. If we cannot use the string.Empty static in all situations, then doesn't that defeat the purpose of it? I thought that we would use it to be sure that we have a system-independent means of referring to the empty string. Is my understanding wrong? Thanks.

    Read the article

  • Get a list/tuple/dict of the arguments passed to a function?

    - by digitala
    Given the following function: def foo(a, b, c): pass How would one obtain a list/tuple/dict/etc of the arguments passed in, without having to build the structure myself? Specifically, I'm looking for Python's version of JavaScript's arguments keyword or PHP's func_get_args() method. What I'm not looking for is a solution using *args or **kwargs; I need to specify the argument names in the function definition (to ensure they're being passed in) but within the function I want to work with them in a list- or dict-style structure.

    Read the article

  • Get a list/tuple/dict of *all* the arguments passed to a function?

    - by Phillip Oldham
    Given the following function: def foo(a, b, c): pass How would one obtain a list/tuple/dict/etc of the arguments passed in? Specifically, I'm looking for Python's version of JavaScript's arguments keyword or PHP's func_get_args() method. What I'm not looking for is a solution using *args or **kwargs; I need to specify the argument names in the function definition (to ensure they're being passed in) but within the function I want to work with them in a list- or dict-style structure.

    Read the article

  • C# Adds Optional and Named Arguments

    Earlier this month Microsoft released Visual Studio 2010, the .NET Framework 4.0 (which includes ASP.NET 4.0), and new versions of their core programming languages: C# 4.0 and Visual Basic 10. In designing the latest versions of C# and VB, Microsoft has worked to bring the two languages into closer parity. Certain features available in C# were missing in VB, and vice-a-versa. Last week I wrote about <a href="http://www.4guysfromrolla.com/articles/042110-1.aspx">Visual Basic 2010's language enhancements</a>, which include implicit line continuation, auto-implemented properties, and collection initializers - three useful features that were available in previous versions of C#. Similarly, C# 4.0 introduces new features to the C# programming language that were

    Read the article

  • .htaccess URL rewriting friendly URL with 2 parameters, the second parameter is optional

    - by letsworktogether
    I'm kind of stuck at this part and was hoping that I'd get some assistance. I'm building a highscores page in PHP, that's going great, it works. However, I dislike the idea of index.php?skill=name and therefore wanted a bit of SEO in this. I have successfully replaced the url with a more friendly version: highscores/skill/name And this is where the problem starts, I have added pagination to the highscores and the page is read from the HTTP_GET page variable ($_GET['page']). I dislike the idea of highscores/skill/name&page=2 and was hoping if you guys could assist me to make the url like the following: Page 1, so accessing the file without declaring the page number: DOMAIN.TLD/highscores/skill/name Page 1 so now the page variable is needed: DOMAIN.TLD/highscores/skill/name/2 As you can tell the "2" will define page 2 and load the correct data for page 2. However, I'm having much trouble in my .htaccess file to configure it this way. RewriteRule ^highscores\/skill\/(.*?)(\/(.*?)*)$ highscores/skills.php?skill=$1&page=$2 [L] # Skills page That is my latest attempt in order to get it to work, unfortunately it does not work, it makes the page look horrible (CSS doesn't work) and it doesn't go to the page specified on the URL.

    Read the article

  • Arguments for or against using Try/Catch as logical operators

    - by James P. Wright
    I just discovered some lovely code in our companies app that uses Try-Catch blocks as logical operators. Meaning, "do some code, if that throws this error, do this code, but if that throws this error do this 3rd thing instead". It uses "Finally" as the "else" statement it appears. I know that this is wrong inherently, but before I go picking a fight I was hoping for some well thought out arguments. And hey, if you have arguments FOR the use of Try-Catch in this manner, please do tell. EDIT For any who are wondering, the language is C# and the code in question is about 30+ lines and is looking for specific exceptions, it is not handling ALL exceptions.

    Read the article

  • Handling optional GPL dependencies

    - by pmr
    Assume I have a library A which is licensed under a two-clause Free BSD style license. Library A optionally depends on library B (the availability of the dependency is configured at build-time), which is licensed under the GPLv3. If I distribute both bundled together, the license will need to be GPL. But am I still able to distribute library A under the FreeBSD license? How do I indicate that the license changes, when the use of library B is enabled? Do I need to distribute two different versions or can I just have one that contains both licenses and states which applies under which conditions? Any example project I can have a look at to see it done?

    Read the article

  • How to hide process arguments from other users?

    - by poolie
    A while ago, I used to use the grsecurity kernel patches, which had an option to hide process arguments from other non-root users. Basically this just made /proc/*/cmdline be mode 0600, and ps handles that properly by showing that the process exists but not its arguments. This is kind of nice if someone on a multiuser machine is running say vi christmas-presents.txt, to use the canonical example. Is there any supported way to do this in Ubuntu, other than by installing a new kernel? (I'm familiar with the technique that lets individual programs alter their argv, but most programs don't do that and anyhow it is racy. This stackoverflow user seems to be asking the same question, but actually just seems very confused.)

    Read the article

  • How to hide process arguments from other users?

    - by poolie
    A while ago, I used to use the grsecurity kernel patches, which had an option to hide process arguments from other non-root users. Basically this just made /proc/*/cmdline be mode 0600, and ps handles that properly by showing that the process exists but not its arguments. This is kind of nice if someone on a multiuser machine is running say vi christmas-presents.txt, to use the canonical example. Is there any supported way to do this in Ubuntu, other than by installing a new kernel? (I'm familiar with the technique that lets individual programs alter their argv, but most programs don't do that and anyhow it is racy. This stackoverflow user seems to be asking the same question, but actually just seems very confused.)

    Read the article

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