Search Results

Search found 3518 results on 141 pages for 'arguments'.

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

  • Supervising multiple gen_servers with same module / different arguments

    - by Justin
    Hi, I have a OTP application comprising a single supervisor supervising a small number of gen_servers. A typical child specification is as follows: {my_server, {my_server, start_link, [123]}, permanent, 5000, worker, [my_server]} No problems so far. I now want to an add extra gen_server to the supervisor structure, using the same module Module/Fn as above, but different arguments, eg {my_server_2, {my_server, start_link, [123]}, permanent, 5000, worker, [my_server_2]} I thought this would work, but no: =SUPERVISOR REPORT==== 15-Apr-2010::16:50:13 === Supervisor: {local,my_sup} Context: start_error Reason: {already_started,<0.179.0>} Offender: [{pid,undefined}, {name,my_server_2}, {mfa,{my_server,start_link,[]}}, {restart_type,permanent}, {shutdown,5000}, {child_type,worker}] Do the module arguments in the second element of each child specification need to be different ? Thanks, Justin

    Read the article

  • Applying a function to an arbitrarily long list of arguments

    - by alphomega
    I want to create a function apply that takes a function with an arbitrary amount of arguments as well as a list of integers, and returns the result of the function (Where each integer in the list is an argument in order. I was thinking something like: apply :: ([Int] -> Int) -> [Int] -> Int apply f x:xs = apply (f x) xs apply f [] = f But I know this won't work because the type signature is wrong - the function doesn't take a list of ints, it just takes some amount of int arguments. Additionally, when I get to the base case the f argument to apply should actually be an integer, violating the type signature anyway. Does anyone know how to deal with this sort of problem?

    Read the article

  • changing command line arguments

    - by Shadi
    Hi, I am writing a C program. It takes its arguments from commandLine. I want to change the commandLine arguments in the code. As they are defined as "const char *", I can not change them using "strcpy", "memcpy", ... Also, you know, I can not just change their type from "const char *" to "char *". Is there any way to change them? Thank you so much in advance. Best regards, Shadi.

    Read the article

  • Moving Function With Arguments To RequireJS

    - by Jazimov
    I'm not only relatively new to JavaScript but also to RequireJS (coming from string C# background). Currently on my web page I have a number of JavaScript functions. Each one takes two arguments. Imagine that they look like this: functionA(x1, y1) { ... } functionB(x2, y2) { ... } functionC(x3, y3) { ... } Currently, these functions exist in a tag on my HTML page and I simply call each as needed. My functions have dependencies on KnockoutJS, jQuery, and some other JS libraries. I currently have Script tags that synchronously load those external .js dependencies. But I want to use RequireJS so that they're loaded asynchronously, as needed. To do this, I plan to move all three functions above into an external .js file (a type of AMD "module") called MyFunctions.js. That file will have a define() call (to RequireJS's define function) that will look something like this: define(["knockout", "jquery", ...], function("ko","jquery", ...) {???} ); My question is how to "wrap" my functionA, functionB, and functionC functions where the ??? is above so that I can use those functions on my page as needed. For example, in the onclick event handler for a button on my HTML page, I would want to call functionA and pass two it two arguments; same for functionB and functionC. I don't fully understand how to expose those functions when they're wrapped in a define that itself is located in an external .js file. I know that define assures that my listed libraries are loaded asynchronously before the callback function is called, but after that's done I don't understand how the web page's script tags would use my functions. Would I need to use require to ensure they're available, such as: require(["myfunctions"],function({not sure what to put here})] I think I understand the basics of RequireJS but I don't understand how to wrap my functions so that they're in external .js files, don't pollute the global namespace, and yet can still be called from the main page so that arguments can be passed to them. I imagine they're are many ways to do this but in reviewing the RequireJS docs and some videos out there, I can't say I understand how... Thank you for any help.

    Read the article

  • Passing arguments to a python service

    - by Grim
    Hi, I need some help with a python service. I have a service written in Python. What I need to do is to pass it some arguments. Let me give you an example to explain it a bit better. Lets say I have a service, that does nothing but writes something to a log. I'd like to write the same thing into the log several times, so I use a loop. I would like to pass the counter for the loop when I start the service, but I have no idea how. I start the service with: win32serviceutil.HandleCommandLine(WinService) I'm looking for something like win32serviceutil.HandleCommandLine(WinService,10) I don't really care how its done, as long as I can pass arguments to it. Have been trying to get this to work for the better part of the day with no luck. Also, the service isn't run directly, but is imported and then run from there.

    Read the article

  • F# - Function with no arguments?

    - by Rubys
    When thinking in a functional mindset, given that functions are supposed to be pure, one can conclude any function with no arguments is basically just a value. However, reallity gets in the way, and with different inputs, I might not need a certain function, and if that function is computationally expensive, I'd like to not evaluate it if it's not needed. I found a workaround, using let func _ = ... and calling it with func 1 or whatever, but that feels very non-idiomatic and confusing to the reader. This boils down to one question: In F#, Is there a proper way to declare a function with zero arguments, without having it evaluated on declaration?

    Read the article

  • Isses using function with variadic arguments

    - by Sausages
    I'm trying to write a logging function and have tried several different attempts at dealing with the variadic arguments, but am having problems with all of them. Here's the latest: - (void) log:(NSString *)format, ... { if (self.loggingEnabled) { va_list vl; va_start(vl, format); NSString* str = [[NSString alloc] initWithFormat:format arguments:vl]; va_end(vl); NSLog(format); } } If I call this like this: [self log:@"I like: %@", @"sausages"]; Then I get an EXC_BAD_ACCESS at the NSLog line (there's also a compiler warning that the format string is not a string literal). However if in XCode's console I do "po str" it displays "I like: sausages" so str seems ok.

    Read the article

  • NSStringWithFormat Swizzled to allow missing format numbered args

    - by coneybeare
    Based on this SO question asked a few hours ago, I have decided to implement a swizzled method that will allow me to take a formatted NSString as the format arg into stringWithFormat, and have it not break when omitting one of the numbered arg references (%1$@, %2$@) I have it working, but this is the first copy, and seeing as this method is going to be potentially called hundreds of thousands of times per app run, I need to bounce this off of some experts to see if this method has any red flags, major performance hits, or optimizations #define NUMARGS(...) (sizeof((int[]){__VA_ARGS__})/sizeof(int)) @implementation NSString (UAFormatOmissions) + (id)uaStringWithFormat:(NSString *)format, ... { if (format != nil) { va_list args; va_start(args, format); // $@ is an ordered variable (%1$@, %2$@...) if ([format rangeOfString:@"$@"].location == NSNotFound) { //call apples method NSString *s = [[[NSString alloc] initWithFormat:format arguments:args] autorelease]; va_end(args); return s; } NSMutableArray *newArgs = (NSMutableArray *)[NSMutableArray arrayWithCapacity:NUMARGS(args)]; id arg = nil; int i = 1; while (arg = va_arg(args, id)) { NSString *f = (NSString *)[NSString stringWithFormat:@"%%%d\$\@", i]; i++; if ([format rangeOfString:f].location == NSNotFound) continue; else [newArgs addObject:arg]; } va_end(args); char *newArgList = (char *)malloc(sizeof(id) * [newArgs count]); [newArgs getObjects:(id *)newArgList]; NSString* result = [[[NSString alloc] initWithFormat:format arguments:newArgList] autorelease]; free(newArgList); return result; } return nil; } The basic algorithm is: search the format string for the %1$@, %2$@ variables by searching for %@ if not found, call the normal stringWithFormat and return else, loop over the args if the format has a position variable (%i$@) for position i, add the arg to the new arg array else, don't add the arg take the new arg array, convert it back into a va_list, and call initWithFormat:arguments: to get the correct string. The idea is that I would run all [NSString stringWithFormat:] calls through this method instead. This might seem unnecessary to many, but click on to the referenced SO question (first line) to see examples of why I need to do this. Ideas? Thoughts? Better implementations? Better Solutions?

    Read the article

  • Too many argumants for function

    - by Stas Kurilin
    I'm starting learning Lisp with Java background. In SICP's exercise there is many tasks where students should create abstract functions with many parameters, like (define (filtered-accumulate combiner null-value term a next b filter)...) in exercise 3.11. In Java (language with safe, static typing discipline) - method with more than 4 arguments usually smells, but in Lisp/Scheme it doesnt, does it? I'm wandering how many arguments do you use in you functions? If you use it in production, do you make such many layers?

    Read the article

  • Naming Optional Parameters in VSB

    - by SteveNeedsSheetNames
    In Visual Basic, I have Functions with a lot of Optional arguments. I would like to be able to pass just a few of these Optional arguments to a Function without having to use numerous commas and spaces to get to the ones I want. Somewhere I saw a way to name params such as OptVar:=val, but that does not seem to work. Just wondering if there is a way to do this. This would help readability. Thanks in advance for the replies.

    Read the article

  • JS function returning another function

    - by Michael
    I want to understand about variables, that has been used in returning function. This is example code Prototype = {} Prototype.F = { bind: function() { var args = arguments, __method = args.shift(), object = args.shift(); return function() { return __method.apply(object, args.concat(arguments)); } } } function ObjectA() { ... this.addListener = Prototype.F.bind(this.eventSource.addListener, this.eventSource); ... } var a = ObjectA(); a.addListener(this); // assuming 'this' here will point to some window object As I understand the returning function in F() is not evaluated until it's called in the last line. It's ok to accept. So addListener will hold a function body containing 'apply'. But what I don't understand, when addListener is called, what kind of parameters it is going to have? particularly _method and args will always be uninitialized?

    Read the article

  • Accessing variable from ARGV

    - by snaken
    I'm writing a cPanel postwwwact script, if you're not familiar with the script its run after a new account is created. it relies on the user account variable being passed to the script which i then use for various things (creating databases etc). However, I can't seem to find the right way to access the variable i want. I'm not that good with shell scripts so i'd appreciate some advice. I had read somewhere that the value i wanted would be included in $ARGV{'user'} but this simply gives "root" as opposed to the value i need. I've tried looping through all the arguments (list of arguments here) like this: #!/bin/sh for var do touch /root/testvars/$var done and the value i want is in there, i'm just not sure how to accurately target it. There's info here on doing this with PHP or Perl but i have to do this as a shell script. EDIT Ideally i would like to be able to call the variable by something other than $1 or $2 etc as this would create issues if an argument is added or removed Any ideas?

    Read the article

  • Removing final bash script argument

    - by ctuffli
    I'm trying to write a script that searches a directory for files and greps for a pattern. Something similar to the below except the find expression is much more complicated (excludes particular directories and files). #!/bin/bash if [ -d "${!#}" ] then path=${!#} else path="." fi find $path -print0 | xargs -0 grep "$@" Obviously, the above doesn't work because "$@" still contains the path. I've tried variants of building up an argument list by iterating over all the arguments to exclude path such as args=${@%$path} find $path -print0 | xargs -0 grep "$path" or whitespace="[[:space:]]" args="" for i in "${@%$path}" do # handle the NULL case if [ ! "$i" ] then continue # quote any arguments containing white-space elif [[ $i =~ $whitespace ]] then args="$args \"$i\"" else args="$args $i" fi done find $path -print0 | xargs -0 grep --color "$args" but these fail with quoted input. For example, # ./find.sh -i "some quoted string" grep: quoted: No such file or directory grep: string: No such file or directory Note that if $@ doesn't contain the path, the first script does do what I want.

    Read the article

  • Constructing a function call in C

    - by 0x6adb015
    Given that I have a pointer to a function (provided by dlsym() for example) and a linked list of typed arguments, how can I construct a C function call with those arguments? Example: struct param { enum type { INT32, INT64, STRING, BOOL } type; union { int i32; long long i64; char *str; bool b; } value; struct param *next; }; int call_this(int (*function)(), struct param *args) { int result; /* magic here that calls function(), which has a prototype of f(int, long long, char *, bool); , when args consist of a linked list of INT32, INT64, STRING, BOOL types. */ return result; } The OS is Linux. I would like the solution to be portable across MIPS, PPC and x86 (all 32 bits) architecture, using GCC as the compiler. Thanks!

    Read the article

  • Python, unit test - Pass command line arguments to setUp of unittest.TestCase

    - by sberry2A
    I have a script that acts as a wrapper for some unit tests written using the Python unittest module. In addition to cleaning up some files, creating an output stream and generating some code, it loads test cases into a suite using unittest.TestLoader().loadTestsFromTestCase() I am already using optparse to pull out several command-line arguments used for determining the output location, whether to regenerate code and whether to do some clean up. I also want to pass a configuration variable, namely an endpoint URI, for use within the test cases. I realize I can add an OptionParser to the setUp method of the TestCase, but I want to instead pass the option to setUp. Is this possible using loadTestsFromTestCase()? I can iterate over the returned TestSuite's TestCases, but can I manually call setUp on the TestCases? ** EDIT ** I wanted to point out that I am able to pass the arguments to setUp if I iterate over the tests and call setUp manually like: (options, args) = op.parse_args() suite = unittest.TestLoader().loadTestsFromTestCase(MyTests.TestSOAPFunctions) for test in suite: test.setUp(options.soap_uri) However, I am using xmlrunner for this and its run method takes a TestSuite as an argument. I assume it will run the setUp method itself, so I would need the parameters available within the XMLTestRunner. I hope this makes sense.

    Read the article

  • CreateProcess doesn't pass command line arguments

    - by mnh
    Hello I have the following code but it isn't working as expected, can't figure out what the problem is. Basically, I'm executing a process (a .NET process) and passing it command line arguments, it is executed successfully by CreateProcess() but CreateProcess() isn't passing the command line arguments What am I doing wrong here?? int main(int argc, char* argv[]) { PROCESS_INFORMATION ProcessInfo; //This is what we get as an [out] parameter STARTUPINFO StartupInfo; //This is an [in] parameter ZeroMemory(&StartupInfo, sizeof(StartupInfo)); StartupInfo.cb = sizeof StartupInfo ; //Only compulsory field LPTSTR cmdArgs = "[email protected]"; if(CreateProcess("D:\\email\\smtp.exe", cmdArgs, NULL,NULL,FALSE,0,NULL, NULL,&StartupInfo,&ProcessInfo)) { WaitForSingleObject(ProcessInfo.hProcess,INFINITE); CloseHandle(ProcessInfo.hThread); CloseHandle(ProcessInfo.hProcess); printf("Yohoo!"); } else { printf("The process could not be started..."); } return 0; } EDIT: Hey one more thing, if I pass my cmdArgs like this: // a space as the first character LPTSTR cmdArgs = " [email protected]"; Then I get the error, then CreateProcess returns TRUE but my target process isn't executed. Object reference not set to an instance of an object

    Read the article

  • nasm/yasm arguments, linkage to C++

    - by arionik
    Hello everybody, I've got a question concerning nasm and its linkage to C++. I declare a litte test function as extern "C" void __cdecl myTest( byte i1, byte i2, int stride, int *width ); and I call it like this: byte i1 = 1, i2 = 2; int stride = 3, width = 4; myTest( i1, i2, stride, &width ); the method only serves to debug assembly and have a look at how the stack pointer is used to get the arguments. beyond that, the pointer arguments value shall be set to 7, to figure out how that works. This is implemented like this: global _myTest _myTest: mov eax, [esp+4] ; 1 mov ebx, [esp+8] ; 2 mov ecx, dword [esp+16] ; width mov edx, dword [esp+12] ; stride mov eax, dword [esp+16] mov dword [eax], 7 ret and compiled via yasm -f win32 -g cv8 -m x86 -o "$(IntDir)\$(InputName).obj" "$(InputPath)" , then linked to the c++ app. In debug mode, everything works fine. the function is called a couple of times and works as expected, whereas in release mode the function works once, but subsequent programm operations fail. It seems to me that something's wrong with stack/frame pointers, near/far, but I'm quite new to this subject and need a little help. thanks in advance! a.

    Read the article

  • Nusphere PHPEd: PHP Function Hints Lost Arguments?

    - by Eli
    Hi All, My PHPEd suddenly stopped showing arguments and arg order in the hints, and now just shows a basic description of the function. Before I go digging around in the config files, has anyone else had this problem? Thanks! Edit: Sorry, I may not have been entirely clear on this. There is no problem with my own classes, only with the actual php functions. Example: How it used to work: I type a PHP function, say strpos. As soon as I type the '(' at the end of it, I get the little yellow box, showing something like this: int strpos ( string $haystack , mixed $needle [, int $offset=0 ] ) with the first argument bold. If I type it, and then a comma, it bolds the second arg, and so on. This is really nice, since PHP functions are a bit scrambled as far as argument order, and I don't have to look them up every time. How it works now: I type a php function, say strpos. As soon as I type the '(' at the end of it, I get the little yellow box. It says something like "strpos - Returns the numeric position of the first occurrence of needle in the haystack string." There are no arguments shown, which makes the little box basically worthless - I know what strpos does, I just want a reminder of the argument order. I think this may be a problem with the included PHPDoc, which I never use, but may be the source of the data for the hint box. I did recently upgrade to 5.6, but ended up removing it and restoring 5.2. I installed to a different folder, and uninstalled from there, but it may have overwritten something in the original folder? I'm using v5.2 (5220). Thanks!

    Read the article

  • C# 4.0 'dynamic' doesn't set ref/out arguments

    - by Buu Nguyen
    I'm experimenting with DynamicObject. One of the things I try to do is setting the values of ref/out arguments, as shown in the code below. However, I am not able to have the values of i and j in Main() set properly (even though they are set correctly in TryInvokeMember()). Does anyone know how to call a DynamicObject object with ref/out arguments and be able to retrieve the values set inside the method? class Program { static void Main(string[] args) { dynamic proxy = new Proxy(new Target()); int i = 10; int j = 20; proxy.Wrap(ref i, ref j); Console.WriteLine(i + ":" + j); // Print "10:20" while expect "20:10" } } class Proxy : DynamicObject { private readonly Target target; public Proxy(Target target) { this.target = target; } public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) { int i = (int) args[0]; int j = (int) args[1]; target.Swap(ref i, ref j); args[0] = i; args[1] = j; result = null; return true; } } class Target { public void Swap(ref int i, ref int j) { int tmp = i; i = j; j = tmp; } }

    Read the article

  • Invoking a method overloaded where all arguments implement the same interface

    - by double07
    Hello, My starting point is the following: - I have a method, transform, which I overloaded to behave differently depending on the type of arguments that are passed in (see transform(A a1, A a2) and transform(A a1, B b) in my example below) - All these arguments implement the same interface, X I would like to apply that transform method on various objects all implementing the X interface. What I came up with was to implement transform(X x1, X x2), which checks for the instance of each object before applying the relevant variant of my transform. Though it works, the code seems ugly and I am also concerned of the performance overhead for evaluating these various instanceof and casting. Is that transform the best I can do in Java or is there a more elegant and/or efficient way of achieving the same behavior? Below is a trivial, working example printing out BA. I am looking for examples on how to improve that code. In my real code, I have naturally more implementations of 'transform' and none are trivial like below. public class A implements X { } public class B implements X { } interface X { } public A transform(A a1, A a2) { System.out.print("A"); return a2; } public A transform(A a1, B b) { System.out.print("B"); return a1; } // Isn't there something better than the code below??? public X transform(X x1, X x2) { if ((x1 instanceof A) && (x2 instanceof A)) { return transform((A) x1, (A) x2); } else if ((x1 instanceof A) && (x2 instanceof B)) { return transform((A) x1, (B) x2); } else { throw new RuntimeException("Transform not implemented for " + x1.getClass() + "," + x2.getClass()); } } @Test public void trivial() { X x1 = new A(); X x2 = new B(); X result = transform(x1, x2); transform(x1, result); }

    Read the article

  • New features of C# 4.0

    This article covers New features of C# 4.0. Article has been divided into below sections. Introduction. Dynamic Lookup. Named and Optional Arguments. Features for COM interop. Variance. Relationship with Visual Basic. Resources. Other interested readings… 22 New Features of Visual Studio 2008 for .NET Professionals 50 New Features of SQL Server 2008 IIS 7.0 New features Introduction It is now close to a year since Microsoft Visual C# 3.0 shipped as part of Visual Studio 2008. In the VS Managed Languages team we are hard at work on creating the next version of the language (with the unsurprising working title of C# 4.0), and this document is a first public description of the planned language features as we currently see them. Please be advised that all this is in early stages of production and is subject to change. Part of the reason for sharing our plans in public so early is precisely to get the kind of feedback that will cause us to improve the final product before it rolls out. Simultaneously with the publication of this whitepaper, a first public CTP (community technology preview) of Visual Studio 2010 is going out as a Virtual PC image for everyone to try. Please use it to play and experiment with the features, and let us know of any thoughts you have. We ask for your understanding and patience working with very early bits, where especially new or newly implemented features do not have the quality or stability of a final product. The aim of the CTP is not to give you a productive work environment but to give you the best possible impression of what we are working on for the next release. The CTP contains a number of walkthroughs, some of which highlight the new language features of C# 4.0. Those are excellent for getting a hands-on guided tour through the details of some common scenarios for the features. You may consider this whitepaper a companion document to these walkthroughs, complementing them with a focus on the overall language features and how they work, as opposed to the specifics of the concrete scenarios. C# 4.0 The major theme for C# 4.0 is dynamic programming. Increasingly, objects are “dynamic” in the sense that their structure and behavior is not captured by a static type, or at least not one that the compiler knows about when compiling your program. Some examples include a. objects from dynamic programming languages, such as Python or Ruby b. COM objects accessed through IDispatch c. ordinary .NET types accessed through reflection d. objects with changing structure, such as HTML DOM objects While C# remains a statically typed language, we aim to vastly improve the interaction with such objects. A secondary theme is co-evolution with Visual Basic. Going forward we will aim to maintain the individual character of each language, but at the same time important new features should be introduced in both languages at the same time. They should be differentiated more by style and feel than by feature set. The new features in C# 4.0 fall into four groups: Dynamic lookup Dynamic lookup allows you to write method, operator and indexer calls, property and field accesses, and even object invocations which bypass the C# static type checking and instead gets resolved at runtime. Named and optional parameters Parameters in C# can now be specified as optional by providing a default value for them in a member declaration. When the member is invoked, optional arguments can be omitted. Furthermore, any argument can be passed by parameter name instead of position. COM specific interop features Dynamic lookup as well as named and optional parameters both help making programming against COM less painful than today. On top of that, however, we are adding a number of other small features that further improve the interop experience. Variance It used to be that an IEnumerable<string> wasn’t an IEnumerable<object>. Now it is – C# embraces type safe “co-and contravariance” and common BCL types are updated to take advantage of that. Dynamic Lookup Dynamic lookup allows you a unified approach to invoking things dynamically. With dynamic lookup, when you have an object in your hand you do not need to worry about whether it comes from COM, IronPython, the HTML DOM or reflection; you just apply operations to it and leave it to the runtime to figure out what exactly those operations mean for that particular object. This affords you enormous flexibility, and can greatly simplify your code, but it does come with a significant drawback: Static typing is not maintained for these operations. A dynamic object is assumed at compile time to support any operation, and only at runtime will you get an error if it wasn’t so. Oftentimes this will be no loss, because the object wouldn’t have a static type anyway, in other cases it is a tradeoff between brevity and safety. In order to facilitate this tradeoff, it is a design goal of C# to allow you to opt in or opt out of dynamic behavior on every single call. The dynamic type C# 4.0 introduces a new static type called dynamic. When you have an object of type dynamic you can “do things to it” that are resolved only at runtime: dynamic d = GetDynamicObject(…); d.M(7); The C# compiler allows you to call a method with any name and any arguments on d because it is of type dynamic. At runtime the actual object that d refers to will be examined to determine what it means to “call M with an int” on it. The type dynamic can be thought of as a special version of the type object, which signals that the object can be used dynamically. It is easy to opt in or out of dynamic behavior: any object can be implicitly converted to dynamic, “suspending belief” until runtime. Conversely, there is an “assignment conversion” from dynamic to any other type, which allows implicit conversion in assignment-like constructs: dynamic d = 7; // implicit conversion int i = d; // assignment conversion Dynamic operations Not only method calls, but also field and property accesses, indexer and operator calls and even delegate invocations can be dispatched dynamically: dynamic d = GetDynamicObject(…); d.M(7); // calling methods d.f = d.P; // getting and settings fields and properties d[“one”] = d[“two”]; // getting and setting thorugh indexers int i = d + 3; // calling operators string s = d(5,7); // invoking as a delegate The role of the C# compiler here is simply to package up the necessary information about “what is being done to d”, so that the runtime can pick it up and determine what the exact meaning of it is given an actual object d. Think of it as deferring part of the compiler’s job to runtime. The result of any dynamic operation is itself of type dynamic. Runtime lookup At runtime a dynamic operation is dispatched according to the nature of its target object d: COM objects If d is a COM object, the operation is dispatched dynamically through COM IDispatch. This allows calling to COM types that don’t have a Primary Interop Assembly (PIA), and relying on COM features that don’t have a counterpart in C#, such as indexed properties and default properties. Dynamic objects If d implements the interface IDynamicObject d itself is asked to perform the operation. Thus by implementing IDynamicObject a type can completely redefine the meaning of dynamic operations. This is used intensively by dynamic languages such as IronPython and IronRuby to implement their own dynamic object models. It will also be used by APIs, e.g. by the HTML DOM to allow direct access to the object’s properties using property syntax. Plain objects Otherwise d is a standard .NET object, and the operation will be dispatched using reflection on its type and a C# “runtime binder” which implements C#’s lookup and overload resolution semantics at runtime. This is essentially a part of the C# compiler running as a runtime component to “finish the work” on dynamic operations that was deferred by the static compiler. Example Assume the following code: dynamic d1 = new Foo(); dynamic d2 = new Bar(); string s; d1.M(s, d2, 3, null); Because the receiver of the call to M is dynamic, the C# compiler does not try to resolve the meaning of the call. Instead it stashes away information for the runtime about the call. This information (often referred to as the “payload”) is essentially equivalent to: “Perform an instance method call of M with the following arguments: 1. a string 2. a dynamic 3. a literal int 3 4. a literal object null” At runtime, assume that the actual type Foo of d1 is not a COM type and does not implement IDynamicObject. In this case the C# runtime binder picks up to finish the overload resolution job based on runtime type information, proceeding as follows: 1. Reflection is used to obtain the actual runtime types of the two objects, d1 and d2, that did not have a static type (or rather had the static type dynamic). The result is Foo for d1 and Bar for d2. 2. Method lookup and overload resolution is performed on the type Foo with the call M(string,Bar,3,null) using ordinary C# semantics. 3. If the method is found it is invoked; otherwise a runtime exception is thrown. Overload resolution with dynamic arguments Even if the receiver of a method call is of a static type, overload resolution can still happen at runtime. This can happen if one or more of the arguments have the type dynamic: Foo foo = new Foo(); dynamic d = new Bar(); var result = foo.M(d); The C# runtime binder will choose between the statically known overloads of M on Foo, based on the runtime type of d, namely Bar. The result is again of type dynamic. The Dynamic Language Runtime An important component in the underlying implementation of dynamic lookup is the Dynamic Language Runtime (DLR), which is a new API in .NET 4.0. The DLR provides most of the infrastructure behind not only C# dynamic lookup but also the implementation of several dynamic programming languages on .NET, such as IronPython and IronRuby. Through this common infrastructure a high degree of interoperability is ensured, but just as importantly the DLR provides excellent caching mechanisms which serve to greatly enhance the efficiency of runtime dispatch. To the user of dynamic lookup in C#, the DLR is invisible except for the improved efficiency. However, if you want to implement your own dynamically dispatched objects, the IDynamicObject interface allows you to interoperate with the DLR and plug in your own behavior. This is a rather advanced task, which requires you to understand a good deal more about the inner workings of the DLR. For API writers, however, it can definitely be worth the trouble in order to vastly improve the usability of e.g. a library representing an inherently dynamic domain. Open issues There are a few limitations and things that might work differently than you would expect. · The DLR allows objects to be created from objects that represent classes. However, the current implementation of C# doesn’t have syntax to support this. · Dynamic lookup will not be able to find extension methods. Whether extension methods apply or not depends on the static context of the call (i.e. which using clauses occur), and this context information is not currently kept as part of the payload. · Anonymous functions (i.e. lambda expressions) cannot appear as arguments to a dynamic method call. The compiler cannot bind (i.e. “understand”) an anonymous function without knowing what type it is converted to. One consequence of these limitations is that you cannot easily use LINQ queries over dynamic objects: dynamic collection = …; var result = collection.Select(e => e + 5); If the Select method is an extension method, dynamic lookup will not find it. Even if it is an instance method, the above does not compile, because a lambda expression cannot be passed as an argument to a dynamic operation. There are no plans to address these limitations in C# 4.0. Named and Optional Arguments Named and optional parameters are really two distinct features, but are often useful together. Optional parameters allow you to omit arguments to member invocations, whereas named arguments is a way to provide an argument using the name of the corresponding parameter instead of relying on its position in the parameter list. Some APIs, most notably COM interfaces such as the Office automation APIs, are written specifically with named and optional parameters in mind. Up until now it has been very painful to call into these APIs from C#, with sometimes as many as thirty arguments having to be explicitly passed, most of which have reasonable default values and could be omitted. Even in APIs for .NET however you sometimes find yourself compelled to write many overloads of a method with different combinations of parameters, in order to provide maximum usability to the callers. Optional parameters are a useful alternative for these situations. Optional parameters A parameter is declared optional simply by providing a default value for it: public void M(int x, int y = 5, int z = 7); Here y and z are optional parameters and can be omitted in calls: M(1, 2, 3); // ordinary call of M M(1, 2); // omitting z – equivalent to M(1, 2, 7) M(1); // omitting both y and z – equivalent to M(1, 5, 7) Named and optional arguments C# 4.0 does not permit you to omit arguments between commas as in M(1,,3). This could lead to highly unreadable comma-counting code. Instead any argument can be passed by name. Thus if you want to omit only y from a call of M you can write: M(1, z: 3); // passing z by name or M(x: 1, z: 3); // passing both x and z by name or even M(z: 3, x: 1); // reversing the order of arguments All forms are equivalent, except that arguments are always evaluated in the order they appear, so in the last example the 3 is evaluated before the 1. Optional and named arguments can be used not only with methods but also with indexers and constructors. Overload resolution Named and optional arguments affect overload resolution, but the changes are relatively simple: A signature is applicable if all its parameters are either optional or have exactly one corresponding argument (by name or position) in the call which is convertible to the parameter type. Betterness rules on conversions are only applied for arguments that are explicitly given – omitted optional arguments are ignored for betterness purposes. If two signatures are equally good, one that does not omit optional parameters is preferred. M(string s, int i = 1); M(object o); M(int i, string s = “Hello”); M(int i); M(5); Given these overloads, we can see the working of the rules above. M(string,int) is not applicable because 5 doesn’t convert to string. M(int,string) is applicable because its second parameter is optional, and so, obviously are M(object) and M(int). M(int,string) and M(int) are both better than M(object) because the conversion from 5 to int is better than the conversion from 5 to object. Finally M(int) is better than M(int,string) because no optional arguments are omitted. Thus the method that gets called is M(int). Features for COM interop Dynamic lookup as well as named and optional parameters greatly improve the experience of interoperating with COM APIs such as the Office Automation APIs. In order to remove even more of the speed bumps, a couple of small COM-specific features are also added to C# 4.0. Dynamic import Many COM methods accept and return variant types, which are represented in the PIAs as object. In the vast majority of cases, a programmer calling these methods already knows the static type of a returned object from context, but explicitly has to perform a cast on the returned value to make use of that knowledge. These casts are so common that they constitute a major nuisance. In order to facilitate a smoother experience, you can now choose to import these COM APIs in such a way that variants are instead represented using the type dynamic. In other words, from your point of view, COM signatures now have occurrences of dynamic instead of object in them. This means that you can easily access members directly off a returned object, or you can assign it to a strongly typed local variable without having to cast. To illustrate, you can now say excel.Cells[1, 1].Value = "Hello"; instead of ((Excel.Range)excel.Cells[1, 1]).Value2 = "Hello"; and Excel.Range range = excel.Cells[1, 1]; instead of Excel.Range range = (Excel.Range)excel.Cells[1, 1]; Compiling without PIAs Primary Interop Assemblies are large .NET assemblies generated from COM interfaces to facilitate strongly typed interoperability. They provide great support at design time, where your experience of the interop is as good as if the types where really defined in .NET. However, at runtime these large assemblies can easily bloat your program, and also cause versioning issues because they are distributed independently of your application. The no-PIA feature allows you to continue to use PIAs at design time without having them around at runtime. Instead, the C# compiler will bake the small part of the PIA that a program actually uses directly into its assembly. At runtime the PIA does not have to be loaded. Omitting ref Because of a different programming model, many COM APIs contain a lot of reference parameters. Contrary to refs in C#, these are typically not meant to mutate a passed-in argument for the subsequent benefit of the caller, but are simply another way of passing value parameters. It therefore seems unreasonable that a C# programmer should have to create temporary variables for all such ref parameters and pass these by reference. Instead, specifically for COM methods, the C# compiler will allow you to pass arguments by value to such a method, and will automatically generate temporary variables to hold the passed-in values, subsequently discarding these when the call returns. In this way the caller sees value semantics, and will not experience any side effects, but the called method still gets a reference. Open issues A few COM interface features still are not surfaced in C#. Most notably these include indexed properties and default properties. As mentioned above these will be respected if you access COM dynamically, but statically typed C# code will still not recognize them. There are currently no plans to address these remaining speed bumps in C# 4.0. Variance An aspect of generics that often comes across as surprising is that the following is illegal: IList<string> strings = new List<string>(); IList<object> objects = strings; The second assignment is disallowed because strings does not have the same element type as objects. There is a perfectly good reason for this. If it were allowed you could write: objects[0] = 5; string s = strings[0]; Allowing an int to be inserted into a list of strings and subsequently extracted as a string. This would be a breach of type safety. However, there are certain interfaces where the above cannot occur, notably where there is no way to insert an object into the collection. Such an interface is IEnumerable<T>. If instead you say: IEnumerable<object> objects = strings; There is no way we can put the wrong kind of thing into strings through objects, because objects doesn’t have a method that takes an element in. Variance is about allowing assignments such as this in cases where it is safe. The result is that a lot of situations that were previously surprising now just work. Covariance In .NET 4.0 the IEnumerable<T> interface will be declared in the following way: public interface IEnumerable<out T> : IEnumerable { IEnumerator<T> GetEnumerator(); } public interface IEnumerator<out T> : IEnumerator { bool MoveNext(); T Current { get; } } The “out” in these declarations signifies that the T can only occur in output position in the interface – the compiler will complain otherwise. In return for this restriction, the interface becomes “covariant” in T, which means that an IEnumerable<A> is considered an IEnumerable<B> if A has a reference conversion to B. As a result, any sequence of strings is also e.g. a sequence of objects. This is useful e.g. in many LINQ methods. Using the declarations above: var result = strings.Union(objects); // succeeds with an IEnumerable<object> This would previously have been disallowed, and you would have had to to some cumbersome wrapping to get the two sequences to have the same element type. Contravariance Type parameters can also have an “in” modifier, restricting them to occur only in input positions. An example is IComparer<T>: public interface IComparer<in T> { public int Compare(T left, T right); } The somewhat baffling result is that an IComparer<object> can in fact be considered an IComparer<string>! It makes sense when you think about it: If a comparer can compare any two objects, it can certainly also compare two strings. This property is referred to as contravariance. A generic type can have both in and out modifiers on its type parameters, as is the case with the Func<…> delegate types: public delegate TResult Func<in TArg, out TResult>(TArg arg); Obviously the argument only ever comes in, and the result only ever comes out. Therefore a Func<object,string> can in fact be used as a Func<string,object>. Limitations Variant type parameters can only be declared on interfaces and delegate types, due to a restriction in the CLR. Variance only applies when there is a reference conversion between the type arguments. For instance, an IEnumerable<int> is not an IEnumerable<object> because the conversion from int to object is a boxing conversion, not a reference conversion. Also please note that the CTP does not contain the new versions of the .NET types mentioned above. In order to experiment with variance you have to declare your own variant interfaces and delegate types. COM Example Here is a larger Office automation example that shows many of the new C# features in action. using System; using System.Diagnostics; using System.Linq; using Excel = Microsoft.Office.Interop.Excel; using Word = Microsoft.Office.Interop.Word; class Program { static void Main(string[] args) { var excel = new Excel.Application(); excel.Visible = true; excel.Workbooks.Add(); // optional arguments omitted excel.Cells[1, 1].Value = "Process Name"; // no casts; Value dynamically excel.Cells[1, 2].Value = "Memory Usage"; // accessed var processes = Process.GetProcesses() .OrderByDescending(p =&gt; p.WorkingSet) .Take(10); int i = 2; foreach (var p in processes) { excel.Cells[i, 1].Value = p.ProcessName; // no casts excel.Cells[i, 2].Value = p.WorkingSet; // no casts i++; } Excel.Range range = excel.Cells[1, 1]; // no casts Excel.Chart chart = excel.ActiveWorkbook.Charts. Add(After: excel.ActiveSheet); // named and optional arguments chart.ChartWizard( Source: range.CurrentRegion, Title: "Memory Usage in " + Environment.MachineName); //named+optional chart.ChartStyle = 45; chart.CopyPicture(Excel.XlPictureAppearance.xlScreen, Excel.XlCopyPictureFormat.xlBitmap, Excel.XlPictureAppearance.xlScreen); var word = new Word.Application(); word.Visible = true; word.Documents.Add(); // optional arguments word.Selection.Paste(); } } The code is much more terse and readable than the C# 3.0 counterpart. Note especially how the Value property is accessed dynamically. This is actually an indexed property, i.e. a property that takes an argument; something which C# does not understand. However the argument is optional. Since the access is dynamic, it goes through the runtime COM binder which knows to substitute the default value and call the indexed property. Thus, dynamic COM allows you to avoid accesses to the puzzling Value2 property of Excel ranges. Relationship with Visual Basic A number of the features introduced to C# 4.0 already exist or will be introduced in some form or other in Visual Basic: · Late binding in VB is similar in many ways to dynamic lookup in C#, and can be expected to make more use of the DLR in the future, leading to further parity with C#. · Named and optional arguments have been part of Visual Basic for a long time, and the C# version of the feature is explicitly engineered with maximal VB interoperability in mind. · NoPIA and variance are both being introduced to VB and C# at the same time. VB in turn is adding a number of features that have hitherto been a mainstay of C#. As a result future versions of C# and VB will have much better feature parity, for the benefit of everyone. Resources All available resources concerning C# 4.0 can be accessed through the C# Dev Center. Specifically, this white paper and other resources can be found at the Code Gallery site. Enjoy! span.fullpost {display:none;}

    Read the article

  • Nginx rewrite: remove .html from URL with arguments

    - by Darko
    How can i remove the .html from an url with argument? eg: http://www.domain.com/somepage.html?argument=whole&bunch=a-lot to: http://www.domain.com/somepage?argument=whole&bunch=a-lot I have tried location / { index index.html index.php; rewrite ^\.html(.*)$ $1 last; try_files $uri $uri/ @handler; expires 30d; ## Assume all files are cachable } and a bunch of other suggestions, but can't seem to make it work.... Tnx

    Read the article

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