Search Results

Search found 50594 results on 2024 pages for 'dynamic class loaders'.

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

  • 7 drived classes with one common base class

    - by user144905
    i have written the following code, //main.cpp #include<iostream> #include<string> #include"human.h" #include"computer.h" #include"referee.h" #include"RandomComputer.h" #include"Avalanche.h" #include"Bureaucrat.h" #include"Toolbox.h" #include"Crescendo.h" #include"PaperDoll.h" #include"FistfullODollors.h" using namespace std; int main() { Avalanche pla1; Avalanche pla2; referee f; pla1.disp(); for (int i=0;i<5;i++) { cout<<pla2.mov[i]; } return 0; } in this program all included classes except referee.h and human.h are drived from computer.h. each drived calls has a char array variable which is initialized when a member of a drived class is declared. the problem is that when i declare tow diffrent drived class memebers lets say Avalache and ToolBox. upon printing the char array for one of them using for loop it prints nothing. However if i declare only one of them in main.cpp the it works properly. and the file for computer.h is as such: #ifndef COMPUTER_H #define COMPUTER_H class computer { public: int nump; char mov[]; void disp(); }; #endif ToolBox.h is like this: #ifndef TOOLBOX_H #define TOOLBOX_H #include"computer.h" class Toolbox: public computer { public: Toolbox(); }; #endif finally Avalanche.h is as following: #ifndef AVALANCHE_H #define AVALANCHE_H #include"computer.h" class Avalanche: public computer { public: Avalanche(); }; #endif

    Read the article

  • Using "public" vars or attributes in class calls, functional approach

    - by marw
    I was always wondering about two things I tend to do in my little projects. Sometimes I will have this design: class FooClass ... self.foo = "it's a bar" self._do_some_stuff(self) def _do_some_stuff(self): print(self.foo) And sometimes this one: class FooClass2 ... self.do_some_stuff(foo="it's a bar") def do_some_stuff(self, foo): print(foo) Although I roughly understand the differences between functional and class approaches, I struggle with the design. For example, in FooClass the self.foo is always accessible as an attribute. If there are numerous calls to it, is that faster than making foo a local variable that is passed from method to method (like in FooClass2)? What happens in memory in both cases? If FooClass2 is preferred (ie. I don't need to access foo) and other attributes inside do not change their states (the class is executed once only and returns the result), should the code then be written as a series of functions in a module?

    Read the article

  • Nested class or not nested class?

    - by eriks
    I have class A and list of A objects. A has a function f that should be executed every X seconds (for the first instance every 1 second, for the seconds instance every 5 seconds, etc.). I have a scheduler class that is responsible to execute the functions at the correct time. What i thought to do is to create a new class, ATime, that will hold ptr to A instance and the time A::f should be executed. The scheduler will hold a min priority queue of Atime. Do you think it is the correct implementation? Should ATime be a nested class of the scheduler?

    Read the article

  • C++ threaded class design from non-threaded class

    - by macs
    I'm working on a library doing audio encoding/decoding. The encoder shall be able to use multiple cores (i.e. multiple threads, using boost library), if available. What i have right now is a class that performs all encoding-relevant operations. The next step i want to take is to make that class threaded. So i'm wondering how to do this. I thought about writing a thread-class, creating n threads for n cores and then calling the encoder with the appropriate arguments. But maybe this is an overkill and there is no need for another class, so i'm going to make use of the "user interface" for thread-creation. I hope there are any suggestions.

    Read the article

  • Include a Class in another model / class / lib

    - by jaycode
    I need to use function "image_path" in my lib class. I tried this (and couple of other variations): class CustomHelpers::Base include ActionView::Helpers::AssetTagHelper def self.image_url(source) abs_path = image_path(source) unless abs_path =~ /^http/ abs_path = "#{request.protocol}#{request.host_with_port}#{abs_path}" end abs_path end end But it didn't work. Am I doing it right? Another question is, how do I find the right class to include? For example if I look at this module: http://api.rubyonrails.org/classes/ActionView/Helpers/AssetTagHelper.html is there a rule of thumb how to include that module in a model / library / class / anything else ?

    Read the article

  • How to call a method from another class that's been instantiated within the current class

    - by Pavan
    my screen has a few views like such __________________ | _____ | | | | | //viewX is a video screen | | | | | viewX | vY | | //viewY is a custom uiview i created. | |____| | //it contains a method which i would like to call that toggles |_________________| //the hidden property of this view. and when it hides, a little | | //button is replaced no the top right corner on top of viewX | viewZ | //the video layer | | |_________________| //viewZ is a view containing many square views - thumbnails. my question is, i dont know how to register for touch events so that it recognises any touch event on no matter which view the user touches the screen.. atm im handling the touch events for each view inside it. so all works well... however what im trying to do is that when the user taps anywhere else on the screen but on viewY, viewY should dissapear by calling that method in the viewY class. this viewY class is instantiated and has no xib file attached to it. the uiview is created progammatically in the viewY class. this whole class for viewY behviour is instantiated in viewX - the video view. my boss says add delegates.. although i have now clue how to do that... any help? is there anyway i can just make it really simple and be able to say REMOVE VIEW no matter which class im calling from? Also ive seen other people achieve this by using these funky arrows - ... <- etc.. although im not sure if thats what i need or how to implement such a thing. ah i think ive made my question quite complicated but i really mean it to be a simple one, and know it can be done in an easy way!

    Read the article

  • Use nested static class as ActionListener for the Outer class

    - by Digvijay Yadav
    I want to use an nested static class as an actionListener for the enclosing class's GUI elements. I did something like this: public class OuterClass { public static void myImplementation() { OuterClass.StartupHandler startupHandler = new OuterClass.StartupHandler(); exitMenuItem.addActionListener(startupHandler); // error Line } public static class StartupHandler implements ActionListener { @Override public void actionPerformed(ActionEvent e) { //throw new UnsupportedOperationException("Not supported yet."); if (e.getSource() == exitMenuItem) { System.exit(1); } else if (e.getSource() == helpMenuItem) { // show help menu } } } } But when I invoke this code I get the NullPointerException at the //error Line. Is this the right method to do do this or there is something I did am missing?

    Read the article

  • Thread class closing from other Class (Activity) with protected void onStop() Android

    - by user1761337
    I have a Problem with Closing the Thread. I will Closing the Thread with onStop,onPause and onDestroy. This is my Source in the Activity Class: @Override protected void onStop(){ super.onStop(); finish(); } @Override protected void onPause() { super.onPause(); finish(); } @Override public void onDestroy() { this.mWakeLock.release(); super.onDestroy(); } And the Thread Class: public class GameThread extends Thread { private SurfaceHolder mSurfaceHolder; private Handler mHandler; private Context mContext; private Paint mLinePaint; private Paint blackPaint; //for consistent rendering private long sleepTime; //amount of time to sleep for (in milliseconds) private long delay=1000/30; //state of game (Running or Paused). int state = 1; public final static int RUNNING = 1; public final static int PAUSED = 2; public final static int STOPED = 3; GameSurface gEngine; public GameThread(SurfaceHolder surfaceHolder, Context context, Handler handler,GameSurface gEngineS){ //data about the screen mSurfaceHolder = surfaceHolder; mHandler = handler; mContext = context; gEngine=gEngineS; } //This is the most important part of the code. It is invoked when the call to start() is //made from the SurfaceView class. It loops continuously until the game is finished or //the application is suspended. private long beforeTime; @Override public void run() { //UPDATE while (state==RUNNING) { Log.d("State","Thread is runnig"); //time before update beforeTime = System.nanoTime(); //This is where we update the game engine gEngine.Update(); //DRAW Canvas c = null; try { //lock canvas so nothing else can use it c = mSurfaceHolder.lockCanvas(null); synchronized (mSurfaceHolder) { //clear the screen with the black painter. //reset the canvas c.drawColor(Color.BLACK); //This is where we draw the game engine. gEngine.doDraw(c); } } finally { // do this in a finally so that if an exception is thrown // during the above, we don't leave the Surface in an // inconsistent state if (c != null) { mSurfaceHolder.unlockCanvasAndPost(c); } } this.sleepTime = delay-((System.nanoTime()-beforeTime)/1000000L); try { //actual sleep code if(sleepTime>0){ this.sleep(sleepTime); } } catch (InterruptedException ex) { Logger.getLogger(GameThread.class.getName()).log(Level.SEVERE, null, ex); } while (state==PAUSED){ Log.d("State","Thread is pausing"); try { this.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }} How i can close the Thread from Activity Class??

    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

  • 24 Hours of PASS: 15 Powerful Dynamic Management Objects - Deck and Demos

    - by Adam Machanic
    Thank you to everyone who attended today's 24 Hours of PASS webcast on Dynamic Management Objects! I was shocked, awed, and somewhat scared when I saw the attendee number peak at over 800. I really appreciate your taking time out of your day to listen to me talk. It's always interesting presenting to people I can't see or hear, so I relied on Twitter for a form of nearly real-time feedback. I would like to especially thank everyone who left me tweets both during and after the presentation. Your feedback...(read more)

    Read the article

  • 24 Hours of PASS: 15 Powerful Dynamic Management Objects - Deck and Demos

    - by Adam Machanic
    Thank you to everyone who attended today's 24 Hours of PASS webcast on Dynamic Management Objects! I was shocked, awed, and somewhat scared when I saw the attendee number peak at over 800. I really appreciate your taking time out of your day to listen to me talk. It's always interesting presenting to people I can't see or hear, so I relied on Twitter for a form of nearly real-time feedback. I would like to especially thank everyone who left me tweets both during and after the presentation. Your feedback...(read more)

    Read the article

  • Dynamic vs Statically typed languages for websites

    - by Bradford
    Wanted to hear what others thought about this statement: I’ll contrast that with building a website. When rendering web pages, often you have very many components interacting on a web page. You have buttons over here and little widgets over there and there are dozens of them on a webpage, as well as possibly dozens or hundreds of web pages on your website that are all dynamic. With a system with a really large surface area like that, using a statically typed language is actually quite inflexible. I would find it painful probably to program in Scala and render a web page with it, when I want to interactively push around buttons and what-not. If the whole system has to be coherent, like the whole system has to type check just to be able to move a button around, I think that can be really inflexible. Source: http://www.infoq.com/interviews/kallen-scala-twitter

    Read the article

  • Looking for a dynamic programming solution

    - by krammer
    Given a sequence of integers in range 1 to n. Each number can appear at most once. Let there be a symbol X in the sequence which means remove the minimum element from the list. There can be an arbitrarily number of X in the sequence. Example: 1,3,4,X,5,2,X The output is 1,2. We need to find the best way to perform this operation. The solution I have been thinking is: Scan the sequence from left to right and count number of X which takes O(n) time. Perform partial sorting and find the k smallest elements (k = number of X) which takes O(n+klogk) time using median of medians. Is there a better way to solve this problem using dynamic programming or any other way ?

    Read the article

  • Reason for perpetual dynamic DNS updates?

    - by mad_vs
    I'm using dynamic DNS (the "adult" version from RFC 2136, not à la DynDNS), and for a while now I've been seeing my laptops with MacOS 10.6.x churning out updates about every 10 seconds. And seemingly redundant updates at that, as the IP is more or less stable (consumer broadband). I don't remember seeing that frequency in the (distant...) past. The lowest time-to-live that MacOS pushes on the entries is 2 minutes, so I have no clue what's going on. ... Jan 12 13:17:18 lambda named[18683]: info: client 84.208.X.X#48715: updating zone 'dynamic.foldr.org/IN': deleting rrset at 'rCosinus._afpovertcp._tcp.dynamic.foldr.org' SRV Jan 12 13:17:18 lambda named[18683]: info: client 84.208.X.X#48715: updating zone 'dynamic.foldr.org/IN': adding an RR at 'rCosinus._afpovertcp._tcp.dynamic.foldr.org' SRV Jan 12 13:17:26 lambda named[18683]: info: client 84.208.X.X#48715: updating zone 'dynamic.foldr.org/IN': deleting rrset at 'rcosinus.dynamic.foldr.org' AAAA ... Additionally, I can't find out what triggers the updates on the laptop-side. Is this a known problem, and how would I go about debugging it? One of the machines is freshly purchased and installed. The only "major" change was installation of the Miredo client for IPv6/Teredo, but even disabling it didn't make a change (except that AAAA records are no longer published).

    Read the article

  • Add class to elements which already have a class

    - by bwstud
    I have a group of divs which I'm dynamically generating when a button is clicked with the class, "brick". This gives them dimension and starting position of top: 0. I'm trying to get them to animate to the bottom of the view using a css transition with a second class assignment which gives them a bottom position: 0;. Can't figure out the syntax for adding a second class to elements with a pre-existing class. On inspection they only show the original class of, "brick". HTML <!DOCTYPE html> <html> <head> <script src="http://code.jquery.com/jquery-2.1.0.min.js"></script> <meta charset="utf-8"> <title>JS Bin</title> </head> <body> <div id="container"> <div id="button" >Click Me</div> </div> </body> </html> CSS #container { width: 100%; height: 100vh; padding: 10vmax; } #button { position: fixed; } .brick { position: relative; top: 0; height: 10vmax; width: 20vmax; background: white; margin: 0; padding: 0; transition: all 1s; } .drop { transition: all 1s; bottom 0; } The offending JS: var brickCount = function() { var count = prompt("How many boxes you lookin' for?"); for(var i=0; i < count; i++) { var newBrick = document.createElement("div"); newBrick.className="brick"; document.querySelector("#container") .appendChild(newBrick); } }; var getBricks = function(){ document.getElementByClass("brick"); }; var changeColor = function(){ getBricks.style.backgroundColor = '#'+Math.floor(Math.random()*16777215).toString(16); }; var addDrop = function() { getBricks.brick = "getBricks.brick" + " drop"; }; var multiple = function() { brickCount(); getBricks(); changeColor(); addDrop(); }; document.getElementById("button").onclick = function() {multiple();}; Thanks!

    Read the article

  • PHP Changing Class Variables Outside of Class

    - by Jamie Bicknell
    Apologies for the wording on this question, I'm having difficulties explaining what I'm after, but hopefully it makes sense. Let's say I have a class, and I wish to pass a variable through one of it's methods, then I have another method which outputs this variable. That's all fine, but what I'm after is that if I update the variable which was originally passed, and do this outside the class methods, it should be reflected in the class. I've created a very basic example: class Test { private $var = ''; function setVar($input) { $this->var = $input; } function getVar() { echo 'Var = ' . $this->var . '<br />'; } } If I run $test = new Test(); $string = 'Howdy'; $test->setVar($string); $test->getVar(); I get Var = Howdy However, this is the flow I would like: $test = new Test(); $test->setVar($string); $string = 'Hello'; $test->getVar(); $string = 'Goodbye'; $test->getVar(); Expected output to be Var = Hello Var = Goodbye I don't know what the correct naming of this would be, and I've tried using references to the original variable but no luck. I've come across this in the past, with the PDO prepared statements, see Example #2 $stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (?, ?)"); $stmt->bindParam(1, $name); $stmt->bindParam(2, $value); // insert one row $name = 'one'; $value = 1; $stmt->execute(); // insert another row with different values $name = 'two'; $value = 2; $stmt->execute(); I know I can change the variable to public and do the following, but it isn't quite the same as how the PDO class handles it, and I'm really looking to mimic that behaviour. $test = new Test(); $test->setVar($string); $test->var = 'Hello'; $test->getVar(); $test->var = 'Goodbye'; $test->getVar(); Any help, ideas, pointers, or advice would be greatly appreciated, thanks.

    Read the article

  • Lightweight, dynamic, fully JavaScript web UI library recommendations

    - by Matt Greer
    I am looking for recommendations for a lightweight, dynamic, fully JavaScript UI library for websites. Doesn't have to be amazing visually, the end result is for simple demos I create. What I want can be summed up as "Ext-like, but not GPL'ed, and a much smaller footprint". I want to be able to construct UIs dynamically and fully through code. My need for this is currently driven by this particle designer. Depending on what query parameters you give it, the UI components change, example 1, example2. Currently this is written in Ext, but Ext's license and footprint are turn offs for me. I like UKI a lot, but it's not very good for dynamically building UIs since everything is absolutely positioned. Extending Uki to support that is something I am considering. Ideally the library would let me make UIs with a pattern along the lines of: var container = new SomeUI.Container(); container.add(new SomeUI.Label('Color Components')); container.add(new SomeUI.NumberField('R')); container.add(new SomeUI.NumberField('G')); container.add(new SomeUI.NumberField('B')); container.add(new SomeUI.CheckBox('Enable Alpha')); container.renderTo(someDiv);

    Read the article

  • How bad is it to have two methods with the same name but different signatures in two classes?

    - by Super User
    I have a design problem related to a public interface, the names of methods, and the understanding of my API and code. I have two classes like this: class A: ... function collision(self): .... ... class B: .... function _collision(self, another_object, l, r, t, b): .... The first class has one public method named collision, and the second has one private method called _collision. The two methods differs in argument type and number. As an example let's say that _collision checks if the object is colliding with another object with certain conditions l, r, t, b (collide on the left side, right side, etc) and returns true or false. The public collision method, on the other hand, resolves all the collisions of the object with other objects. The two methods have the same name because I think it's better to avoid overloading the design with different names for methods that do almost the same thing, but in distinct contexts and classes. Is this clear enough to the reader or I should change the method's name?

    Read the article

  • How bad it's have two methods with the same name but differents signatures in two classes?

    - by Super User
    I have a design problem relationated with the public interface, the names of methods and the understanding of my API and my code. I have two classes like this: class A: ... function collision(self): .... ... class B: .... function _collision(self, another_object, l, r, t, b): .... The first class have one public method named collision and the second have one private method called _collision. The two methods differs in arguments type and number. In the API _m method is private. For the example let's say that the _collision method checks if the object is colliding with another_ object with certain conditions l, r, t, b (for example, collide the left side, the right side, etc) and returns true or false according to the case. The collision method, on the other hand, resolves all the collisions of the object with other objects. The two methods have the same name because I think is better avoid overload the design with different names for methods who do almost the same think, but in distinct contexts and classes. This is clear enough to the reader or I should change the method's name?

    Read the article

  • private class calling a method from its outer class

    - by oxinabox.ucc.asn.au
    Ok, so I have a class for a "Advanced Data Structure" (in this case a kinda tree) SO I implimented a Iterator as a private class with in it. So the iterator needs to implement a remove function to remove the last retuirned element. now my ADT already impliments a remove function, and in this case there is very little (thinking about it, i think nothing) to be gain by implimenting a different remove function for the iterator. so how do I go about calling the remove from my ADT sketch of my struture: public class ADT { ... private class ADT_Iterator impliments java.util.Itorator{ ... public void remove(){ //where I want to call the ADT's remove function from } ... public void remove( Object paramFoo ) { ... } ... } So just calling remove(FooInstance) won't work (will it?) and this.remove(FooInstance) is the same thing. what do i call? (and changign the name of the ADT's remove function is not an option, as that AD T has to meet an Interace wich I am note at liberty to change) I could make both of them call a removeHelper functon, I guess...

    Read the article

  • passing reference of class to another class android error

    - by prolink007
    I recently asked the precursor to this question and had a great reply. However, when i was working this into my android application i am getting an unexpected error and was wondering if everyone could take a look at my code and help me see what i am doing wrong. Link to the initial question: passing reference of class to another class My ERROR: "The constructor ConnectDevice(new View.OnClickListener(){}) is undefined" The above is an error detected by eclipse. Thanks in advance! Below are My code snippets: public class SmartApp extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.intro); final Button connectDeviceButton = (Button) findViewById(R.id.connectDeviceButton); connectDeviceButton.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { Thread cThread = new Thread(new ConnectDevice(this)); cThread.start(); } }); } } public class ConnectDevice implements Runnable { private boolean connected; private SmartApp smartAppRef; private ObjectInputStream ois; public ConnectDevice(SmartApp smartAppRef) { this.smartAppRef = smartAppRef; } }

    Read the article

  • C++ Problem: Class Promotion using derived class

    - by Michael Fitzpatrick
    I have a class for Float32 that is derived from Float32_base class Float32_base { public: // Constructors Float32_base(float x) : value(x) {}; Float32_base(void) : value(0) {}; operator float32(void) {return value;}; Float32_base operator =(float x) {value = x; return *this;}; Float32_base operator +(float x) const { return value + x;}; protected: float value; } class Float32 : public Float32_base { public: float Tad() { return value + .01; } } int main() { Float32 x, y, z; x = 1; y = 2; // WILL NOT COMPILE! z = (x + y).Tad(); // COMPILES OK z = ((Float32)(x + y)).Tad(); } The issue is that the + operator returns a Float32_base and Tad() is not in that class. But 'x' and 'y' are Float32's. Is there a way that I can get the code in the first line to compile without having to resort to a typecast like I did on the next line?

    Read the article

  • The dynamic Type in C# Simplifies COM Member Access from Visual FoxPro

    - by Rick Strahl
    I’ve written quite a bit about Visual FoxPro interoperating with .NET in the past both for ASP.NET interacting with Visual FoxPro COM objects as well as Visual FoxPro calling into .NET code via COM Interop. COM Interop with Visual FoxPro has a number of problems but one of them at least got a lot easier with the introduction of dynamic type support in .NET. One of the biggest problems with COM interop has been that it’s been really difficult to pass dynamic objects from FoxPro to .NET and get them properly typed. The only way that any strong typing can occur in .NET for FoxPro components is via COM type library exports of Visual FoxPro components. Due to limitations in Visual FoxPro’s type library support as well as the dynamic nature of the Visual FoxPro language where few things are or can be described in the form of a COM type library, a lot of useful interaction between FoxPro and .NET required the use of messy Reflection code in .NET. Reflection is .NET’s base interface to runtime type discovery and dynamic execution of code without requiring strong typing. In FoxPro terms it’s similar to EVALUATE() functionality albeit with a much more complex API and corresponiding syntax. The Reflection APIs are fairly powerful, but they are rather awkward to use and require a lot of code. Even with the creation of wrapper utility classes for common EVAL() style Reflection functionality dynamically access COM objects passed to .NET often is pretty tedious and ugly. Let’s look at a simple example. In the following code I use some FoxPro code to dynamically create an object in code and then pass this object to .NET. An alternative to this might also be to create a new object on the fly by using SCATTER NAME on a database record. How the object is created is inconsequential, other than the fact that it’s not defined as a COM object – it’s a pure FoxPro object that is passed to .NET. Here’s the code: *** Create .NET COM InstanceloNet = CREATEOBJECT('DotNetCom.DotNetComPublisher') *** Create a Customer Object Instance (factory method) loCustomer = GetCustomer() loCustomer.Name = "Rick Strahl" loCustomer.Company = "West Wind Technologies" loCustomer.creditLimit = 9999999999.99 loCustomer.Address.StreetAddress = "32 Kaiea Place" loCustomer.Address.Phone = "808 579-8342" loCustomer.Address.Email = "[email protected]" *** Pass Fox Object and echo back values ? loNet.PassRecordObject(loObject) RETURN FUNCTION GetCustomer LOCAL loCustomer, loAddress loCustomer = CREATEOBJECT("EMPTY") ADDPROPERTY(loCustomer,"Name","") ADDPROPERTY(loCustomer,"Company","") ADDPROPERTY(loCUstomer,"CreditLimit",0.00) ADDPROPERTY(loCustomer,"Entered",DATETIME()) loAddress = CREATEOBJECT("Empty") ADDPROPERTY(loAddress,"StreetAddress","") ADDPROPERTY(loAddress,"Phone","") ADDPROPERTY(loAddress,"Email","") ADDPROPERTY(loCustomer,"Address",loAddress) RETURN loCustomer ENDFUNC Now prior to .NET 4.0 you’d have to access this object passed to .NET via Reflection and the method code to do this would looks something like this in the .NET component: public string PassRecordObject(object FoxObject) { // *** using raw Reflection string Company = (string) FoxObject.GetType().InvokeMember( "Company", BindingFlags.GetProperty,null, FoxObject,null); // using the easier ComUtils wrappers string Name = (string) ComUtils.GetProperty(FoxObject,"Name"); // Getting Address object – then getting child properties object Address = ComUtils.GetProperty(FoxObject,"Address");    string Street = (string) ComUtils.GetProperty(FoxObject,"StreetAddress"); // using ComUtils 'Ex' functions you can use . Syntax     string StreetAddress = (string) ComUtils.GetPropertyEx(FoxObject,"AddressStreetAddress"); return Name + Environment.NewLine + Company + Environment.NewLine + StreetAddress + Environment.NewLine + " FOX"; } Note that the FoxObject is passed in as type object which has no specific type. Since the object doesn’t exist in .NET as a type signature the object is passed without any specific type information as plain non-descript object. To retrieve a property the Reflection APIs like Type.InvokeMember or Type.GetProperty().GetValue() etc. need to be used. I made this code a little simpler by using the Reflection Wrappers I mentioned earlier but even with those ComUtils calls the code is pretty ugly requiring passing the objects for each call and casting each element. Using .NET 4.0 Dynamic Typing makes this Code a lot cleaner Enter .NET 4.0 and the dynamic type. Replacing the input parameter to the .NET method from type object to dynamic makes the code to access the FoxPro component inside of .NET much more natural: public string PassRecordObjectDynamic(dynamic FoxObject) { // *** using raw Reflection string Company = FoxObject.Company; // *** using the easier ComUtils class string Name = FoxObject.Name; // *** using ComUtils 'ex' functions to use . Syntax string Address = FoxObject.Address.StreetAddress; return Name + Environment.NewLine + Company + Environment.NewLine + Address + Environment.NewLine + " FOX"; } As you can see the parameter is of type dynamic which as the name implies performs Reflection lookups and evaluation on the fly so all the Reflection code in the last example goes away. The code can use regular object ‘.’ syntax to reference each of the members of the object. You can access properties and call methods this way using natural object language. Also note that all the type casts that were required in the Reflection code go away – dynamic types like var can infer the type to cast to based on the target assignment. As long as the type can be inferred by the compiler at compile time (ie. the left side of the expression is strongly typed) no explicit casts are required. Note that although you get to use plain object syntax in the code above you don’t get Intellisense in Visual Studio because the type is dynamic and thus has no hard type definition in .NET . The above example calls a .NET Component from VFP, but it also works the other way around. Another frequent scenario is an .NET code calling into a FoxPro COM object that returns a dynamic result. Assume you have a FoxPro COM object returns a FoxPro Cursor Record as an object: DEFINE CLASS FoxData AS SESSION OlePublic cAppStartPath = "" FUNCTION INIT THIS.cAppStartPath = ADDBS( JustPath(Application.ServerName) ) SET PATH TO ( THIS.cAppStartpath ) ENDFUNC FUNCTION GetRecord(lnPk) LOCAL loCustomer SELECT * FROM tt_Cust WHERE pk = lnPk ; INTO CURSOR TCustomer IF _TALLY < 1 RETURN NULL ENDIF SCATTER NAME loCustomer MEMO RETURN loCustomer ENDFUNC ENDDEFINE If you call this from a .NET application you can now retrieve this data via COM Interop and cast the result as dynamic to simplify the data access of the dynamic FoxPro type that was created on the fly: int pk = 0; int.TryParse(Request.QueryString["id"],out pk); // Create Fox COM Object with Com Callable Wrapper FoxData foxData = new FoxData(); dynamic foxRecord = foxData.GetRecord(pk); string company = foxRecord.Company; DateTime entered = foxRecord.Entered; This code looks simple and natural as it should be – heck you could write code like this in days long gone by in scripting languages like ASP classic for example. Compared to the Reflection code that previously was necessary to run similar code this is much easier to write, understand and maintain. For COM interop and Visual FoxPro operation dynamic type support in .NET 4.0 is a huge improvement and certainly makes it much easier to deal with FoxPro code that calls into .NET. Regardless of whether you’re using COM for calling Visual FoxPro objects from .NET (ASP.NET calling a COM component and getting a dynamic result returned) or whether FoxPro code is calling into a .NET COM component from a FoxPro desktop application. At one point or another FoxPro likely ends up passing complex dynamic data to .NET and for this the dynamic typing makes coding much cleaner and more readable without having to create custom Reflection wrappers. As a bonus the dynamic runtime that underlies the dynamic type is fairly efficient in terms of making Reflection calls especially if members are repeatedly accessed. © Rick Strahl, West Wind Technologies, 2005-2010Posted in COM  FoxPro  .NET  CSharp  

    Read the article

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